diff --git a/__pycache__/metrics_logger.cpython-312.pyc b/__pycache__/metrics_logger.cpython-312.pyc index 102fa1b7..eda369a4 100644 Binary files a/__pycache__/metrics_logger.cpython-312.pyc and b/__pycache__/metrics_logger.cpython-312.pyc differ diff --git a/__pycache__/twilio_stream.cpython-312.pyc b/__pycache__/twilio_stream.cpython-312.pyc new file mode 100644 index 00000000..588bf816 Binary files /dev/null and b/__pycache__/twilio_stream.cpython-312.pyc differ diff --git a/call_twilio.py b/call_twilio.py new file mode 100644 index 00000000..ee594840 --- /dev/null +++ b/call_twilio.py @@ -0,0 +1,55 @@ +import os +from twilio.rest import Client +from dotenv import load_dotenv + +load_dotenv() + +def make_call(to_number): + try: + client = Client(os.getenv("TWILIO_ACCOUNT_SID"), os.getenv("TWILIO_AUTH_TOKEN")) + + # Use your ngrok URL for the voice webhook + voice_url = f"{os.getenv('NGROK_URL')}/voice" + + print(f"Making call to {to_number}") + print(f"Voice webhook URL: {voice_url}") + + call = client.calls.create( + to=to_number, + from_=os.getenv("TWILIO_NUMBER"), + url=voice_url, # Twilio will fetch TwiML from this URL + method="POST" + ) + print(f"✅ Call initiated successfully!") + print(f"Call SID: {call.sid}") + print(f"Call Status: {call.status}") + + except Exception as e: + print(f"❌ Error making call: {e}") + +def test_webhook(): + """Test if the webhook URL is accessible""" + try: + import requests + webhook_url = f"{os.getenv('NGROK_URL')}/voice" + response = requests.get(webhook_url) + if response.status_code == 200: + print(f"✅ Webhook URL is accessible: {webhook_url}") + else: + print(f"❌ Webhook URL returned status {response.status_code}: {webhook_url}") + except Exception as e: + print(f"❌ Cannot reach webhook URL: {e}") + +if __name__ == "__main__": + print("=== Voice AI Agent Call Initiator ===") + + # Test webhook first + print("\n1. Testing webhook URL...") + test_webhook() + + # Make call + print("\n2. Initiating call...") + phone = input("Enter the phone number to call (with country code, e.g. +15551234567): ") + make_call(phone) + + print("\n3. Call initiated! Answer your phone and start speaking.") \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 2859f898..ac695a62 100644 Binary files a/requirements.txt and b/requirements.txt differ diff --git a/twilio_stream.py b/twilio_stream.py new file mode 100644 index 00000000..bcabad8c --- /dev/null +++ b/twilio_stream.py @@ -0,0 +1,102 @@ +import os +import requests +from fastapi import FastAPI, Request, Form +from fastapi.responses import Response +from dotenv import load_dotenv + +load_dotenv() +app = FastAPI() + +# Helper: Send text to Groq LLM and get response +def ask_groq(prompt): + try: + url = "https://api.groq.com/openai/v1/chat/completions" + headers = { + "Authorization": f"Bearer {os.getenv('GROQ_API_KEY')}", + "Content-Type": "application/json" + } + data = { + "model": "llama3-8b-8192", + "messages": [ + {"role": "system", "content": "You are a helpful AI assistant. Keep responses short and conversational for phone calls, under 50 words."}, + {"role": "user", "content": prompt} + ], + "max_tokens": 100, + "temperature": 0.7 + } + resp = requests.post(url, headers=headers, json=data) + resp.raise_for_status() + return resp.json()["choices"][0]["message"]["content"] + except Exception as e: + print(f"Groq API error: {e}") + return "I'm sorry, I'm having trouble processing your request right now." + +@app.get("/") +def read_root(): + return {"message": "Voice AI Agent is running!"} + +@app.api_route("/voice", methods=["GET", "POST"]) +async def voice(request: Request): + print("📞 Twilio voice call received!") + + # Initial greeting when call starts + message = "Hello! I am your AI assistant. How can I help you today?" + + print(f"📞 AI says: {message}") + + # Return TwiML to make Twilio speak and listen + response = f""" + + {message} + + Please speak now. + + I didn't hear anything. Goodbye! +""" + + return Response(content=response, media_type="application/xml") + +@app.api_route("/process-speech", methods=["POST"]) +async def process_speech(request: Request): + form = await request.form() + user_speech = form.get("SpeechResult", "") + confidence = form.get("Confidence", "0") + + print(f"📞 User said: '{user_speech}' (confidence: {confidence})") + + if user_speech and user_speech.strip(): + # Send to Groq LLM + ai_response = ask_groq(user_speech) + print(f"📞 AI responds: {ai_response}") + + # Continue conversation + response = f""" + + {ai_response} + + Is there anything else I can help you with? + + Thank you for calling. Goodbye! +""" + else: + # No speech detected + response = f""" + + I didn't hear anything clearly. Let me try again. + + Please speak clearly. + + Thank you for calling. Goodbye! +""" + + return Response(content=response, media_type="application/xml") + +# Health check endpoint +@app.get("/health") +def health_check(): + return {"status": "healthy", "message": "Voice AI Agent is running"} + +# Graceful shutdown +@app.on_event("shutdown") +async def shutdown_event(): + print("Shutting down Voice AI Agent...") \ No newline at end of file diff --git a/venv/Lib/site-packages/__pycache__/deprecation.cpython-312.pyc b/venv/Lib/site-packages/__pycache__/deprecation.cpython-312.pyc index 43b6f912..ed876329 100644 Binary files a/venv/Lib/site-packages/__pycache__/deprecation.cpython-312.pyc and b/venv/Lib/site-packages/__pycache__/deprecation.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/__pycache__/mypy_extensions.cpython-312.pyc b/venv/Lib/site-packages/__pycache__/mypy_extensions.cpython-312.pyc index 9223a813..86669ca5 100644 Binary files a/venv/Lib/site-packages/__pycache__/mypy_extensions.cpython-312.pyc and b/venv/Lib/site-packages/__pycache__/mypy_extensions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/__pycache__/six.cpython-312.pyc b/venv/Lib/site-packages/__pycache__/six.cpython-312.pyc index 5b08eeba..7648701d 100644 Binary files a/venv/Lib/site-packages/__pycache__/six.cpython-312.pyc and b/venv/Lib/site-packages/__pycache__/six.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/__pycache__/typing_extensions.cpython-312.pyc b/venv/Lib/site-packages/__pycache__/typing_extensions.cpython-312.pyc index f4ac62c4..efa9d8e2 100644 Binary files a/venv/Lib/site-packages/__pycache__/typing_extensions.cpython-312.pyc and b/venv/Lib/site-packages/__pycache__/typing_extensions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/__pycache__/typing_inspect.cpython-312.pyc b/venv/Lib/site-packages/__pycache__/typing_inspect.cpython-312.pyc index b064f60a..32167c93 100644 Binary files a/venv/Lib/site-packages/__pycache__/typing_inspect.cpython-312.pyc and b/venv/Lib/site-packages/__pycache__/typing_inspect.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aenum/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/aenum/__pycache__/__init__.cpython-312.pyc index a08a276a..42eb0846 100644 Binary files a/venv/Lib/site-packages/aenum/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/aenum/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aenum/__pycache__/_common.cpython-312.pyc b/venv/Lib/site-packages/aenum/__pycache__/_common.cpython-312.pyc index 8dd2539c..70384d5a 100644 Binary files a/venv/Lib/site-packages/aenum/__pycache__/_common.cpython-312.pyc and b/venv/Lib/site-packages/aenum/__pycache__/_common.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aenum/__pycache__/_constant.cpython-312.pyc b/venv/Lib/site-packages/aenum/__pycache__/_constant.cpython-312.pyc index e48bc777..0dae00f0 100644 Binary files a/venv/Lib/site-packages/aenum/__pycache__/_constant.cpython-312.pyc and b/venv/Lib/site-packages/aenum/__pycache__/_constant.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aenum/__pycache__/_enum.cpython-312.pyc b/venv/Lib/site-packages/aenum/__pycache__/_enum.cpython-312.pyc index a6476cfa..715ab950 100644 Binary files a/venv/Lib/site-packages/aenum/__pycache__/_enum.cpython-312.pyc and b/venv/Lib/site-packages/aenum/__pycache__/_enum.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aenum/__pycache__/_py3.cpython-312.pyc b/venv/Lib/site-packages/aenum/__pycache__/_py3.cpython-312.pyc index 460165f8..dbc7ed37 100644 Binary files a/venv/Lib/site-packages/aenum/__pycache__/_py3.cpython-312.pyc and b/venv/Lib/site-packages/aenum/__pycache__/_py3.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aenum/__pycache__/_tuple.cpython-312.pyc b/venv/Lib/site-packages/aenum/__pycache__/_tuple.cpython-312.pyc index e4942434..c29cccd2 100644 Binary files a/venv/Lib/site-packages/aenum/__pycache__/_tuple.cpython-312.pyc and b/venv/Lib/site-packages/aenum/__pycache__/_tuple.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiofiles/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/aiofiles/__pycache__/__init__.cpython-312.pyc index 0bb7b31d..e7c5bb46 100644 Binary files a/venv/Lib/site-packages/aiofiles/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/aiofiles/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiofiles/__pycache__/base.cpython-312.pyc b/venv/Lib/site-packages/aiofiles/__pycache__/base.cpython-312.pyc index 8f4d65b5..66596786 100644 Binary files a/venv/Lib/site-packages/aiofiles/__pycache__/base.cpython-312.pyc and b/venv/Lib/site-packages/aiofiles/__pycache__/base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiofiles/tempfile/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/aiofiles/tempfile/__pycache__/__init__.cpython-312.pyc index ee1f49fd..9fc6288f 100644 Binary files a/venv/Lib/site-packages/aiofiles/tempfile/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/aiofiles/tempfile/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiofiles/tempfile/__pycache__/temptypes.cpython-312.pyc b/venv/Lib/site-packages/aiofiles/tempfile/__pycache__/temptypes.cpython-312.pyc index f3725f3c..afdd3967 100644 Binary files a/venv/Lib/site-packages/aiofiles/tempfile/__pycache__/temptypes.cpython-312.pyc and b/venv/Lib/site-packages/aiofiles/tempfile/__pycache__/temptypes.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiofiles/threadpool/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/aiofiles/threadpool/__pycache__/__init__.cpython-312.pyc index 76874b47..dc3f6169 100644 Binary files a/venv/Lib/site-packages/aiofiles/threadpool/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/aiofiles/threadpool/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiofiles/threadpool/__pycache__/binary.cpython-312.pyc b/venv/Lib/site-packages/aiofiles/threadpool/__pycache__/binary.cpython-312.pyc index 488c8ae1..d6bbfc96 100644 Binary files a/venv/Lib/site-packages/aiofiles/threadpool/__pycache__/binary.cpython-312.pyc and b/venv/Lib/site-packages/aiofiles/threadpool/__pycache__/binary.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiofiles/threadpool/__pycache__/text.cpython-312.pyc b/venv/Lib/site-packages/aiofiles/threadpool/__pycache__/text.cpython-312.pyc index d1d069c1..d242abf5 100644 Binary files a/venv/Lib/site-packages/aiofiles/threadpool/__pycache__/text.cpython-312.pyc and b/venv/Lib/site-packages/aiofiles/threadpool/__pycache__/text.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiofiles/threadpool/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/aiofiles/threadpool/__pycache__/utils.cpython-312.pyc index 51751fcb..2dd2789f 100644 Binary files a/venv/Lib/site-packages/aiofiles/threadpool/__pycache__/utils.cpython-312.pyc and b/venv/Lib/site-packages/aiofiles/threadpool/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohappyeyeballs/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/aiohappyeyeballs/__pycache__/__init__.cpython-312.pyc index 32a806ae..0dc85f85 100644 Binary files a/venv/Lib/site-packages/aiohappyeyeballs/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/aiohappyeyeballs/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohappyeyeballs/__pycache__/_staggered.cpython-312.pyc b/venv/Lib/site-packages/aiohappyeyeballs/__pycache__/_staggered.cpython-312.pyc index d892c521..7ffaa0e9 100644 Binary files a/venv/Lib/site-packages/aiohappyeyeballs/__pycache__/_staggered.cpython-312.pyc and b/venv/Lib/site-packages/aiohappyeyeballs/__pycache__/_staggered.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohappyeyeballs/__pycache__/impl.cpython-312.pyc b/venv/Lib/site-packages/aiohappyeyeballs/__pycache__/impl.cpython-312.pyc index b04855a6..36823b2b 100644 Binary files a/venv/Lib/site-packages/aiohappyeyeballs/__pycache__/impl.cpython-312.pyc and b/venv/Lib/site-packages/aiohappyeyeballs/__pycache__/impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohappyeyeballs/__pycache__/types.cpython-312.pyc b/venv/Lib/site-packages/aiohappyeyeballs/__pycache__/types.cpython-312.pyc index 690ca320..512b4408 100644 Binary files a/venv/Lib/site-packages/aiohappyeyeballs/__pycache__/types.cpython-312.pyc and b/venv/Lib/site-packages/aiohappyeyeballs/__pycache__/types.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohappyeyeballs/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/aiohappyeyeballs/__pycache__/utils.cpython-312.pyc index c6d338aa..ba39d612 100644 Binary files a/venv/Lib/site-packages/aiohappyeyeballs/__pycache__/utils.cpython-312.pyc and b/venv/Lib/site-packages/aiohappyeyeballs/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/__init__.cpython-312.pyc index c9328d2d..ecc5c80b 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/_cookie_helpers.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/_cookie_helpers.cpython-312.pyc index 98aab296..7956c5d5 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/_cookie_helpers.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/_cookie_helpers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/abc.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/abc.cpython-312.pyc index 73cf76cd..422d76ef 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/abc.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/abc.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/base_protocol.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/base_protocol.cpython-312.pyc index 211aab8b..b2158a7b 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/base_protocol.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/base_protocol.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/client.cpython-312.pyc index eea8084f..27ee0c0c 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/client.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/client.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/client_exceptions.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/client_exceptions.cpython-312.pyc index 38c5fef8..44170866 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/client_exceptions.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/client_exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/client_middleware_digest_auth.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/client_middleware_digest_auth.cpython-312.pyc index 41980690..224c4745 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/client_middleware_digest_auth.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/client_middleware_digest_auth.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/client_middlewares.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/client_middlewares.cpython-312.pyc index f0e9b421..4ba67651 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/client_middlewares.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/client_middlewares.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/client_proto.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/client_proto.cpython-312.pyc index 9386bf57..9de73f4c 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/client_proto.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/client_proto.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/client_reqrep.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/client_reqrep.cpython-312.pyc index 77e266e9..656e3ad0 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/client_reqrep.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/client_reqrep.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/client_ws.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/client_ws.cpython-312.pyc index d11ef368..26b2cdb3 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/client_ws.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/client_ws.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/compression_utils.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/compression_utils.cpython-312.pyc index 9f1172b4..67e18e50 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/compression_utils.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/compression_utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/connector.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/connector.cpython-312.pyc index 63c2bfa4..d598367f 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/connector.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/connector.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/cookiejar.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/cookiejar.cpython-312.pyc index ab8507ab..01277731 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/cookiejar.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/cookiejar.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/formdata.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/formdata.cpython-312.pyc index 8c19f681..3806245a 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/formdata.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/formdata.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/hdrs.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/hdrs.cpython-312.pyc index 5f97d7b0..f2f2e21d 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/hdrs.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/hdrs.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/helpers.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/helpers.cpython-312.pyc index 609b0f6a..7f3f2227 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/helpers.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/helpers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/http.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/http.cpython-312.pyc index f36cb36e..fc08ed41 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/http.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/http.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/http_exceptions.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/http_exceptions.cpython-312.pyc index cbae997e..6adb2306 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/http_exceptions.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/http_exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/http_parser.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/http_parser.cpython-312.pyc index 2ed6652a..f231c88e 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/http_parser.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/http_parser.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/http_websocket.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/http_websocket.cpython-312.pyc index f4f8f173..67d38fce 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/http_websocket.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/http_websocket.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/http_writer.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/http_writer.cpython-312.pyc index 3e6273e7..da248463 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/http_writer.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/http_writer.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/log.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/log.cpython-312.pyc index 2de14e02..550d2f6f 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/log.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/log.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/multipart.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/multipart.cpython-312.pyc index 84ac7e95..1a9dd59a 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/multipart.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/multipart.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/payload.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/payload.cpython-312.pyc index 24a00573..0181c705 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/payload.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/payload.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/payload_streamer.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/payload_streamer.cpython-312.pyc index 4fb38e0d..61c655fd 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/payload_streamer.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/payload_streamer.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/resolver.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/resolver.cpython-312.pyc index 611fd6b4..538fd3b7 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/resolver.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/resolver.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/streams.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/streams.cpython-312.pyc index 3650a264..89889d22 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/streams.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/streams.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/tcp_helpers.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/tcp_helpers.cpython-312.pyc index a28c6952..cda4184c 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/tcp_helpers.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/tcp_helpers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/tracing.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/tracing.cpython-312.pyc index 6d162e7b..626ae6a6 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/tracing.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/tracing.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/typedefs.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/typedefs.cpython-312.pyc index 579cc514..dc1fc66a 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/typedefs.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/typedefs.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/web.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/web.cpython-312.pyc index e241efb5..4eca2b6d 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/web.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/web.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/web_app.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/web_app.cpython-312.pyc index fe4ccd22..9fcb8bf4 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/web_app.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/web_app.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/web_exceptions.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/web_exceptions.cpython-312.pyc index e9c7afe2..a4d95d06 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/web_exceptions.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/web_exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/web_fileresponse.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/web_fileresponse.cpython-312.pyc index 6a0847d5..58d154a8 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/web_fileresponse.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/web_fileresponse.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/web_log.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/web_log.cpython-312.pyc index 53ecbe13..0ddd3198 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/web_log.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/web_log.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/web_middlewares.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/web_middlewares.cpython-312.pyc index 381a21b1..23256bbe 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/web_middlewares.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/web_middlewares.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/web_protocol.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/web_protocol.cpython-312.pyc index 175f21d4..d042194a 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/web_protocol.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/web_protocol.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/web_request.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/web_request.cpython-312.pyc index fadc254a..fce46323 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/web_request.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/web_request.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/web_response.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/web_response.cpython-312.pyc index 0ea50815..f77b2931 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/web_response.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/web_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/web_routedef.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/web_routedef.cpython-312.pyc index fd2b3f55..5b596e62 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/web_routedef.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/web_routedef.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/web_runner.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/web_runner.cpython-312.pyc index bae2c43d..80c70045 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/web_runner.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/web_runner.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/web_server.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/web_server.cpython-312.pyc index 1c03e011..9ff04354 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/web_server.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/web_server.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/web_urldispatcher.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/web_urldispatcher.cpython-312.pyc index 22bc5d99..e4319472 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/web_urldispatcher.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/web_urldispatcher.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/__pycache__/web_ws.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/__pycache__/web_ws.cpython-312.pyc index 9c88afe7..8a422ef3 100644 Binary files a/venv/Lib/site-packages/aiohttp/__pycache__/web_ws.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/__pycache__/web_ws.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/_websocket/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/_websocket/__pycache__/__init__.cpython-312.pyc index 8cb6a50a..bb3c4bf6 100644 Binary files a/venv/Lib/site-packages/aiohttp/_websocket/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/_websocket/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/_websocket/__pycache__/helpers.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/_websocket/__pycache__/helpers.cpython-312.pyc index d018b15a..18854bdb 100644 Binary files a/venv/Lib/site-packages/aiohttp/_websocket/__pycache__/helpers.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/_websocket/__pycache__/helpers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/_websocket/__pycache__/models.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/_websocket/__pycache__/models.cpython-312.pyc index d256c39f..a9fc59e2 100644 Binary files a/venv/Lib/site-packages/aiohttp/_websocket/__pycache__/models.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/_websocket/__pycache__/models.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/_websocket/__pycache__/reader.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/_websocket/__pycache__/reader.cpython-312.pyc index 27b7c3ec..f309b4e2 100644 Binary files a/venv/Lib/site-packages/aiohttp/_websocket/__pycache__/reader.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/_websocket/__pycache__/reader.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp/_websocket/__pycache__/writer.cpython-312.pyc b/venv/Lib/site-packages/aiohttp/_websocket/__pycache__/writer.cpython-312.pyc index 037316ca..94a07553 100644 Binary files a/venv/Lib/site-packages/aiohttp/_websocket/__pycache__/writer.cpython-312.pyc and b/venv/Lib/site-packages/aiohttp/_websocket/__pycache__/writer.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp_retry-2.9.1.dist-info/AUTHORS b/venv/Lib/site-packages/aiohttp_retry-2.9.1.dist-info/AUTHORS new file mode 100644 index 00000000..4ba09538 --- /dev/null +++ b/venv/Lib/site-packages/aiohttp_retry-2.9.1.dist-info/AUTHORS @@ -0,0 +1 @@ +Dmitry Inyutin diff --git a/venv/Lib/site-packages/deepgram_sdk-4.2.0.dist-info/INSTALLER b/venv/Lib/site-packages/aiohttp_retry-2.9.1.dist-info/INSTALLER similarity index 100% rename from venv/Lib/site-packages/deepgram_sdk-4.2.0.dist-info/INSTALLER rename to venv/Lib/site-packages/aiohttp_retry-2.9.1.dist-info/INSTALLER diff --git a/venv/Lib/site-packages/aiohttp_retry-2.9.1.dist-info/LICENSE b/venv/Lib/site-packages/aiohttp_retry-2.9.1.dist-info/LICENSE new file mode 100644 index 00000000..175ff4ab --- /dev/null +++ b/venv/Lib/site-packages/aiohttp_retry-2.9.1.dist-info/LICENSE @@ -0,0 +1,8 @@ +The MIT License (MIT) +Copyright (c) 2020 aiohttp_retry Authors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/venv/Lib/site-packages/aiohttp_retry-2.9.1.dist-info/METADATA b/venv/Lib/site-packages/aiohttp_retry-2.9.1.dist-info/METADATA new file mode 100644 index 00000000..8f6a5f96 --- /dev/null +++ b/venv/Lib/site-packages/aiohttp_retry-2.9.1.dist-info/METADATA @@ -0,0 +1,261 @@ +Metadata-Version: 2.1 +Name: aiohttp-retry +Version: 2.9.1 +Summary: Simple retry client for aiohttp +Home-page: https://github.com/inyutin/aiohttp_retry +Author: Dmitry Inyutin +Author-email: inyutin.da@gmail.com +License: MIT +Keywords: aiohttp retry client +Platform: any +Classifier: Programming Language :: Python :: 3 +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Requires-Python: >=3.7 +Description-Content-Type: text/markdown +License-File: LICENSE +License-File: AUTHORS +Requires-Dist: aiohttp + +# Simple aiohttp retry client + +Python 3.7 or higher. + +**Install**: `pip install aiohttp-retry`. + +[!["Buy Me A Coffee"](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/inyutin) + + +### Breaking API changes +- Everything between [2.7.0 - 2.8.3) is yanked. +There is a bug with evaluate_response_callback, it led to infinite retries + +- 2.8.0 is incorrect and yanked. +https://github.com/inyutin/aiohttp_retry/issues/79 + +- Since 2.5.6 this is a new parameter in ```get_timeout``` func called "response". +If you have defined your own ```RetryOptions```, you should add this param into it. +Issue about this: https://github.com/inyutin/aiohttp_retry/issues/59 + +### Examples of usage: +```python +from aiohttp_retry import RetryClient, ExponentialRetry + +async def main(): + retry_options = ExponentialRetry(attempts=1) + retry_client = RetryClient(raise_for_status=False, retry_options=retry_options) + async with retry_client.get('https://ya.ru') as response: + print(response.status) + + await retry_client.close() +``` + +```python +from aiohttp import ClientSession +from aiohttp_retry import RetryClient + +async def main(): + client_session = ClientSession() + retry_client = RetryClient(client_session=client_session) + async with retry_client.get('https://ya.ru') as response: + print(response.status) + + await client_session.close() +``` + +```python +from aiohttp_retry import RetryClient, RandomRetry + +async def main(): + retry_options = RandomRetry(attempts=1) + retry_client = RetryClient(raise_for_status=False, retry_options=retry_options) + + response = await retry_client.get('/ping') + print(response.status) + + await retry_client.close() +``` + +```python +from aiohttp_retry import RetryClient + +async def main(): + async with RetryClient() as client: + async with client.get('https://ya.ru') as response: + print(response.status) +``` + +You can change parameters between attempts by passing multiple requests params: +```python +from aiohttp_retry import RetryClient, RequestParams, ExponentialRetry + +async def main(): + retry_client = RetryClient(raise_for_status=False) + + async with retry_client.requests( + params_list=[ + RequestParams( + method='GET', + url='https://ya.ru', + ), + RequestParams( + method='GET', + url='https://ya.ru', + headers={'some_header': 'some_value'}, + ), + ] + ) as response: + print(response.status) + + await retry_client.close() +``` + +You can also add some logic, F.E. logging, on failures by using trace mechanic. +```python +import logging +import sys +from types import SimpleNamespace + +from aiohttp import ClientSession, TraceConfig, TraceRequestStartParams + +from aiohttp_retry import RetryClient, ExponentialRetry + + +handler = logging.StreamHandler(sys.stdout) +logging.basicConfig(handlers=[handler]) +logger = logging.getLogger(__name__) +retry_options = ExponentialRetry(attempts=2) + + +async def on_request_start( + session: ClientSession, + trace_config_ctx: SimpleNamespace, + params: TraceRequestStartParams, +) -> None: + current_attempt = trace_config_ctx.trace_request_ctx['current_attempt'] + if retry_options.attempts <= current_attempt: + logger.warning('Wow! We are in last attempt') + + +async def main(): + trace_config = TraceConfig() + trace_config.on_request_start.append(on_request_start) + retry_client = RetryClient(retry_options=retry_options, trace_configs=[trace_config]) + + response = await retry_client.get('https://httpstat.us/503', ssl=False) + print(response.status) + + await retry_client.close() +``` +Look tests for more examples. \ +**Be aware: last request returns as it is.** +**If the last request ended with exception, that this exception will be raised from RetryClient request** + +### Documentation +`RetryClient` takes the same arguments as ClientSession[[docs](https://docs.aiohttp.org/en/stable/client_reference.html)] \ +`RetryClient` has methods: +- request +- get +- options +- head +- post +- put +- patch +- put +- delete + +They are same as for `ClientSession`, but take one possible additional argument: +```python +class RetryOptionsBase: + def __init__( + self, + attempts: int = 3, # How many times we should retry + statuses: Iterable[int] | None = None, # On which statuses we should retry + exceptions: Iterable[type[Exception]] | None = None, # On which exceptions we should retry, by default on all + retry_all_server_errors: bool = True, # If should retry all 500 errors or not + # a callback that will run on response to decide if retry + evaluate_response_callback: EvaluateResponseCallbackType | None = None, + ): + ... + + @abc.abstractmethod + def get_timeout(self, attempt: int, response: Optional[Response] = None) -> float: + raise NotImplementedError + +``` +You can specify `RetryOptions` both for `RetryClient` and it's methods. +`RetryOptions` in methods override `RetryOptions` defined in `RetryClient` constructor. + +**Important**: by default all 5xx responses are retried + statuses you specified as ```statuses``` param +If you will pass ```retry_all_server_errors=False``` than you can manually set what 5xx errors to retry. + +You can define your own timeouts logic or use: +- ```ExponentialRetry``` with exponential backoff +- ```RandomRetry``` for random backoff +- ```ListRetry``` with backoff you predefine by list +- ```FibonacciRetry``` with backoff that looks like fibonacci sequence +- ```JitterRetry``` exponential retry with a bit of randomness + +**Important**: you can proceed server response as an parameter for calculating next timeout. +However this response can be None, server didn't make a response or you have set up ```raise_for_status=True``` +Look here for an example: https://github.com/inyutin/aiohttp_retry/issues/59 + +Additionally, you can specify ```evaluate_response_callback```. It receive a ```ClientResponse``` and decide to retry or not by returning a bool. +It can be useful, if server API sometimes response with malformed data. + +#### Request Trace Context +`RetryClient` add *current attempt number* to `request_trace_ctx` (see examples, +for more info see [aiohttp doc](https://docs.aiohttp.org/en/stable/client_advanced.html#aiohttp-client-tracing)). + +### Change parameters between retries +`RetryClient` also has a method called `requests`. This method should be used if you want to make requests with different params. +```python +@dataclass +class RequestParams: + method: str + url: _RAW_URL_TYPE + headers: dict[str, Any] | None = None + trace_request_ctx: dict[str, Any] | None = None + kwargs: dict[str, Any] | None = None +``` + +```python +def requests( + self, + params_list: list[RequestParams], + retry_options: RetryOptionsBase | None = None, + raise_for_status: bool | None = None, +) -> _RequestContext: +``` + +You can find an example of usage above or in tests. +But basically `RequestParams` is a structure to define params for `ClientSession.request` func. +`method`, `url`, `headers` `trace_request_ctx` defined outside kwargs, because they are popular. + +There is also an old way to change URL between retries by specifying ```url``` as list of urls. Example: +```python +from aiohttp_retry import RetryClient + +retry_client = RetryClient() +async with retry_client.get(url=['/internal_error', '/ping']) as response: + text = await response.text() + assert response.status == 200 + assert text == 'Ok!' + +await retry_client.close() +``` + +In this example we request ```/interval_error```, fail and then successfully request ```/ping```. +If you specify less urls than ```attempts``` number in ```RetryOptions```, ```RetryClient``` will request last url at last attempts. +This means that in example above we would request ```/ping``` once again in case of failure. + +### Types + +`aiohttp_retry` is a typed project. It should be fully compatible with mypy. + +It also introduce one special type: +``` +ClientType = Union[ClientSession, RetryClient] +``` + +This type can be imported by ```from aiohttp_retry.types import ClientType``` diff --git a/venv/Lib/site-packages/aiohttp_retry-2.9.1.dist-info/RECORD b/venv/Lib/site-packages/aiohttp_retry-2.9.1.dist-info/RECORD new file mode 100644 index 00000000..c04cce82 --- /dev/null +++ b/venv/Lib/site-packages/aiohttp_retry-2.9.1.dist-info/RECORD @@ -0,0 +1,16 @@ +aiohttp_retry-2.9.1.dist-info/AUTHORS,sha256=GlJRXBnogod3eAzFrL3YBj8lrNy1PVoeaKCnNm2zN5M,38 +aiohttp_retry-2.9.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +aiohttp_retry-2.9.1.dist-info/LICENSE,sha256=rKYSbPXF6EyrQeo7xh9TV4YWMWqD6-EwzeDUt2boof4,1087 +aiohttp_retry-2.9.1.dist-info/METADATA,sha256=NVvnJQd6heUBRFSC8S1AR5TtTODUR4JmoY3grJKfkwg,8750 +aiohttp_retry-2.9.1.dist-info/RECORD,, +aiohttp_retry-2.9.1.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92 +aiohttp_retry-2.9.1.dist-info/top_level.txt,sha256=b-4ybD7H7PD7sNUDod6pes6gfHuEde1xETO4fHqAMog,14 +aiohttp_retry/__init__.py,sha256=YIVHUfIbOL5QhMEOs7cQlyrmm57o2SgjYC_V-P0aUes,79 +aiohttp_retry/__pycache__/__init__.cpython-312.pyc,, +aiohttp_retry/__pycache__/client.cpython-312.pyc,, +aiohttp_retry/__pycache__/retry_options.cpython-312.pyc,, +aiohttp_retry/__pycache__/types.cpython-312.pyc,, +aiohttp_retry/client.py,sha256=VjrglGKv8KPyVXn1RLnv3vXcAm83m8WDJyXX9Pds_yo,12328 +aiohttp_retry/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +aiohttp_retry/retry_options.py,sha256=l9k-P_0v-K7Q9F1wY2Z_jjUNlhplH2_F9zZ73xZ-El0,9014 +aiohttp_retry/types.py,sha256=lO3nb__G8p1jWBcD9ptKh_YHgEy6pPOH_HCNM69BH8s,141 diff --git a/venv/Lib/site-packages/aiohttp_retry-2.9.1.dist-info/WHEEL b/venv/Lib/site-packages/aiohttp_retry-2.9.1.dist-info/WHEEL new file mode 100644 index 00000000..98c0d20b --- /dev/null +++ b/venv/Lib/site-packages/aiohttp_retry-2.9.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.42.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/venv/Lib/site-packages/aiohttp_retry-2.9.1.dist-info/top_level.txt b/venv/Lib/site-packages/aiohttp_retry-2.9.1.dist-info/top_level.txt new file mode 100644 index 00000000..ea6602f9 --- /dev/null +++ b/venv/Lib/site-packages/aiohttp_retry-2.9.1.dist-info/top_level.txt @@ -0,0 +1 @@ +aiohttp_retry diff --git a/venv/Lib/site-packages/aiohttp_retry/__init__.py b/venv/Lib/site-packages/aiohttp_retry/__init__.py new file mode 100644 index 00000000..25968d59 --- /dev/null +++ b/venv/Lib/site-packages/aiohttp_retry/__init__.py @@ -0,0 +1,2 @@ +from .client import * # noqa: F403 +from .retry_options import * # noqa: F403 diff --git a/venv/Lib/site-packages/aiohttp_retry/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/aiohttp_retry/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..e07ead01 Binary files /dev/null and b/venv/Lib/site-packages/aiohttp_retry/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp_retry/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/aiohttp_retry/__pycache__/client.cpython-312.pyc new file mode 100644 index 00000000..635b5c86 Binary files /dev/null and b/venv/Lib/site-packages/aiohttp_retry/__pycache__/client.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp_retry/__pycache__/retry_options.cpython-312.pyc b/venv/Lib/site-packages/aiohttp_retry/__pycache__/retry_options.cpython-312.pyc new file mode 100644 index 00000000..8f2afc86 Binary files /dev/null and b/venv/Lib/site-packages/aiohttp_retry/__pycache__/retry_options.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp_retry/__pycache__/types.cpython-312.pyc b/venv/Lib/site-packages/aiohttp_retry/__pycache__/types.cpython-312.pyc new file mode 100644 index 00000000..cd763032 Binary files /dev/null and b/venv/Lib/site-packages/aiohttp_retry/__pycache__/types.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/aiohttp_retry/client.py b/venv/Lib/site-packages/aiohttp_retry/client.py new file mode 100644 index 00000000..42d55e1a --- /dev/null +++ b/venv/Lib/site-packages/aiohttp_retry/client.py @@ -0,0 +1,415 @@ +from __future__ import annotations + +import asyncio +import logging +import sys +from abc import abstractmethod +from dataclasses import dataclass +from typing import ( + TYPE_CHECKING, + Any, + Awaitable, + Callable, + Generator, + List, + Tuple, + Union, +) + +from aiohttp import ClientResponse, ClientSession, hdrs +from aiohttp.typedefs import StrOrURL +from yarl import URL as YARL_URL + +from .retry_options import ExponentialRetry, RetryOptionsBase + +_MIN_SERVER_ERROR_STATUS = 500 + +if TYPE_CHECKING: + from types import TracebackType + +if sys.version_info >= (3, 8): + from typing import Protocol +else: + from typing_extensions import Protocol + + +class _Logger(Protocol): + """_Logger defines which methods logger object should have.""" + + @abstractmethod + def debug(self, msg: str, *args: Any, **kwargs: Any) -> None: + pass + + @abstractmethod + def warning(self, msg: str, *args: Any, **kwargs: Any) -> None: + pass + + @abstractmethod + def exception(self, msg: str, *args: Any, **kwargs: Any) -> None: + pass + + +# url itself or list of urls for changing between retries +_RAW_URL_TYPE = Union[StrOrURL, YARL_URL] +_URL_TYPE = Union[_RAW_URL_TYPE, List[_RAW_URL_TYPE], Tuple[_RAW_URL_TYPE, ...]] +_LoggerType = Union[_Logger, logging.Logger] + +RequestFunc = Callable[..., Awaitable[ClientResponse]] + + +@dataclass +class RequestParams: + method: str + url: _RAW_URL_TYPE + headers: dict[str, Any] | None = None + trace_request_ctx: dict[str, Any] | None = None + kwargs: dict[str, Any] | None = None + + +class _RequestContext: + def __init__( + self, + request_func: RequestFunc, + params_list: list[RequestParams], + logger: _LoggerType, + retry_options: RetryOptionsBase, + raise_for_status: bool = False, + ) -> None: + assert len(params_list) > 0 # noqa: S101 + + self._request_func = request_func + self._params_list = params_list + self._logger = logger + self._retry_options = retry_options + self._raise_for_status = raise_for_status + + self._response: ClientResponse | None = None + + async def _is_skip_retry(self, current_attempt: int, response: ClientResponse) -> bool: + if current_attempt == self._retry_options.attempts: + return True + + if response.method.upper() not in self._retry_options.methods: + return True + + if response.status >= _MIN_SERVER_ERROR_STATUS and self._retry_options.retry_all_server_errors: + return False + + if response.status in self._retry_options.statuses: + return False + + if self._retry_options.evaluate_response_callback is None: + return True + + return await self._retry_options.evaluate_response_callback(response) + + async def _do_request(self) -> ClientResponse: + current_attempt = 0 + + while True: + self._logger.debug(f"Attempt {current_attempt+1} out of {self._retry_options.attempts}") + + current_attempt += 1 + try: + try: + params = self._params_list[current_attempt - 1] + except IndexError: + params = self._params_list[-1] + + response: ClientResponse = await self._request_func( + params.method, + params.url, + headers=params.headers, + trace_request_ctx={ + "current_attempt": current_attempt, + **(params.trace_request_ctx or {}), + }, + **(params.kwargs or {}), + ) + + debug_message = f"Retrying after response code: {response.status}" + skip_retry = await self._is_skip_retry(current_attempt, response) + + if skip_retry: + if self._raise_for_status: + response.raise_for_status() + self._response = response + return self._response + retry_wait = self._retry_options.get_timeout(attempt=current_attempt, response=response) + + except Exception as e: + if current_attempt >= self._retry_options.attempts: + raise + + is_exc_valid = any(isinstance(e, exc) for exc in self._retry_options.exceptions) + if not is_exc_valid: + raise + + debug_message = f"Retrying after exception: {e!r}" + retry_wait = self._retry_options.get_timeout(attempt=current_attempt, response=None) + + self._logger.debug(debug_message) + await asyncio.sleep(retry_wait) + + def __await__(self) -> Generator[Any, None, ClientResponse]: + return self.__aenter__().__await__() + + async def __aenter__(self) -> ClientResponse: + return await self._do_request() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self._response is not None and not self._response.closed: + self._response.close() + + +def _url_to_urls(url: _URL_TYPE) -> tuple[StrOrURL, ...]: + if isinstance(url, (str, YARL_URL)): + return (url,) + + if isinstance(url, list): + urls = tuple(url) + elif isinstance(url, tuple): + urls = url + else: + msg = "you can pass url only by str or list/tuple" # type: ignore[unreachable] + raise ValueError(msg) # noqa: TRY004 + + if len(urls) == 0: + msg = "you can pass url by str or list/tuple with attempts count size" + raise ValueError(msg) + + return urls + + +class RetryClient: + def __init__( + self, + client_session: ClientSession | None = None, + logger: _LoggerType | None = None, + retry_options: RetryOptionsBase | None = None, + raise_for_status: bool = False, + *args: Any, + **kwargs: Any, + ) -> None: + if client_session is not None: + client = client_session + closed = None + else: + client = ClientSession(*args, **kwargs) + closed = False + + self._client = client + self._closed = closed + + self._logger: _LoggerType = logger or logging.getLogger("aiohttp_retry") + self._retry_options: RetryOptionsBase = retry_options or ExponentialRetry() + self._raise_for_status = raise_for_status + + @property + def retry_options(self) -> RetryOptionsBase: + return self._retry_options + + def requests( + self, + params_list: list[RequestParams], + retry_options: RetryOptionsBase | None = None, + raise_for_status: bool | None = None, + ) -> _RequestContext: + return self._make_requests( + params_list=params_list, + retry_options=retry_options, + raise_for_status=raise_for_status, + ) + + def request( + self, + method: str, + url: StrOrURL, + retry_options: RetryOptionsBase | None = None, + raise_for_status: bool | None = None, + **kwargs: Any, + ) -> _RequestContext: + return self._make_request( + method=method, + url=url, + retry_options=retry_options, + raise_for_status=raise_for_status, + **kwargs, + ) + + def get( + self, + url: _URL_TYPE, + retry_options: RetryOptionsBase | None = None, + raise_for_status: bool | None = None, + **kwargs: Any, + ) -> _RequestContext: + return self._make_request( + method=hdrs.METH_GET, + url=url, + retry_options=retry_options, + raise_for_status=raise_for_status, + **kwargs, + ) + + def options( + self, + url: _URL_TYPE, + retry_options: RetryOptionsBase | None = None, + raise_for_status: bool | None = None, + **kwargs: Any, + ) -> _RequestContext: + return self._make_request( + method=hdrs.METH_OPTIONS, + url=url, + retry_options=retry_options, + raise_for_status=raise_for_status, + **kwargs, + ) + + def head( + self, + url: _URL_TYPE, + retry_options: RetryOptionsBase | None = None, + raise_for_status: bool | None = None, + **kwargs: Any, + ) -> _RequestContext: + return self._make_request( + method=hdrs.METH_HEAD, + url=url, + retry_options=retry_options, + raise_for_status=raise_for_status, + **kwargs, + ) + + def post( + self, + url: _URL_TYPE, + retry_options: RetryOptionsBase | None = None, + raise_for_status: bool | None = None, + **kwargs: Any, + ) -> _RequestContext: + return self._make_request( + method=hdrs.METH_POST, + url=url, + retry_options=retry_options, + raise_for_status=raise_for_status, + **kwargs, + ) + + def put( + self, + url: _URL_TYPE, + retry_options: RetryOptionsBase | None = None, + raise_for_status: bool | None = None, + **kwargs: Any, + ) -> _RequestContext: + return self._make_request( + method=hdrs.METH_PUT, + url=url, + retry_options=retry_options, + raise_for_status=raise_for_status, + **kwargs, + ) + + def patch( + self, + url: _URL_TYPE, + retry_options: RetryOptionsBase | None = None, + raise_for_status: bool | None = None, + **kwargs: Any, + ) -> _RequestContext: + return self._make_request( + method=hdrs.METH_PATCH, + url=url, + retry_options=retry_options, + raise_for_status=raise_for_status, + **kwargs, + ) + + def delete( + self, + url: _URL_TYPE, + retry_options: RetryOptionsBase | None = None, + raise_for_status: bool | None = None, + **kwargs: Any, + ) -> _RequestContext: + return self._make_request( + method=hdrs.METH_DELETE, + url=url, + retry_options=retry_options, + raise_for_status=raise_for_status, + **kwargs, + ) + + async def close(self) -> None: + await self._client.close() + self._closed = True + + def _make_request( + self, + method: str, + url: _URL_TYPE, + retry_options: RetryOptionsBase | None = None, + raise_for_status: bool | None = None, + **kwargs: Any, + ) -> _RequestContext: + url_list = _url_to_urls(url) + params_list = [ + RequestParams( + method=method, + url=url, + headers=kwargs.pop("headers", {}), + trace_request_ctx=kwargs.pop("trace_request_ctx", None), + kwargs=kwargs, + ) + for url in url_list + ] + + return self._make_requests( + params_list=params_list, + retry_options=retry_options, + raise_for_status=raise_for_status, + ) + + def _make_requests( + self, + params_list: list[RequestParams], + retry_options: RetryOptionsBase | None = None, + raise_for_status: bool | None = None, + ) -> _RequestContext: + if retry_options is None: + retry_options = self._retry_options + if raise_for_status is None: + raise_for_status = self._raise_for_status + return _RequestContext( + request_func=self._client.request, + params_list=params_list, + logger=self._logger, + retry_options=retry_options, + raise_for_status=raise_for_status, + ) + + async def __aenter__(self) -> RetryClient: # noqa: PYI034 + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + await self.close() + + def __del__(self) -> None: + if getattr(self, "_closed", None) is None: + # in case object was not initialized (__init__ raised an exception) + return + + if not self._closed: + self._logger.warning("Aiohttp retry client was not closed") diff --git a/venv/Lib/site-packages/deepgram_sdk-4.2.0.dist-info/REQUESTED b/venv/Lib/site-packages/aiohttp_retry/py.typed similarity index 100% rename from venv/Lib/site-packages/deepgram_sdk-4.2.0.dist-info/REQUESTED rename to venv/Lib/site-packages/aiohttp_retry/py.typed diff --git a/venv/Lib/site-packages/aiohttp_retry/retry_options.py b/venv/Lib/site-packages/aiohttp_retry/retry_options.py new file mode 100644 index 00000000..2af17fa6 --- /dev/null +++ b/venv/Lib/site-packages/aiohttp_retry/retry_options.py @@ -0,0 +1,228 @@ +from __future__ import annotations + +import abc +import random +from typing import Any, Awaitable, Callable, Iterable +from warnings import warn + +from aiohttp import ClientResponse + +EvaluateResponseCallbackType = Callable[[ClientResponse], Awaitable[bool]] + + +class RetryOptionsBase: + def __init__( + self, + attempts: int = 3, # How many times we should retry + statuses: Iterable[int] | None = None, # On which statuses we should retry + exceptions: Iterable[type[Exception]] | None = None, # On which exceptions we should retry, by default on all + methods: Iterable[str] | None = None, # On which HTTP methods we should retry + retry_all_server_errors: bool = True, # If should retry all 500 errors or not + # a callback that will run on response to decide if retry + evaluate_response_callback: EvaluateResponseCallbackType | None = None, + ) -> None: + self.attempts: int = attempts + if statuses is None: + statuses = set() + self.statuses: Iterable[int] = statuses + + if exceptions is None: + exceptions = set() + self.exceptions: Iterable[type[Exception]] = exceptions + + if methods is None: + methods = {"HEAD", "GET", "PUT", "DELETE", "OPTIONS", "TRACE", "POST", "CONNECT", "PATCH"} + self.methods: Iterable[str] = {method.upper() for method in methods} + + self.retry_all_server_errors = retry_all_server_errors + self.evaluate_response_callback = evaluate_response_callback + + @abc.abstractmethod + def get_timeout(self, attempt: int, response: ClientResponse | None = None) -> float: + raise NotImplementedError + + +class ExponentialRetry(RetryOptionsBase): + def __init__( + self, + attempts: int = 3, # How many times we should retry + start_timeout: float = 0.1, # Base timeout time, then it exponentially grow + max_timeout: float = 30.0, # Max possible timeout between tries + factor: float = 2.0, # How much we increase timeout each time + statuses: set[int] | None = None, # On which statuses we should retry + exceptions: set[type[Exception]] | None = None, # On which exceptions we should retry + methods: set[str] | None = None, # On which HTTP methods we should retry + retry_all_server_errors: bool = True, + evaluate_response_callback: EvaluateResponseCallbackType | None = None, + ) -> None: + super().__init__( + attempts=attempts, + statuses=statuses, + exceptions=exceptions, + methods=methods, + retry_all_server_errors=retry_all_server_errors, + evaluate_response_callback=evaluate_response_callback, + ) + + self._start_timeout: float = start_timeout + self._max_timeout: float = max_timeout + self._factor: float = factor + + def get_timeout( + self, + attempt: int, + response: ClientResponse | None = None, # noqa: ARG002 + ) -> float: + """Return timeout with exponential backoff.""" + timeout = self._start_timeout * (self._factor**attempt) + return min(timeout, self._max_timeout) + + +def RetryOptions(*args: Any, **kwargs: Any) -> ExponentialRetry: # noqa: N802 + warn("RetryOptions is deprecated, use ExponentialRetry", stacklevel=1) + return ExponentialRetry(*args, **kwargs) + + +class RandomRetry(RetryOptionsBase): + def __init__( + self, + attempts: int = 3, # How many times we should retry + statuses: Iterable[int] | None = None, # On which statuses we should retry + exceptions: Iterable[type[Exception]] | None = None, # On which exceptions we should retry + methods: Iterable[str] | None = None, # On which HTTP methods we should retry + min_timeout: float = 0.1, # Minimum possible timeout + max_timeout: float = 3.0, # Maximum possible timeout between tries + random_func: Callable[[], float] = random.random, # Random number generator + retry_all_server_errors: bool = True, + evaluate_response_callback: EvaluateResponseCallbackType | None = None, + ) -> None: + super().__init__( + attempts=attempts, + statuses=statuses, + exceptions=exceptions, + methods=methods, + retry_all_server_errors=retry_all_server_errors, + evaluate_response_callback=evaluate_response_callback, + ) + + self.attempts: int = attempts + self.min_timeout: float = min_timeout + self.max_timeout: float = max_timeout + self.random = random_func + + def get_timeout( + self, + attempt: int, # noqa: ARG002 + response: ClientResponse | None = None, # noqa: ARG002 + ) -> float: + """Generate random timeouts.""" + return self.min_timeout + self.random() * (self.max_timeout - self.min_timeout) + + +class ListRetry(RetryOptionsBase): + def __init__( + self, + timeouts: list[float], + statuses: Iterable[int] | None = None, # On which statuses we should retry + exceptions: Iterable[type[Exception]] | None = None, # On which exceptions we should retry + methods: Iterable[str] | None = None, # On which HTTP methods we should retry + retry_all_server_errors: bool = True, + evaluate_response_callback: EvaluateResponseCallbackType | None = None, + ) -> None: + super().__init__( + attempts=len(timeouts), + statuses=statuses, + exceptions=exceptions, + methods=methods, + retry_all_server_errors=retry_all_server_errors, + evaluate_response_callback=evaluate_response_callback, + ) + self.timeouts = timeouts + + def get_timeout( + self, + attempt: int, + response: ClientResponse | None = None, # noqa: ARG002 + ) -> float: + """Timeouts from a defined list.""" + return self.timeouts[attempt] + + +class FibonacciRetry(RetryOptionsBase): + def __init__( + self, + attempts: int = 3, + multiplier: float = 1.0, + statuses: Iterable[int] | None = None, + exceptions: Iterable[type[Exception]] | None = None, + methods: Iterable[str] | None = None, + max_timeout: float = 3.0, # Maximum possible timeout between tries + retry_all_server_errors: bool = True, + evaluate_response_callback: EvaluateResponseCallbackType | None = None, + ) -> None: + super().__init__( + attempts=attempts, + statuses=statuses, + exceptions=exceptions, + methods=methods, + retry_all_server_errors=retry_all_server_errors, + evaluate_response_callback=evaluate_response_callback, + ) + + self.max_timeout = max_timeout + self.multiplier = multiplier + self.prev_step = 1.0 + self.current_step = 1.0 + + def get_timeout( + self, + attempt: int, # noqa: ARG002 + response: ClientResponse | None = None, # noqa: ARG002 + ) -> float: + new_current_step = self.prev_step + self.current_step + self.prev_step = self.current_step + self.current_step = new_current_step + + return min(self.multiplier * new_current_step, self.max_timeout) + + +class JitterRetry(ExponentialRetry): + """https://github.com/inyutin/aiohttp_retry/issues/44.""" + + def __init__( + self, + attempts: int = 3, # How many times we should retry + start_timeout: float = 0.1, # Base timeout time, then it exponentially grow + max_timeout: float = 30.0, # Max possible timeout between tries + factor: float = 2.0, # How much we increase timeout each time + statuses: set[int] | None = None, # On which statuses we should retry + exceptions: set[type[Exception]] | None = None, # On which exceptions we should retry + methods: set[str] | None = None, # On which HTTP methods we should retry + random_interval_size: float = 2.0, # size of interval for random component + retry_all_server_errors: bool = True, + evaluate_response_callback: EvaluateResponseCallbackType | None = None, + ) -> None: + super().__init__( + attempts=attempts, + start_timeout=start_timeout, + max_timeout=max_timeout, + factor=factor, + statuses=statuses, + exceptions=exceptions, + methods=methods, + retry_all_server_errors=retry_all_server_errors, + evaluate_response_callback=evaluate_response_callback, + ) + + self._start_timeout: float = start_timeout + self._max_timeout: float = max_timeout + self._factor: float = factor + self._random_interval_size = random_interval_size + + def get_timeout( + self, + attempt: int, + response: ClientResponse | None = None, # noqa: ARG002 + ) -> float: + timeout: float = super().get_timeout(attempt) + random.uniform(0, self._random_interval_size) ** self._factor + return timeout diff --git a/venv/Lib/site-packages/aiohttp_retry/types.py b/venv/Lib/site-packages/aiohttp_retry/types.py new file mode 100644 index 00000000..b14af2ab --- /dev/null +++ b/venv/Lib/site-packages/aiohttp_retry/types.py @@ -0,0 +1,7 @@ +from typing import Union + +from aiohttp import ClientSession + +from .client import RetryClient + +ClientType = Union[ClientSession, RetryClient] diff --git a/venv/Lib/site-packages/aiosignal/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/aiosignal/__pycache__/__init__.cpython-312.pyc index b9d5b305..b71f7a19 100644 Binary files a/venv/Lib/site-packages/aiosignal/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/aiosignal/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/annotated_types/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/annotated_types/__pycache__/__init__.cpython-312.pyc index 8c0499a0..d1f70f04 100644 Binary files a/venv/Lib/site-packages/annotated_types/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/annotated_types/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/anyio/__pycache__/__init__.cpython-312.pyc index 9048f226..eca10b0a 100644 Binary files a/venv/Lib/site-packages/anyio/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/anyio/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/__pycache__/from_thread.cpython-312.pyc b/venv/Lib/site-packages/anyio/__pycache__/from_thread.cpython-312.pyc index deb50d30..db5a0add 100644 Binary files a/venv/Lib/site-packages/anyio/__pycache__/from_thread.cpython-312.pyc and b/venv/Lib/site-packages/anyio/__pycache__/from_thread.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/__pycache__/lowlevel.cpython-312.pyc b/venv/Lib/site-packages/anyio/__pycache__/lowlevel.cpython-312.pyc index 1c85870e..b9f6ec42 100644 Binary files a/venv/Lib/site-packages/anyio/__pycache__/lowlevel.cpython-312.pyc and b/venv/Lib/site-packages/anyio/__pycache__/lowlevel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/__pycache__/to_thread.cpython-312.pyc b/venv/Lib/site-packages/anyio/__pycache__/to_thread.cpython-312.pyc index ebd756f9..8a62bf82 100644 Binary files a/venv/Lib/site-packages/anyio/__pycache__/to_thread.cpython-312.pyc and b/venv/Lib/site-packages/anyio/__pycache__/to_thread.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/_backends/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/anyio/_backends/__pycache__/__init__.cpython-312.pyc index b8e703ce..574479a4 100644 Binary files a/venv/Lib/site-packages/anyio/_backends/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/anyio/_backends/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/_backends/__pycache__/_asyncio.cpython-312.pyc b/venv/Lib/site-packages/anyio/_backends/__pycache__/_asyncio.cpython-312.pyc index a09c22b2..7c7a822a 100644 Binary files a/venv/Lib/site-packages/anyio/_backends/__pycache__/_asyncio.cpython-312.pyc and b/venv/Lib/site-packages/anyio/_backends/__pycache__/_asyncio.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/_core/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/anyio/_core/__pycache__/__init__.cpython-312.pyc index d7c0bd8e..ade8b842 100644 Binary files a/venv/Lib/site-packages/anyio/_core/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/anyio/_core/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/_core/__pycache__/_eventloop.cpython-312.pyc b/venv/Lib/site-packages/anyio/_core/__pycache__/_eventloop.cpython-312.pyc index e1d4ca88..a303761a 100644 Binary files a/venv/Lib/site-packages/anyio/_core/__pycache__/_eventloop.cpython-312.pyc and b/venv/Lib/site-packages/anyio/_core/__pycache__/_eventloop.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/_core/__pycache__/_exceptions.cpython-312.pyc b/venv/Lib/site-packages/anyio/_core/__pycache__/_exceptions.cpython-312.pyc index 2a05c016..8068fcfb 100644 Binary files a/venv/Lib/site-packages/anyio/_core/__pycache__/_exceptions.cpython-312.pyc and b/venv/Lib/site-packages/anyio/_core/__pycache__/_exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/_core/__pycache__/_fileio.cpython-312.pyc b/venv/Lib/site-packages/anyio/_core/__pycache__/_fileio.cpython-312.pyc index 637df5cb..c6331f50 100644 Binary files a/venv/Lib/site-packages/anyio/_core/__pycache__/_fileio.cpython-312.pyc and b/venv/Lib/site-packages/anyio/_core/__pycache__/_fileio.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/_core/__pycache__/_resources.cpython-312.pyc b/venv/Lib/site-packages/anyio/_core/__pycache__/_resources.cpython-312.pyc index 88443b4c..19d5c8c6 100644 Binary files a/venv/Lib/site-packages/anyio/_core/__pycache__/_resources.cpython-312.pyc and b/venv/Lib/site-packages/anyio/_core/__pycache__/_resources.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/_core/__pycache__/_signals.cpython-312.pyc b/venv/Lib/site-packages/anyio/_core/__pycache__/_signals.cpython-312.pyc index e5a46da7..263c108e 100644 Binary files a/venv/Lib/site-packages/anyio/_core/__pycache__/_signals.cpython-312.pyc and b/venv/Lib/site-packages/anyio/_core/__pycache__/_signals.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/_core/__pycache__/_sockets.cpython-312.pyc b/venv/Lib/site-packages/anyio/_core/__pycache__/_sockets.cpython-312.pyc index 1a391139..921b54c4 100644 Binary files a/venv/Lib/site-packages/anyio/_core/__pycache__/_sockets.cpython-312.pyc and b/venv/Lib/site-packages/anyio/_core/__pycache__/_sockets.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/_core/__pycache__/_streams.cpython-312.pyc b/venv/Lib/site-packages/anyio/_core/__pycache__/_streams.cpython-312.pyc index 7114a153..e4394708 100644 Binary files a/venv/Lib/site-packages/anyio/_core/__pycache__/_streams.cpython-312.pyc and b/venv/Lib/site-packages/anyio/_core/__pycache__/_streams.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/_core/__pycache__/_subprocesses.cpython-312.pyc b/venv/Lib/site-packages/anyio/_core/__pycache__/_subprocesses.cpython-312.pyc index d63aac3b..40654d12 100644 Binary files a/venv/Lib/site-packages/anyio/_core/__pycache__/_subprocesses.cpython-312.pyc and b/venv/Lib/site-packages/anyio/_core/__pycache__/_subprocesses.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/_core/__pycache__/_synchronization.cpython-312.pyc b/venv/Lib/site-packages/anyio/_core/__pycache__/_synchronization.cpython-312.pyc index 4165d186..73a31719 100644 Binary files a/venv/Lib/site-packages/anyio/_core/__pycache__/_synchronization.cpython-312.pyc and b/venv/Lib/site-packages/anyio/_core/__pycache__/_synchronization.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/_core/__pycache__/_tasks.cpython-312.pyc b/venv/Lib/site-packages/anyio/_core/__pycache__/_tasks.cpython-312.pyc index 278d4d7e..51a0b132 100644 Binary files a/venv/Lib/site-packages/anyio/_core/__pycache__/_tasks.cpython-312.pyc and b/venv/Lib/site-packages/anyio/_core/__pycache__/_tasks.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/_core/__pycache__/_tempfile.cpython-312.pyc b/venv/Lib/site-packages/anyio/_core/__pycache__/_tempfile.cpython-312.pyc index 181f9f6b..543159d2 100644 Binary files a/venv/Lib/site-packages/anyio/_core/__pycache__/_tempfile.cpython-312.pyc and b/venv/Lib/site-packages/anyio/_core/__pycache__/_tempfile.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/_core/__pycache__/_testing.cpython-312.pyc b/venv/Lib/site-packages/anyio/_core/__pycache__/_testing.cpython-312.pyc index 1671c19a..7e6a22ea 100644 Binary files a/venv/Lib/site-packages/anyio/_core/__pycache__/_testing.cpython-312.pyc and b/venv/Lib/site-packages/anyio/_core/__pycache__/_testing.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/_core/__pycache__/_typedattr.cpython-312.pyc b/venv/Lib/site-packages/anyio/_core/__pycache__/_typedattr.cpython-312.pyc index ac23c4d4..8876b11b 100644 Binary files a/venv/Lib/site-packages/anyio/_core/__pycache__/_typedattr.cpython-312.pyc and b/venv/Lib/site-packages/anyio/_core/__pycache__/_typedattr.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/abc/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/anyio/abc/__pycache__/__init__.cpython-312.pyc index 68358729..b8c7b174 100644 Binary files a/venv/Lib/site-packages/anyio/abc/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/anyio/abc/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/abc/__pycache__/_eventloop.cpython-312.pyc b/venv/Lib/site-packages/anyio/abc/__pycache__/_eventloop.cpython-312.pyc index 5a27ccfe..58ed0c9d 100644 Binary files a/venv/Lib/site-packages/anyio/abc/__pycache__/_eventloop.cpython-312.pyc and b/venv/Lib/site-packages/anyio/abc/__pycache__/_eventloop.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/abc/__pycache__/_resources.cpython-312.pyc b/venv/Lib/site-packages/anyio/abc/__pycache__/_resources.cpython-312.pyc index db2bd8fe..450a10a0 100644 Binary files a/venv/Lib/site-packages/anyio/abc/__pycache__/_resources.cpython-312.pyc and b/venv/Lib/site-packages/anyio/abc/__pycache__/_resources.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/abc/__pycache__/_sockets.cpython-312.pyc b/venv/Lib/site-packages/anyio/abc/__pycache__/_sockets.cpython-312.pyc index defebb38..3a7965c6 100644 Binary files a/venv/Lib/site-packages/anyio/abc/__pycache__/_sockets.cpython-312.pyc and b/venv/Lib/site-packages/anyio/abc/__pycache__/_sockets.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/abc/__pycache__/_streams.cpython-312.pyc b/venv/Lib/site-packages/anyio/abc/__pycache__/_streams.cpython-312.pyc index a0426e61..e47609b5 100644 Binary files a/venv/Lib/site-packages/anyio/abc/__pycache__/_streams.cpython-312.pyc and b/venv/Lib/site-packages/anyio/abc/__pycache__/_streams.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/abc/__pycache__/_subprocesses.cpython-312.pyc b/venv/Lib/site-packages/anyio/abc/__pycache__/_subprocesses.cpython-312.pyc index 98c99691..fb7b02ea 100644 Binary files a/venv/Lib/site-packages/anyio/abc/__pycache__/_subprocesses.cpython-312.pyc and b/venv/Lib/site-packages/anyio/abc/__pycache__/_subprocesses.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/abc/__pycache__/_tasks.cpython-312.pyc b/venv/Lib/site-packages/anyio/abc/__pycache__/_tasks.cpython-312.pyc index 4daa54bd..35ef9a35 100644 Binary files a/venv/Lib/site-packages/anyio/abc/__pycache__/_tasks.cpython-312.pyc and b/venv/Lib/site-packages/anyio/abc/__pycache__/_tasks.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/abc/__pycache__/_testing.cpython-312.pyc b/venv/Lib/site-packages/anyio/abc/__pycache__/_testing.cpython-312.pyc index c912146d..43e43714 100644 Binary files a/venv/Lib/site-packages/anyio/abc/__pycache__/_testing.cpython-312.pyc and b/venv/Lib/site-packages/anyio/abc/__pycache__/_testing.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/streams/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/anyio/streams/__pycache__/__init__.cpython-312.pyc index 2ba74045..50048371 100644 Binary files a/venv/Lib/site-packages/anyio/streams/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/anyio/streams/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/streams/__pycache__/memory.cpython-312.pyc b/venv/Lib/site-packages/anyio/streams/__pycache__/memory.cpython-312.pyc index 1f3b411a..7e580b5e 100644 Binary files a/venv/Lib/site-packages/anyio/streams/__pycache__/memory.cpython-312.pyc and b/venv/Lib/site-packages/anyio/streams/__pycache__/memory.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/streams/__pycache__/stapled.cpython-312.pyc b/venv/Lib/site-packages/anyio/streams/__pycache__/stapled.cpython-312.pyc index 32e3e3a8..99fccbe3 100644 Binary files a/venv/Lib/site-packages/anyio/streams/__pycache__/stapled.cpython-312.pyc and b/venv/Lib/site-packages/anyio/streams/__pycache__/stapled.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/anyio/streams/__pycache__/tls.cpython-312.pyc b/venv/Lib/site-packages/anyio/streams/__pycache__/tls.cpython-312.pyc index 093382b4..71ec43fd 100644 Binary files a/venv/Lib/site-packages/anyio/streams/__pycache__/tls.cpython-312.pyc and b/venv/Lib/site-packages/anyio/streams/__pycache__/tls.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/attr/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/attr/__pycache__/__init__.cpython-312.pyc index 6bc98666..c2bab46d 100644 Binary files a/venv/Lib/site-packages/attr/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/attr/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/attr/__pycache__/_cmp.cpython-312.pyc b/venv/Lib/site-packages/attr/__pycache__/_cmp.cpython-312.pyc index 96e1273f..6dab291f 100644 Binary files a/venv/Lib/site-packages/attr/__pycache__/_cmp.cpython-312.pyc and b/venv/Lib/site-packages/attr/__pycache__/_cmp.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/attr/__pycache__/_compat.cpython-312.pyc b/venv/Lib/site-packages/attr/__pycache__/_compat.cpython-312.pyc index 39123050..d7429f6e 100644 Binary files a/venv/Lib/site-packages/attr/__pycache__/_compat.cpython-312.pyc and b/venv/Lib/site-packages/attr/__pycache__/_compat.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/attr/__pycache__/_config.cpython-312.pyc b/venv/Lib/site-packages/attr/__pycache__/_config.cpython-312.pyc index 15af1379..4dee2a28 100644 Binary files a/venv/Lib/site-packages/attr/__pycache__/_config.cpython-312.pyc and b/venv/Lib/site-packages/attr/__pycache__/_config.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/attr/__pycache__/_funcs.cpython-312.pyc b/venv/Lib/site-packages/attr/__pycache__/_funcs.cpython-312.pyc index f4fb8803..d8bf7c15 100644 Binary files a/venv/Lib/site-packages/attr/__pycache__/_funcs.cpython-312.pyc and b/venv/Lib/site-packages/attr/__pycache__/_funcs.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/attr/__pycache__/_make.cpython-312.pyc b/venv/Lib/site-packages/attr/__pycache__/_make.cpython-312.pyc index 770beca9..bc9ba1d5 100644 Binary files a/venv/Lib/site-packages/attr/__pycache__/_make.cpython-312.pyc and b/venv/Lib/site-packages/attr/__pycache__/_make.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/attr/__pycache__/_next_gen.cpython-312.pyc b/venv/Lib/site-packages/attr/__pycache__/_next_gen.cpython-312.pyc index 8c8a3897..5b2e3d7a 100644 Binary files a/venv/Lib/site-packages/attr/__pycache__/_next_gen.cpython-312.pyc and b/venv/Lib/site-packages/attr/__pycache__/_next_gen.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/attr/__pycache__/_version_info.cpython-312.pyc b/venv/Lib/site-packages/attr/__pycache__/_version_info.cpython-312.pyc index 8e2dd174..04a3d550 100644 Binary files a/venv/Lib/site-packages/attr/__pycache__/_version_info.cpython-312.pyc and b/venv/Lib/site-packages/attr/__pycache__/_version_info.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/attr/__pycache__/converters.cpython-312.pyc b/venv/Lib/site-packages/attr/__pycache__/converters.cpython-312.pyc index d17252ea..cee58bb4 100644 Binary files a/venv/Lib/site-packages/attr/__pycache__/converters.cpython-312.pyc and b/venv/Lib/site-packages/attr/__pycache__/converters.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/attr/__pycache__/exceptions.cpython-312.pyc b/venv/Lib/site-packages/attr/__pycache__/exceptions.cpython-312.pyc index 732f358c..345e5808 100644 Binary files a/venv/Lib/site-packages/attr/__pycache__/exceptions.cpython-312.pyc and b/venv/Lib/site-packages/attr/__pycache__/exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/attr/__pycache__/filters.cpython-312.pyc b/venv/Lib/site-packages/attr/__pycache__/filters.cpython-312.pyc index c06a2dce..7b267a20 100644 Binary files a/venv/Lib/site-packages/attr/__pycache__/filters.cpython-312.pyc and b/venv/Lib/site-packages/attr/__pycache__/filters.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/attr/__pycache__/setters.cpython-312.pyc b/venv/Lib/site-packages/attr/__pycache__/setters.cpython-312.pyc index 5ba3ed81..cce88967 100644 Binary files a/venv/Lib/site-packages/attr/__pycache__/setters.cpython-312.pyc and b/venv/Lib/site-packages/attr/__pycache__/setters.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/attr/__pycache__/validators.cpython-312.pyc b/venv/Lib/site-packages/attr/__pycache__/validators.cpython-312.pyc index a3f47c55..7638bbd6 100644 Binary files a/venv/Lib/site-packages/attr/__pycache__/validators.cpython-312.pyc and b/venv/Lib/site-packages/attr/__pycache__/validators.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/av/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/av/__pycache__/__init__.cpython-312.pyc index 0816cc59..60937aa7 100644 Binary files a/venv/Lib/site-packages/av/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/av/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/av/__pycache__/about.cpython-312.pyc b/venv/Lib/site-packages/av/__pycache__/about.cpython-312.pyc index 20e825f4..7319afe0 100644 Binary files a/venv/Lib/site-packages/av/__pycache__/about.cpython-312.pyc and b/venv/Lib/site-packages/av/__pycache__/about.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/av/audio/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/av/audio/__pycache__/__init__.cpython-312.pyc index d17a1a3b..2f1fdc0e 100644 Binary files a/venv/Lib/site-packages/av/audio/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/av/audio/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/av/codec/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/av/codec/__pycache__/__init__.cpython-312.pyc index 83076827..f57986d8 100644 Binary files a/venv/Lib/site-packages/av/codec/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/av/codec/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/av/container/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/av/container/__pycache__/__init__.cpython-312.pyc index e909f7ce..c7806262 100644 Binary files a/venv/Lib/site-packages/av/container/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/av/container/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/av/filter/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/av/filter/__pycache__/__init__.cpython-312.pyc index eeb0bfa5..a6b7c6b1 100644 Binary files a/venv/Lib/site-packages/av/filter/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/av/filter/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/av/sidedata/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/av/sidedata/__pycache__/__init__.cpython-312.pyc index 1cc1c110..22f1ae64 100644 Binary files a/venv/Lib/site-packages/av/sidedata/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/av/sidedata/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/av/video/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/av/video/__pycache__/__init__.cpython-312.pyc index ab4a2784..3ad84082 100644 Binary files a/venv/Lib/site-packages/av/video/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/av/video/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/certifi/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/certifi/__pycache__/__init__.cpython-312.pyc index 7edce3eb..4addb1c7 100644 Binary files a/venv/Lib/site-packages/certifi/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/certifi/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/certifi/__pycache__/core.cpython-312.pyc b/venv/Lib/site-packages/certifi/__pycache__/core.cpython-312.pyc index 3b49490a..89e7db1b 100644 Binary files a/venv/Lib/site-packages/certifi/__pycache__/core.cpython-312.pyc and b/venv/Lib/site-packages/certifi/__pycache__/core.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/charset_normalizer-3.4.2.dist-info/INSTALLER b/venv/Lib/site-packages/charset_normalizer-3.4.2.dist-info/INSTALLER new file mode 100644 index 00000000..a1b589e3 --- /dev/null +++ b/venv/Lib/site-packages/charset_normalizer-3.4.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/Lib/site-packages/charset_normalizer-3.4.2.dist-info/METADATA b/venv/Lib/site-packages/charset_normalizer-3.4.2.dist-info/METADATA new file mode 100644 index 00000000..573d88b9 --- /dev/null +++ b/venv/Lib/site-packages/charset_normalizer-3.4.2.dist-info/METADATA @@ -0,0 +1,731 @@ +Metadata-Version: 2.4 +Name: charset-normalizer +Version: 3.4.2 +Summary: The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet. +Author-email: "Ahmed R. TAHRI" +Maintainer-email: "Ahmed R. TAHRI" +License: MIT +Project-URL: Changelog, https://github.com/jawah/charset_normalizer/blob/master/CHANGELOG.md +Project-URL: Documentation, https://charset-normalizer.readthedocs.io/ +Project-URL: Code, https://github.com/jawah/charset_normalizer +Project-URL: Issue tracker, https://github.com/jawah/charset_normalizer/issues +Keywords: encoding,charset,charset-detector,detector,normalization,unicode,chardet,detect +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Text Processing :: Linguistic +Classifier: Topic :: Utilities +Classifier: Typing :: Typed +Requires-Python: >=3.7 +Description-Content-Type: text/markdown +License-File: LICENSE +Provides-Extra: unicode-backport +Dynamic: license-file + +

Charset Detection, for Everyone 👋

+ +

+ The Real First Universal Charset Detector
+ + + + + Download Count Total + + + + +

+

+ Featured Packages
+ + Static Badge + + + Static Badge + +

+

+ In other language (unofficial port - by the community)
+ + Static Badge + +

+ +> A library that helps you read text from an unknown charset encoding.
Motivated by `chardet`, +> I'm trying to resolve the issue by taking a new approach. +> All IANA character set names for which the Python core library provides codecs are supported. + +

+ >>>>> 👉 Try Me Online Now, Then Adopt Me 👈 <<<<< +

+ +This project offers you an alternative to **Universal Charset Encoding Detector**, also known as **Chardet**. + +| Feature | [Chardet](https://github.com/chardet/chardet) | Charset Normalizer | [cChardet](https://github.com/PyYoshi/cChardet) | +|--------------------------------------------------|:---------------------------------------------:|:--------------------------------------------------------------------------------------------------:|:-----------------------------------------------:| +| `Fast` | ❌ | ✅ | ✅ | +| `Universal**` | ❌ | ✅ | ❌ | +| `Reliable` **without** distinguishable standards | ❌ | ✅ | ✅ | +| `Reliable` **with** distinguishable standards | ✅ | ✅ | ✅ | +| `License` | LGPL-2.1
_restrictive_ | MIT | MPL-1.1
_restrictive_ | +| `Native Python` | ✅ | ✅ | ❌ | +| `Detect spoken language` | ❌ | ✅ | N/A | +| `UnicodeDecodeError Safety` | ❌ | ✅ | ❌ | +| `Whl Size (min)` | 193.6 kB | 42 kB | ~200 kB | +| `Supported Encoding` | 33 | 🎉 [99](https://charset-normalizer.readthedocs.io/en/latest/user/support.html#supported-encodings) | 40 | + +

+Reading Normalized TextCat Reading Text +

+ +*\*\* : They are clearly using specific code for a specific encoding even if covering most of used one*
+ +## ⚡ Performance + +This package offer better performance than its counterpart Chardet. Here are some numbers. + +| Package | Accuracy | Mean per file (ms) | File per sec (est) | +|-----------------------------------------------|:--------:|:------------------:|:------------------:| +| [chardet](https://github.com/chardet/chardet) | 86 % | 63 ms | 16 file/sec | +| charset-normalizer | **98 %** | **10 ms** | 100 file/sec | + +| Package | 99th percentile | 95th percentile | 50th percentile | +|-----------------------------------------------|:---------------:|:---------------:|:---------------:| +| [chardet](https://github.com/chardet/chardet) | 265 ms | 71 ms | 7 ms | +| charset-normalizer | 100 ms | 50 ms | 5 ms | + +_updated as of december 2024 using CPython 3.12_ + +Chardet's performance on larger file (1MB+) are very poor. Expect huge difference on large payload. + +> Stats are generated using 400+ files using default parameters. More details on used files, see GHA workflows. +> And yes, these results might change at any time. The dataset can be updated to include more files. +> The actual delays heavily depends on your CPU capabilities. The factors should remain the same. +> Keep in mind that the stats are generous and that Chardet accuracy vs our is measured using Chardet initial capability +> (e.g. Supported Encoding) Challenge-them if you want. + +## ✨ Installation + +Using pip: + +```sh +pip install charset-normalizer -U +``` + +## 🚀 Basic Usage + +### CLI +This package comes with a CLI. + +``` +usage: normalizer [-h] [-v] [-a] [-n] [-m] [-r] [-f] [-t THRESHOLD] + file [file ...] + +The Real First Universal Charset Detector. Discover originating encoding used +on text file. Normalize text to unicode. + +positional arguments: + files File(s) to be analysed + +optional arguments: + -h, --help show this help message and exit + -v, --verbose Display complementary information about file if any. + Stdout will contain logs about the detection process. + -a, --with-alternative + Output complementary possibilities if any. Top-level + JSON WILL be a list. + -n, --normalize Permit to normalize input file. If not set, program + does not write anything. + -m, --minimal Only output the charset detected to STDOUT. Disabling + JSON output. + -r, --replace Replace file when trying to normalize it instead of + creating a new one. + -f, --force Replace file without asking if you are sure, use this + flag with caution. + -t THRESHOLD, --threshold THRESHOLD + Define a custom maximum amount of chaos allowed in + decoded content. 0. <= chaos <= 1. + --version Show version information and exit. +``` + +```bash +normalizer ./data/sample.1.fr.srt +``` + +or + +```bash +python -m charset_normalizer ./data/sample.1.fr.srt +``` + +🎉 Since version 1.4.0 the CLI produce easily usable stdout result in JSON format. + +```json +{ + "path": "/home/default/projects/charset_normalizer/data/sample.1.fr.srt", + "encoding": "cp1252", + "encoding_aliases": [ + "1252", + "windows_1252" + ], + "alternative_encodings": [ + "cp1254", + "cp1256", + "cp1258", + "iso8859_14", + "iso8859_15", + "iso8859_16", + "iso8859_3", + "iso8859_9", + "latin_1", + "mbcs" + ], + "language": "French", + "alphabets": [ + "Basic Latin", + "Latin-1 Supplement" + ], + "has_sig_or_bom": false, + "chaos": 0.149, + "coherence": 97.152, + "unicode_path": null, + "is_preferred": true +} +``` + +### Python +*Just print out normalized text* +```python +from charset_normalizer import from_path + +results = from_path('./my_subtitle.srt') + +print(str(results.best())) +``` + +*Upgrade your code without effort* +```python +from charset_normalizer import detect +``` + +The above code will behave the same as **chardet**. We ensure that we offer the best (reasonable) BC result possible. + +See the docs for advanced usage : [readthedocs.io](https://charset-normalizer.readthedocs.io/en/latest/) + +## 😇 Why + +When I started using Chardet, I noticed that it was not suited to my expectations, and I wanted to propose a +reliable alternative using a completely different method. Also! I never back down on a good challenge! + +I **don't care** about the **originating charset** encoding, because **two different tables** can +produce **two identical rendered string.** +What I want is to get readable text, the best I can. + +In a way, **I'm brute forcing text decoding.** How cool is that ? 😎 + +Don't confuse package **ftfy** with charset-normalizer or chardet. ftfy goal is to repair Unicode string whereas charset-normalizer to convert raw file in unknown encoding to unicode. + +## 🍰 How + + - Discard all charset encoding table that could not fit the binary content. + - Measure noise, or the mess once opened (by chunks) with a corresponding charset encoding. + - Extract matches with the lowest mess detected. + - Additionally, we measure coherence / probe for a language. + +**Wait a minute**, what is noise/mess and coherence according to **YOU ?** + +*Noise :* I opened hundred of text files, **written by humans**, with the wrong encoding table. **I observed**, then +**I established** some ground rules about **what is obvious** when **it seems like** a mess (aka. defining noise in rendered text). + I know that my interpretation of what is noise is probably incomplete, feel free to contribute in order to + improve or rewrite it. + +*Coherence :* For each language there is on earth, we have computed ranked letter appearance occurrences (the best we can). So I thought +that intel is worth something here. So I use those records against decoded text to check if I can detect intelligent design. + +## ⚡ Known limitations + + - Language detection is unreliable when text contains two or more languages sharing identical letters. (eg. HTML (english tags) + Turkish content (Sharing Latin characters)) + - Every charset detector heavily depends on sufficient content. In common cases, do not bother run detection on very tiny content. + +## ⚠️ About Python EOLs + +**If you are running:** + +- Python >=2.7,<3.5: Unsupported +- Python 3.5: charset-normalizer < 2.1 +- Python 3.6: charset-normalizer < 3.1 +- Python 3.7: charset-normalizer < 4.0 + +Upgrade your Python interpreter as soon as possible. + +## 👤 Contributing + +Contributions, issues and feature requests are very much welcome.
+Feel free to check [issues page](https://github.com/ousret/charset_normalizer/issues) if you want to contribute. + +## 📝 License + +Copyright © [Ahmed TAHRI @Ousret](https://github.com/Ousret).
+This project is [MIT](https://github.com/Ousret/charset_normalizer/blob/master/LICENSE) licensed. + +Characters frequencies used in this project © 2012 [Denny Vrandečić](http://simia.net/letters/) + +## 💼 For Enterprise + +Professional support for charset-normalizer is available as part of the [Tidelift +Subscription][1]. Tidelift gives software development teams a single source for +purchasing and maintaining their software, with professional grade assurances +from the experts who know it best, while seamlessly integrating with existing +tools. + +[1]: https://tidelift.com/subscription/pkg/pypi-charset-normalizer?utm_source=pypi-charset-normalizer&utm_medium=readme + +[![OpenSSF Best Practices](https://www.bestpractices.dev/projects/7297/badge)](https://www.bestpractices.dev/projects/7297) + +# Changelog +All notable changes to charset-normalizer will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). + +## [3.4.2](https://github.com/Ousret/charset_normalizer/compare/3.4.1...3.4.2) (2025-05-02) + +### Fixed +- Addressed the DeprecationWarning in our CLI regarding `argparse.FileType` by backporting the target class into the package. (#591) +- Improved the overall reliability of the detector with CJK Ideographs. (#605) (#587) + +### Changed +- Optional mypyc compilation upgraded to version 1.15 for Python >= 3.8 + +## [3.4.1](https://github.com/Ousret/charset_normalizer/compare/3.4.0...3.4.1) (2024-12-24) + +### Changed +- Project metadata are now stored using `pyproject.toml` instead of `setup.cfg` using setuptools as the build backend. +- Enforce annotation delayed loading for a simpler and consistent types in the project. +- Optional mypyc compilation upgraded to version 1.14 for Python >= 3.8 + +### Added +- pre-commit configuration. +- noxfile. + +### Removed +- `build-requirements.txt` as per using `pyproject.toml` native build configuration. +- `bin/integration.py` and `bin/serve.py` in favor of downstream integration test (see noxfile). +- `setup.cfg` in favor of `pyproject.toml` metadata configuration. +- Unused `utils.range_scan` function. + +### Fixed +- Converting content to Unicode bytes may insert `utf_8` instead of preferred `utf-8`. (#572) +- Deprecation warning "'count' is passed as positional argument" when converting to Unicode bytes on Python 3.13+ + +## [3.4.0](https://github.com/Ousret/charset_normalizer/compare/3.3.2...3.4.0) (2024-10-08) + +### Added +- Argument `--no-preemptive` in the CLI to prevent the detector to search for hints. +- Support for Python 3.13 (#512) + +### Fixed +- Relax the TypeError exception thrown when trying to compare a CharsetMatch with anything else than a CharsetMatch. +- Improved the general reliability of the detector based on user feedbacks. (#520) (#509) (#498) (#407) (#537) +- Declared charset in content (preemptive detection) not changed when converting to utf-8 bytes. (#381) + +## [3.3.2](https://github.com/Ousret/charset_normalizer/compare/3.3.1...3.3.2) (2023-10-31) + +### Fixed +- Unintentional memory usage regression when using large payload that match several encoding (#376) +- Regression on some detection case showcased in the documentation (#371) + +### Added +- Noise (md) probe that identify malformed arabic representation due to the presence of letters in isolated form (credit to my wife) + +## [3.3.1](https://github.com/Ousret/charset_normalizer/compare/3.3.0...3.3.1) (2023-10-22) + +### Changed +- Optional mypyc compilation upgraded to version 1.6.1 for Python >= 3.8 +- Improved the general detection reliability based on reports from the community + +## [3.3.0](https://github.com/Ousret/charset_normalizer/compare/3.2.0...3.3.0) (2023-09-30) + +### Added +- Allow to execute the CLI (e.g. normalizer) through `python -m charset_normalizer.cli` or `python -m charset_normalizer` +- Support for 9 forgotten encoding that are supported by Python but unlisted in `encoding.aliases` as they have no alias (#323) + +### Removed +- (internal) Redundant utils.is_ascii function and unused function is_private_use_only +- (internal) charset_normalizer.assets is moved inside charset_normalizer.constant + +### Changed +- (internal) Unicode code blocks in constants are updated using the latest v15.0.0 definition to improve detection +- Optional mypyc compilation upgraded to version 1.5.1 for Python >= 3.8 + +### Fixed +- Unable to properly sort CharsetMatch when both chaos/noise and coherence were close due to an unreachable condition in \_\_lt\_\_ (#350) + +## [3.2.0](https://github.com/Ousret/charset_normalizer/compare/3.1.0...3.2.0) (2023-06-07) + +### Changed +- Typehint for function `from_path` no longer enforce `PathLike` as its first argument +- Minor improvement over the global detection reliability + +### Added +- Introduce function `is_binary` that relies on main capabilities, and optimized to detect binaries +- Propagate `enable_fallback` argument throughout `from_bytes`, `from_path`, and `from_fp` that allow a deeper control over the detection (default True) +- Explicit support for Python 3.12 + +### Fixed +- Edge case detection failure where a file would contain 'very-long' camel cased word (Issue #289) + +## [3.1.0](https://github.com/Ousret/charset_normalizer/compare/3.0.1...3.1.0) (2023-03-06) + +### Added +- Argument `should_rename_legacy` for legacy function `detect` and disregard any new arguments without errors (PR #262) + +### Removed +- Support for Python 3.6 (PR #260) + +### Changed +- Optional speedup provided by mypy/c 1.0.1 + +## [3.0.1](https://github.com/Ousret/charset_normalizer/compare/3.0.0...3.0.1) (2022-11-18) + +### Fixed +- Multi-bytes cutter/chunk generator did not always cut correctly (PR #233) + +### Changed +- Speedup provided by mypy/c 0.990 on Python >= 3.7 + +## [3.0.0](https://github.com/Ousret/charset_normalizer/compare/2.1.1...3.0.0) (2022-10-20) + +### Added +- Extend the capability of explain=True when cp_isolation contains at most two entries (min one), will log in details of the Mess-detector results +- Support for alternative language frequency set in charset_normalizer.assets.FREQUENCIES +- Add parameter `language_threshold` in `from_bytes`, `from_path` and `from_fp` to adjust the minimum expected coherence ratio +- `normalizer --version` now specify if current version provide extra speedup (meaning mypyc compilation whl) + +### Changed +- Build with static metadata using 'build' frontend +- Make the language detection stricter +- Optional: Module `md.py` can be compiled using Mypyc to provide an extra speedup up to 4x faster than v2.1 + +### Fixed +- CLI with opt --normalize fail when using full path for files +- TooManyAccentuatedPlugin induce false positive on the mess detection when too few alpha character have been fed to it +- Sphinx warnings when generating the documentation + +### Removed +- Coherence detector no longer return 'Simple English' instead return 'English' +- Coherence detector no longer return 'Classical Chinese' instead return 'Chinese' +- Breaking: Method `first()` and `best()` from CharsetMatch +- UTF-7 will no longer appear as "detected" without a recognized SIG/mark (is unreliable/conflict with ASCII) +- Breaking: Class aliases CharsetDetector, CharsetDoctor, CharsetNormalizerMatch and CharsetNormalizerMatches +- Breaking: Top-level function `normalize` +- Breaking: Properties `chaos_secondary_pass`, `coherence_non_latin` and `w_counter` from CharsetMatch +- Support for the backport `unicodedata2` + +## [3.0.0rc1](https://github.com/Ousret/charset_normalizer/compare/3.0.0b2...3.0.0rc1) (2022-10-18) + +### Added +- Extend the capability of explain=True when cp_isolation contains at most two entries (min one), will log in details of the Mess-detector results +- Support for alternative language frequency set in charset_normalizer.assets.FREQUENCIES +- Add parameter `language_threshold` in `from_bytes`, `from_path` and `from_fp` to adjust the minimum expected coherence ratio + +### Changed +- Build with static metadata using 'build' frontend +- Make the language detection stricter + +### Fixed +- CLI with opt --normalize fail when using full path for files +- TooManyAccentuatedPlugin induce false positive on the mess detection when too few alpha character have been fed to it + +### Removed +- Coherence detector no longer return 'Simple English' instead return 'English' +- Coherence detector no longer return 'Classical Chinese' instead return 'Chinese' + +## [3.0.0b2](https://github.com/Ousret/charset_normalizer/compare/3.0.0b1...3.0.0b2) (2022-08-21) + +### Added +- `normalizer --version` now specify if current version provide extra speedup (meaning mypyc compilation whl) + +### Removed +- Breaking: Method `first()` and `best()` from CharsetMatch +- UTF-7 will no longer appear as "detected" without a recognized SIG/mark (is unreliable/conflict with ASCII) + +### Fixed +- Sphinx warnings when generating the documentation + +## [3.0.0b1](https://github.com/Ousret/charset_normalizer/compare/2.1.0...3.0.0b1) (2022-08-15) + +### Changed +- Optional: Module `md.py` can be compiled using Mypyc to provide an extra speedup up to 4x faster than v2.1 + +### Removed +- Breaking: Class aliases CharsetDetector, CharsetDoctor, CharsetNormalizerMatch and CharsetNormalizerMatches +- Breaking: Top-level function `normalize` +- Breaking: Properties `chaos_secondary_pass`, `coherence_non_latin` and `w_counter` from CharsetMatch +- Support for the backport `unicodedata2` + +## [2.1.1](https://github.com/Ousret/charset_normalizer/compare/2.1.0...2.1.1) (2022-08-19) + +### Deprecated +- Function `normalize` scheduled for removal in 3.0 + +### Changed +- Removed useless call to decode in fn is_unprintable (#206) + +### Fixed +- Third-party library (i18n xgettext) crashing not recognizing utf_8 (PEP 263) with underscore from [@aleksandernovikov](https://github.com/aleksandernovikov) (#204) + +## [2.1.0](https://github.com/Ousret/charset_normalizer/compare/2.0.12...2.1.0) (2022-06-19) + +### Added +- Output the Unicode table version when running the CLI with `--version` (PR #194) + +### Changed +- Re-use decoded buffer for single byte character sets from [@nijel](https://github.com/nijel) (PR #175) +- Fixing some performance bottlenecks from [@deedy5](https://github.com/deedy5) (PR #183) + +### Fixed +- Workaround potential bug in cpython with Zero Width No-Break Space located in Arabic Presentation Forms-B, Unicode 1.1 not acknowledged as space (PR #175) +- CLI default threshold aligned with the API threshold from [@oleksandr-kuzmenko](https://github.com/oleksandr-kuzmenko) (PR #181) + +### Removed +- Support for Python 3.5 (PR #192) + +### Deprecated +- Use of backport unicodedata from `unicodedata2` as Python is quickly catching up, scheduled for removal in 3.0 (PR #194) + +## [2.0.12](https://github.com/Ousret/charset_normalizer/compare/2.0.11...2.0.12) (2022-02-12) + +### Fixed +- ASCII miss-detection on rare cases (PR #170) + +## [2.0.11](https://github.com/Ousret/charset_normalizer/compare/2.0.10...2.0.11) (2022-01-30) + +### Added +- Explicit support for Python 3.11 (PR #164) + +### Changed +- The logging behavior have been completely reviewed, now using only TRACE and DEBUG levels (PR #163 #165) + +## [2.0.10](https://github.com/Ousret/charset_normalizer/compare/2.0.9...2.0.10) (2022-01-04) + +### Fixed +- Fallback match entries might lead to UnicodeDecodeError for large bytes sequence (PR #154) + +### Changed +- Skipping the language-detection (CD) on ASCII (PR #155) + +## [2.0.9](https://github.com/Ousret/charset_normalizer/compare/2.0.8...2.0.9) (2021-12-03) + +### Changed +- Moderating the logging impact (since 2.0.8) for specific environments (PR #147) + +### Fixed +- Wrong logging level applied when setting kwarg `explain` to True (PR #146) + +## [2.0.8](https://github.com/Ousret/charset_normalizer/compare/2.0.7...2.0.8) (2021-11-24) +### Changed +- Improvement over Vietnamese detection (PR #126) +- MD improvement on trailing data and long foreign (non-pure latin) data (PR #124) +- Efficiency improvements in cd/alphabet_languages from [@adbar](https://github.com/adbar) (PR #122) +- call sum() without an intermediary list following PEP 289 recommendations from [@adbar](https://github.com/adbar) (PR #129) +- Code style as refactored by Sourcery-AI (PR #131) +- Minor adjustment on the MD around european words (PR #133) +- Remove and replace SRTs from assets / tests (PR #139) +- Initialize the library logger with a `NullHandler` by default from [@nmaynes](https://github.com/nmaynes) (PR #135) +- Setting kwarg `explain` to True will add provisionally (bounded to function lifespan) a specific stream handler (PR #135) + +### Fixed +- Fix large (misleading) sequence giving UnicodeDecodeError (PR #137) +- Avoid using too insignificant chunk (PR #137) + +### Added +- Add and expose function `set_logging_handler` to configure a specific StreamHandler from [@nmaynes](https://github.com/nmaynes) (PR #135) +- Add `CHANGELOG.md` entries, format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) (PR #141) + +## [2.0.7](https://github.com/Ousret/charset_normalizer/compare/2.0.6...2.0.7) (2021-10-11) +### Added +- Add support for Kazakh (Cyrillic) language detection (PR #109) + +### Changed +- Further, improve inferring the language from a given single-byte code page (PR #112) +- Vainly trying to leverage PEP263 when PEP3120 is not supported (PR #116) +- Refactoring for potential performance improvements in loops from [@adbar](https://github.com/adbar) (PR #113) +- Various detection improvement (MD+CD) (PR #117) + +### Removed +- Remove redundant logging entry about detected language(s) (PR #115) + +### Fixed +- Fix a minor inconsistency between Python 3.5 and other versions regarding language detection (PR #117 #102) + +## [2.0.6](https://github.com/Ousret/charset_normalizer/compare/2.0.5...2.0.6) (2021-09-18) +### Fixed +- Unforeseen regression with the loss of the backward-compatibility with some older minor of Python 3.5.x (PR #100) +- Fix CLI crash when using --minimal output in certain cases (PR #103) + +### Changed +- Minor improvement to the detection efficiency (less than 1%) (PR #106 #101) + +## [2.0.5](https://github.com/Ousret/charset_normalizer/compare/2.0.4...2.0.5) (2021-09-14) +### Changed +- The project now comply with: flake8, mypy, isort and black to ensure a better overall quality (PR #81) +- The BC-support with v1.x was improved, the old staticmethods are restored (PR #82) +- The Unicode detection is slightly improved (PR #93) +- Add syntax sugar \_\_bool\_\_ for results CharsetMatches list-container (PR #91) + +### Removed +- The project no longer raise warning on tiny content given for detection, will be simply logged as warning instead (PR #92) + +### Fixed +- In some rare case, the chunks extractor could cut in the middle of a multi-byte character and could mislead the mess detection (PR #95) +- Some rare 'space' characters could trip up the UnprintablePlugin/Mess detection (PR #96) +- The MANIFEST.in was not exhaustive (PR #78) + +## [2.0.4](https://github.com/Ousret/charset_normalizer/compare/2.0.3...2.0.4) (2021-07-30) +### Fixed +- The CLI no longer raise an unexpected exception when no encoding has been found (PR #70) +- Fix accessing the 'alphabets' property when the payload contains surrogate characters (PR #68) +- The logger could mislead (explain=True) on detected languages and the impact of one MBCS match (PR #72) +- Submatch factoring could be wrong in rare edge cases (PR #72) +- Multiple files given to the CLI were ignored when publishing results to STDOUT. (After the first path) (PR #72) +- Fix line endings from CRLF to LF for certain project files (PR #67) + +### Changed +- Adjust the MD to lower the sensitivity, thus improving the global detection reliability (PR #69 #76) +- Allow fallback on specified encoding if any (PR #71) + +## [2.0.3](https://github.com/Ousret/charset_normalizer/compare/2.0.2...2.0.3) (2021-07-16) +### Changed +- Part of the detection mechanism has been improved to be less sensitive, resulting in more accurate detection results. Especially ASCII. (PR #63) +- According to the community wishes, the detection will fall back on ASCII or UTF-8 in a last-resort case. (PR #64) + +## [2.0.2](https://github.com/Ousret/charset_normalizer/compare/2.0.1...2.0.2) (2021-07-15) +### Fixed +- Empty/Too small JSON payload miss-detection fixed. Report from [@tseaver](https://github.com/tseaver) (PR #59) + +### Changed +- Don't inject unicodedata2 into sys.modules from [@akx](https://github.com/akx) (PR #57) + +## [2.0.1](https://github.com/Ousret/charset_normalizer/compare/2.0.0...2.0.1) (2021-07-13) +### Fixed +- Make it work where there isn't a filesystem available, dropping assets frequencies.json. Report from [@sethmlarson](https://github.com/sethmlarson). (PR #55) +- Using explain=False permanently disable the verbose output in the current runtime (PR #47) +- One log entry (language target preemptive) was not show in logs when using explain=True (PR #47) +- Fix undesired exception (ValueError) on getitem of instance CharsetMatches (PR #52) + +### Changed +- Public function normalize default args values were not aligned with from_bytes (PR #53) + +### Added +- You may now use charset aliases in cp_isolation and cp_exclusion arguments (PR #47) + +## [2.0.0](https://github.com/Ousret/charset_normalizer/compare/1.4.1...2.0.0) (2021-07-02) +### Changed +- 4x to 5 times faster than the previous 1.4.0 release. At least 2x faster than Chardet. +- Accent has been made on UTF-8 detection, should perform rather instantaneous. +- The backward compatibility with Chardet has been greatly improved. The legacy detect function returns an identical charset name whenever possible. +- The detection mechanism has been slightly improved, now Turkish content is detected correctly (most of the time) +- The program has been rewritten to ease the readability and maintainability. (+Using static typing)+ +- utf_7 detection has been reinstated. + +### Removed +- This package no longer require anything when used with Python 3.5 (Dropped cached_property) +- Removed support for these languages: Catalan, Esperanto, Kazakh, Baque, Volapük, Azeri, Galician, Nynorsk, Macedonian, and Serbocroatian. +- The exception hook on UnicodeDecodeError has been removed. + +### Deprecated +- Methods coherence_non_latin, w_counter, chaos_secondary_pass of the class CharsetMatch are now deprecated and scheduled for removal in v3.0 + +### Fixed +- The CLI output used the relative path of the file(s). Should be absolute. + +## [1.4.1](https://github.com/Ousret/charset_normalizer/compare/1.4.0...1.4.1) (2021-05-28) +### Fixed +- Logger configuration/usage no longer conflict with others (PR #44) + +## [1.4.0](https://github.com/Ousret/charset_normalizer/compare/1.3.9...1.4.0) (2021-05-21) +### Removed +- Using standard logging instead of using the package loguru. +- Dropping nose test framework in favor of the maintained pytest. +- Choose to not use dragonmapper package to help with gibberish Chinese/CJK text. +- Require cached_property only for Python 3.5 due to constraint. Dropping for every other interpreter version. +- Stop support for UTF-7 that does not contain a SIG. +- Dropping PrettyTable, replaced with pure JSON output in CLI. + +### Fixed +- BOM marker in a CharsetNormalizerMatch instance could be False in rare cases even if obviously present. Due to the sub-match factoring process. +- Not searching properly for the BOM when trying utf32/16 parent codec. + +### Changed +- Improving the package final size by compressing frequencies.json. +- Huge improvement over the larges payload. + +### Added +- CLI now produces JSON consumable output. +- Return ASCII if given sequences fit. Given reasonable confidence. + +## [1.3.9](https://github.com/Ousret/charset_normalizer/compare/1.3.8...1.3.9) (2021-05-13) + +### Fixed +- In some very rare cases, you may end up getting encode/decode errors due to a bad bytes payload (PR #40) + +## [1.3.8](https://github.com/Ousret/charset_normalizer/compare/1.3.7...1.3.8) (2021-05-12) + +### Fixed +- Empty given payload for detection may cause an exception if trying to access the `alphabets` property. (PR #39) + +## [1.3.7](https://github.com/Ousret/charset_normalizer/compare/1.3.6...1.3.7) (2021-05-12) + +### Fixed +- The legacy detect function should return UTF-8-SIG if sig is present in the payload. (PR #38) + +## [1.3.6](https://github.com/Ousret/charset_normalizer/compare/1.3.5...1.3.6) (2021-02-09) + +### Changed +- Amend the previous release to allow prettytable 2.0 (PR #35) + +## [1.3.5](https://github.com/Ousret/charset_normalizer/compare/1.3.4...1.3.5) (2021-02-08) + +### Fixed +- Fix error while using the package with a python pre-release interpreter (PR #33) + +### Changed +- Dependencies refactoring, constraints revised. + +### Added +- Add python 3.9 and 3.10 to the supported interpreters + +MIT License + +Copyright (c) 2025 TAHRI Ahmed R. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/venv/Lib/site-packages/charset_normalizer-3.4.2.dist-info/RECORD b/venv/Lib/site-packages/charset_normalizer-3.4.2.dist-info/RECORD new file mode 100644 index 00000000..3c285017 --- /dev/null +++ b/venv/Lib/site-packages/charset_normalizer-3.4.2.dist-info/RECORD @@ -0,0 +1,35 @@ +../../Scripts/normalizer.exe,sha256=R1sjOGFwcrjsSq3CdDHBZsnnjZ7CvMcc4k686Ao8DQg,108420 +charset_normalizer-3.4.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +charset_normalizer-3.4.2.dist-info/METADATA,sha256=WneNNyl9QvsRZYzK1FeEC6Wwag4iIFoTAoevPgpZFTY,36474 +charset_normalizer-3.4.2.dist-info/RECORD,, +charset_normalizer-3.4.2.dist-info/WHEEL,sha256=PqPfOxA7mGIdQ4POxRbyNp_0DDxNzJM1gpSaGcLLjlo,101 +charset_normalizer-3.4.2.dist-info/entry_points.txt,sha256=8C-Y3iXIfyXQ83Tpir2B8t-XLJYpxF5xbb38d_js-h4,65 +charset_normalizer-3.4.2.dist-info/licenses/LICENSE,sha256=GFd0hdNwTxpHne2OVzwJds_tMV_S_ReYP6mI2kwvcNE,1092 +charset_normalizer-3.4.2.dist-info/top_level.txt,sha256=7ASyzePr8_xuZWJsnqJjIBtyV8vhEo0wBCv1MPRRi3Q,19 +charset_normalizer/__init__.py,sha256=0NT8MHi7SKq3juMqYfOdrkzjisK0L73lneNHH4qaUAs,1638 +charset_normalizer/__main__.py,sha256=2sj_BS6H0sU25C1bMqz9DVwa6kOK9lchSEbSU-_iu7M,115 +charset_normalizer/__pycache__/__init__.cpython-312.pyc,, +charset_normalizer/__pycache__/__main__.cpython-312.pyc,, +charset_normalizer/__pycache__/api.cpython-312.pyc,, +charset_normalizer/__pycache__/cd.cpython-312.pyc,, +charset_normalizer/__pycache__/constant.cpython-312.pyc,, +charset_normalizer/__pycache__/legacy.cpython-312.pyc,, +charset_normalizer/__pycache__/md.cpython-312.pyc,, +charset_normalizer/__pycache__/models.cpython-312.pyc,, +charset_normalizer/__pycache__/utils.cpython-312.pyc,, +charset_normalizer/__pycache__/version.cpython-312.pyc,, +charset_normalizer/api.py,sha256=2a0p2Gnhbdo9O6C04CNxTSN23fIbgOF20nxb0pWPNFM,23285 +charset_normalizer/cd.py,sha256=uq8nVxRpR6Guc16ACvOWtL8KO3w7vYaCh8hHisuOyTg,12917 +charset_normalizer/cli/__init__.py,sha256=d9MUx-1V_qD3x9igIy4JT4oC5CU0yjulk7QyZWeRFhg,144 +charset_normalizer/cli/__main__.py,sha256=-pdJCyPywouPyFsC8_eTSgTmvh1YEvgjsvy1WZ0XjaA,13027 +charset_normalizer/cli/__pycache__/__init__.cpython-312.pyc,, +charset_normalizer/cli/__pycache__/__main__.cpython-312.pyc,, +charset_normalizer/constant.py,sha256=mCJmYzpBU27Ut9kiNWWoBbhhxQ-aRVw3K7LSwoFwBGI,44728 +charset_normalizer/legacy.py,sha256=NgK-8ZQa_M9FHgQjdNSiYzMaB332QGuElZSfCf2y2sQ,2351 +charset_normalizer/md.cp312-win_amd64.pyd,sha256=Rl7qVeM9DRj8hZuyoyQjaRKsZ6zkpojb7Nx1nNTbjr8,10752 +charset_normalizer/md.py,sha256=LSuW2hNgXSgF7JGdRapLAHLuj6pABHiP85LTNAYmu7c,20780 +charset_normalizer/md__mypyc.cp312-win_amd64.pyd,sha256=WXIlB5bZkRXY2k4r70Pmyf7eLRw6zLib-dXXkRIrOZA,125952 +charset_normalizer/models.py,sha256=ZR2PE-fqf6dASZfqdE5Uhkmr0o1MciSdXOjuNqwkmvg,12754 +charset_normalizer/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +charset_normalizer/utils.py,sha256=XtWIQeOuz7cnGebMzyi4Vvi1JtA84QBSIeR9PDzF7pw,12584 +charset_normalizer/version.py,sha256=wtpyUZ7M57rCLclP3QjzRD0Nj2hvnMOzLZI-vwfTdWs,123 diff --git a/venv/Lib/site-packages/charset_normalizer-3.4.2.dist-info/WHEEL b/venv/Lib/site-packages/charset_normalizer-3.4.2.dist-info/WHEEL new file mode 100644 index 00000000..97266467 --- /dev/null +++ b/venv/Lib/site-packages/charset_normalizer-3.4.2.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.1.0) +Root-Is-Purelib: false +Tag: cp312-cp312-win_amd64 + diff --git a/venv/Lib/site-packages/charset_normalizer-3.4.2.dist-info/entry_points.txt b/venv/Lib/site-packages/charset_normalizer-3.4.2.dist-info/entry_points.txt new file mode 100644 index 00000000..ec920125 --- /dev/null +++ b/venv/Lib/site-packages/charset_normalizer-3.4.2.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +normalizer = charset_normalizer:cli.cli_detect diff --git a/venv/Lib/site-packages/charset_normalizer-3.4.2.dist-info/licenses/LICENSE b/venv/Lib/site-packages/charset_normalizer-3.4.2.dist-info/licenses/LICENSE new file mode 100644 index 00000000..9725772c --- /dev/null +++ b/venv/Lib/site-packages/charset_normalizer-3.4.2.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 TAHRI Ahmed R. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/venv/Lib/site-packages/charset_normalizer-3.4.2.dist-info/top_level.txt b/venv/Lib/site-packages/charset_normalizer-3.4.2.dist-info/top_level.txt new file mode 100644 index 00000000..66958f0a --- /dev/null +++ b/venv/Lib/site-packages/charset_normalizer-3.4.2.dist-info/top_level.txt @@ -0,0 +1 @@ +charset_normalizer diff --git a/venv/Lib/site-packages/charset_normalizer/__init__.py b/venv/Lib/site-packages/charset_normalizer/__init__.py new file mode 100644 index 00000000..0d3a3799 --- /dev/null +++ b/venv/Lib/site-packages/charset_normalizer/__init__.py @@ -0,0 +1,48 @@ +""" +Charset-Normalizer +~~~~~~~~~~~~~~ +The Real First Universal Charset Detector. +A library that helps you read text from an unknown charset encoding. +Motivated by chardet, This package is trying to resolve the issue by taking a new approach. +All IANA character set names for which the Python core library provides codecs are supported. + +Basic usage: + >>> from charset_normalizer import from_bytes + >>> results = from_bytes('Bсеки човек има право на образование. Oбразованието!'.encode('utf_8')) + >>> best_guess = results.best() + >>> str(best_guess) + 'Bсеки човек има право на образование. Oбразованието!' + +Others methods and usages are available - see the full documentation +at . +:copyright: (c) 2021 by Ahmed TAHRI +:license: MIT, see LICENSE for more details. +""" + +from __future__ import annotations + +import logging + +from .api import from_bytes, from_fp, from_path, is_binary +from .legacy import detect +from .models import CharsetMatch, CharsetMatches +from .utils import set_logging_handler +from .version import VERSION, __version__ + +__all__ = ( + "from_fp", + "from_path", + "from_bytes", + "is_binary", + "detect", + "CharsetMatch", + "CharsetMatches", + "__version__", + "VERSION", + "set_logging_handler", +) + +# Attach a NullHandler to the top level logger by default +# https://docs.python.org/3.3/howto/logging.html#configuring-logging-for-a-library + +logging.getLogger("charset_normalizer").addHandler(logging.NullHandler()) diff --git a/venv/Lib/site-packages/charset_normalizer/__main__.py b/venv/Lib/site-packages/charset_normalizer/__main__.py new file mode 100644 index 00000000..e0e76f7b --- /dev/null +++ b/venv/Lib/site-packages/charset_normalizer/__main__.py @@ -0,0 +1,6 @@ +from __future__ import annotations + +from .cli import cli_detect + +if __name__ == "__main__": + cli_detect() diff --git a/venv/Lib/site-packages/charset_normalizer/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/charset_normalizer/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..4affcfa3 Binary files /dev/null and b/venv/Lib/site-packages/charset_normalizer/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/charset_normalizer/__pycache__/__main__.cpython-312.pyc b/venv/Lib/site-packages/charset_normalizer/__pycache__/__main__.cpython-312.pyc new file mode 100644 index 00000000..fe1aa758 Binary files /dev/null and b/venv/Lib/site-packages/charset_normalizer/__pycache__/__main__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/charset_normalizer/__pycache__/api.cpython-312.pyc b/venv/Lib/site-packages/charset_normalizer/__pycache__/api.cpython-312.pyc new file mode 100644 index 00000000..70db0b9a Binary files /dev/null and b/venv/Lib/site-packages/charset_normalizer/__pycache__/api.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/charset_normalizer/__pycache__/cd.cpython-312.pyc b/venv/Lib/site-packages/charset_normalizer/__pycache__/cd.cpython-312.pyc new file mode 100644 index 00000000..4da67779 Binary files /dev/null and b/venv/Lib/site-packages/charset_normalizer/__pycache__/cd.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/charset_normalizer/__pycache__/constant.cpython-312.pyc b/venv/Lib/site-packages/charset_normalizer/__pycache__/constant.cpython-312.pyc new file mode 100644 index 00000000..07929718 Binary files /dev/null and b/venv/Lib/site-packages/charset_normalizer/__pycache__/constant.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/charset_normalizer/__pycache__/legacy.cpython-312.pyc b/venv/Lib/site-packages/charset_normalizer/__pycache__/legacy.cpython-312.pyc new file mode 100644 index 00000000..d3cc27c9 Binary files /dev/null and b/venv/Lib/site-packages/charset_normalizer/__pycache__/legacy.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/charset_normalizer/__pycache__/md.cpython-312.pyc b/venv/Lib/site-packages/charset_normalizer/__pycache__/md.cpython-312.pyc new file mode 100644 index 00000000..98753be7 Binary files /dev/null and b/venv/Lib/site-packages/charset_normalizer/__pycache__/md.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/charset_normalizer/__pycache__/models.cpython-312.pyc b/venv/Lib/site-packages/charset_normalizer/__pycache__/models.cpython-312.pyc new file mode 100644 index 00000000..46ddfdc9 Binary files /dev/null and b/venv/Lib/site-packages/charset_normalizer/__pycache__/models.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/charset_normalizer/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/charset_normalizer/__pycache__/utils.cpython-312.pyc new file mode 100644 index 00000000..74685c58 Binary files /dev/null and b/venv/Lib/site-packages/charset_normalizer/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/charset_normalizer/__pycache__/version.cpython-312.pyc b/venv/Lib/site-packages/charset_normalizer/__pycache__/version.cpython-312.pyc new file mode 100644 index 00000000..d58f3981 Binary files /dev/null and b/venv/Lib/site-packages/charset_normalizer/__pycache__/version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/charset_normalizer/api.py b/venv/Lib/site-packages/charset_normalizer/api.py new file mode 100644 index 00000000..2c8c0618 --- /dev/null +++ b/venv/Lib/site-packages/charset_normalizer/api.py @@ -0,0 +1,668 @@ +from __future__ import annotations + +import logging +from os import PathLike +from typing import BinaryIO + +from .cd import ( + coherence_ratio, + encoding_languages, + mb_encoding_languages, + merge_coherence_ratios, +) +from .constant import IANA_SUPPORTED, TOO_BIG_SEQUENCE, TOO_SMALL_SEQUENCE, TRACE +from .md import mess_ratio +from .models import CharsetMatch, CharsetMatches +from .utils import ( + any_specified_encoding, + cut_sequence_chunks, + iana_name, + identify_sig_or_bom, + is_cp_similar, + is_multi_byte_encoding, + should_strip_sig_or_bom, +) + +logger = logging.getLogger("charset_normalizer") +explain_handler = logging.StreamHandler() +explain_handler.setFormatter( + logging.Formatter("%(asctime)s | %(levelname)s | %(message)s") +) + + +def from_bytes( + sequences: bytes | bytearray, + steps: int = 5, + chunk_size: int = 512, + threshold: float = 0.2, + cp_isolation: list[str] | None = None, + cp_exclusion: list[str] | None = None, + preemptive_behaviour: bool = True, + explain: bool = False, + language_threshold: float = 0.1, + enable_fallback: bool = True, +) -> CharsetMatches: + """ + Given a raw bytes sequence, return the best possibles charset usable to render str objects. + If there is no results, it is a strong indicator that the source is binary/not text. + By default, the process will extract 5 blocks of 512o each to assess the mess and coherence of a given sequence. + And will give up a particular code page after 20% of measured mess. Those criteria are customizable at will. + + The preemptive behavior DOES NOT replace the traditional detection workflow, it prioritize a particular code page + but never take it for granted. Can improve the performance. + + You may want to focus your attention to some code page or/and not others, use cp_isolation and cp_exclusion for that + purpose. + + This function will strip the SIG in the payload/sequence every time except on UTF-16, UTF-32. + By default the library does not setup any handler other than the NullHandler, if you choose to set the 'explain' + toggle to True it will alter the logger configuration to add a StreamHandler that is suitable for debugging. + Custom logging format and handler can be set manually. + """ + + if not isinstance(sequences, (bytearray, bytes)): + raise TypeError( + "Expected object of type bytes or bytearray, got: {}".format( + type(sequences) + ) + ) + + if explain: + previous_logger_level: int = logger.level + logger.addHandler(explain_handler) + logger.setLevel(TRACE) + + length: int = len(sequences) + + if length == 0: + logger.debug("Encoding detection on empty bytes, assuming utf_8 intention.") + if explain: # Defensive: ensure exit path clean handler + logger.removeHandler(explain_handler) + logger.setLevel(previous_logger_level or logging.WARNING) + return CharsetMatches([CharsetMatch(sequences, "utf_8", 0.0, False, [], "")]) + + if cp_isolation is not None: + logger.log( + TRACE, + "cp_isolation is set. use this flag for debugging purpose. " + "limited list of encoding allowed : %s.", + ", ".join(cp_isolation), + ) + cp_isolation = [iana_name(cp, False) for cp in cp_isolation] + else: + cp_isolation = [] + + if cp_exclusion is not None: + logger.log( + TRACE, + "cp_exclusion is set. use this flag for debugging purpose. " + "limited list of encoding excluded : %s.", + ", ".join(cp_exclusion), + ) + cp_exclusion = [iana_name(cp, False) for cp in cp_exclusion] + else: + cp_exclusion = [] + + if length <= (chunk_size * steps): + logger.log( + TRACE, + "override steps (%i) and chunk_size (%i) as content does not fit (%i byte(s) given) parameters.", + steps, + chunk_size, + length, + ) + steps = 1 + chunk_size = length + + if steps > 1 and length / steps < chunk_size: + chunk_size = int(length / steps) + + is_too_small_sequence: bool = len(sequences) < TOO_SMALL_SEQUENCE + is_too_large_sequence: bool = len(sequences) >= TOO_BIG_SEQUENCE + + if is_too_small_sequence: + logger.log( + TRACE, + "Trying to detect encoding from a tiny portion of ({}) byte(s).".format( + length + ), + ) + elif is_too_large_sequence: + logger.log( + TRACE, + "Using lazy str decoding because the payload is quite large, ({}) byte(s).".format( + length + ), + ) + + prioritized_encodings: list[str] = [] + + specified_encoding: str | None = ( + any_specified_encoding(sequences) if preemptive_behaviour else None + ) + + if specified_encoding is not None: + prioritized_encodings.append(specified_encoding) + logger.log( + TRACE, + "Detected declarative mark in sequence. Priority +1 given for %s.", + specified_encoding, + ) + + tested: set[str] = set() + tested_but_hard_failure: list[str] = [] + tested_but_soft_failure: list[str] = [] + + fallback_ascii: CharsetMatch | None = None + fallback_u8: CharsetMatch | None = None + fallback_specified: CharsetMatch | None = None + + results: CharsetMatches = CharsetMatches() + + early_stop_results: CharsetMatches = CharsetMatches() + + sig_encoding, sig_payload = identify_sig_or_bom(sequences) + + if sig_encoding is not None: + prioritized_encodings.append(sig_encoding) + logger.log( + TRACE, + "Detected a SIG or BOM mark on first %i byte(s). Priority +1 given for %s.", + len(sig_payload), + sig_encoding, + ) + + prioritized_encodings.append("ascii") + + if "utf_8" not in prioritized_encodings: + prioritized_encodings.append("utf_8") + + for encoding_iana in prioritized_encodings + IANA_SUPPORTED: + if cp_isolation and encoding_iana not in cp_isolation: + continue + + if cp_exclusion and encoding_iana in cp_exclusion: + continue + + if encoding_iana in tested: + continue + + tested.add(encoding_iana) + + decoded_payload: str | None = None + bom_or_sig_available: bool = sig_encoding == encoding_iana + strip_sig_or_bom: bool = bom_or_sig_available and should_strip_sig_or_bom( + encoding_iana + ) + + if encoding_iana in {"utf_16", "utf_32"} and not bom_or_sig_available: + logger.log( + TRACE, + "Encoding %s won't be tested as-is because it require a BOM. Will try some sub-encoder LE/BE.", + encoding_iana, + ) + continue + if encoding_iana in {"utf_7"} and not bom_or_sig_available: + logger.log( + TRACE, + "Encoding %s won't be tested as-is because detection is unreliable without BOM/SIG.", + encoding_iana, + ) + continue + + try: + is_multi_byte_decoder: bool = is_multi_byte_encoding(encoding_iana) + except (ModuleNotFoundError, ImportError): + logger.log( + TRACE, + "Encoding %s does not provide an IncrementalDecoder", + encoding_iana, + ) + continue + + try: + if is_too_large_sequence and is_multi_byte_decoder is False: + str( + ( + sequences[: int(50e4)] + if strip_sig_or_bom is False + else sequences[len(sig_payload) : int(50e4)] + ), + encoding=encoding_iana, + ) + else: + decoded_payload = str( + ( + sequences + if strip_sig_or_bom is False + else sequences[len(sig_payload) :] + ), + encoding=encoding_iana, + ) + except (UnicodeDecodeError, LookupError) as e: + if not isinstance(e, LookupError): + logger.log( + TRACE, + "Code page %s does not fit given bytes sequence at ALL. %s", + encoding_iana, + str(e), + ) + tested_but_hard_failure.append(encoding_iana) + continue + + similar_soft_failure_test: bool = False + + for encoding_soft_failed in tested_but_soft_failure: + if is_cp_similar(encoding_iana, encoding_soft_failed): + similar_soft_failure_test = True + break + + if similar_soft_failure_test: + logger.log( + TRACE, + "%s is deemed too similar to code page %s and was consider unsuited already. Continuing!", + encoding_iana, + encoding_soft_failed, + ) + continue + + r_ = range( + 0 if not bom_or_sig_available else len(sig_payload), + length, + int(length / steps), + ) + + multi_byte_bonus: bool = ( + is_multi_byte_decoder + and decoded_payload is not None + and len(decoded_payload) < length + ) + + if multi_byte_bonus: + logger.log( + TRACE, + "Code page %s is a multi byte encoding table and it appear that at least one character " + "was encoded using n-bytes.", + encoding_iana, + ) + + max_chunk_gave_up: int = int(len(r_) / 4) + + max_chunk_gave_up = max(max_chunk_gave_up, 2) + early_stop_count: int = 0 + lazy_str_hard_failure = False + + md_chunks: list[str] = [] + md_ratios = [] + + try: + for chunk in cut_sequence_chunks( + sequences, + encoding_iana, + r_, + chunk_size, + bom_or_sig_available, + strip_sig_or_bom, + sig_payload, + is_multi_byte_decoder, + decoded_payload, + ): + md_chunks.append(chunk) + + md_ratios.append( + mess_ratio( + chunk, + threshold, + explain is True and 1 <= len(cp_isolation) <= 2, + ) + ) + + if md_ratios[-1] >= threshold: + early_stop_count += 1 + + if (early_stop_count >= max_chunk_gave_up) or ( + bom_or_sig_available and strip_sig_or_bom is False + ): + break + except ( + UnicodeDecodeError + ) as e: # Lazy str loading may have missed something there + logger.log( + TRACE, + "LazyStr Loading: After MD chunk decode, code page %s does not fit given bytes sequence at ALL. %s", + encoding_iana, + str(e), + ) + early_stop_count = max_chunk_gave_up + lazy_str_hard_failure = True + + # We might want to check the sequence again with the whole content + # Only if initial MD tests passes + if ( + not lazy_str_hard_failure + and is_too_large_sequence + and not is_multi_byte_decoder + ): + try: + sequences[int(50e3) :].decode(encoding_iana, errors="strict") + except UnicodeDecodeError as e: + logger.log( + TRACE, + "LazyStr Loading: After final lookup, code page %s does not fit given bytes sequence at ALL. %s", + encoding_iana, + str(e), + ) + tested_but_hard_failure.append(encoding_iana) + continue + + mean_mess_ratio: float = sum(md_ratios) / len(md_ratios) if md_ratios else 0.0 + if mean_mess_ratio >= threshold or early_stop_count >= max_chunk_gave_up: + tested_but_soft_failure.append(encoding_iana) + logger.log( + TRACE, + "%s was excluded because of initial chaos probing. Gave up %i time(s). " + "Computed mean chaos is %f %%.", + encoding_iana, + early_stop_count, + round(mean_mess_ratio * 100, ndigits=3), + ) + # Preparing those fallbacks in case we got nothing. + if ( + enable_fallback + and encoding_iana in ["ascii", "utf_8", specified_encoding] + and not lazy_str_hard_failure + ): + fallback_entry = CharsetMatch( + sequences, + encoding_iana, + threshold, + False, + [], + decoded_payload, + preemptive_declaration=specified_encoding, + ) + if encoding_iana == specified_encoding: + fallback_specified = fallback_entry + elif encoding_iana == "ascii": + fallback_ascii = fallback_entry + else: + fallback_u8 = fallback_entry + continue + + logger.log( + TRACE, + "%s passed initial chaos probing. Mean measured chaos is %f %%", + encoding_iana, + round(mean_mess_ratio * 100, ndigits=3), + ) + + if not is_multi_byte_decoder: + target_languages: list[str] = encoding_languages(encoding_iana) + else: + target_languages = mb_encoding_languages(encoding_iana) + + if target_languages: + logger.log( + TRACE, + "{} should target any language(s) of {}".format( + encoding_iana, str(target_languages) + ), + ) + + cd_ratios = [] + + # We shall skip the CD when its about ASCII + # Most of the time its not relevant to run "language-detection" on it. + if encoding_iana != "ascii": + for chunk in md_chunks: + chunk_languages = coherence_ratio( + chunk, + language_threshold, + ",".join(target_languages) if target_languages else None, + ) + + cd_ratios.append(chunk_languages) + + cd_ratios_merged = merge_coherence_ratios(cd_ratios) + + if cd_ratios_merged: + logger.log( + TRACE, + "We detected language {} using {}".format( + cd_ratios_merged, encoding_iana + ), + ) + + current_match = CharsetMatch( + sequences, + encoding_iana, + mean_mess_ratio, + bom_or_sig_available, + cd_ratios_merged, + ( + decoded_payload + if ( + is_too_large_sequence is False + or encoding_iana in [specified_encoding, "ascii", "utf_8"] + ) + else None + ), + preemptive_declaration=specified_encoding, + ) + + results.append(current_match) + + if ( + encoding_iana in [specified_encoding, "ascii", "utf_8"] + and mean_mess_ratio < 0.1 + ): + # If md says nothing to worry about, then... stop immediately! + if mean_mess_ratio == 0.0: + logger.debug( + "Encoding detection: %s is most likely the one.", + current_match.encoding, + ) + if explain: # Defensive: ensure exit path clean handler + logger.removeHandler(explain_handler) + logger.setLevel(previous_logger_level) + return CharsetMatches([current_match]) + + early_stop_results.append(current_match) + + if ( + len(early_stop_results) + and (specified_encoding is None or specified_encoding in tested) + and "ascii" in tested + and "utf_8" in tested + ): + probable_result: CharsetMatch = early_stop_results.best() # type: ignore[assignment] + logger.debug( + "Encoding detection: %s is most likely the one.", + probable_result.encoding, + ) + if explain: # Defensive: ensure exit path clean handler + logger.removeHandler(explain_handler) + logger.setLevel(previous_logger_level) + + return CharsetMatches([probable_result]) + + if encoding_iana == sig_encoding: + logger.debug( + "Encoding detection: %s is most likely the one as we detected a BOM or SIG within " + "the beginning of the sequence.", + encoding_iana, + ) + if explain: # Defensive: ensure exit path clean handler + logger.removeHandler(explain_handler) + logger.setLevel(previous_logger_level) + return CharsetMatches([results[encoding_iana]]) + + if len(results) == 0: + if fallback_u8 or fallback_ascii or fallback_specified: + logger.log( + TRACE, + "Nothing got out of the detection process. Using ASCII/UTF-8/Specified fallback.", + ) + + if fallback_specified: + logger.debug( + "Encoding detection: %s will be used as a fallback match", + fallback_specified.encoding, + ) + results.append(fallback_specified) + elif ( + (fallback_u8 and fallback_ascii is None) + or ( + fallback_u8 + and fallback_ascii + and fallback_u8.fingerprint != fallback_ascii.fingerprint + ) + or (fallback_u8 is not None) + ): + logger.debug("Encoding detection: utf_8 will be used as a fallback match") + results.append(fallback_u8) + elif fallback_ascii: + logger.debug("Encoding detection: ascii will be used as a fallback match") + results.append(fallback_ascii) + + if results: + logger.debug( + "Encoding detection: Found %s as plausible (best-candidate) for content. With %i alternatives.", + results.best().encoding, # type: ignore + len(results) - 1, + ) + else: + logger.debug("Encoding detection: Unable to determine any suitable charset.") + + if explain: + logger.removeHandler(explain_handler) + logger.setLevel(previous_logger_level) + + return results + + +def from_fp( + fp: BinaryIO, + steps: int = 5, + chunk_size: int = 512, + threshold: float = 0.20, + cp_isolation: list[str] | None = None, + cp_exclusion: list[str] | None = None, + preemptive_behaviour: bool = True, + explain: bool = False, + language_threshold: float = 0.1, + enable_fallback: bool = True, +) -> CharsetMatches: + """ + Same thing than the function from_bytes but using a file pointer that is already ready. + Will not close the file pointer. + """ + return from_bytes( + fp.read(), + steps, + chunk_size, + threshold, + cp_isolation, + cp_exclusion, + preemptive_behaviour, + explain, + language_threshold, + enable_fallback, + ) + + +def from_path( + path: str | bytes | PathLike, # type: ignore[type-arg] + steps: int = 5, + chunk_size: int = 512, + threshold: float = 0.20, + cp_isolation: list[str] | None = None, + cp_exclusion: list[str] | None = None, + preemptive_behaviour: bool = True, + explain: bool = False, + language_threshold: float = 0.1, + enable_fallback: bool = True, +) -> CharsetMatches: + """ + Same thing than the function from_bytes but with one extra step. Opening and reading given file path in binary mode. + Can raise IOError. + """ + with open(path, "rb") as fp: + return from_fp( + fp, + steps, + chunk_size, + threshold, + cp_isolation, + cp_exclusion, + preemptive_behaviour, + explain, + language_threshold, + enable_fallback, + ) + + +def is_binary( + fp_or_path_or_payload: PathLike | str | BinaryIO | bytes, # type: ignore[type-arg] + steps: int = 5, + chunk_size: int = 512, + threshold: float = 0.20, + cp_isolation: list[str] | None = None, + cp_exclusion: list[str] | None = None, + preemptive_behaviour: bool = True, + explain: bool = False, + language_threshold: float = 0.1, + enable_fallback: bool = False, +) -> bool: + """ + Detect if the given input (file, bytes, or path) points to a binary file. aka. not a string. + Based on the same main heuristic algorithms and default kwargs at the sole exception that fallbacks match + are disabled to be stricter around ASCII-compatible but unlikely to be a string. + """ + if isinstance(fp_or_path_or_payload, (str, PathLike)): + guesses = from_path( + fp_or_path_or_payload, + steps=steps, + chunk_size=chunk_size, + threshold=threshold, + cp_isolation=cp_isolation, + cp_exclusion=cp_exclusion, + preemptive_behaviour=preemptive_behaviour, + explain=explain, + language_threshold=language_threshold, + enable_fallback=enable_fallback, + ) + elif isinstance( + fp_or_path_or_payload, + ( + bytes, + bytearray, + ), + ): + guesses = from_bytes( + fp_or_path_or_payload, + steps=steps, + chunk_size=chunk_size, + threshold=threshold, + cp_isolation=cp_isolation, + cp_exclusion=cp_exclusion, + preemptive_behaviour=preemptive_behaviour, + explain=explain, + language_threshold=language_threshold, + enable_fallback=enable_fallback, + ) + else: + guesses = from_fp( + fp_or_path_or_payload, + steps=steps, + chunk_size=chunk_size, + threshold=threshold, + cp_isolation=cp_isolation, + cp_exclusion=cp_exclusion, + preemptive_behaviour=preemptive_behaviour, + explain=explain, + language_threshold=language_threshold, + enable_fallback=enable_fallback, + ) + + return not guesses diff --git a/venv/Lib/site-packages/charset_normalizer/cd.py b/venv/Lib/site-packages/charset_normalizer/cd.py new file mode 100644 index 00000000..71a3ed51 --- /dev/null +++ b/venv/Lib/site-packages/charset_normalizer/cd.py @@ -0,0 +1,395 @@ +from __future__ import annotations + +import importlib +from codecs import IncrementalDecoder +from collections import Counter +from functools import lru_cache +from typing import Counter as TypeCounter + +from .constant import ( + FREQUENCIES, + KO_NAMES, + LANGUAGE_SUPPORTED_COUNT, + TOO_SMALL_SEQUENCE, + ZH_NAMES, +) +from .md import is_suspiciously_successive_range +from .models import CoherenceMatches +from .utils import ( + is_accentuated, + is_latin, + is_multi_byte_encoding, + is_unicode_range_secondary, + unicode_range, +) + + +def encoding_unicode_range(iana_name: str) -> list[str]: + """ + Return associated unicode ranges in a single byte code page. + """ + if is_multi_byte_encoding(iana_name): + raise OSError("Function not supported on multi-byte code page") + + decoder = importlib.import_module(f"encodings.{iana_name}").IncrementalDecoder + + p: IncrementalDecoder = decoder(errors="ignore") + seen_ranges: dict[str, int] = {} + character_count: int = 0 + + for i in range(0x40, 0xFF): + chunk: str = p.decode(bytes([i])) + + if chunk: + character_range: str | None = unicode_range(chunk) + + if character_range is None: + continue + + if is_unicode_range_secondary(character_range) is False: + if character_range not in seen_ranges: + seen_ranges[character_range] = 0 + seen_ranges[character_range] += 1 + character_count += 1 + + return sorted( + [ + character_range + for character_range in seen_ranges + if seen_ranges[character_range] / character_count >= 0.15 + ] + ) + + +def unicode_range_languages(primary_range: str) -> list[str]: + """ + Return inferred languages used with a unicode range. + """ + languages: list[str] = [] + + for language, characters in FREQUENCIES.items(): + for character in characters: + if unicode_range(character) == primary_range: + languages.append(language) + break + + return languages + + +@lru_cache() +def encoding_languages(iana_name: str) -> list[str]: + """ + Single-byte encoding language association. Some code page are heavily linked to particular language(s). + This function does the correspondence. + """ + unicode_ranges: list[str] = encoding_unicode_range(iana_name) + primary_range: str | None = None + + for specified_range in unicode_ranges: + if "Latin" not in specified_range: + primary_range = specified_range + break + + if primary_range is None: + return ["Latin Based"] + + return unicode_range_languages(primary_range) + + +@lru_cache() +def mb_encoding_languages(iana_name: str) -> list[str]: + """ + Multi-byte encoding language association. Some code page are heavily linked to particular language(s). + This function does the correspondence. + """ + if ( + iana_name.startswith("shift_") + or iana_name.startswith("iso2022_jp") + or iana_name.startswith("euc_j") + or iana_name == "cp932" + ): + return ["Japanese"] + if iana_name.startswith("gb") or iana_name in ZH_NAMES: + return ["Chinese"] + if iana_name.startswith("iso2022_kr") or iana_name in KO_NAMES: + return ["Korean"] + + return [] + + +@lru_cache(maxsize=LANGUAGE_SUPPORTED_COUNT) +def get_target_features(language: str) -> tuple[bool, bool]: + """ + Determine main aspects from a supported language if it contains accents and if is pure Latin. + """ + target_have_accents: bool = False + target_pure_latin: bool = True + + for character in FREQUENCIES[language]: + if not target_have_accents and is_accentuated(character): + target_have_accents = True + if target_pure_latin and is_latin(character) is False: + target_pure_latin = False + + return target_have_accents, target_pure_latin + + +def alphabet_languages( + characters: list[str], ignore_non_latin: bool = False +) -> list[str]: + """ + Return associated languages associated to given characters. + """ + languages: list[tuple[str, float]] = [] + + source_have_accents = any(is_accentuated(character) for character in characters) + + for language, language_characters in FREQUENCIES.items(): + target_have_accents, target_pure_latin = get_target_features(language) + + if ignore_non_latin and target_pure_latin is False: + continue + + if target_have_accents is False and source_have_accents: + continue + + character_count: int = len(language_characters) + + character_match_count: int = len( + [c for c in language_characters if c in characters] + ) + + ratio: float = character_match_count / character_count + + if ratio >= 0.2: + languages.append((language, ratio)) + + languages = sorted(languages, key=lambda x: x[1], reverse=True) + + return [compatible_language[0] for compatible_language in languages] + + +def characters_popularity_compare( + language: str, ordered_characters: list[str] +) -> float: + """ + Determine if a ordered characters list (by occurrence from most appearance to rarest) match a particular language. + The result is a ratio between 0. (absolutely no correspondence) and 1. (near perfect fit). + Beware that is function is not strict on the match in order to ease the detection. (Meaning close match is 1.) + """ + if language not in FREQUENCIES: + raise ValueError(f"{language} not available") + + character_approved_count: int = 0 + FREQUENCIES_language_set = set(FREQUENCIES[language]) + + ordered_characters_count: int = len(ordered_characters) + target_language_characters_count: int = len(FREQUENCIES[language]) + + large_alphabet: bool = target_language_characters_count > 26 + + for character, character_rank in zip( + ordered_characters, range(0, ordered_characters_count) + ): + if character not in FREQUENCIES_language_set: + continue + + character_rank_in_language: int = FREQUENCIES[language].index(character) + expected_projection_ratio: float = ( + target_language_characters_count / ordered_characters_count + ) + character_rank_projection: int = int(character_rank * expected_projection_ratio) + + if ( + large_alphabet is False + and abs(character_rank_projection - character_rank_in_language) > 4 + ): + continue + + if ( + large_alphabet is True + and abs(character_rank_projection - character_rank_in_language) + < target_language_characters_count / 3 + ): + character_approved_count += 1 + continue + + characters_before_source: list[str] = FREQUENCIES[language][ + 0:character_rank_in_language + ] + characters_after_source: list[str] = FREQUENCIES[language][ + character_rank_in_language: + ] + characters_before: list[str] = ordered_characters[0:character_rank] + characters_after: list[str] = ordered_characters[character_rank:] + + before_match_count: int = len( + set(characters_before) & set(characters_before_source) + ) + + after_match_count: int = len( + set(characters_after) & set(characters_after_source) + ) + + if len(characters_before_source) == 0 and before_match_count <= 4: + character_approved_count += 1 + continue + + if len(characters_after_source) == 0 and after_match_count <= 4: + character_approved_count += 1 + continue + + if ( + before_match_count / len(characters_before_source) >= 0.4 + or after_match_count / len(characters_after_source) >= 0.4 + ): + character_approved_count += 1 + continue + + return character_approved_count / len(ordered_characters) + + +def alpha_unicode_split(decoded_sequence: str) -> list[str]: + """ + Given a decoded text sequence, return a list of str. Unicode range / alphabet separation. + Ex. a text containing English/Latin with a bit a Hebrew will return two items in the resulting list; + One containing the latin letters and the other hebrew. + """ + layers: dict[str, str] = {} + + for character in decoded_sequence: + if character.isalpha() is False: + continue + + character_range: str | None = unicode_range(character) + + if character_range is None: + continue + + layer_target_range: str | None = None + + for discovered_range in layers: + if ( + is_suspiciously_successive_range(discovered_range, character_range) + is False + ): + layer_target_range = discovered_range + break + + if layer_target_range is None: + layer_target_range = character_range + + if layer_target_range not in layers: + layers[layer_target_range] = character.lower() + continue + + layers[layer_target_range] += character.lower() + + return list(layers.values()) + + +def merge_coherence_ratios(results: list[CoherenceMatches]) -> CoherenceMatches: + """ + This function merge results previously given by the function coherence_ratio. + The return type is the same as coherence_ratio. + """ + per_language_ratios: dict[str, list[float]] = {} + for result in results: + for sub_result in result: + language, ratio = sub_result + if language not in per_language_ratios: + per_language_ratios[language] = [ratio] + continue + per_language_ratios[language].append(ratio) + + merge = [ + ( + language, + round( + sum(per_language_ratios[language]) / len(per_language_ratios[language]), + 4, + ), + ) + for language in per_language_ratios + ] + + return sorted(merge, key=lambda x: x[1], reverse=True) + + +def filter_alt_coherence_matches(results: CoherenceMatches) -> CoherenceMatches: + """ + We shall NOT return "English—" in CoherenceMatches because it is an alternative + of "English". This function only keeps the best match and remove the em-dash in it. + """ + index_results: dict[str, list[float]] = dict() + + for result in results: + language, ratio = result + no_em_name: str = language.replace("—", "") + + if no_em_name not in index_results: + index_results[no_em_name] = [] + + index_results[no_em_name].append(ratio) + + if any(len(index_results[e]) > 1 for e in index_results): + filtered_results: CoherenceMatches = [] + + for language in index_results: + filtered_results.append((language, max(index_results[language]))) + + return filtered_results + + return results + + +@lru_cache(maxsize=2048) +def coherence_ratio( + decoded_sequence: str, threshold: float = 0.1, lg_inclusion: str | None = None +) -> CoherenceMatches: + """ + Detect ANY language that can be identified in given sequence. The sequence will be analysed by layers. + A layer = Character extraction by alphabets/ranges. + """ + + results: list[tuple[str, float]] = [] + ignore_non_latin: bool = False + + sufficient_match_count: int = 0 + + lg_inclusion_list = lg_inclusion.split(",") if lg_inclusion is not None else [] + if "Latin Based" in lg_inclusion_list: + ignore_non_latin = True + lg_inclusion_list.remove("Latin Based") + + for layer in alpha_unicode_split(decoded_sequence): + sequence_frequencies: TypeCounter[str] = Counter(layer) + most_common = sequence_frequencies.most_common() + + character_count: int = sum(o for c, o in most_common) + + if character_count <= TOO_SMALL_SEQUENCE: + continue + + popular_character_ordered: list[str] = [c for c, o in most_common] + + for language in lg_inclusion_list or alphabet_languages( + popular_character_ordered, ignore_non_latin + ): + ratio: float = characters_popularity_compare( + language, popular_character_ordered + ) + + if ratio < threshold: + continue + elif ratio >= 0.8: + sufficient_match_count += 1 + + results.append((language, round(ratio, 4))) + + if sufficient_match_count >= 3: + break + + return sorted( + filter_alt_coherence_matches(results), key=lambda x: x[1], reverse=True + ) diff --git a/venv/Lib/site-packages/charset_normalizer/cli/__init__.py b/venv/Lib/site-packages/charset_normalizer/cli/__init__.py new file mode 100644 index 00000000..543a5a4d --- /dev/null +++ b/venv/Lib/site-packages/charset_normalizer/cli/__init__.py @@ -0,0 +1,8 @@ +from __future__ import annotations + +from .__main__ import cli_detect, query_yes_no + +__all__ = ( + "cli_detect", + "query_yes_no", +) diff --git a/venv/Lib/site-packages/charset_normalizer/cli/__main__.py b/venv/Lib/site-packages/charset_normalizer/cli/__main__.py new file mode 100644 index 00000000..cb64156a --- /dev/null +++ b/venv/Lib/site-packages/charset_normalizer/cli/__main__.py @@ -0,0 +1,381 @@ +from __future__ import annotations + +import argparse +import sys +import typing +from json import dumps +from os.path import abspath, basename, dirname, join, realpath +from platform import python_version +from unicodedata import unidata_version + +import charset_normalizer.md as md_module +from charset_normalizer import from_fp +from charset_normalizer.models import CliDetectionResult +from charset_normalizer.version import __version__ + + +def query_yes_no(question: str, default: str = "yes") -> bool: + """Ask a yes/no question via input() and return their answer. + + "question" is a string that is presented to the user. + "default" is the presumed answer if the user just hits . + It must be "yes" (the default), "no" or None (meaning + an answer is required of the user). + + The "answer" return value is True for "yes" or False for "no". + + Credit goes to (c) https://stackoverflow.com/questions/3041986/apt-command-line-interface-like-yes-no-input + """ + valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} + if default is None: + prompt = " [y/n] " + elif default == "yes": + prompt = " [Y/n] " + elif default == "no": + prompt = " [y/N] " + else: + raise ValueError("invalid default answer: '%s'" % default) + + while True: + sys.stdout.write(question + prompt) + choice = input().lower() + if default is not None and choice == "": + return valid[default] + elif choice in valid: + return valid[choice] + else: + sys.stdout.write("Please respond with 'yes' or 'no' (or 'y' or 'n').\n") + + +class FileType: + """Factory for creating file object types + + Instances of FileType are typically passed as type= arguments to the + ArgumentParser add_argument() method. + + Keyword Arguments: + - mode -- A string indicating how the file is to be opened. Accepts the + same values as the builtin open() function. + - bufsize -- The file's desired buffer size. Accepts the same values as + the builtin open() function. + - encoding -- The file's encoding. Accepts the same values as the + builtin open() function. + - errors -- A string indicating how encoding and decoding errors are to + be handled. Accepts the same value as the builtin open() function. + + Backported from CPython 3.12 + """ + + def __init__( + self, + mode: str = "r", + bufsize: int = -1, + encoding: str | None = None, + errors: str | None = None, + ): + self._mode = mode + self._bufsize = bufsize + self._encoding = encoding + self._errors = errors + + def __call__(self, string: str) -> typing.IO: # type: ignore[type-arg] + # the special argument "-" means sys.std{in,out} + if string == "-": + if "r" in self._mode: + return sys.stdin.buffer if "b" in self._mode else sys.stdin + elif any(c in self._mode for c in "wax"): + return sys.stdout.buffer if "b" in self._mode else sys.stdout + else: + msg = f'argument "-" with mode {self._mode}' + raise ValueError(msg) + + # all other arguments are used as file names + try: + return open(string, self._mode, self._bufsize, self._encoding, self._errors) + except OSError as e: + message = f"can't open '{string}': {e}" + raise argparse.ArgumentTypeError(message) + + def __repr__(self) -> str: + args = self._mode, self._bufsize + kwargs = [("encoding", self._encoding), ("errors", self._errors)] + args_str = ", ".join( + [repr(arg) for arg in args if arg != -1] + + [f"{kw}={arg!r}" for kw, arg in kwargs if arg is not None] + ) + return f"{type(self).__name__}({args_str})" + + +def cli_detect(argv: list[str] | None = None) -> int: + """ + CLI assistant using ARGV and ArgumentParser + :param argv: + :return: 0 if everything is fine, anything else equal trouble + """ + parser = argparse.ArgumentParser( + description="The Real First Universal Charset Detector. " + "Discover originating encoding used on text file. " + "Normalize text to unicode." + ) + + parser.add_argument( + "files", type=FileType("rb"), nargs="+", help="File(s) to be analysed" + ) + parser.add_argument( + "-v", + "--verbose", + action="store_true", + default=False, + dest="verbose", + help="Display complementary information about file if any. " + "Stdout will contain logs about the detection process.", + ) + parser.add_argument( + "-a", + "--with-alternative", + action="store_true", + default=False, + dest="alternatives", + help="Output complementary possibilities if any. Top-level JSON WILL be a list.", + ) + parser.add_argument( + "-n", + "--normalize", + action="store_true", + default=False, + dest="normalize", + help="Permit to normalize input file. If not set, program does not write anything.", + ) + parser.add_argument( + "-m", + "--minimal", + action="store_true", + default=False, + dest="minimal", + help="Only output the charset detected to STDOUT. Disabling JSON output.", + ) + parser.add_argument( + "-r", + "--replace", + action="store_true", + default=False, + dest="replace", + help="Replace file when trying to normalize it instead of creating a new one.", + ) + parser.add_argument( + "-f", + "--force", + action="store_true", + default=False, + dest="force", + help="Replace file without asking if you are sure, use this flag with caution.", + ) + parser.add_argument( + "-i", + "--no-preemptive", + action="store_true", + default=False, + dest="no_preemptive", + help="Disable looking at a charset declaration to hint the detector.", + ) + parser.add_argument( + "-t", + "--threshold", + action="store", + default=0.2, + type=float, + dest="threshold", + help="Define a custom maximum amount of noise allowed in decoded content. 0. <= noise <= 1.", + ) + parser.add_argument( + "--version", + action="version", + version="Charset-Normalizer {} - Python {} - Unicode {} - SpeedUp {}".format( + __version__, + python_version(), + unidata_version, + "OFF" if md_module.__file__.lower().endswith(".py") else "ON", + ), + help="Show version information and exit.", + ) + + args = parser.parse_args(argv) + + if args.replace is True and args.normalize is False: + if args.files: + for my_file in args.files: + my_file.close() + print("Use --replace in addition of --normalize only.", file=sys.stderr) + return 1 + + if args.force is True and args.replace is False: + if args.files: + for my_file in args.files: + my_file.close() + print("Use --force in addition of --replace only.", file=sys.stderr) + return 1 + + if args.threshold < 0.0 or args.threshold > 1.0: + if args.files: + for my_file in args.files: + my_file.close() + print("--threshold VALUE should be between 0. AND 1.", file=sys.stderr) + return 1 + + x_ = [] + + for my_file in args.files: + matches = from_fp( + my_file, + threshold=args.threshold, + explain=args.verbose, + preemptive_behaviour=args.no_preemptive is False, + ) + + best_guess = matches.best() + + if best_guess is None: + print( + 'Unable to identify originating encoding for "{}". {}'.format( + my_file.name, + ( + "Maybe try increasing maximum amount of chaos." + if args.threshold < 1.0 + else "" + ), + ), + file=sys.stderr, + ) + x_.append( + CliDetectionResult( + abspath(my_file.name), + None, + [], + [], + "Unknown", + [], + False, + 1.0, + 0.0, + None, + True, + ) + ) + else: + x_.append( + CliDetectionResult( + abspath(my_file.name), + best_guess.encoding, + best_guess.encoding_aliases, + [ + cp + for cp in best_guess.could_be_from_charset + if cp != best_guess.encoding + ], + best_guess.language, + best_guess.alphabets, + best_guess.bom, + best_guess.percent_chaos, + best_guess.percent_coherence, + None, + True, + ) + ) + + if len(matches) > 1 and args.alternatives: + for el in matches: + if el != best_guess: + x_.append( + CliDetectionResult( + abspath(my_file.name), + el.encoding, + el.encoding_aliases, + [ + cp + for cp in el.could_be_from_charset + if cp != el.encoding + ], + el.language, + el.alphabets, + el.bom, + el.percent_chaos, + el.percent_coherence, + None, + False, + ) + ) + + if args.normalize is True: + if best_guess.encoding.startswith("utf") is True: + print( + '"{}" file does not need to be normalized, as it already came from unicode.'.format( + my_file.name + ), + file=sys.stderr, + ) + if my_file.closed is False: + my_file.close() + continue + + dir_path = dirname(realpath(my_file.name)) + file_name = basename(realpath(my_file.name)) + + o_: list[str] = file_name.split(".") + + if args.replace is False: + o_.insert(-1, best_guess.encoding) + if my_file.closed is False: + my_file.close() + elif ( + args.force is False + and query_yes_no( + 'Are you sure to normalize "{}" by replacing it ?'.format( + my_file.name + ), + "no", + ) + is False + ): + if my_file.closed is False: + my_file.close() + continue + + try: + x_[0].unicode_path = join(dir_path, ".".join(o_)) + + with open(x_[0].unicode_path, "wb") as fp: + fp.write(best_guess.output()) + except OSError as e: + print(str(e), file=sys.stderr) + if my_file.closed is False: + my_file.close() + return 2 + + if my_file.closed is False: + my_file.close() + + if args.minimal is False: + print( + dumps( + [el.__dict__ for el in x_] if len(x_) > 1 else x_[0].__dict__, + ensure_ascii=True, + indent=4, + ) + ) + else: + for my_file in args.files: + print( + ", ".join( + [ + el.encoding or "undefined" + for el in x_ + if el.path == abspath(my_file.name) + ] + ) + ) + + return 0 + + +if __name__ == "__main__": + cli_detect() diff --git a/venv/Lib/site-packages/charset_normalizer/cli/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/charset_normalizer/cli/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..474ab0b5 Binary files /dev/null and b/venv/Lib/site-packages/charset_normalizer/cli/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/charset_normalizer/cli/__pycache__/__main__.cpython-312.pyc b/venv/Lib/site-packages/charset_normalizer/cli/__pycache__/__main__.cpython-312.pyc new file mode 100644 index 00000000..c35abae4 Binary files /dev/null and b/venv/Lib/site-packages/charset_normalizer/cli/__pycache__/__main__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/charset_normalizer/constant.py b/venv/Lib/site-packages/charset_normalizer/constant.py new file mode 100644 index 00000000..cc71a019 --- /dev/null +++ b/venv/Lib/site-packages/charset_normalizer/constant.py @@ -0,0 +1,2015 @@ +from __future__ import annotations + +from codecs import BOM_UTF8, BOM_UTF16_BE, BOM_UTF16_LE, BOM_UTF32_BE, BOM_UTF32_LE +from encodings.aliases import aliases +from re import IGNORECASE +from re import compile as re_compile + +# Contain for each eligible encoding a list of/item bytes SIG/BOM +ENCODING_MARKS: dict[str, bytes | list[bytes]] = { + "utf_8": BOM_UTF8, + "utf_7": [ + b"\x2b\x2f\x76\x38", + b"\x2b\x2f\x76\x39", + b"\x2b\x2f\x76\x2b", + b"\x2b\x2f\x76\x2f", + b"\x2b\x2f\x76\x38\x2d", + ], + "gb18030": b"\x84\x31\x95\x33", + "utf_32": [BOM_UTF32_BE, BOM_UTF32_LE], + "utf_16": [BOM_UTF16_BE, BOM_UTF16_LE], +} + +TOO_SMALL_SEQUENCE: int = 32 +TOO_BIG_SEQUENCE: int = int(10e6) + +UTF8_MAXIMAL_ALLOCATION: int = 1_112_064 + +# Up-to-date Unicode ucd/15.0.0 +UNICODE_RANGES_COMBINED: dict[str, range] = { + "Control character": range(32), + "Basic Latin": range(32, 128), + "Latin-1 Supplement": range(128, 256), + "Latin Extended-A": range(256, 384), + "Latin Extended-B": range(384, 592), + "IPA Extensions": range(592, 688), + "Spacing Modifier Letters": range(688, 768), + "Combining Diacritical Marks": range(768, 880), + "Greek and Coptic": range(880, 1024), + "Cyrillic": range(1024, 1280), + "Cyrillic Supplement": range(1280, 1328), + "Armenian": range(1328, 1424), + "Hebrew": range(1424, 1536), + "Arabic": range(1536, 1792), + "Syriac": range(1792, 1872), + "Arabic Supplement": range(1872, 1920), + "Thaana": range(1920, 1984), + "NKo": range(1984, 2048), + "Samaritan": range(2048, 2112), + "Mandaic": range(2112, 2144), + "Syriac Supplement": range(2144, 2160), + "Arabic Extended-B": range(2160, 2208), + "Arabic Extended-A": range(2208, 2304), + "Devanagari": range(2304, 2432), + "Bengali": range(2432, 2560), + "Gurmukhi": range(2560, 2688), + "Gujarati": range(2688, 2816), + "Oriya": range(2816, 2944), + "Tamil": range(2944, 3072), + "Telugu": range(3072, 3200), + "Kannada": range(3200, 3328), + "Malayalam": range(3328, 3456), + "Sinhala": range(3456, 3584), + "Thai": range(3584, 3712), + "Lao": range(3712, 3840), + "Tibetan": range(3840, 4096), + "Myanmar": range(4096, 4256), + "Georgian": range(4256, 4352), + "Hangul Jamo": range(4352, 4608), + "Ethiopic": range(4608, 4992), + "Ethiopic Supplement": range(4992, 5024), + "Cherokee": range(5024, 5120), + "Unified Canadian Aboriginal Syllabics": range(5120, 5760), + "Ogham": range(5760, 5792), + "Runic": range(5792, 5888), + "Tagalog": range(5888, 5920), + "Hanunoo": range(5920, 5952), + "Buhid": range(5952, 5984), + "Tagbanwa": range(5984, 6016), + "Khmer": range(6016, 6144), + "Mongolian": range(6144, 6320), + "Unified Canadian Aboriginal Syllabics Extended": range(6320, 6400), + "Limbu": range(6400, 6480), + "Tai Le": range(6480, 6528), + "New Tai Lue": range(6528, 6624), + "Khmer Symbols": range(6624, 6656), + "Buginese": range(6656, 6688), + "Tai Tham": range(6688, 6832), + "Combining Diacritical Marks Extended": range(6832, 6912), + "Balinese": range(6912, 7040), + "Sundanese": range(7040, 7104), + "Batak": range(7104, 7168), + "Lepcha": range(7168, 7248), + "Ol Chiki": range(7248, 7296), + "Cyrillic Extended-C": range(7296, 7312), + "Georgian Extended": range(7312, 7360), + "Sundanese Supplement": range(7360, 7376), + "Vedic Extensions": range(7376, 7424), + "Phonetic Extensions": range(7424, 7552), + "Phonetic Extensions Supplement": range(7552, 7616), + "Combining Diacritical Marks Supplement": range(7616, 7680), + "Latin Extended Additional": range(7680, 7936), + "Greek Extended": range(7936, 8192), + "General Punctuation": range(8192, 8304), + "Superscripts and Subscripts": range(8304, 8352), + "Currency Symbols": range(8352, 8400), + "Combining Diacritical Marks for Symbols": range(8400, 8448), + "Letterlike Symbols": range(8448, 8528), + "Number Forms": range(8528, 8592), + "Arrows": range(8592, 8704), + "Mathematical Operators": range(8704, 8960), + "Miscellaneous Technical": range(8960, 9216), + "Control Pictures": range(9216, 9280), + "Optical Character Recognition": range(9280, 9312), + "Enclosed Alphanumerics": range(9312, 9472), + "Box Drawing": range(9472, 9600), + "Block Elements": range(9600, 9632), + "Geometric Shapes": range(9632, 9728), + "Miscellaneous Symbols": range(9728, 9984), + "Dingbats": range(9984, 10176), + "Miscellaneous Mathematical Symbols-A": range(10176, 10224), + "Supplemental Arrows-A": range(10224, 10240), + "Braille Patterns": range(10240, 10496), + "Supplemental Arrows-B": range(10496, 10624), + "Miscellaneous Mathematical Symbols-B": range(10624, 10752), + "Supplemental Mathematical Operators": range(10752, 11008), + "Miscellaneous Symbols and Arrows": range(11008, 11264), + "Glagolitic": range(11264, 11360), + "Latin Extended-C": range(11360, 11392), + "Coptic": range(11392, 11520), + "Georgian Supplement": range(11520, 11568), + "Tifinagh": range(11568, 11648), + "Ethiopic Extended": range(11648, 11744), + "Cyrillic Extended-A": range(11744, 11776), + "Supplemental Punctuation": range(11776, 11904), + "CJK Radicals Supplement": range(11904, 12032), + "Kangxi Radicals": range(12032, 12256), + "Ideographic Description Characters": range(12272, 12288), + "CJK Symbols and Punctuation": range(12288, 12352), + "Hiragana": range(12352, 12448), + "Katakana": range(12448, 12544), + "Bopomofo": range(12544, 12592), + "Hangul Compatibility Jamo": range(12592, 12688), + "Kanbun": range(12688, 12704), + "Bopomofo Extended": range(12704, 12736), + "CJK Strokes": range(12736, 12784), + "Katakana Phonetic Extensions": range(12784, 12800), + "Enclosed CJK Letters and Months": range(12800, 13056), + "CJK Compatibility": range(13056, 13312), + "CJK Unified Ideographs Extension A": range(13312, 19904), + "Yijing Hexagram Symbols": range(19904, 19968), + "CJK Unified Ideographs": range(19968, 40960), + "Yi Syllables": range(40960, 42128), + "Yi Radicals": range(42128, 42192), + "Lisu": range(42192, 42240), + "Vai": range(42240, 42560), + "Cyrillic Extended-B": range(42560, 42656), + "Bamum": range(42656, 42752), + "Modifier Tone Letters": range(42752, 42784), + "Latin Extended-D": range(42784, 43008), + "Syloti Nagri": range(43008, 43056), + "Common Indic Number Forms": range(43056, 43072), + "Phags-pa": range(43072, 43136), + "Saurashtra": range(43136, 43232), + "Devanagari Extended": range(43232, 43264), + "Kayah Li": range(43264, 43312), + "Rejang": range(43312, 43360), + "Hangul Jamo Extended-A": range(43360, 43392), + "Javanese": range(43392, 43488), + "Myanmar Extended-B": range(43488, 43520), + "Cham": range(43520, 43616), + "Myanmar Extended-A": range(43616, 43648), + "Tai Viet": range(43648, 43744), + "Meetei Mayek Extensions": range(43744, 43776), + "Ethiopic Extended-A": range(43776, 43824), + "Latin Extended-E": range(43824, 43888), + "Cherokee Supplement": range(43888, 43968), + "Meetei Mayek": range(43968, 44032), + "Hangul Syllables": range(44032, 55216), + "Hangul Jamo Extended-B": range(55216, 55296), + "High Surrogates": range(55296, 56192), + "High Private Use Surrogates": range(56192, 56320), + "Low Surrogates": range(56320, 57344), + "Private Use Area": range(57344, 63744), + "CJK Compatibility Ideographs": range(63744, 64256), + "Alphabetic Presentation Forms": range(64256, 64336), + "Arabic Presentation Forms-A": range(64336, 65024), + "Variation Selectors": range(65024, 65040), + "Vertical Forms": range(65040, 65056), + "Combining Half Marks": range(65056, 65072), + "CJK Compatibility Forms": range(65072, 65104), + "Small Form Variants": range(65104, 65136), + "Arabic Presentation Forms-B": range(65136, 65280), + "Halfwidth and Fullwidth Forms": range(65280, 65520), + "Specials": range(65520, 65536), + "Linear B Syllabary": range(65536, 65664), + "Linear B Ideograms": range(65664, 65792), + "Aegean Numbers": range(65792, 65856), + "Ancient Greek Numbers": range(65856, 65936), + "Ancient Symbols": range(65936, 66000), + "Phaistos Disc": range(66000, 66048), + "Lycian": range(66176, 66208), + "Carian": range(66208, 66272), + "Coptic Epact Numbers": range(66272, 66304), + "Old Italic": range(66304, 66352), + "Gothic": range(66352, 66384), + "Old Permic": range(66384, 66432), + "Ugaritic": range(66432, 66464), + "Old Persian": range(66464, 66528), + "Deseret": range(66560, 66640), + "Shavian": range(66640, 66688), + "Osmanya": range(66688, 66736), + "Osage": range(66736, 66816), + "Elbasan": range(66816, 66864), + "Caucasian Albanian": range(66864, 66928), + "Vithkuqi": range(66928, 67008), + "Linear A": range(67072, 67456), + "Latin Extended-F": range(67456, 67520), + "Cypriot Syllabary": range(67584, 67648), + "Imperial Aramaic": range(67648, 67680), + "Palmyrene": range(67680, 67712), + "Nabataean": range(67712, 67760), + "Hatran": range(67808, 67840), + "Phoenician": range(67840, 67872), + "Lydian": range(67872, 67904), + "Meroitic Hieroglyphs": range(67968, 68000), + "Meroitic Cursive": range(68000, 68096), + "Kharoshthi": range(68096, 68192), + "Old South Arabian": range(68192, 68224), + "Old North Arabian": range(68224, 68256), + "Manichaean": range(68288, 68352), + "Avestan": range(68352, 68416), + "Inscriptional Parthian": range(68416, 68448), + "Inscriptional Pahlavi": range(68448, 68480), + "Psalter Pahlavi": range(68480, 68528), + "Old Turkic": range(68608, 68688), + "Old Hungarian": range(68736, 68864), + "Hanifi Rohingya": range(68864, 68928), + "Rumi Numeral Symbols": range(69216, 69248), + "Yezidi": range(69248, 69312), + "Arabic Extended-C": range(69312, 69376), + "Old Sogdian": range(69376, 69424), + "Sogdian": range(69424, 69488), + "Old Uyghur": range(69488, 69552), + "Chorasmian": range(69552, 69600), + "Elymaic": range(69600, 69632), + "Brahmi": range(69632, 69760), + "Kaithi": range(69760, 69840), + "Sora Sompeng": range(69840, 69888), + "Chakma": range(69888, 69968), + "Mahajani": range(69968, 70016), + "Sharada": range(70016, 70112), + "Sinhala Archaic Numbers": range(70112, 70144), + "Khojki": range(70144, 70224), + "Multani": range(70272, 70320), + "Khudawadi": range(70320, 70400), + "Grantha": range(70400, 70528), + "Newa": range(70656, 70784), + "Tirhuta": range(70784, 70880), + "Siddham": range(71040, 71168), + "Modi": range(71168, 71264), + "Mongolian Supplement": range(71264, 71296), + "Takri": range(71296, 71376), + "Ahom": range(71424, 71504), + "Dogra": range(71680, 71760), + "Warang Citi": range(71840, 71936), + "Dives Akuru": range(71936, 72032), + "Nandinagari": range(72096, 72192), + "Zanabazar Square": range(72192, 72272), + "Soyombo": range(72272, 72368), + "Unified Canadian Aboriginal Syllabics Extended-A": range(72368, 72384), + "Pau Cin Hau": range(72384, 72448), + "Devanagari Extended-A": range(72448, 72544), + "Bhaiksuki": range(72704, 72816), + "Marchen": range(72816, 72896), + "Masaram Gondi": range(72960, 73056), + "Gunjala Gondi": range(73056, 73136), + "Makasar": range(73440, 73472), + "Kawi": range(73472, 73568), + "Lisu Supplement": range(73648, 73664), + "Tamil Supplement": range(73664, 73728), + "Cuneiform": range(73728, 74752), + "Cuneiform Numbers and Punctuation": range(74752, 74880), + "Early Dynastic Cuneiform": range(74880, 75088), + "Cypro-Minoan": range(77712, 77824), + "Egyptian Hieroglyphs": range(77824, 78896), + "Egyptian Hieroglyph Format Controls": range(78896, 78944), + "Anatolian Hieroglyphs": range(82944, 83584), + "Bamum Supplement": range(92160, 92736), + "Mro": range(92736, 92784), + "Tangsa": range(92784, 92880), + "Bassa Vah": range(92880, 92928), + "Pahawh Hmong": range(92928, 93072), + "Medefaidrin": range(93760, 93856), + "Miao": range(93952, 94112), + "Ideographic Symbols and Punctuation": range(94176, 94208), + "Tangut": range(94208, 100352), + "Tangut Components": range(100352, 101120), + "Khitan Small Script": range(101120, 101632), + "Tangut Supplement": range(101632, 101760), + "Kana Extended-B": range(110576, 110592), + "Kana Supplement": range(110592, 110848), + "Kana Extended-A": range(110848, 110896), + "Small Kana Extension": range(110896, 110960), + "Nushu": range(110960, 111360), + "Duployan": range(113664, 113824), + "Shorthand Format Controls": range(113824, 113840), + "Znamenny Musical Notation": range(118528, 118736), + "Byzantine Musical Symbols": range(118784, 119040), + "Musical Symbols": range(119040, 119296), + "Ancient Greek Musical Notation": range(119296, 119376), + "Kaktovik Numerals": range(119488, 119520), + "Mayan Numerals": range(119520, 119552), + "Tai Xuan Jing Symbols": range(119552, 119648), + "Counting Rod Numerals": range(119648, 119680), + "Mathematical Alphanumeric Symbols": range(119808, 120832), + "Sutton SignWriting": range(120832, 121520), + "Latin Extended-G": range(122624, 122880), + "Glagolitic Supplement": range(122880, 122928), + "Cyrillic Extended-D": range(122928, 123024), + "Nyiakeng Puachue Hmong": range(123136, 123216), + "Toto": range(123536, 123584), + "Wancho": range(123584, 123648), + "Nag Mundari": range(124112, 124160), + "Ethiopic Extended-B": range(124896, 124928), + "Mende Kikakui": range(124928, 125152), + "Adlam": range(125184, 125280), + "Indic Siyaq Numbers": range(126064, 126144), + "Ottoman Siyaq Numbers": range(126208, 126288), + "Arabic Mathematical Alphabetic Symbols": range(126464, 126720), + "Mahjong Tiles": range(126976, 127024), + "Domino Tiles": range(127024, 127136), + "Playing Cards": range(127136, 127232), + "Enclosed Alphanumeric Supplement": range(127232, 127488), + "Enclosed Ideographic Supplement": range(127488, 127744), + "Miscellaneous Symbols and Pictographs": range(127744, 128512), + "Emoticons range(Emoji)": range(128512, 128592), + "Ornamental Dingbats": range(128592, 128640), + "Transport and Map Symbols": range(128640, 128768), + "Alchemical Symbols": range(128768, 128896), + "Geometric Shapes Extended": range(128896, 129024), + "Supplemental Arrows-C": range(129024, 129280), + "Supplemental Symbols and Pictographs": range(129280, 129536), + "Chess Symbols": range(129536, 129648), + "Symbols and Pictographs Extended-A": range(129648, 129792), + "Symbols for Legacy Computing": range(129792, 130048), + "CJK Unified Ideographs Extension B": range(131072, 173792), + "CJK Unified Ideographs Extension C": range(173824, 177984), + "CJK Unified Ideographs Extension D": range(177984, 178208), + "CJK Unified Ideographs Extension E": range(178208, 183984), + "CJK Unified Ideographs Extension F": range(183984, 191472), + "CJK Compatibility Ideographs Supplement": range(194560, 195104), + "CJK Unified Ideographs Extension G": range(196608, 201552), + "CJK Unified Ideographs Extension H": range(201552, 205744), + "Tags": range(917504, 917632), + "Variation Selectors Supplement": range(917760, 918000), + "Supplementary Private Use Area-A": range(983040, 1048576), + "Supplementary Private Use Area-B": range(1048576, 1114112), +} + + +UNICODE_SECONDARY_RANGE_KEYWORD: list[str] = [ + "Supplement", + "Extended", + "Extensions", + "Modifier", + "Marks", + "Punctuation", + "Symbols", + "Forms", + "Operators", + "Miscellaneous", + "Drawing", + "Block", + "Shapes", + "Supplemental", + "Tags", +] + +RE_POSSIBLE_ENCODING_INDICATION = re_compile( + r"(?:(?:encoding)|(?:charset)|(?:coding))(?:[\:= ]{1,10})(?:[\"\']?)([a-zA-Z0-9\-_]+)(?:[\"\']?)", + IGNORECASE, +) + +IANA_NO_ALIASES = [ + "cp720", + "cp737", + "cp856", + "cp874", + "cp875", + "cp1006", + "koi8_r", + "koi8_t", + "koi8_u", +] + +IANA_SUPPORTED: list[str] = sorted( + filter( + lambda x: x.endswith("_codec") is False + and x not in {"rot_13", "tactis", "mbcs"}, + list(set(aliases.values())) + IANA_NO_ALIASES, + ) +) + +IANA_SUPPORTED_COUNT: int = len(IANA_SUPPORTED) + +# pre-computed code page that are similar using the function cp_similarity. +IANA_SUPPORTED_SIMILAR: dict[str, list[str]] = { + "cp037": ["cp1026", "cp1140", "cp273", "cp500"], + "cp1026": ["cp037", "cp1140", "cp273", "cp500"], + "cp1125": ["cp866"], + "cp1140": ["cp037", "cp1026", "cp273", "cp500"], + "cp1250": ["iso8859_2"], + "cp1251": ["kz1048", "ptcp154"], + "cp1252": ["iso8859_15", "iso8859_9", "latin_1"], + "cp1253": ["iso8859_7"], + "cp1254": ["iso8859_15", "iso8859_9", "latin_1"], + "cp1257": ["iso8859_13"], + "cp273": ["cp037", "cp1026", "cp1140", "cp500"], + "cp437": ["cp850", "cp858", "cp860", "cp861", "cp862", "cp863", "cp865"], + "cp500": ["cp037", "cp1026", "cp1140", "cp273"], + "cp850": ["cp437", "cp857", "cp858", "cp865"], + "cp857": ["cp850", "cp858", "cp865"], + "cp858": ["cp437", "cp850", "cp857", "cp865"], + "cp860": ["cp437", "cp861", "cp862", "cp863", "cp865"], + "cp861": ["cp437", "cp860", "cp862", "cp863", "cp865"], + "cp862": ["cp437", "cp860", "cp861", "cp863", "cp865"], + "cp863": ["cp437", "cp860", "cp861", "cp862", "cp865"], + "cp865": ["cp437", "cp850", "cp857", "cp858", "cp860", "cp861", "cp862", "cp863"], + "cp866": ["cp1125"], + "iso8859_10": ["iso8859_14", "iso8859_15", "iso8859_4", "iso8859_9", "latin_1"], + "iso8859_11": ["tis_620"], + "iso8859_13": ["cp1257"], + "iso8859_14": [ + "iso8859_10", + "iso8859_15", + "iso8859_16", + "iso8859_3", + "iso8859_9", + "latin_1", + ], + "iso8859_15": [ + "cp1252", + "cp1254", + "iso8859_10", + "iso8859_14", + "iso8859_16", + "iso8859_3", + "iso8859_9", + "latin_1", + ], + "iso8859_16": [ + "iso8859_14", + "iso8859_15", + "iso8859_2", + "iso8859_3", + "iso8859_9", + "latin_1", + ], + "iso8859_2": ["cp1250", "iso8859_16", "iso8859_4"], + "iso8859_3": ["iso8859_14", "iso8859_15", "iso8859_16", "iso8859_9", "latin_1"], + "iso8859_4": ["iso8859_10", "iso8859_2", "iso8859_9", "latin_1"], + "iso8859_7": ["cp1253"], + "iso8859_9": [ + "cp1252", + "cp1254", + "cp1258", + "iso8859_10", + "iso8859_14", + "iso8859_15", + "iso8859_16", + "iso8859_3", + "iso8859_4", + "latin_1", + ], + "kz1048": ["cp1251", "ptcp154"], + "latin_1": [ + "cp1252", + "cp1254", + "cp1258", + "iso8859_10", + "iso8859_14", + "iso8859_15", + "iso8859_16", + "iso8859_3", + "iso8859_4", + "iso8859_9", + ], + "mac_iceland": ["mac_roman", "mac_turkish"], + "mac_roman": ["mac_iceland", "mac_turkish"], + "mac_turkish": ["mac_iceland", "mac_roman"], + "ptcp154": ["cp1251", "kz1048"], + "tis_620": ["iso8859_11"], +} + + +CHARDET_CORRESPONDENCE: dict[str, str] = { + "iso2022_kr": "ISO-2022-KR", + "iso2022_jp": "ISO-2022-JP", + "euc_kr": "EUC-KR", + "tis_620": "TIS-620", + "utf_32": "UTF-32", + "euc_jp": "EUC-JP", + "koi8_r": "KOI8-R", + "iso8859_1": "ISO-8859-1", + "iso8859_2": "ISO-8859-2", + "iso8859_5": "ISO-8859-5", + "iso8859_6": "ISO-8859-6", + "iso8859_7": "ISO-8859-7", + "iso8859_8": "ISO-8859-8", + "utf_16": "UTF-16", + "cp855": "IBM855", + "mac_cyrillic": "MacCyrillic", + "gb2312": "GB2312", + "gb18030": "GB18030", + "cp932": "CP932", + "cp866": "IBM866", + "utf_8": "utf-8", + "utf_8_sig": "UTF-8-SIG", + "shift_jis": "SHIFT_JIS", + "big5": "Big5", + "cp1250": "windows-1250", + "cp1251": "windows-1251", + "cp1252": "Windows-1252", + "cp1253": "windows-1253", + "cp1255": "windows-1255", + "cp1256": "windows-1256", + "cp1254": "Windows-1254", + "cp949": "CP949", +} + + +COMMON_SAFE_ASCII_CHARACTERS: set[str] = { + "<", + ">", + "=", + ":", + "/", + "&", + ";", + "{", + "}", + "[", + "]", + ",", + "|", + '"', + "-", + "(", + ")", +} + +# Sample character sets — replace with full lists if needed +COMMON_CHINESE_CHARACTERS = "的一是在不了有和人这中大为上个国我以要他时来用们生到作地于出就分对成会可主发年动同工也能下过子说产种面而方后多定行学法所民得经十三之进着等部度家电力里如水化高自二理起小物现实加量都两体制机当使点从业本去把性好应开它合还因由其些然前外天政四日那社义事平形相全表间样与关各重新线内数正心反你明看原又么利比或但质气第向道命此变条只没结解问意建月公无系军很情者最立代想已通并提直题党程展五果料象员革位入常文总次品式活设及管特件长求老头基资边流路级少图山统接知较将组见计别她手角期根论运农指几九区强放决西被干做必战先回则任取据处队南给色光门即保治北造百规热领七海口东导器压志世金增争济阶油思术极交受联什认六共权收证改清己美再采转更单风切打白教速花带安场身车例真务具万每目至达走积示议声报斗完类八离华名确才科张信马节话米整空元况今集温传土许步群广石记需段研界拉林律叫且究观越织装影算低持音众书布复容儿须际商非验连断深难近矿千周委素技备半办青省列习响约支般史感劳便团往酸历市克何除消构府太准精值号率族维划选标写存候毛亲快效斯院查江型眼王按格养易置派层片始却专状育厂京识适属圆包火住调满县局照参红细引听该铁价严龙飞" + +COMMON_JAPANESE_CHARACTERS = "日一国年大十二本中長出三時行見月分後前生五間上東四今金九入学高円子外八六下来気小七山話女北午百書先名川千水半男西電校語土木聞食車何南万毎白天母火右読友左休父雨" + +COMMON_KOREAN_CHARACTERS = "一二三四五六七八九十百千萬上下左右中人女子大小山川日月火水木金土父母天地國名年時文校學生" + +# Combine all into a set +COMMON_CJK_CHARACTERS = set( + "".join( + [ + COMMON_CHINESE_CHARACTERS, + COMMON_JAPANESE_CHARACTERS, + COMMON_KOREAN_CHARACTERS, + ] + ) +) + +KO_NAMES: set[str] = {"johab", "cp949", "euc_kr"} +ZH_NAMES: set[str] = {"big5", "cp950", "big5hkscs", "hz"} + +# Logging LEVEL below DEBUG +TRACE: int = 5 + + +# Language label that contain the em dash "—" +# character are to be considered alternative seq to origin +FREQUENCIES: dict[str, list[str]] = { + "English": [ + "e", + "a", + "t", + "i", + "o", + "n", + "s", + "r", + "h", + "l", + "d", + "c", + "u", + "m", + "f", + "p", + "g", + "w", + "y", + "b", + "v", + "k", + "x", + "j", + "z", + "q", + ], + "English—": [ + "e", + "a", + "t", + "i", + "o", + "n", + "s", + "r", + "h", + "l", + "d", + "c", + "m", + "u", + "f", + "p", + "g", + "w", + "b", + "y", + "v", + "k", + "j", + "x", + "z", + "q", + ], + "German": [ + "e", + "n", + "i", + "r", + "s", + "t", + "a", + "d", + "h", + "u", + "l", + "g", + "o", + "c", + "m", + "b", + "f", + "k", + "w", + "z", + "p", + "v", + "ü", + "ä", + "ö", + "j", + ], + "French": [ + "e", + "a", + "s", + "n", + "i", + "t", + "r", + "l", + "u", + "o", + "d", + "c", + "p", + "m", + "é", + "v", + "g", + "f", + "b", + "h", + "q", + "à", + "x", + "è", + "y", + "j", + ], + "Dutch": [ + "e", + "n", + "a", + "i", + "r", + "t", + "o", + "d", + "s", + "l", + "g", + "h", + "v", + "m", + "u", + "k", + "c", + "p", + "b", + "w", + "j", + "z", + "f", + "y", + "x", + "ë", + ], + "Italian": [ + "e", + "i", + "a", + "o", + "n", + "l", + "t", + "r", + "s", + "c", + "d", + "u", + "p", + "m", + "g", + "v", + "f", + "b", + "z", + "h", + "q", + "è", + "à", + "k", + "y", + "ò", + ], + "Polish": [ + "a", + "i", + "o", + "e", + "n", + "r", + "z", + "w", + "s", + "c", + "t", + "k", + "y", + "d", + "p", + "m", + "u", + "l", + "j", + "ł", + "g", + "b", + "h", + "ą", + "ę", + "ó", + ], + "Spanish": [ + "e", + "a", + "o", + "n", + "s", + "r", + "i", + "l", + "d", + "t", + "c", + "u", + "m", + "p", + "b", + "g", + "v", + "f", + "y", + "ó", + "h", + "q", + "í", + "j", + "z", + "á", + ], + "Russian": [ + "о", + "а", + "е", + "и", + "н", + "с", + "т", + "р", + "в", + "л", + "к", + "м", + "д", + "п", + "у", + "г", + "я", + "ы", + "з", + "б", + "й", + "ь", + "ч", + "х", + "ж", + "ц", + ], + # Jap-Kanji + "Japanese": [ + "人", + "一", + "大", + "亅", + "丁", + "丨", + "竹", + "笑", + "口", + "日", + "今", + "二", + "彳", + "行", + "十", + "土", + "丶", + "寸", + "寺", + "時", + "乙", + "丿", + "乂", + "气", + "気", + "冂", + "巾", + "亠", + "市", + "目", + "儿", + "見", + "八", + "小", + "凵", + "県", + "月", + "彐", + "門", + "間", + "木", + "東", + "山", + "出", + "本", + "中", + "刀", + "分", + "耳", + "又", + "取", + "最", + "言", + "田", + "心", + "思", + "刂", + "前", + "京", + "尹", + "事", + "生", + "厶", + "云", + "会", + "未", + "来", + "白", + "冫", + "楽", + "灬", + "馬", + "尸", + "尺", + "駅", + "明", + "耂", + "者", + "了", + "阝", + "都", + "高", + "卜", + "占", + "厂", + "广", + "店", + "子", + "申", + "奄", + "亻", + "俺", + "上", + "方", + "冖", + "学", + "衣", + "艮", + "食", + "自", + ], + # Jap-Katakana + "Japanese—": [ + "ー", + "ン", + "ス", + "・", + "ル", + "ト", + "リ", + "イ", + "ア", + "ラ", + "ッ", + "ク", + "ド", + "シ", + "レ", + "ジ", + "タ", + "フ", + "ロ", + "カ", + "テ", + "マ", + "ィ", + "グ", + "バ", + "ム", + "プ", + "オ", + "コ", + "デ", + "ニ", + "ウ", + "メ", + "サ", + "ビ", + "ナ", + "ブ", + "ャ", + "エ", + "ュ", + "チ", + "キ", + "ズ", + "ダ", + "パ", + "ミ", + "ェ", + "ョ", + "ハ", + "セ", + "ベ", + "ガ", + "モ", + "ツ", + "ネ", + "ボ", + "ソ", + "ノ", + "ァ", + "ヴ", + "ワ", + "ポ", + "ペ", + "ピ", + "ケ", + "ゴ", + "ギ", + "ザ", + "ホ", + "ゲ", + "ォ", + "ヤ", + "ヒ", + "ユ", + "ヨ", + "ヘ", + "ゼ", + "ヌ", + "ゥ", + "ゾ", + "ヶ", + "ヂ", + "ヲ", + "ヅ", + "ヵ", + "ヱ", + "ヰ", + "ヮ", + "ヽ", + "゠", + "ヾ", + "ヷ", + "ヿ", + "ヸ", + "ヹ", + "ヺ", + ], + # Jap-Hiragana + "Japanese——": [ + "の", + "に", + "る", + "た", + "と", + "は", + "し", + "い", + "を", + "で", + "て", + "が", + "な", + "れ", + "か", + "ら", + "さ", + "っ", + "り", + "す", + "あ", + "も", + "こ", + "ま", + "う", + "く", + "よ", + "き", + "ん", + "め", + "お", + "け", + "そ", + "つ", + "だ", + "や", + "え", + "ど", + "わ", + "ち", + "み", + "せ", + "じ", + "ば", + "へ", + "び", + "ず", + "ろ", + "ほ", + "げ", + "む", + "べ", + "ひ", + "ょ", + "ゆ", + "ぶ", + "ご", + "ゃ", + "ね", + "ふ", + "ぐ", + "ぎ", + "ぼ", + "ゅ", + "づ", + "ざ", + "ぞ", + "ぬ", + "ぜ", + "ぱ", + "ぽ", + "ぷ", + "ぴ", + "ぃ", + "ぁ", + "ぇ", + "ぺ", + "ゞ", + "ぢ", + "ぉ", + "ぅ", + "ゐ", + "ゝ", + "ゑ", + "゛", + "゜", + "ゎ", + "ゔ", + "゚", + "ゟ", + "゙", + "ゕ", + "ゖ", + ], + "Portuguese": [ + "a", + "e", + "o", + "s", + "i", + "r", + "d", + "n", + "t", + "m", + "u", + "c", + "l", + "p", + "g", + "v", + "b", + "f", + "h", + "ã", + "q", + "é", + "ç", + "á", + "z", + "í", + ], + "Swedish": [ + "e", + "a", + "n", + "r", + "t", + "s", + "i", + "l", + "d", + "o", + "m", + "k", + "g", + "v", + "h", + "f", + "u", + "p", + "ä", + "c", + "b", + "ö", + "å", + "y", + "j", + "x", + ], + "Chinese": [ + "的", + "一", + "是", + "不", + "了", + "在", + "人", + "有", + "我", + "他", + "这", + "个", + "们", + "中", + "来", + "上", + "大", + "为", + "和", + "国", + "地", + "到", + "以", + "说", + "时", + "要", + "就", + "出", + "会", + "可", + "也", + "你", + "对", + "生", + "能", + "而", + "子", + "那", + "得", + "于", + "着", + "下", + "自", + "之", + "年", + "过", + "发", + "后", + "作", + "里", + "用", + "道", + "行", + "所", + "然", + "家", + "种", + "事", + "成", + "方", + "多", + "经", + "么", + "去", + "法", + "学", + "如", + "都", + "同", + "现", + "当", + "没", + "动", + "面", + "起", + "看", + "定", + "天", + "分", + "还", + "进", + "好", + "小", + "部", + "其", + "些", + "主", + "样", + "理", + "心", + "她", + "本", + "前", + "开", + "但", + "因", + "只", + "从", + "想", + "实", + ], + "Ukrainian": [ + "о", + "а", + "н", + "і", + "и", + "р", + "в", + "т", + "е", + "с", + "к", + "л", + "у", + "д", + "м", + "п", + "з", + "я", + "ь", + "б", + "г", + "й", + "ч", + "х", + "ц", + "ї", + ], + "Norwegian": [ + "e", + "r", + "n", + "t", + "a", + "s", + "i", + "o", + "l", + "d", + "g", + "k", + "m", + "v", + "f", + "p", + "u", + "b", + "h", + "å", + "y", + "j", + "ø", + "c", + "æ", + "w", + ], + "Finnish": [ + "a", + "i", + "n", + "t", + "e", + "s", + "l", + "o", + "u", + "k", + "ä", + "m", + "r", + "v", + "j", + "h", + "p", + "y", + "d", + "ö", + "g", + "c", + "b", + "f", + "w", + "z", + ], + "Vietnamese": [ + "n", + "h", + "t", + "i", + "c", + "g", + "a", + "o", + "u", + "m", + "l", + "r", + "à", + "đ", + "s", + "e", + "v", + "p", + "b", + "y", + "ư", + "d", + "á", + "k", + "ộ", + "ế", + ], + "Czech": [ + "o", + "e", + "a", + "n", + "t", + "s", + "i", + "l", + "v", + "r", + "k", + "d", + "u", + "m", + "p", + "í", + "c", + "h", + "z", + "á", + "y", + "j", + "b", + "ě", + "é", + "ř", + ], + "Hungarian": [ + "e", + "a", + "t", + "l", + "s", + "n", + "k", + "r", + "i", + "o", + "z", + "á", + "é", + "g", + "m", + "b", + "y", + "v", + "d", + "h", + "u", + "p", + "j", + "ö", + "f", + "c", + ], + "Korean": [ + "이", + "다", + "에", + "의", + "는", + "로", + "하", + "을", + "가", + "고", + "지", + "서", + "한", + "은", + "기", + "으", + "년", + "대", + "사", + "시", + "를", + "리", + "도", + "인", + "스", + "일", + ], + "Indonesian": [ + "a", + "n", + "e", + "i", + "r", + "t", + "u", + "s", + "d", + "k", + "m", + "l", + "g", + "p", + "b", + "o", + "h", + "y", + "j", + "c", + "w", + "f", + "v", + "z", + "x", + "q", + ], + "Turkish": [ + "a", + "e", + "i", + "n", + "r", + "l", + "ı", + "k", + "d", + "t", + "s", + "m", + "y", + "u", + "o", + "b", + "ü", + "ş", + "v", + "g", + "z", + "h", + "c", + "p", + "ç", + "ğ", + ], + "Romanian": [ + "e", + "i", + "a", + "r", + "n", + "t", + "u", + "l", + "o", + "c", + "s", + "d", + "p", + "m", + "ă", + "f", + "v", + "î", + "g", + "b", + "ș", + "ț", + "z", + "h", + "â", + "j", + ], + "Farsi": [ + "ا", + "ی", + "ر", + "د", + "ن", + "ه", + "و", + "م", + "ت", + "ب", + "س", + "ل", + "ک", + "ش", + "ز", + "ف", + "گ", + "ع", + "خ", + "ق", + "ج", + "آ", + "پ", + "ح", + "ط", + "ص", + ], + "Arabic": [ + "ا", + "ل", + "ي", + "م", + "و", + "ن", + "ر", + "ت", + "ب", + "ة", + "ع", + "د", + "س", + "ف", + "ه", + "ك", + "ق", + "أ", + "ح", + "ج", + "ش", + "ط", + "ص", + "ى", + "خ", + "إ", + ], + "Danish": [ + "e", + "r", + "n", + "t", + "a", + "i", + "s", + "d", + "l", + "o", + "g", + "m", + "k", + "f", + "v", + "u", + "b", + "h", + "p", + "å", + "y", + "ø", + "æ", + "c", + "j", + "w", + ], + "Serbian": [ + "а", + "и", + "о", + "е", + "н", + "р", + "с", + "у", + "т", + "к", + "ј", + "в", + "д", + "м", + "п", + "л", + "г", + "з", + "б", + "a", + "i", + "e", + "o", + "n", + "ц", + "ш", + ], + "Lithuanian": [ + "i", + "a", + "s", + "o", + "r", + "e", + "t", + "n", + "u", + "k", + "m", + "l", + "p", + "v", + "d", + "j", + "g", + "ė", + "b", + "y", + "ų", + "š", + "ž", + "c", + "ą", + "į", + ], + "Slovene": [ + "e", + "a", + "i", + "o", + "n", + "r", + "s", + "l", + "t", + "j", + "v", + "k", + "d", + "p", + "m", + "u", + "z", + "b", + "g", + "h", + "č", + "c", + "š", + "ž", + "f", + "y", + ], + "Slovak": [ + "o", + "a", + "e", + "n", + "i", + "r", + "v", + "t", + "s", + "l", + "k", + "d", + "m", + "p", + "u", + "c", + "h", + "j", + "b", + "z", + "á", + "y", + "ý", + "í", + "č", + "é", + ], + "Hebrew": [ + "י", + "ו", + "ה", + "ל", + "ר", + "ב", + "ת", + "מ", + "א", + "ש", + "נ", + "ע", + "ם", + "ד", + "ק", + "ח", + "פ", + "ס", + "כ", + "ג", + "ט", + "צ", + "ן", + "ז", + "ך", + ], + "Bulgarian": [ + "а", + "и", + "о", + "е", + "н", + "т", + "р", + "с", + "в", + "л", + "к", + "д", + "п", + "м", + "з", + "г", + "я", + "ъ", + "у", + "б", + "ч", + "ц", + "й", + "ж", + "щ", + "х", + ], + "Croatian": [ + "a", + "i", + "o", + "e", + "n", + "r", + "j", + "s", + "t", + "u", + "k", + "l", + "v", + "d", + "m", + "p", + "g", + "z", + "b", + "c", + "č", + "h", + "š", + "ž", + "ć", + "f", + ], + "Hindi": [ + "क", + "र", + "स", + "न", + "त", + "म", + "ह", + "प", + "य", + "ल", + "व", + "ज", + "द", + "ग", + "ब", + "श", + "ट", + "अ", + "ए", + "थ", + "भ", + "ड", + "च", + "ध", + "ष", + "इ", + ], + "Estonian": [ + "a", + "i", + "e", + "s", + "t", + "l", + "u", + "n", + "o", + "k", + "r", + "d", + "m", + "v", + "g", + "p", + "j", + "h", + "ä", + "b", + "õ", + "ü", + "f", + "c", + "ö", + "y", + ], + "Thai": [ + "า", + "น", + "ร", + "อ", + "ก", + "เ", + "ง", + "ม", + "ย", + "ล", + "ว", + "ด", + "ท", + "ส", + "ต", + "ะ", + "ป", + "บ", + "ค", + "ห", + "แ", + "จ", + "พ", + "ช", + "ข", + "ใ", + ], + "Greek": [ + "α", + "τ", + "ο", + "ι", + "ε", + "ν", + "ρ", + "σ", + "κ", + "η", + "π", + "ς", + "υ", + "μ", + "λ", + "ί", + "ό", + "ά", + "γ", + "έ", + "δ", + "ή", + "ω", + "χ", + "θ", + "ύ", + ], + "Tamil": [ + "க", + "த", + "ப", + "ட", + "ர", + "ம", + "ல", + "ன", + "வ", + "ற", + "ய", + "ள", + "ச", + "ந", + "இ", + "ண", + "அ", + "ஆ", + "ழ", + "ங", + "எ", + "உ", + "ஒ", + "ஸ", + ], + "Kazakh": [ + "а", + "ы", + "е", + "н", + "т", + "р", + "л", + "і", + "д", + "с", + "м", + "қ", + "к", + "о", + "б", + "и", + "у", + "ғ", + "ж", + "ң", + "з", + "ш", + "й", + "п", + "г", + "ө", + ], +} + +LANGUAGE_SUPPORTED_COUNT: int = len(FREQUENCIES) diff --git a/venv/Lib/site-packages/charset_normalizer/legacy.py b/venv/Lib/site-packages/charset_normalizer/legacy.py new file mode 100644 index 00000000..e221beca --- /dev/null +++ b/venv/Lib/site-packages/charset_normalizer/legacy.py @@ -0,0 +1,64 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any +from warnings import warn + +from .api import from_bytes +from .constant import CHARDET_CORRESPONDENCE + +# TODO: remove this check when dropping Python 3.7 support +if TYPE_CHECKING: + from typing_extensions import TypedDict + + class ResultDict(TypedDict): + encoding: str | None + language: str + confidence: float | None + + +def detect( + byte_str: bytes, should_rename_legacy: bool = False, **kwargs: Any +) -> ResultDict: + """ + chardet legacy method + Detect the encoding of the given byte string. It should be mostly backward-compatible. + Encoding name will match Chardet own writing whenever possible. (Not on encoding name unsupported by it) + This function is deprecated and should be used to migrate your project easily, consult the documentation for + further information. Not planned for removal. + + :param byte_str: The byte sequence to examine. + :param should_rename_legacy: Should we rename legacy encodings + to their more modern equivalents? + """ + if len(kwargs): + warn( + f"charset-normalizer disregard arguments '{','.join(list(kwargs.keys()))}' in legacy function detect()" + ) + + if not isinstance(byte_str, (bytearray, bytes)): + raise TypeError( # pragma: nocover + f"Expected object of type bytes or bytearray, got: {type(byte_str)}" + ) + + if isinstance(byte_str, bytearray): + byte_str = bytes(byte_str) + + r = from_bytes(byte_str).best() + + encoding = r.encoding if r is not None else None + language = r.language if r is not None and r.language != "Unknown" else "" + confidence = 1.0 - r.chaos if r is not None else None + + # Note: CharsetNormalizer does not return 'UTF-8-SIG' as the sig get stripped in the detection/normalization process + # but chardet does return 'utf-8-sig' and it is a valid codec name. + if r is not None and encoding == "utf_8" and r.bom: + encoding += "_sig" + + if should_rename_legacy is False and encoding in CHARDET_CORRESPONDENCE: + encoding = CHARDET_CORRESPONDENCE[encoding] + + return { + "encoding": encoding, + "language": language, + "confidence": confidence, + } diff --git a/venv/Lib/site-packages/charset_normalizer/md.cp312-win_amd64.pyd b/venv/Lib/site-packages/charset_normalizer/md.cp312-win_amd64.pyd new file mode 100644 index 00000000..4c6c2cf5 Binary files /dev/null and b/venv/Lib/site-packages/charset_normalizer/md.cp312-win_amd64.pyd differ diff --git a/venv/Lib/site-packages/charset_normalizer/md.py b/venv/Lib/site-packages/charset_normalizer/md.py new file mode 100644 index 00000000..12ce024b --- /dev/null +++ b/venv/Lib/site-packages/charset_normalizer/md.py @@ -0,0 +1,635 @@ +from __future__ import annotations + +from functools import lru_cache +from logging import getLogger + +from .constant import ( + COMMON_SAFE_ASCII_CHARACTERS, + TRACE, + UNICODE_SECONDARY_RANGE_KEYWORD, +) +from .utils import ( + is_accentuated, + is_arabic, + is_arabic_isolated_form, + is_case_variable, + is_cjk, + is_emoticon, + is_hangul, + is_hiragana, + is_katakana, + is_latin, + is_punctuation, + is_separator, + is_symbol, + is_thai, + is_unprintable, + remove_accent, + unicode_range, + is_cjk_uncommon, +) + + +class MessDetectorPlugin: + """ + Base abstract class used for mess detection plugins. + All detectors MUST extend and implement given methods. + """ + + def eligible(self, character: str) -> bool: + """ + Determine if given character should be fed in. + """ + raise NotImplementedError # pragma: nocover + + def feed(self, character: str) -> None: + """ + The main routine to be executed upon character. + Insert the logic in witch the text would be considered chaotic. + """ + raise NotImplementedError # pragma: nocover + + def reset(self) -> None: # pragma: no cover + """ + Permit to reset the plugin to the initial state. + """ + raise NotImplementedError + + @property + def ratio(self) -> float: + """ + Compute the chaos ratio based on what your feed() has seen. + Must NOT be lower than 0.; No restriction gt 0. + """ + raise NotImplementedError # pragma: nocover + + +class TooManySymbolOrPunctuationPlugin(MessDetectorPlugin): + def __init__(self) -> None: + self._punctuation_count: int = 0 + self._symbol_count: int = 0 + self._character_count: int = 0 + + self._last_printable_char: str | None = None + self._frenzy_symbol_in_word: bool = False + + def eligible(self, character: str) -> bool: + return character.isprintable() + + def feed(self, character: str) -> None: + self._character_count += 1 + + if ( + character != self._last_printable_char + and character not in COMMON_SAFE_ASCII_CHARACTERS + ): + if is_punctuation(character): + self._punctuation_count += 1 + elif ( + character.isdigit() is False + and is_symbol(character) + and is_emoticon(character) is False + ): + self._symbol_count += 2 + + self._last_printable_char = character + + def reset(self) -> None: # Abstract + self._punctuation_count = 0 + self._character_count = 0 + self._symbol_count = 0 + + @property + def ratio(self) -> float: + if self._character_count == 0: + return 0.0 + + ratio_of_punctuation: float = ( + self._punctuation_count + self._symbol_count + ) / self._character_count + + return ratio_of_punctuation if ratio_of_punctuation >= 0.3 else 0.0 + + +class TooManyAccentuatedPlugin(MessDetectorPlugin): + def __init__(self) -> None: + self._character_count: int = 0 + self._accentuated_count: int = 0 + + def eligible(self, character: str) -> bool: + return character.isalpha() + + def feed(self, character: str) -> None: + self._character_count += 1 + + if is_accentuated(character): + self._accentuated_count += 1 + + def reset(self) -> None: # Abstract + self._character_count = 0 + self._accentuated_count = 0 + + @property + def ratio(self) -> float: + if self._character_count < 8: + return 0.0 + + ratio_of_accentuation: float = self._accentuated_count / self._character_count + return ratio_of_accentuation if ratio_of_accentuation >= 0.35 else 0.0 + + +class UnprintablePlugin(MessDetectorPlugin): + def __init__(self) -> None: + self._unprintable_count: int = 0 + self._character_count: int = 0 + + def eligible(self, character: str) -> bool: + return True + + def feed(self, character: str) -> None: + if is_unprintable(character): + self._unprintable_count += 1 + self._character_count += 1 + + def reset(self) -> None: # Abstract + self._unprintable_count = 0 + + @property + def ratio(self) -> float: + if self._character_count == 0: + return 0.0 + + return (self._unprintable_count * 8) / self._character_count + + +class SuspiciousDuplicateAccentPlugin(MessDetectorPlugin): + def __init__(self) -> None: + self._successive_count: int = 0 + self._character_count: int = 0 + + self._last_latin_character: str | None = None + + def eligible(self, character: str) -> bool: + return character.isalpha() and is_latin(character) + + def feed(self, character: str) -> None: + self._character_count += 1 + if ( + self._last_latin_character is not None + and is_accentuated(character) + and is_accentuated(self._last_latin_character) + ): + if character.isupper() and self._last_latin_character.isupper(): + self._successive_count += 1 + # Worse if its the same char duplicated with different accent. + if remove_accent(character) == remove_accent(self._last_latin_character): + self._successive_count += 1 + self._last_latin_character = character + + def reset(self) -> None: # Abstract + self._successive_count = 0 + self._character_count = 0 + self._last_latin_character = None + + @property + def ratio(self) -> float: + if self._character_count == 0: + return 0.0 + + return (self._successive_count * 2) / self._character_count + + +class SuspiciousRange(MessDetectorPlugin): + def __init__(self) -> None: + self._suspicious_successive_range_count: int = 0 + self._character_count: int = 0 + self._last_printable_seen: str | None = None + + def eligible(self, character: str) -> bool: + return character.isprintable() + + def feed(self, character: str) -> None: + self._character_count += 1 + + if ( + character.isspace() + or is_punctuation(character) + or character in COMMON_SAFE_ASCII_CHARACTERS + ): + self._last_printable_seen = None + return + + if self._last_printable_seen is None: + self._last_printable_seen = character + return + + unicode_range_a: str | None = unicode_range(self._last_printable_seen) + unicode_range_b: str | None = unicode_range(character) + + if is_suspiciously_successive_range(unicode_range_a, unicode_range_b): + self._suspicious_successive_range_count += 1 + + self._last_printable_seen = character + + def reset(self) -> None: # Abstract + self._character_count = 0 + self._suspicious_successive_range_count = 0 + self._last_printable_seen = None + + @property + def ratio(self) -> float: + if self._character_count <= 13: + return 0.0 + + ratio_of_suspicious_range_usage: float = ( + self._suspicious_successive_range_count * 2 + ) / self._character_count + + return ratio_of_suspicious_range_usage + + +class SuperWeirdWordPlugin(MessDetectorPlugin): + def __init__(self) -> None: + self._word_count: int = 0 + self._bad_word_count: int = 0 + self._foreign_long_count: int = 0 + + self._is_current_word_bad: bool = False + self._foreign_long_watch: bool = False + + self._character_count: int = 0 + self._bad_character_count: int = 0 + + self._buffer: str = "" + self._buffer_accent_count: int = 0 + self._buffer_glyph_count: int = 0 + + def eligible(self, character: str) -> bool: + return True + + def feed(self, character: str) -> None: + if character.isalpha(): + self._buffer += character + if is_accentuated(character): + self._buffer_accent_count += 1 + if ( + self._foreign_long_watch is False + and (is_latin(character) is False or is_accentuated(character)) + and is_cjk(character) is False + and is_hangul(character) is False + and is_katakana(character) is False + and is_hiragana(character) is False + and is_thai(character) is False + ): + self._foreign_long_watch = True + if ( + is_cjk(character) + or is_hangul(character) + or is_katakana(character) + or is_hiragana(character) + or is_thai(character) + ): + self._buffer_glyph_count += 1 + return + if not self._buffer: + return + if ( + character.isspace() or is_punctuation(character) or is_separator(character) + ) and self._buffer: + self._word_count += 1 + buffer_length: int = len(self._buffer) + + self._character_count += buffer_length + + if buffer_length >= 4: + if self._buffer_accent_count / buffer_length >= 0.5: + self._is_current_word_bad = True + # Word/Buffer ending with an upper case accentuated letter are so rare, + # that we will consider them all as suspicious. Same weight as foreign_long suspicious. + elif ( + is_accentuated(self._buffer[-1]) + and self._buffer[-1].isupper() + and all(_.isupper() for _ in self._buffer) is False + ): + self._foreign_long_count += 1 + self._is_current_word_bad = True + elif self._buffer_glyph_count == 1: + self._is_current_word_bad = True + self._foreign_long_count += 1 + if buffer_length >= 24 and self._foreign_long_watch: + camel_case_dst = [ + i + for c, i in zip(self._buffer, range(0, buffer_length)) + if c.isupper() + ] + probable_camel_cased: bool = False + + if camel_case_dst and (len(camel_case_dst) / buffer_length <= 0.3): + probable_camel_cased = True + + if not probable_camel_cased: + self._foreign_long_count += 1 + self._is_current_word_bad = True + + if self._is_current_word_bad: + self._bad_word_count += 1 + self._bad_character_count += len(self._buffer) + self._is_current_word_bad = False + + self._foreign_long_watch = False + self._buffer = "" + self._buffer_accent_count = 0 + self._buffer_glyph_count = 0 + elif ( + character not in {"<", ">", "-", "=", "~", "|", "_"} + and character.isdigit() is False + and is_symbol(character) + ): + self._is_current_word_bad = True + self._buffer += character + + def reset(self) -> None: # Abstract + self._buffer = "" + self._is_current_word_bad = False + self._foreign_long_watch = False + self._bad_word_count = 0 + self._word_count = 0 + self._character_count = 0 + self._bad_character_count = 0 + self._foreign_long_count = 0 + + @property + def ratio(self) -> float: + if self._word_count <= 10 and self._foreign_long_count == 0: + return 0.0 + + return self._bad_character_count / self._character_count + + +class CjkUncommonPlugin(MessDetectorPlugin): + """ + Detect messy CJK text that probably means nothing. + """ + + def __init__(self) -> None: + self._character_count: int = 0 + self._uncommon_count: int = 0 + + def eligible(self, character: str) -> bool: + return is_cjk(character) + + def feed(self, character: str) -> None: + self._character_count += 1 + + if is_cjk_uncommon(character): + self._uncommon_count += 1 + return + + def reset(self) -> None: # Abstract + self._character_count = 0 + self._uncommon_count = 0 + + @property + def ratio(self) -> float: + if self._character_count < 8: + return 0.0 + + uncommon_form_usage: float = self._uncommon_count / self._character_count + + # we can be pretty sure it's garbage when uncommon characters are widely + # used. otherwise it could just be traditional chinese for example. + return uncommon_form_usage / 10 if uncommon_form_usage > 0.5 else 0.0 + + +class ArchaicUpperLowerPlugin(MessDetectorPlugin): + def __init__(self) -> None: + self._buf: bool = False + + self._character_count_since_last_sep: int = 0 + + self._successive_upper_lower_count: int = 0 + self._successive_upper_lower_count_final: int = 0 + + self._character_count: int = 0 + + self._last_alpha_seen: str | None = None + self._current_ascii_only: bool = True + + def eligible(self, character: str) -> bool: + return True + + def feed(self, character: str) -> None: + is_concerned = character.isalpha() and is_case_variable(character) + chunk_sep = is_concerned is False + + if chunk_sep and self._character_count_since_last_sep > 0: + if ( + self._character_count_since_last_sep <= 64 + and character.isdigit() is False + and self._current_ascii_only is False + ): + self._successive_upper_lower_count_final += ( + self._successive_upper_lower_count + ) + + self._successive_upper_lower_count = 0 + self._character_count_since_last_sep = 0 + self._last_alpha_seen = None + self._buf = False + self._character_count += 1 + self._current_ascii_only = True + + return + + if self._current_ascii_only is True and character.isascii() is False: + self._current_ascii_only = False + + if self._last_alpha_seen is not None: + if (character.isupper() and self._last_alpha_seen.islower()) or ( + character.islower() and self._last_alpha_seen.isupper() + ): + if self._buf is True: + self._successive_upper_lower_count += 2 + self._buf = False + else: + self._buf = True + else: + self._buf = False + + self._character_count += 1 + self._character_count_since_last_sep += 1 + self._last_alpha_seen = character + + def reset(self) -> None: # Abstract + self._character_count = 0 + self._character_count_since_last_sep = 0 + self._successive_upper_lower_count = 0 + self._successive_upper_lower_count_final = 0 + self._last_alpha_seen = None + self._buf = False + self._current_ascii_only = True + + @property + def ratio(self) -> float: + if self._character_count == 0: + return 0.0 + + return self._successive_upper_lower_count_final / self._character_count + + +class ArabicIsolatedFormPlugin(MessDetectorPlugin): + def __init__(self) -> None: + self._character_count: int = 0 + self._isolated_form_count: int = 0 + + def reset(self) -> None: # Abstract + self._character_count = 0 + self._isolated_form_count = 0 + + def eligible(self, character: str) -> bool: + return is_arabic(character) + + def feed(self, character: str) -> None: + self._character_count += 1 + + if is_arabic_isolated_form(character): + self._isolated_form_count += 1 + + @property + def ratio(self) -> float: + if self._character_count < 8: + return 0.0 + + isolated_form_usage: float = self._isolated_form_count / self._character_count + + return isolated_form_usage + + +@lru_cache(maxsize=1024) +def is_suspiciously_successive_range( + unicode_range_a: str | None, unicode_range_b: str | None +) -> bool: + """ + Determine if two Unicode range seen next to each other can be considered as suspicious. + """ + if unicode_range_a is None or unicode_range_b is None: + return True + + if unicode_range_a == unicode_range_b: + return False + + if "Latin" in unicode_range_a and "Latin" in unicode_range_b: + return False + + if "Emoticons" in unicode_range_a or "Emoticons" in unicode_range_b: + return False + + # Latin characters can be accompanied with a combining diacritical mark + # eg. Vietnamese. + if ("Latin" in unicode_range_a or "Latin" in unicode_range_b) and ( + "Combining" in unicode_range_a or "Combining" in unicode_range_b + ): + return False + + keywords_range_a, keywords_range_b = ( + unicode_range_a.split(" "), + unicode_range_b.split(" "), + ) + + for el in keywords_range_a: + if el in UNICODE_SECONDARY_RANGE_KEYWORD: + continue + if el in keywords_range_b: + return False + + # Japanese Exception + range_a_jp_chars, range_b_jp_chars = ( + unicode_range_a + in ( + "Hiragana", + "Katakana", + ), + unicode_range_b in ("Hiragana", "Katakana"), + ) + if (range_a_jp_chars or range_b_jp_chars) and ( + "CJK" in unicode_range_a or "CJK" in unicode_range_b + ): + return False + if range_a_jp_chars and range_b_jp_chars: + return False + + if "Hangul" in unicode_range_a or "Hangul" in unicode_range_b: + if "CJK" in unicode_range_a or "CJK" in unicode_range_b: + return False + if unicode_range_a == "Basic Latin" or unicode_range_b == "Basic Latin": + return False + + # Chinese/Japanese use dedicated range for punctuation and/or separators. + if ("CJK" in unicode_range_a or "CJK" in unicode_range_b) or ( + unicode_range_a in ["Katakana", "Hiragana"] + and unicode_range_b in ["Katakana", "Hiragana"] + ): + if "Punctuation" in unicode_range_a or "Punctuation" in unicode_range_b: + return False + if "Forms" in unicode_range_a or "Forms" in unicode_range_b: + return False + if unicode_range_a == "Basic Latin" or unicode_range_b == "Basic Latin": + return False + + return True + + +@lru_cache(maxsize=2048) +def mess_ratio( + decoded_sequence: str, maximum_threshold: float = 0.2, debug: bool = False +) -> float: + """ + Compute a mess ratio given a decoded bytes sequence. The maximum threshold does stop the computation earlier. + """ + + detectors: list[MessDetectorPlugin] = [ + md_class() for md_class in MessDetectorPlugin.__subclasses__() + ] + + length: int = len(decoded_sequence) + 1 + + mean_mess_ratio: float = 0.0 + + if length < 512: + intermediary_mean_mess_ratio_calc: int = 32 + elif length <= 1024: + intermediary_mean_mess_ratio_calc = 64 + else: + intermediary_mean_mess_ratio_calc = 128 + + for character, index in zip(decoded_sequence + "\n", range(length)): + for detector in detectors: + if detector.eligible(character): + detector.feed(character) + + if ( + index > 0 and index % intermediary_mean_mess_ratio_calc == 0 + ) or index == length - 1: + mean_mess_ratio = sum(dt.ratio for dt in detectors) + + if mean_mess_ratio >= maximum_threshold: + break + + if debug: + logger = getLogger("charset_normalizer") + + logger.log( + TRACE, + "Mess-detector extended-analysis start. " + f"intermediary_mean_mess_ratio_calc={intermediary_mean_mess_ratio_calc} mean_mess_ratio={mean_mess_ratio} " + f"maximum_threshold={maximum_threshold}", + ) + + if len(decoded_sequence) > 16: + logger.log(TRACE, f"Starting with: {decoded_sequence[:16]}") + logger.log(TRACE, f"Ending with: {decoded_sequence[-16::]}") + + for dt in detectors: + logger.log(TRACE, f"{dt.__class__}: {dt.ratio}") + + return round(mean_mess_ratio, 3) diff --git a/venv/Lib/site-packages/charset_normalizer/md__mypyc.cp312-win_amd64.pyd b/venv/Lib/site-packages/charset_normalizer/md__mypyc.cp312-win_amd64.pyd new file mode 100644 index 00000000..18e8e829 Binary files /dev/null and b/venv/Lib/site-packages/charset_normalizer/md__mypyc.cp312-win_amd64.pyd differ diff --git a/venv/Lib/site-packages/charset_normalizer/models.py b/venv/Lib/site-packages/charset_normalizer/models.py new file mode 100644 index 00000000..1042758f --- /dev/null +++ b/venv/Lib/site-packages/charset_normalizer/models.py @@ -0,0 +1,360 @@ +from __future__ import annotations + +from encodings.aliases import aliases +from hashlib import sha256 +from json import dumps +from re import sub +from typing import Any, Iterator, List, Tuple + +from .constant import RE_POSSIBLE_ENCODING_INDICATION, TOO_BIG_SEQUENCE +from .utils import iana_name, is_multi_byte_encoding, unicode_range + + +class CharsetMatch: + def __init__( + self, + payload: bytes, + guessed_encoding: str, + mean_mess_ratio: float, + has_sig_or_bom: bool, + languages: CoherenceMatches, + decoded_payload: str | None = None, + preemptive_declaration: str | None = None, + ): + self._payload: bytes = payload + + self._encoding: str = guessed_encoding + self._mean_mess_ratio: float = mean_mess_ratio + self._languages: CoherenceMatches = languages + self._has_sig_or_bom: bool = has_sig_or_bom + self._unicode_ranges: list[str] | None = None + + self._leaves: list[CharsetMatch] = [] + self._mean_coherence_ratio: float = 0.0 + + self._output_payload: bytes | None = None + self._output_encoding: str | None = None + + self._string: str | None = decoded_payload + + self._preemptive_declaration: str | None = preemptive_declaration + + def __eq__(self, other: object) -> bool: + if not isinstance(other, CharsetMatch): + if isinstance(other, str): + return iana_name(other) == self.encoding + return False + return self.encoding == other.encoding and self.fingerprint == other.fingerprint + + def __lt__(self, other: object) -> bool: + """ + Implemented to make sorted available upon CharsetMatches items. + """ + if not isinstance(other, CharsetMatch): + raise ValueError + + chaos_difference: float = abs(self.chaos - other.chaos) + coherence_difference: float = abs(self.coherence - other.coherence) + + # Below 1% difference --> Use Coherence + if chaos_difference < 0.01 and coherence_difference > 0.02: + return self.coherence > other.coherence + elif chaos_difference < 0.01 and coherence_difference <= 0.02: + # When having a difficult decision, use the result that decoded as many multi-byte as possible. + # preserve RAM usage! + if len(self._payload) >= TOO_BIG_SEQUENCE: + return self.chaos < other.chaos + return self.multi_byte_usage > other.multi_byte_usage + + return self.chaos < other.chaos + + @property + def multi_byte_usage(self) -> float: + return 1.0 - (len(str(self)) / len(self.raw)) + + def __str__(self) -> str: + # Lazy Str Loading + if self._string is None: + self._string = str(self._payload, self._encoding, "strict") + return self._string + + def __repr__(self) -> str: + return f"" + + def add_submatch(self, other: CharsetMatch) -> None: + if not isinstance(other, CharsetMatch) or other == self: + raise ValueError( + "Unable to add instance <{}> as a submatch of a CharsetMatch".format( + other.__class__ + ) + ) + + other._string = None # Unload RAM usage; dirty trick. + self._leaves.append(other) + + @property + def encoding(self) -> str: + return self._encoding + + @property + def encoding_aliases(self) -> list[str]: + """ + Encoding name are known by many name, using this could help when searching for IBM855 when it's listed as CP855. + """ + also_known_as: list[str] = [] + for u, p in aliases.items(): + if self.encoding == u: + also_known_as.append(p) + elif self.encoding == p: + also_known_as.append(u) + return also_known_as + + @property + def bom(self) -> bool: + return self._has_sig_or_bom + + @property + def byte_order_mark(self) -> bool: + return self._has_sig_or_bom + + @property + def languages(self) -> list[str]: + """ + Return the complete list of possible languages found in decoded sequence. + Usually not really useful. Returned list may be empty even if 'language' property return something != 'Unknown'. + """ + return [e[0] for e in self._languages] + + @property + def language(self) -> str: + """ + Most probable language found in decoded sequence. If none were detected or inferred, the property will return + "Unknown". + """ + if not self._languages: + # Trying to infer the language based on the given encoding + # Its either English or we should not pronounce ourselves in certain cases. + if "ascii" in self.could_be_from_charset: + return "English" + + # doing it there to avoid circular import + from charset_normalizer.cd import encoding_languages, mb_encoding_languages + + languages = ( + mb_encoding_languages(self.encoding) + if is_multi_byte_encoding(self.encoding) + else encoding_languages(self.encoding) + ) + + if len(languages) == 0 or "Latin Based" in languages: + return "Unknown" + + return languages[0] + + return self._languages[0][0] + + @property + def chaos(self) -> float: + return self._mean_mess_ratio + + @property + def coherence(self) -> float: + if not self._languages: + return 0.0 + return self._languages[0][1] + + @property + def percent_chaos(self) -> float: + return round(self.chaos * 100, ndigits=3) + + @property + def percent_coherence(self) -> float: + return round(self.coherence * 100, ndigits=3) + + @property + def raw(self) -> bytes: + """ + Original untouched bytes. + """ + return self._payload + + @property + def submatch(self) -> list[CharsetMatch]: + return self._leaves + + @property + def has_submatch(self) -> bool: + return len(self._leaves) > 0 + + @property + def alphabets(self) -> list[str]: + if self._unicode_ranges is not None: + return self._unicode_ranges + # list detected ranges + detected_ranges: list[str | None] = [unicode_range(char) for char in str(self)] + # filter and sort + self._unicode_ranges = sorted(list({r for r in detected_ranges if r})) + return self._unicode_ranges + + @property + def could_be_from_charset(self) -> list[str]: + """ + The complete list of encoding that output the exact SAME str result and therefore could be the originating + encoding. + This list does include the encoding available in property 'encoding'. + """ + return [self._encoding] + [m.encoding for m in self._leaves] + + def output(self, encoding: str = "utf_8") -> bytes: + """ + Method to get re-encoded bytes payload using given target encoding. Default to UTF-8. + Any errors will be simply ignored by the encoder NOT replaced. + """ + if self._output_encoding is None or self._output_encoding != encoding: + self._output_encoding = encoding + decoded_string = str(self) + if ( + self._preemptive_declaration is not None + and self._preemptive_declaration.lower() + not in ["utf-8", "utf8", "utf_8"] + ): + patched_header = sub( + RE_POSSIBLE_ENCODING_INDICATION, + lambda m: m.string[m.span()[0] : m.span()[1]].replace( + m.groups()[0], + iana_name(self._output_encoding).replace("_", "-"), # type: ignore[arg-type] + ), + decoded_string[:8192], + count=1, + ) + + decoded_string = patched_header + decoded_string[8192:] + + self._output_payload = decoded_string.encode(encoding, "replace") + + return self._output_payload # type: ignore + + @property + def fingerprint(self) -> str: + """ + Retrieve the unique SHA256 computed using the transformed (re-encoded) payload. Not the original one. + """ + return sha256(self.output()).hexdigest() + + +class CharsetMatches: + """ + Container with every CharsetMatch items ordered by default from most probable to the less one. + Act like a list(iterable) but does not implements all related methods. + """ + + def __init__(self, results: list[CharsetMatch] | None = None): + self._results: list[CharsetMatch] = sorted(results) if results else [] + + def __iter__(self) -> Iterator[CharsetMatch]: + yield from self._results + + def __getitem__(self, item: int | str) -> CharsetMatch: + """ + Retrieve a single item either by its position or encoding name (alias may be used here). + Raise KeyError upon invalid index or encoding not present in results. + """ + if isinstance(item, int): + return self._results[item] + if isinstance(item, str): + item = iana_name(item, False) + for result in self._results: + if item in result.could_be_from_charset: + return result + raise KeyError + + def __len__(self) -> int: + return len(self._results) + + def __bool__(self) -> bool: + return len(self._results) > 0 + + def append(self, item: CharsetMatch) -> None: + """ + Insert a single match. Will be inserted accordingly to preserve sort. + Can be inserted as a submatch. + """ + if not isinstance(item, CharsetMatch): + raise ValueError( + "Cannot append instance '{}' to CharsetMatches".format( + str(item.__class__) + ) + ) + # We should disable the submatch factoring when the input file is too heavy (conserve RAM usage) + if len(item.raw) < TOO_BIG_SEQUENCE: + for match in self._results: + if match.fingerprint == item.fingerprint and match.chaos == item.chaos: + match.add_submatch(item) + return + self._results.append(item) + self._results = sorted(self._results) + + def best(self) -> CharsetMatch | None: + """ + Simply return the first match. Strict equivalent to matches[0]. + """ + if not self._results: + return None + return self._results[0] + + def first(self) -> CharsetMatch | None: + """ + Redundant method, call the method best(). Kept for BC reasons. + """ + return self.best() + + +CoherenceMatch = Tuple[str, float] +CoherenceMatches = List[CoherenceMatch] + + +class CliDetectionResult: + def __init__( + self, + path: str, + encoding: str | None, + encoding_aliases: list[str], + alternative_encodings: list[str], + language: str, + alphabets: list[str], + has_sig_or_bom: bool, + chaos: float, + coherence: float, + unicode_path: str | None, + is_preferred: bool, + ): + self.path: str = path + self.unicode_path: str | None = unicode_path + self.encoding: str | None = encoding + self.encoding_aliases: list[str] = encoding_aliases + self.alternative_encodings: list[str] = alternative_encodings + self.language: str = language + self.alphabets: list[str] = alphabets + self.has_sig_or_bom: bool = has_sig_or_bom + self.chaos: float = chaos + self.coherence: float = coherence + self.is_preferred: bool = is_preferred + + @property + def __dict__(self) -> dict[str, Any]: # type: ignore + return { + "path": self.path, + "encoding": self.encoding, + "encoding_aliases": self.encoding_aliases, + "alternative_encodings": self.alternative_encodings, + "language": self.language, + "alphabets": self.alphabets, + "has_sig_or_bom": self.has_sig_or_bom, + "chaos": self.chaos, + "coherence": self.coherence, + "unicode_path": self.unicode_path, + "is_preferred": self.is_preferred, + } + + def to_json(self) -> str: + return dumps(self.__dict__, ensure_ascii=True, indent=4) diff --git a/venv/Lib/site-packages/charset_normalizer/py.typed b/venv/Lib/site-packages/charset_normalizer/py.typed new file mode 100644 index 00000000..e69de29b diff --git a/venv/Lib/site-packages/charset_normalizer/utils.py b/venv/Lib/site-packages/charset_normalizer/utils.py new file mode 100644 index 00000000..6bf0384c --- /dev/null +++ b/venv/Lib/site-packages/charset_normalizer/utils.py @@ -0,0 +1,414 @@ +from __future__ import annotations + +import importlib +import logging +import unicodedata +from codecs import IncrementalDecoder +from encodings.aliases import aliases +from functools import lru_cache +from re import findall +from typing import Generator + +from _multibytecodec import ( # type: ignore[import-not-found,import] + MultibyteIncrementalDecoder, +) + +from .constant import ( + ENCODING_MARKS, + IANA_SUPPORTED_SIMILAR, + RE_POSSIBLE_ENCODING_INDICATION, + UNICODE_RANGES_COMBINED, + UNICODE_SECONDARY_RANGE_KEYWORD, + UTF8_MAXIMAL_ALLOCATION, + COMMON_CJK_CHARACTERS, +) + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_accentuated(character: str) -> bool: + try: + description: str = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + return ( + "WITH GRAVE" in description + or "WITH ACUTE" in description + or "WITH CEDILLA" in description + or "WITH DIAERESIS" in description + or "WITH CIRCUMFLEX" in description + or "WITH TILDE" in description + or "WITH MACRON" in description + or "WITH RING ABOVE" in description + ) + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def remove_accent(character: str) -> str: + decomposed: str = unicodedata.decomposition(character) + if not decomposed: + return character + + codes: list[str] = decomposed.split(" ") + + return chr(int(codes[0], 16)) + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def unicode_range(character: str) -> str | None: + """ + Retrieve the Unicode range official name from a single character. + """ + character_ord: int = ord(character) + + for range_name, ord_range in UNICODE_RANGES_COMBINED.items(): + if character_ord in ord_range: + return range_name + + return None + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_latin(character: str) -> bool: + try: + description: str = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + return "LATIN" in description + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_punctuation(character: str) -> bool: + character_category: str = unicodedata.category(character) + + if "P" in character_category: + return True + + character_range: str | None = unicode_range(character) + + if character_range is None: + return False + + return "Punctuation" in character_range + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_symbol(character: str) -> bool: + character_category: str = unicodedata.category(character) + + if "S" in character_category or "N" in character_category: + return True + + character_range: str | None = unicode_range(character) + + if character_range is None: + return False + + return "Forms" in character_range and character_category != "Lo" + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_emoticon(character: str) -> bool: + character_range: str | None = unicode_range(character) + + if character_range is None: + return False + + return "Emoticons" in character_range or "Pictographs" in character_range + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_separator(character: str) -> bool: + if character.isspace() or character in {"|", "+", "<", ">"}: + return True + + character_category: str = unicodedata.category(character) + + return "Z" in character_category or character_category in {"Po", "Pd", "Pc"} + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_case_variable(character: str) -> bool: + return character.islower() != character.isupper() + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_cjk(character: str) -> bool: + try: + character_name = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + + return "CJK" in character_name + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_hiragana(character: str) -> bool: + try: + character_name = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + + return "HIRAGANA" in character_name + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_katakana(character: str) -> bool: + try: + character_name = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + + return "KATAKANA" in character_name + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_hangul(character: str) -> bool: + try: + character_name = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + + return "HANGUL" in character_name + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_thai(character: str) -> bool: + try: + character_name = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + + return "THAI" in character_name + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_arabic(character: str) -> bool: + try: + character_name = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + + return "ARABIC" in character_name + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_arabic_isolated_form(character: str) -> bool: + try: + character_name = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + + return "ARABIC" in character_name and "ISOLATED FORM" in character_name + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_cjk_uncommon(character: str) -> bool: + return character not in COMMON_CJK_CHARACTERS + + +@lru_cache(maxsize=len(UNICODE_RANGES_COMBINED)) +def is_unicode_range_secondary(range_name: str) -> bool: + return any(keyword in range_name for keyword in UNICODE_SECONDARY_RANGE_KEYWORD) + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_unprintable(character: str) -> bool: + return ( + character.isspace() is False # includes \n \t \r \v + and character.isprintable() is False + and character != "\x1a" # Why? Its the ASCII substitute character. + and character != "\ufeff" # bug discovered in Python, + # Zero Width No-Break Space located in Arabic Presentation Forms-B, Unicode 1.1 not acknowledged as space. + ) + + +def any_specified_encoding(sequence: bytes, search_zone: int = 8192) -> str | None: + """ + Extract using ASCII-only decoder any specified encoding in the first n-bytes. + """ + if not isinstance(sequence, bytes): + raise TypeError + + seq_len: int = len(sequence) + + results: list[str] = findall( + RE_POSSIBLE_ENCODING_INDICATION, + sequence[: min(seq_len, search_zone)].decode("ascii", errors="ignore"), + ) + + if len(results) == 0: + return None + + for specified_encoding in results: + specified_encoding = specified_encoding.lower().replace("-", "_") + + encoding_alias: str + encoding_iana: str + + for encoding_alias, encoding_iana in aliases.items(): + if encoding_alias == specified_encoding: + return encoding_iana + if encoding_iana == specified_encoding: + return encoding_iana + + return None + + +@lru_cache(maxsize=128) +def is_multi_byte_encoding(name: str) -> bool: + """ + Verify is a specific encoding is a multi byte one based on it IANA name + """ + return name in { + "utf_8", + "utf_8_sig", + "utf_16", + "utf_16_be", + "utf_16_le", + "utf_32", + "utf_32_le", + "utf_32_be", + "utf_7", + } or issubclass( + importlib.import_module(f"encodings.{name}").IncrementalDecoder, + MultibyteIncrementalDecoder, + ) + + +def identify_sig_or_bom(sequence: bytes) -> tuple[str | None, bytes]: + """ + Identify and extract SIG/BOM in given sequence. + """ + + for iana_encoding in ENCODING_MARKS: + marks: bytes | list[bytes] = ENCODING_MARKS[iana_encoding] + + if isinstance(marks, bytes): + marks = [marks] + + for mark in marks: + if sequence.startswith(mark): + return iana_encoding, mark + + return None, b"" + + +def should_strip_sig_or_bom(iana_encoding: str) -> bool: + return iana_encoding not in {"utf_16", "utf_32"} + + +def iana_name(cp_name: str, strict: bool = True) -> str: + """Returns the Python normalized encoding name (Not the IANA official name).""" + cp_name = cp_name.lower().replace("-", "_") + + encoding_alias: str + encoding_iana: str + + for encoding_alias, encoding_iana in aliases.items(): + if cp_name in [encoding_alias, encoding_iana]: + return encoding_iana + + if strict: + raise ValueError(f"Unable to retrieve IANA for '{cp_name}'") + + return cp_name + + +def cp_similarity(iana_name_a: str, iana_name_b: str) -> float: + if is_multi_byte_encoding(iana_name_a) or is_multi_byte_encoding(iana_name_b): + return 0.0 + + decoder_a = importlib.import_module(f"encodings.{iana_name_a}").IncrementalDecoder + decoder_b = importlib.import_module(f"encodings.{iana_name_b}").IncrementalDecoder + + id_a: IncrementalDecoder = decoder_a(errors="ignore") + id_b: IncrementalDecoder = decoder_b(errors="ignore") + + character_match_count: int = 0 + + for i in range(255): + to_be_decoded: bytes = bytes([i]) + if id_a.decode(to_be_decoded) == id_b.decode(to_be_decoded): + character_match_count += 1 + + return character_match_count / 254 + + +def is_cp_similar(iana_name_a: str, iana_name_b: str) -> bool: + """ + Determine if two code page are at least 80% similar. IANA_SUPPORTED_SIMILAR dict was generated using + the function cp_similarity. + """ + return ( + iana_name_a in IANA_SUPPORTED_SIMILAR + and iana_name_b in IANA_SUPPORTED_SIMILAR[iana_name_a] + ) + + +def set_logging_handler( + name: str = "charset_normalizer", + level: int = logging.INFO, + format_string: str = "%(asctime)s | %(levelname)s | %(message)s", +) -> None: + logger = logging.getLogger(name) + logger.setLevel(level) + + handler = logging.StreamHandler() + handler.setFormatter(logging.Formatter(format_string)) + logger.addHandler(handler) + + +def cut_sequence_chunks( + sequences: bytes, + encoding_iana: str, + offsets: range, + chunk_size: int, + bom_or_sig_available: bool, + strip_sig_or_bom: bool, + sig_payload: bytes, + is_multi_byte_decoder: bool, + decoded_payload: str | None = None, +) -> Generator[str, None, None]: + if decoded_payload and is_multi_byte_decoder is False: + for i in offsets: + chunk = decoded_payload[i : i + chunk_size] + if not chunk: + break + yield chunk + else: + for i in offsets: + chunk_end = i + chunk_size + if chunk_end > len(sequences) + 8: + continue + + cut_sequence = sequences[i : i + chunk_size] + + if bom_or_sig_available and strip_sig_or_bom is False: + cut_sequence = sig_payload + cut_sequence + + chunk = cut_sequence.decode( + encoding_iana, + errors="ignore" if is_multi_byte_decoder else "strict", + ) + + # multi-byte bad cutting detector and adjustment + # not the cleanest way to perform that fix but clever enough for now. + if is_multi_byte_decoder and i > 0: + chunk_partial_size_chk: int = min(chunk_size, 16) + + if ( + decoded_payload + and chunk[:chunk_partial_size_chk] not in decoded_payload + ): + for j in range(i, i - 4, -1): + cut_sequence = sequences[j:chunk_end] + + if bom_or_sig_available and strip_sig_or_bom is False: + cut_sequence = sig_payload + cut_sequence + + chunk = cut_sequence.decode(encoding_iana, errors="ignore") + + if chunk[:chunk_partial_size_chk] in decoded_payload: + break + + yield chunk diff --git a/venv/Lib/site-packages/charset_normalizer/version.py b/venv/Lib/site-packages/charset_normalizer/version.py new file mode 100644 index 00000000..e5687e3c --- /dev/null +++ b/venv/Lib/site-packages/charset_normalizer/version.py @@ -0,0 +1,8 @@ +""" +Expose version +""" + +from __future__ import annotations + +__version__ = "3.4.2" +VERSION = __version__.split(".") diff --git a/venv/Lib/site-packages/click/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/click/__pycache__/__init__.cpython-312.pyc index 73ac6339..66d1f05e 100644 Binary files a/venv/Lib/site-packages/click/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/click/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/click/__pycache__/_compat.cpython-312.pyc b/venv/Lib/site-packages/click/__pycache__/_compat.cpython-312.pyc index 624c5ed6..62f68a6e 100644 Binary files a/venv/Lib/site-packages/click/__pycache__/_compat.cpython-312.pyc and b/venv/Lib/site-packages/click/__pycache__/_compat.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/click/__pycache__/_textwrap.cpython-312.pyc b/venv/Lib/site-packages/click/__pycache__/_textwrap.cpython-312.pyc index 4e5e79f7..90993e8b 100644 Binary files a/venv/Lib/site-packages/click/__pycache__/_textwrap.cpython-312.pyc and b/venv/Lib/site-packages/click/__pycache__/_textwrap.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/click/__pycache__/_winconsole.cpython-312.pyc b/venv/Lib/site-packages/click/__pycache__/_winconsole.cpython-312.pyc index 3858e750..5714d0b3 100644 Binary files a/venv/Lib/site-packages/click/__pycache__/_winconsole.cpython-312.pyc and b/venv/Lib/site-packages/click/__pycache__/_winconsole.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/click/__pycache__/core.cpython-312.pyc b/venv/Lib/site-packages/click/__pycache__/core.cpython-312.pyc index bbaed556..1467ac87 100644 Binary files a/venv/Lib/site-packages/click/__pycache__/core.cpython-312.pyc and b/venv/Lib/site-packages/click/__pycache__/core.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/click/__pycache__/decorators.cpython-312.pyc b/venv/Lib/site-packages/click/__pycache__/decorators.cpython-312.pyc index 7450607b..91e0de51 100644 Binary files a/venv/Lib/site-packages/click/__pycache__/decorators.cpython-312.pyc and b/venv/Lib/site-packages/click/__pycache__/decorators.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/click/__pycache__/exceptions.cpython-312.pyc b/venv/Lib/site-packages/click/__pycache__/exceptions.cpython-312.pyc index bb0d622c..7177efb7 100644 Binary files a/venv/Lib/site-packages/click/__pycache__/exceptions.cpython-312.pyc and b/venv/Lib/site-packages/click/__pycache__/exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/click/__pycache__/formatting.cpython-312.pyc b/venv/Lib/site-packages/click/__pycache__/formatting.cpython-312.pyc index ff876e71..747c62b6 100644 Binary files a/venv/Lib/site-packages/click/__pycache__/formatting.cpython-312.pyc and b/venv/Lib/site-packages/click/__pycache__/formatting.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/click/__pycache__/globals.cpython-312.pyc b/venv/Lib/site-packages/click/__pycache__/globals.cpython-312.pyc index 8d8b0755..f6aaa1c5 100644 Binary files a/venv/Lib/site-packages/click/__pycache__/globals.cpython-312.pyc and b/venv/Lib/site-packages/click/__pycache__/globals.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/click/__pycache__/parser.cpython-312.pyc b/venv/Lib/site-packages/click/__pycache__/parser.cpython-312.pyc index fbcb3c74..72f552ae 100644 Binary files a/venv/Lib/site-packages/click/__pycache__/parser.cpython-312.pyc and b/venv/Lib/site-packages/click/__pycache__/parser.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/click/__pycache__/termui.cpython-312.pyc b/venv/Lib/site-packages/click/__pycache__/termui.cpython-312.pyc index 327c2115..e2e1be3a 100644 Binary files a/venv/Lib/site-packages/click/__pycache__/termui.cpython-312.pyc and b/venv/Lib/site-packages/click/__pycache__/termui.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/click/__pycache__/types.cpython-312.pyc b/venv/Lib/site-packages/click/__pycache__/types.cpython-312.pyc index 654d3dae..ee471f24 100644 Binary files a/venv/Lib/site-packages/click/__pycache__/types.cpython-312.pyc and b/venv/Lib/site-packages/click/__pycache__/types.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/click/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/click/__pycache__/utils.cpython-312.pyc index e9131172..9ebd94c3 100644 Binary files a/venv/Lib/site-packages/click/__pycache__/utils.cpython-312.pyc and b/venv/Lib/site-packages/click/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/colorama/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/colorama/__pycache__/__init__.cpython-312.pyc index 8478e19f..fcc6c771 100644 Binary files a/venv/Lib/site-packages/colorama/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/colorama/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/colorama/__pycache__/ansi.cpython-312.pyc b/venv/Lib/site-packages/colorama/__pycache__/ansi.cpython-312.pyc index b573c1c6..fa53ca73 100644 Binary files a/venv/Lib/site-packages/colorama/__pycache__/ansi.cpython-312.pyc and b/venv/Lib/site-packages/colorama/__pycache__/ansi.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/colorama/__pycache__/ansitowin32.cpython-312.pyc b/venv/Lib/site-packages/colorama/__pycache__/ansitowin32.cpython-312.pyc index 0c21ed95..6d183455 100644 Binary files a/venv/Lib/site-packages/colorama/__pycache__/ansitowin32.cpython-312.pyc and b/venv/Lib/site-packages/colorama/__pycache__/ansitowin32.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/colorama/__pycache__/initialise.cpython-312.pyc b/venv/Lib/site-packages/colorama/__pycache__/initialise.cpython-312.pyc index f97c3eb0..c4e08019 100644 Binary files a/venv/Lib/site-packages/colorama/__pycache__/initialise.cpython-312.pyc and b/venv/Lib/site-packages/colorama/__pycache__/initialise.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/colorama/__pycache__/win32.cpython-312.pyc b/venv/Lib/site-packages/colorama/__pycache__/win32.cpython-312.pyc index 59f6216c..00a06f1a 100644 Binary files a/venv/Lib/site-packages/colorama/__pycache__/win32.cpython-312.pyc and b/venv/Lib/site-packages/colorama/__pycache__/win32.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/colorama/__pycache__/winterm.cpython-312.pyc b/venv/Lib/site-packages/colorama/__pycache__/winterm.cpython-312.pyc index ec2fdf1d..b0eeb50b 100644 Binary files a/venv/Lib/site-packages/colorama/__pycache__/winterm.cpython-312.pyc and b/venv/Lib/site-packages/colorama/__pycache__/winterm.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dataclasses_json/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/dataclasses_json/__pycache__/__init__.cpython-312.pyc index 0c4858f2..18f2ac8a 100644 Binary files a/venv/Lib/site-packages/dataclasses_json/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/dataclasses_json/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dataclasses_json/__pycache__/__version__.cpython-312.pyc b/venv/Lib/site-packages/dataclasses_json/__pycache__/__version__.cpython-312.pyc index 231d311f..ce431ac6 100644 Binary files a/venv/Lib/site-packages/dataclasses_json/__pycache__/__version__.cpython-312.pyc and b/venv/Lib/site-packages/dataclasses_json/__pycache__/__version__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dataclasses_json/__pycache__/api.cpython-312.pyc b/venv/Lib/site-packages/dataclasses_json/__pycache__/api.cpython-312.pyc index a66577a2..ccaa01be 100644 Binary files a/venv/Lib/site-packages/dataclasses_json/__pycache__/api.cpython-312.pyc and b/venv/Lib/site-packages/dataclasses_json/__pycache__/api.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dataclasses_json/__pycache__/cfg.cpython-312.pyc b/venv/Lib/site-packages/dataclasses_json/__pycache__/cfg.cpython-312.pyc index 4c2fb379..f5122505 100644 Binary files a/venv/Lib/site-packages/dataclasses_json/__pycache__/cfg.cpython-312.pyc and b/venv/Lib/site-packages/dataclasses_json/__pycache__/cfg.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dataclasses_json/__pycache__/core.cpython-312.pyc b/venv/Lib/site-packages/dataclasses_json/__pycache__/core.cpython-312.pyc index f41ecb60..ae86e135 100644 Binary files a/venv/Lib/site-packages/dataclasses_json/__pycache__/core.cpython-312.pyc and b/venv/Lib/site-packages/dataclasses_json/__pycache__/core.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dataclasses_json/__pycache__/mm.cpython-312.pyc b/venv/Lib/site-packages/dataclasses_json/__pycache__/mm.cpython-312.pyc index 30ff1584..018091ef 100644 Binary files a/venv/Lib/site-packages/dataclasses_json/__pycache__/mm.cpython-312.pyc and b/venv/Lib/site-packages/dataclasses_json/__pycache__/mm.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dataclasses_json/__pycache__/stringcase.cpython-312.pyc b/venv/Lib/site-packages/dataclasses_json/__pycache__/stringcase.cpython-312.pyc index 931afef9..155cc71e 100644 Binary files a/venv/Lib/site-packages/dataclasses_json/__pycache__/stringcase.cpython-312.pyc and b/venv/Lib/site-packages/dataclasses_json/__pycache__/stringcase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dataclasses_json/__pycache__/undefined.cpython-312.pyc b/venv/Lib/site-packages/dataclasses_json/__pycache__/undefined.cpython-312.pyc index 43272115..d0ddd732 100644 Binary files a/venv/Lib/site-packages/dataclasses_json/__pycache__/undefined.cpython-312.pyc and b/venv/Lib/site-packages/dataclasses_json/__pycache__/undefined.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dataclasses_json/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/dataclasses_json/__pycache__/utils.cpython-312.pyc index d3279aa2..85d2503b 100644 Binary files a/venv/Lib/site-packages/dataclasses_json/__pycache__/utils.cpython-312.pyc and b/venv/Lib/site-packages/dataclasses_json/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dateutil/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/dateutil/__pycache__/__init__.cpython-312.pyc index 63fdc1fa..0c11d8c4 100644 Binary files a/venv/Lib/site-packages/dateutil/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/dateutil/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dateutil/__pycache__/_common.cpython-312.pyc b/venv/Lib/site-packages/dateutil/__pycache__/_common.cpython-312.pyc index 1e9896a1..1c13816c 100644 Binary files a/venv/Lib/site-packages/dateutil/__pycache__/_common.cpython-312.pyc and b/venv/Lib/site-packages/dateutil/__pycache__/_common.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dateutil/__pycache__/_version.cpython-312.pyc b/venv/Lib/site-packages/dateutil/__pycache__/_version.cpython-312.pyc index e8460ca0..f1ef4ee2 100644 Binary files a/venv/Lib/site-packages/dateutil/__pycache__/_version.cpython-312.pyc and b/venv/Lib/site-packages/dateutil/__pycache__/_version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dateutil/__pycache__/relativedelta.cpython-312.pyc b/venv/Lib/site-packages/dateutil/__pycache__/relativedelta.cpython-312.pyc index f46a8f44..43103401 100644 Binary files a/venv/Lib/site-packages/dateutil/__pycache__/relativedelta.cpython-312.pyc and b/venv/Lib/site-packages/dateutil/__pycache__/relativedelta.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dateutil/parser/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/dateutil/parser/__pycache__/__init__.cpython-312.pyc index 93b0eb4e..1c57c58e 100644 Binary files a/venv/Lib/site-packages/dateutil/parser/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/dateutil/parser/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dateutil/parser/__pycache__/_parser.cpython-312.pyc b/venv/Lib/site-packages/dateutil/parser/__pycache__/_parser.cpython-312.pyc index 5467c5fc..acf1d571 100644 Binary files a/venv/Lib/site-packages/dateutil/parser/__pycache__/_parser.cpython-312.pyc and b/venv/Lib/site-packages/dateutil/parser/__pycache__/_parser.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dateutil/parser/__pycache__/isoparser.cpython-312.pyc b/venv/Lib/site-packages/dateutil/parser/__pycache__/isoparser.cpython-312.pyc index 5095dccb..330108e2 100644 Binary files a/venv/Lib/site-packages/dateutil/parser/__pycache__/isoparser.cpython-312.pyc and b/venv/Lib/site-packages/dateutil/parser/__pycache__/isoparser.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dateutil/tz/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/dateutil/tz/__pycache__/__init__.cpython-312.pyc index ff0bb38b..4148a5ed 100644 Binary files a/venv/Lib/site-packages/dateutil/tz/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/dateutil/tz/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dateutil/tz/__pycache__/_common.cpython-312.pyc b/venv/Lib/site-packages/dateutil/tz/__pycache__/_common.cpython-312.pyc index 3383c9d6..12bd7a23 100644 Binary files a/venv/Lib/site-packages/dateutil/tz/__pycache__/_common.cpython-312.pyc and b/venv/Lib/site-packages/dateutil/tz/__pycache__/_common.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dateutil/tz/__pycache__/_factories.cpython-312.pyc b/venv/Lib/site-packages/dateutil/tz/__pycache__/_factories.cpython-312.pyc index 5231c9c3..206a2455 100644 Binary files a/venv/Lib/site-packages/dateutil/tz/__pycache__/_factories.cpython-312.pyc and b/venv/Lib/site-packages/dateutil/tz/__pycache__/_factories.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dateutil/tz/__pycache__/tz.cpython-312.pyc b/venv/Lib/site-packages/dateutil/tz/__pycache__/tz.cpython-312.pyc index 3e1c061a..c9c887f5 100644 Binary files a/venv/Lib/site-packages/dateutil/tz/__pycache__/tz.cpython-312.pyc and b/venv/Lib/site-packages/dateutil/tz/__pycache__/tz.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dateutil/tz/__pycache__/win.cpython-312.pyc b/venv/Lib/site-packages/dateutil/tz/__pycache__/win.cpython-312.pyc index 376b8448..e58ab5c2 100644 Binary files a/venv/Lib/site-packages/dateutil/tz/__pycache__/win.cpython-312.pyc and b/venv/Lib/site-packages/dateutil/tz/__pycache__/win.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/deepgram/__init__.py b/venv/Lib/site-packages/deepgram/__init__.py index f564a53a..d8658897 100644 --- a/venv/Lib/site-packages/deepgram/__init__.py +++ b/venv/Lib/site-packages/deepgram/__init__.py @@ -1,381 +1,77 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT +from typing import Union +import re +from ._types import Options +from .keys import Keys +from .transcription import Transcription +from .projects import Projects +from .usage import Usage +from .billing import Billing +from .members import Members +from .scopes import Scopes +from .invitations import Invitations +from .extra import Extra +from .errors import DeepgramSetupError, DeepgramApiError -# version -__version__ = "v4.2.0" -# entry point for the deepgram python sdk -import logging -from .utils import VerboseLogger -from .utils import ( - NOTICE, - SPAM, - SUCCESS, - VERBOSE, - WARNING, - ERROR, - FATAL, - CRITICAL, - INFO, - DEBUG, - NOTSET, -) +def api_key_is_valid(api_key: str) -> bool: + pattern = r"^[a-f0-9]{40}$" + return re.match(pattern, api_key) is not None -from .client import Deepgram, DeepgramClient -from .client import DeepgramClientOptions, ClientOptionsFromEnv -from .client import ( - DeepgramError, - DeepgramTypeError, - DeepgramModuleError, - DeepgramApiError, - DeepgramUnknownApiError, -) -from .errors import DeepgramApiKeyError -# listen/read client -from .client import ListenRouter, ReadRouter, SpeakRouter, AgentRouter +class Deepgram: + def __init__(self, options: Union[str, Options]) -> None: + if not isinstance(options, (str, dict)): + raise DeepgramSetupError("`options` must be a dictionary or an API key string") -# common -from .client import ( - TextSource, - BufferSource, - StreamSource, - FileSource, - UrlSource, -) -from .client import BaseResponse -from .client import ( - Average, - Intent, - Intents, - IntentsInfo, - Segment, - SentimentInfo, - Sentiment, - Sentiments, - SummaryInfo, - Topic, - Topics, - TopicsInfo, -) -from .client import ( - ModelInfo, - Hit, - Search, -) -from .client import ( - OpenResponse, - CloseResponse, - UnhandledResponse, - ErrorResponse, -) + # Convert to dictionary if the api key was passed as a string + if isinstance(options, str): + options: Options = {"api_key": options} -# speect-to-text WS -from .client import LiveClient, AsyncLiveClient # backward compat -from .client import ListenWebSocketClient, AsyncListenWebSocketClient -from .client import LiveTranscriptionEvents -from .client import LiveOptions, ListenWebSocketOptions -from .client import ( - #### top level - LiveResultResponse, - ListenWSMetadataResponse, - SpeechStartedResponse, - UtteranceEndResponse, - #### common websocket response - # OpenResponse, - # CloseResponse, - # UnhandledResponse, - # ErrorResponse, - #### unique - ListenWSMetadata, - ListenWSAlternative, - ListenWSChannel, - ListenWSWord, -) + if "api_key" not in options: + raise DeepgramSetupError("API key is required") + if not api_key_is_valid(options["api_key"]): + raise DeepgramSetupError("Invalid API key") -# prerecorded -from .client import PreRecordedClient, AsyncPreRecordedClient # backward compat -from .client import ListenRESTClient, AsyncListenRESTClient -from .client import ( - # common - # UrlSource, - # BufferSource, - # StreamSource, - # TextSource, - # FileSource, - # unique - PreRecordedStreamSource, - PrerecordedSource, - ListenRestSource, - SpeakRESTSource, -) -from .client import ( - ListenRESTOptions, - PrerecordedOptions, -) -from .client import ( - #### top level - AsyncPrerecordedResponse, - PrerecordedResponse, - SyncPrerecordedResponse, - #### shared - # Average, - # Alternative, - # Channel, - # Intent, - # Intents, - # IntentsInfo, - # Segment, - # SentimentInfo, - # Sentiment, - # Sentiments, - # SummaryInfo, - # Topic, - # Topics, - # TopicsInfo, - # Word, - #### unique - Entity, - Hit, - ListenRESTMetadata, - ModelInfo, - Paragraph, - Paragraphs, - ListenRESTResults, - Search, - Sentence, - Summaries, - SummaryV1, - SummaryV2, - Translation, - Utterance, - Warning, - ListenRESTAlternative, - ListenRESTChannel, - ListenRESTWord, -) + if "api_url" in options and options.get("api_url", None) is None: + raise DeepgramSetupError("API URL must be valid or omitted") -# read -from .client import ReadClient, AsyncReadClient -from .client import AnalyzeClient, AsyncAnalyzeClient -from .client import ( - AnalyzeOptions, - AnalyzeStreamSource, - AnalyzeSource, -) -from .client import ( - #### top level - AsyncAnalyzeResponse, - SyncAnalyzeResponse, - AnalyzeResponse, - #### shared - # Average, - # Intent, - # Intents, - # IntentsInfo, - # Segment, - # SentimentInfo, - # Sentiment, - # Sentiments, - # SummaryInfo, - # Topic, - # Topics, - # TopicsInfo, - #### unique - AnalyzeMetadata, - AnalyzeResults, - AnalyzeSummary, -) + self.options = options -# speak -## speak REST -from .client import ( - #### top level - SpeakRESTOptions, - SpeakOptions, # backward compat - #### common - # TextSource, - # BufferSource, - # StreamSource, - # FileSource, - #### unique - SpeakSource, - SpeakRestSource, -) + @property + def keys(self) -> Keys: + return Keys(self.options) -from .client import ( - SpeakClient, # backward compat - SpeakRESTClient, - AsyncSpeakRESTClient, -) + @property + def transcription(self) -> Transcription: + return Transcription(self.options) -from .client import ( - SpeakResponse, # backward compat - SpeakRESTResponse, -) + @property + def projects(self) -> Projects: + return Projects(self.options) -## speak WebSocket -from .client import SpeakWebSocketEvents, SpeakWebSocketMessage + @property + def usage(self) -> Usage: + return Usage(self.options) -from .client import ( - SpeakWSOptions, -) + @property + def billing(self) -> Billing: + return Billing(self.options) -from .client import ( - SpeakWebSocketClient, - AsyncSpeakWebSocketClient, - SpeakWSClient, - AsyncSpeakWSClient, -) + @property + def members(self) -> Members: + return Members(self.options) -from .client import ( - #### top level - SpeakWSMetadataResponse, - FlushedResponse, - ClearedResponse, - WarningResponse, - #### common websocket response - # OpenResponse, - # CloseResponse, - # UnhandledResponse, - # ErrorResponse, -) + @property + def scopes(self) -> Scopes: + return Scopes(self.options) -# manage -from .client import ManageClient, AsyncManageClient -from .client import ( - ProjectOptions, - KeyOptions, - ScopeOptions, - InviteOptions, - UsageRequestOptions, - UsageSummaryOptions, - UsageFieldsOptions, -) + @property + def invitations(self) -> Invitations: + return Invitations(self.options) -# manage client responses -from .client import ( - #### top level - Message, - ProjectsResponse, - ModelResponse, - ModelsResponse, - MembersResponse, - KeyResponse, - KeysResponse, - ScopesResponse, - InvitesResponse, - UsageRequest, - UsageResponse, - UsageRequestsResponse, - UsageSummaryResponse, - UsageFieldsResponse, - BalancesResponse, - #### shared - Project, - STTDetails, - TTSMetadata, - TTSDetails, - Member, - Key, - Invite, - Config, - STTUsageDetails, - Callback, - TokenDetail, - SpeechSegment, - TTSUsageDetails, - STTTokens, - TTSTokens, - UsageSummaryResults, - Resolution, - UsageModel, - Balance, -) + @property + def extra(self) -> Extra: + return Extra(self.options) -# selfhosted -from .client import ( - OnPremClient, - AsyncOnPremClient, - SelfHostedClient, - AsyncSelfHostedClient, -) - -# agent -from .client import AgentWebSocketEvents - -# websocket -from .client import ( - AgentWebSocketClient, - AsyncAgentWebSocketClient, -) - -from .client import ( - #### common websocket response - # OpenResponse, - # CloseResponse, - # ErrorResponse, - # UnhandledResponse, - #### unique - WelcomeResponse, - SettingsAppliedResponse, - ConversationTextResponse, - UserStartedSpeakingResponse, - AgentThinkingResponse, - FunctionCallRequest, - AgentStartedSpeakingResponse, - AgentAudioDoneResponse, - InjectionRefusedResponse, -) - -from .client import ( - # top level - SettingsOptions, - UpdatePromptOptions, - UpdateSpeakOptions, - InjectAgentMessageOptions, - FunctionCallResponse, - AgentKeepAlive, - # sub level - Listen, - Speak, - Header, - Item, - Properties, - Parameters, - Function, - Think, - Provider, - Agent, - Input, - Output, - Audio, - Endpoint, -) - -# utilities -# pylint: disable=wrong-import-position -from .audio import Microphone, DeepgramMicrophoneError -from .audio import ( - INPUT_LOGGING, - INPUT_CHANNELS, - INPUT_RATE, - INPUT_CHUNK, -) - -LOGGING = INPUT_LOGGING -CHANNELS = INPUT_CHANNELS -RATE = INPUT_RATE -CHUNK = INPUT_CHUNK - -from .audio import Speaker -from .audio import ( - OUTPUT_LOGGING, - OUTPUT_CHANNELS, - OUTPUT_RATE, - OUTPUT_CHUNK, -) - -# pylint: enable=wrong-import-position +__all__ = [Deepgram, DeepgramSetupError, DeepgramApiError] diff --git a/venv/Lib/site-packages/deepgram/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/__pycache__/__init__.cpython-312.pyc index 61f0d324..e35d0103 100644 Binary files a/venv/Lib/site-packages/deepgram/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/deepgram/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/deepgram/__pycache__/_constants.cpython-312.pyc b/venv/Lib/site-packages/deepgram/__pycache__/_constants.cpython-312.pyc new file mode 100644 index 00000000..5edce7b9 Binary files /dev/null and b/venv/Lib/site-packages/deepgram/__pycache__/_constants.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/deepgram/__pycache__/_enums.cpython-312.pyc b/venv/Lib/site-packages/deepgram/__pycache__/_enums.cpython-312.pyc new file mode 100644 index 00000000..41ccba1c Binary files /dev/null and b/venv/Lib/site-packages/deepgram/__pycache__/_enums.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/deepgram/__pycache__/_types.cpython-312.pyc b/venv/Lib/site-packages/deepgram/__pycache__/_types.cpython-312.pyc new file mode 100644 index 00000000..812da6c2 Binary files /dev/null and b/venv/Lib/site-packages/deepgram/__pycache__/_types.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/deepgram/__pycache__/_utils.cpython-312.pyc b/venv/Lib/site-packages/deepgram/__pycache__/_utils.cpython-312.pyc new file mode 100644 index 00000000..81ec1436 Binary files /dev/null and b/venv/Lib/site-packages/deepgram/__pycache__/_utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/deepgram/__pycache__/_version.cpython-312.pyc b/venv/Lib/site-packages/deepgram/__pycache__/_version.cpython-312.pyc new file mode 100644 index 00000000..0202d8ea Binary files /dev/null and b/venv/Lib/site-packages/deepgram/__pycache__/_version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/deepgram/__pycache__/billing.cpython-312.pyc b/venv/Lib/site-packages/deepgram/__pycache__/billing.cpython-312.pyc new file mode 100644 index 00000000..e5290ab2 Binary files /dev/null and b/venv/Lib/site-packages/deepgram/__pycache__/billing.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/deepgram/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/__pycache__/client.cpython-312.pyc deleted file mode 100644 index 33ad045b..00000000 Binary files a/venv/Lib/site-packages/deepgram/__pycache__/client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/__pycache__/errors.cpython-312.pyc b/venv/Lib/site-packages/deepgram/__pycache__/errors.cpython-312.pyc index 8a009acb..62d77a7d 100644 Binary files a/venv/Lib/site-packages/deepgram/__pycache__/errors.cpython-312.pyc and b/venv/Lib/site-packages/deepgram/__pycache__/errors.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/deepgram/__pycache__/extra.cpython-312.pyc b/venv/Lib/site-packages/deepgram/__pycache__/extra.cpython-312.pyc new file mode 100644 index 00000000..74128c55 Binary files /dev/null and b/venv/Lib/site-packages/deepgram/__pycache__/extra.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/deepgram/__pycache__/invitations.cpython-312.pyc b/venv/Lib/site-packages/deepgram/__pycache__/invitations.cpython-312.pyc new file mode 100644 index 00000000..4414a91a Binary files /dev/null and b/venv/Lib/site-packages/deepgram/__pycache__/invitations.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/deepgram/__pycache__/keys.cpython-312.pyc b/venv/Lib/site-packages/deepgram/__pycache__/keys.cpython-312.pyc new file mode 100644 index 00000000..68b8f380 Binary files /dev/null and b/venv/Lib/site-packages/deepgram/__pycache__/keys.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/deepgram/__pycache__/members.cpython-312.pyc b/venv/Lib/site-packages/deepgram/__pycache__/members.cpython-312.pyc new file mode 100644 index 00000000..797465a3 Binary files /dev/null and b/venv/Lib/site-packages/deepgram/__pycache__/members.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/deepgram/__pycache__/options.cpython-312.pyc b/venv/Lib/site-packages/deepgram/__pycache__/options.cpython-312.pyc deleted file mode 100644 index 3016e140..00000000 Binary files a/venv/Lib/site-packages/deepgram/__pycache__/options.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/__pycache__/projects.cpython-312.pyc b/venv/Lib/site-packages/deepgram/__pycache__/projects.cpython-312.pyc new file mode 100644 index 00000000..ff69586a Binary files /dev/null and b/venv/Lib/site-packages/deepgram/__pycache__/projects.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/deepgram/__pycache__/scopes.cpython-312.pyc b/venv/Lib/site-packages/deepgram/__pycache__/scopes.cpython-312.pyc new file mode 100644 index 00000000..ec627781 Binary files /dev/null and b/venv/Lib/site-packages/deepgram/__pycache__/scopes.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/deepgram/__pycache__/transcription.cpython-312.pyc b/venv/Lib/site-packages/deepgram/__pycache__/transcription.cpython-312.pyc new file mode 100644 index 00000000..ce6a46fc Binary files /dev/null and b/venv/Lib/site-packages/deepgram/__pycache__/transcription.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/deepgram/__pycache__/usage.cpython-312.pyc b/venv/Lib/site-packages/deepgram/__pycache__/usage.cpython-312.pyc new file mode 100644 index 00000000..8925636d Binary files /dev/null and b/venv/Lib/site-packages/deepgram/__pycache__/usage.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/deepgram/_constants.py b/venv/Lib/site-packages/deepgram/_constants.py new file mode 100644 index 00000000..993680ce --- /dev/null +++ b/venv/Lib/site-packages/deepgram/_constants.py @@ -0,0 +1 @@ +DEFAULT_ENDPOINT = "https://api.deepgram.com/v1" diff --git a/venv/Lib/site-packages/deepgram/_enums.py b/venv/Lib/site-packages/deepgram/_enums.py new file mode 100644 index 00000000..d766b6ff --- /dev/null +++ b/venv/Lib/site-packages/deepgram/_enums.py @@ -0,0 +1,12 @@ +from enum import Enum + + +class LiveTranscriptionEvent(Enum): + OPEN = 'open' + CLOSE = 'close' + TRANSCRIPT_RECEIVED = 'transcript_received' + ERROR = 'error' + +class Caption(Enum): + SRT = 'srt' + WEBVTT = 'webvtt' diff --git a/venv/Lib/site-packages/deepgram/_types.py b/venv/Lib/site-packages/deepgram/_types.py new file mode 100644 index 00000000..12fd867b --- /dev/null +++ b/venv/Lib/site-packages/deepgram/_types.py @@ -0,0 +1,474 @@ +# We want these types to be flexible to allow for updated API responses +# or cutting-edge options to not break the client for older SDK versions; +# as such, everything is implemented using TypedDicts +# instead of, say, dataclasses. + +import sys +from datetime import datetime +from typing import Optional, List, Union, Any, Dict + +if sys.version_info >= (3, 8): + from typing import TypedDict, Literal +else: + from typing_extensions import TypedDict, Literal +if sys.version_info >= (3, 9, 2): + from collections.abc import Callable, Awaitable +else: + from typing import Callable, Awaitable + + +class UpdateResponse(TypedDict): + message: str + + +# Transcription + + +class Options(TypedDict, total=False): + api_key: str + api_url: str # this URL should /not/ include a trailing slash + suppress_warnings: bool + raise_warnings_as_errors: bool + + +class UrlSource(TypedDict): + url: str + + +class BufferSource(TypedDict): + buffer: bytes + mimetype: str + + +TranscriptionSource = Union[UrlSource, BufferSource] + + +BoostedKeyword = TypedDict( + "BoostedKeyword", + { + "word": str, + "boost": float, + }, +) +Keyword = Union[str, BoostedKeyword] + + +class TranscriptionOptions(TypedDict, total=False): + # References for the different meanings and values of these properties + # can be found in the Deepgram docs: + # https://developers.deepgram.com/documentation/features/ + model: str + version: str + language: str + punctuate: bool + profanity_filter: bool + redact: List[str] + diarize: Literal["false", "true"] + diarize_version: str + version: str + multichannel: bool + alternatives: int + # numerals will be deprecated in the future + numerals: bool + numbers: bool + numbers_spaces: bool + search: List[str] + callback: str + keywords: List[str] + keyword_boost: str + ner: str + tier: str + dates: bool + date_format: str + times: bool + dictation: bool + measurements: bool + smart_format: bool + replace: Union[str, List[str]] + tag: List[str] + filler_words: bool + + +class PrerecordedOptions(TranscriptionOptions, total=False): + # References for the different meanings and values of these properties + # can be found in the Deepgram docs: + # https://developers.deepgram.com/documentation/features/ + utterances: bool + utt_split: float + detect_entities: bool + summarize: Union[bool, str] + paragraphs: bool + detect_language: bool + detect_topics: bool + translate: List[str] + analyze_sentiment: bool + sentiment: bool + sentiment_threshold: float + + +class LiveOptions(TranscriptionOptions, total=False): + # References for the different meanings and values of these properties + # can be found in the Deepgram docs: + # https://developers.deepgram.com/documentation/features/ + interim_results: bool + endpointing: bool + vad_turnoff: int + encoding: str + channels: int + sample_rate: int + + +class ToggleConfigOptions(TypedDict): + numerals: bool + + +class WordBase(TypedDict): + word: str + start: float + end: float + confidence: float + speaker: Optional[int] + speaker_confidence: Optional[float] + punctuated_word: Optional[str] + + +class Hit(TypedDict): + confidence: float + start: float + end: float + snippet: str + + +class Search(TypedDict): + query: str + hits: List[Hit] + + +class Translation(TypedDict): + translation: str + language: str + + +class Alternative(TypedDict): + transcript: str + confidence: float + words: List[WordBase] + detected_language: Optional[str] + translation: Optional[List[Translation]] + + +class Summary(TypedDict): + summary: str + start_word: float + end_word: float + + +class Entity(TypedDict): + label: str + value: str + confidence: float + start_word: float + end_word: float + + +class Sentence(TypedDict): + text: str + start: float + end: float + + +class Paragraph(TypedDict): + sentences: List[Sentence] + num_words: float + start: float + end: float + + +class ParagraphGroup(TypedDict): + transcript: str + paragraphs: List[Paragraph] + + +class Topic(TypedDict): + topics: List[str] + text: str + start_word: float + end_word: float + + +class Channel(TypedDict): + search: Optional[List[Search]] + alternatives: List[Alternative] + summaries: Optional[List[Summary]] + entities: Optional[List[Entity]] + paragraphs: Optional[ParagraphGroup] + topics: Optional[List[Topic]] + + +class Utterance(TypedDict): + start: float + end: float + confidence: float + channel: int + transcript: str + words: List[WordBase] + speaker: Optional[int] + speaker_confidence: Optional[float] + id: str + + +class Warning(TypedDict): + parameter: str + type: Literal[ + "unsupported_language", + "unsupported_model", + "unsupported_encoding", + "deprecated", + ] + message: str + + +class SummaryV2(TypedDict): + short: str + result: Literal["success", "failure"] + + +class Metadata(TypedDict): + request_id: str + transaction_key: str + sha256: str + created: str + duration: float + channels: int + models: List[str] + model_info: Dict[str, Any] + warnings: List[Warning] + + +TranscriptionResults = TypedDict( + "TranscriptionResults", + { + "channels": List[Channel], + "utterances": Optional[List[Utterance]], + "summary": Optional[SummaryV2], + }, +) + + +class PrerecordedTranscriptionResponse(TypedDict, total=False): + request_id: str + metadata: Metadata + results: TranscriptionResults + + +StreamingMetadata = TypedDict( + "StreamingMetadata", + { + "request_id": str, + "model_uuid": str, + }, +) + + +class LiveTranscriptionResponse(TypedDict): + channel_index: List[int] + duration: float + start: float + is_final: bool + speech_final: bool + channel: Channel + metadata: StreamingMetadata + + +EventHandler = Union[Callable[[Any], None], Callable[[Any], Awaitable[None]]] + + +# Keys + + +class Key(TypedDict): + api_key_id: str + key: Optional[str] + comment: str + created: datetime + scopes: List[str] + + +# Members + + +class Member(TypedDict): + email: str + first_name: str + last_name: str + id: str + scopes: Optional[List[str]] + + +class KeyBundle(TypedDict): + api_key: Key + member: Member + + +class KeyResponse(TypedDict): + api_keys: List[KeyBundle] + + +# Projects + + +class Project(TypedDict): + project_id: str + name: str + + +class ProjectResponse(TypedDict): + projects: List[Project] + + +# Usage + + +class UsageRequestListOptions(TypedDict): + start: Optional[str] + end: Optional[str] + page: Optional[int] + limit: Optional[int] + status: Literal["succeeded", "failed"] + + +class UsageRequestDetails(TypedDict): + usd: float + dutation: float + total_audio: float + channels: int + streams: int + model: str + method: Literal["sync", "async", "streaming"] + tags: List[str] + features: List[str] + config: Dict[str, bool] # TODO: add all possible request options + + +class UsageRequestDetail(TypedDict): + details: UsageRequestDetails + + +class UsageRequestMessage(TypedDict): + message: Optional[str] + + +class UsageCallback(TypedDict): + code: int + completed: str + + +class UsageRequest(TypedDict): + request_id: str + created: str + path: str + accessor: str + response: Optional[Union[UsageRequestDetail, UsageRequestMessage]] + callback: Optional[UsageCallback] + + +class UsageRequestList(TypedDict): + page: int + limit: int + requests: Optional[List[UsageRequest]] + + +class UsageOptions(TypedDict, total=False): + start: str + end: str + accessor: str + tag: List[str] + method: Literal["sync", "async", "streaming"] + model: str + multichannel: bool + interim_results: bool + punctuate: bool + ner: bool + utterances: bool + replace: Union[str, List[str]] + profanity_filter: bool + keywords: bool + diarize: bool + detect_language: bool + search: bool + redact: bool + alternatives: bool + numerals: bool + detect_entities: bool + summarize: Union[bool, str] + paragraphs: bool + detect_language: bool + detect_topics: bool + translate: bool + analyze_sentiment: bool + sentiment_threshold: float + + +class UsageResponseDetail(TypedDict): + start: str + end: str + hours: float + requests: int + + +UsageResponseResolution = TypedDict( + "UsageResponseResolution", {"units": str, "amount": int} +) + + +class UsageResponse(TypedDict): + start: str + end: str + resolution: UsageResponseResolution + results: List[UsageResponseDetail] + + +class UsageFieldOptions(TypedDict, total=False): + start: str + end: str + + +class UsageField(TypedDict): + tags: List[str] + models: List[str] + processing_methods: List[str] + languages: List[str] + features: List[str] + + +# Billing + + +class Balance(TypedDict): + balance_id: str + amount: float + units: str + purchase: str + + +class BalanceResponse(TypedDict): + projects: List[Balance] + + +# Scope + + +class Scope(TypedDict): + scopes: List[str] + + +# Invitation + + +class Invitation(TypedDict): + email: str + scope: str + + +class InvitationResponse(TypedDict): + message: str diff --git a/venv/Lib/site-packages/deepgram/_utils.py b/venv/Lib/site-packages/deepgram/_utils.py new file mode 100644 index 00000000..d869742f --- /dev/null +++ b/venv/Lib/site-packages/deepgram/_utils.py @@ -0,0 +1,242 @@ +from typing import Any, Union, Optional, IO, Mapping, Tuple, List, cast +import aiohttp +import urllib.parse +import urllib.request +import urllib.error +import io +import json +import re +import platform +import websockets +import websockets.client +import websockets.exceptions +import warnings +from ._constants import DEFAULT_ENDPOINT +from ._types import Options +from ._version import __version__ +from .errors import DeepgramApiError + +Payload = Optional[Union[dict, str, bytes, IO]] + +RETRY_COUNT = 4 + + +def _prepare_headers( + options: Options, headers: Mapping[str, str] = None +) -> dict: + if headers is None: + headers = {} + auth = ( + None if 'api_key' not in options + else cast(str, options.get('auth_method', 'Token')) + + ' ' + options['api_key'] + ) + return { + **headers, + 'Authorization': auth, + 'User-Agent': ( + f'deepgram/{__version__} python/{platform.python_version()}' + ) + } + + +def _normalize_payload(payload: Payload) -> Optional[Union[bytes, IO]]: + if payload is None: + return None + if isinstance(payload, dict): + return json.dumps(payload).encode('utf-8') + if isinstance(payload, str): + return payload.encode('utf-8') + return payload + + +def _make_query_string(params: Mapping[str, Any] = None) -> str: + if params is None: + params = {} + + def elem_decomposer(key: str, value: Any) -> List[Tuple[str, str]]: + if value in [None, ""]: + return [] + if isinstance(value, list): + # break into multiple parameters + return [elem_decomposer(key, item)[0] for item in value] + # just take the first element in the sublist, + # rather than trying to flatten recursively + # passing nested lists as query parameters + # isn't really well-defined, nor does anything + # in our API currently take things like that as of 2021-08-10 + # so everything coming through this second pass + # should be a 1-item list + if isinstance(value, bool): + # make sure False and True stay lowercased + # in accordance with DG convention + return [(key, str(value).lower())] + return [(key, str(value))] + + # sublist for each original parameter + unflattened = [elem_decomposer(k, v) for k, v in params.items()] + # flatten + flattened: List[Tuple[str, str]] = sum(unflattened, []) + return ('?' if flattened else '') + urllib.parse.urlencode(flattened) + + +async def _request( + path: str, options: Options, + method: str = 'GET', payload: Payload = None, + headers: Optional[Mapping[str, str]] = None, + timeout: float = None, +) -> Any: + if headers is None: + headers = {} + destination = cast(str, options.get('api_url', DEFAULT_ENDPOINT)) + path + updated_headers = _prepare_headers(options, headers) + + if timeout is None: + timeout = aiohttp.client.DEFAULT_TIMEOUT + else: + timeout = aiohttp.ClientTimeout(total=timeout) + + async def attempt(): + # Define `content` outside the try block so we can differentiate between errors + # thrown by `aiohttp.request` and `resp.raise_for_status()`. This can be removed + # after the aiohttp issue mentioned below is fixed. + content = None + try: + async with aiohttp.request( + method, destination, data=_normalize_payload(payload), + headers=updated_headers, timeout=timeout + ) as resp: + # The error handling for this async code is more difficult than normal + # because aiohttp does not include the response body in the exception + # object. We therefore need to read the response body before throwing + # an error, and attach the response body to the error. This should + # be fixed by aiohttp in v4.x. See the github issue here for info: + # https://github.com/aio-libs/aiohttp/issues/4600 + # Once that work is complete, we can use `raise_for_status=True` as a + # parameter in the `aiohttp.request` call. + content = (await resp.text()).strip() + resp.raise_for_status() + if not content: + return None + body = json.loads(content) + if body.get('error') or body.get('err_msg'): + raise DeepgramApiError(body, http_library_error=None) + if options.get("raise_warnings_as_errors") and "metadata" in body and "warnings" in body["metadata"]: + raise DeepgramApiError({"warnings": body["metadata"]["warnings"]}, http_library_error=None) + if (not options.get("suppress_warnings")) and "metadata" in body and "warnings" in body["metadata"]: + for warning in body["metadata"]["warnings"]: + warnings.warn(warning["message"]) + return body + except aiohttp.ClientResponseError as exc: + # If the request returned a response body and errored, return the response body. + # Otherwise return the request's error message. + if content is not None: + try: + body = json.loads(content) + raise DeepgramApiError(body, http_library_error=exc) from exc if exc.status < 500 else exc + except: + pass + else: + raise DeepgramApiError(exc.message, http_library_error=exc) from exc if exc.status < 500 else exc + except aiohttp.ClientError as exc: + raise DeepgramApiError(exc, http_library_error=exc) from exc + + tries = RETRY_COUNT + while tries > 0: + try: + return await attempt() + except aiohttp.ClientError as exc: + if isinstance(payload, io.IOBase): + # stream is now invalid as payload + # the way aiohttp handles streaming form data + # means that just seeking this back still runs into issues + raise DeepgramApiError(exc, http_library_error=exc) from exc + tries -= 1 + continue + return await attempt() + + +def _sync_request( + path: str, options: Options, + method: str = 'GET', payload: Payload = None, + headers: Optional[Mapping[str, str]] = None, + timeout: float = None +) -> Any: + if headers is None: + headers = {} + destination = cast(str, options.get('api_url', DEFAULT_ENDPOINT)) + path + updated_headers = _prepare_headers(options, headers) + + def attempt(): + req = urllib.request.Request( + destination, + data=_normalize_payload(payload), + headers=updated_headers, + method=method) + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + content = resp.read().strip() + if not content: + return None + body = json.loads(content) + if body.get('error') or body.get('err_msg'): + raise DeepgramApiError(body, http_library_error=None) + if options.get("raise_warnings_as_errors") and "metadata" in body and "warnings" in body["metadata"]: + raise DeepgramApiError({"warnings": body["metadata"]["warnings"]}, http_library_error=None) + if (not options.get("suppress_warnings")) and "metadata" in body and "warnings" in body["metadata"]: + for warning in body["metadata"]["warnings"]: + warnings.warn(warning["message"]) + return body + except urllib.error.HTTPError as exc: + # Try to get the HTTP error's request body. Deepgram returns a JSON response + # body for error messages. We want to return that as the error message if + # it exists. + try: + error_body = json.loads(exc.read().decode("utf-8")) + except Exception: + error_body = str(exc) + raise DeepgramApiError(error_body, http_library_error=exc) from exc + + tries = RETRY_COUNT + while tries > 0: + try: + return attempt() + except urllib.error.URLError as exc: + if isinstance(payload, io.IOBase): + # stream is now invalid as payload + # the way aiohttp handles streaming form data + # means that just seeking this back still runs into issues + raise DeepgramApiError(exc, http_library_error=exc) from exc + tries -= 1 + continue + return attempt() + + +async def _socket_connect( + path: str, options: Options, headers: Optional[Mapping[str, str]] = None +) -> websockets.client.WebSocketClientProtocol: + if headers is None: + headers = {} + destination = re.sub( + r'^http', 'ws', cast(str, options.get('api_url', DEFAULT_ENDPOINT)) + ) + path + updated_headers = _prepare_headers(options, headers) + + async def attempt(): + try: + # If we're streaming too much faster than realtime, + # connection might close without an aggressive ping interval + return await websockets.connect( + destination, extra_headers=updated_headers, ping_interval=5 + ) + except websockets.exceptions.InvalidHandshake as exc: + raise DeepgramApiError(exc, http_library_error=exc) from exc + + tries = RETRY_COUNT + while tries > 0: + try: + return await attempt() + except Exception as exc: + tries -= 1 + continue + return await attempt() diff --git a/venv/Lib/site-packages/deepgram/_version.py b/venv/Lib/site-packages/deepgram/_version.py new file mode 100644 index 00000000..c37d7c6a --- /dev/null +++ b/venv/Lib/site-packages/deepgram/_version.py @@ -0,0 +1 @@ +__version__ = 'v2.12.0' diff --git a/venv/Lib/site-packages/deepgram/audio/__init__.py b/venv/Lib/site-packages/deepgram/audio/__init__.py deleted file mode 100644 index dcadaa4c..00000000 --- a/venv/Lib/site-packages/deepgram/audio/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .microphone import Microphone -from .microphone import DeepgramMicrophoneError -from .microphone import ( - LOGGING as INPUT_LOGGING, - CHANNELS as INPUT_CHANNELS, - RATE as INPUT_RATE, - CHUNK as INPUT_CHUNK, -) - -from .speaker import Speaker -from .speaker import DeepgramSpeakerError -from .speaker import ( - LOGGING as OUTPUT_LOGGING, - CHANNELS as OUTPUT_CHANNELS, - RATE as OUTPUT_RATE, - CHUNK as OUTPUT_CHUNK, - PLAYBACK_DELTA as OUTPUT_PLAYBACK_DELTA, -) diff --git a/venv/Lib/site-packages/deepgram/audio/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/audio/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index decb220c..00000000 Binary files a/venv/Lib/site-packages/deepgram/audio/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/audio/microphone/__init__.py b/venv/Lib/site-packages/deepgram/audio/microphone/__init__.py deleted file mode 100644 index d5ead2f1..00000000 --- a/venv/Lib/site-packages/deepgram/audio/microphone/__init__.py +++ /dev/null @@ -1,7 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .microphone import Microphone -from .constants import LOGGING, CHANNELS, RATE, CHUNK -from .errors import DeepgramMicrophoneError diff --git a/venv/Lib/site-packages/deepgram/audio/microphone/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/audio/microphone/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index aa45e618..00000000 Binary files a/venv/Lib/site-packages/deepgram/audio/microphone/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/audio/microphone/__pycache__/constants.cpython-312.pyc b/venv/Lib/site-packages/deepgram/audio/microphone/__pycache__/constants.cpython-312.pyc deleted file mode 100644 index 82f13128..00000000 Binary files a/venv/Lib/site-packages/deepgram/audio/microphone/__pycache__/constants.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/audio/microphone/__pycache__/errors.cpython-312.pyc b/venv/Lib/site-packages/deepgram/audio/microphone/__pycache__/errors.cpython-312.pyc deleted file mode 100644 index 41c9dd8b..00000000 Binary files a/venv/Lib/site-packages/deepgram/audio/microphone/__pycache__/errors.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/audio/microphone/__pycache__/microphone.cpython-312.pyc b/venv/Lib/site-packages/deepgram/audio/microphone/__pycache__/microphone.cpython-312.pyc deleted file mode 100644 index dac224e5..00000000 Binary files a/venv/Lib/site-packages/deepgram/audio/microphone/__pycache__/microphone.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/audio/microphone/constants.py b/venv/Lib/site-packages/deepgram/audio/microphone/constants.py deleted file mode 100644 index 4aed8106..00000000 --- a/venv/Lib/site-packages/deepgram/audio/microphone/constants.py +++ /dev/null @@ -1,11 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from ...utils import verboselogs - -# Constants for microphone -LOGGING = verboselogs.WARNING -CHANNELS = 1 -RATE = 16000 -CHUNK = 8194 diff --git a/venv/Lib/site-packages/deepgram/audio/microphone/errors.py b/venv/Lib/site-packages/deepgram/audio/microphone/errors.py deleted file mode 100644 index 6e7fe5ef..00000000 --- a/venv/Lib/site-packages/deepgram/audio/microphone/errors.py +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - - -# exceptions for microphone -class DeepgramMicrophoneError(Exception): - """ - Exception raised for known errors related to Microphone library. - - Attributes: - message (str): The error message describing the exception. - """ - - def __init__(self, message: str): - super().__init__(message) - self.name = "DeepgramMicrophoneError" - self.message = message - - def __str__(self): - return f"{self.name}: {self.message}" diff --git a/venv/Lib/site-packages/deepgram/audio/microphone/microphone.py b/venv/Lib/site-packages/deepgram/audio/microphone/microphone.py deleted file mode 100644 index 3a3ad341..00000000 --- a/venv/Lib/site-packages/deepgram/audio/microphone/microphone.py +++ /dev/null @@ -1,302 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -import inspect -import asyncio -import threading -from typing import Optional, Callable, Union, TYPE_CHECKING -import logging - -from ...utils import verboselogs - -from .constants import LOGGING, CHANNELS, RATE, CHUNK - -if TYPE_CHECKING: - import pyaudio - - -class Microphone: # pylint: disable=too-many-instance-attributes - """ - This implements a microphone for local audio input. This uses PyAudio under the hood. - """ - - _logger: verboselogs.VerboseLogger - - _audio: Optional["pyaudio.PyAudio"] = None - _stream: Optional["pyaudio.Stream"] = None - - _chunk: int - _rate: int - _format: int - _channels: int - _input_device_index: Optional[int] - _is_muted: bool - - _asyncio_loop: asyncio.AbstractEventLoop - _asyncio_thread: Optional[threading.Thread] = None - _exit: threading.Event - - _push_callback_org: Optional[Callable] = None - _push_callback: Optional[Callable] = None - - def __init__( - self, - push_callback: Optional[Callable] = None, - verbose: int = LOGGING, - rate: int = RATE, - chunk: int = CHUNK, - channels: int = CHANNELS, - input_device_index: Optional[int] = None, - ): # pylint: disable=too-many-positional-arguments - # dynamic import of pyaudio as not to force the requirements on the SDK (and users) - import pyaudio # pylint: disable=import-outside-toplevel - - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(verbose) - - self._exit = threading.Event() - - self._audio = pyaudio.PyAudio() - self._chunk = chunk - self._rate = rate - self._format = pyaudio.paInt16 - self._channels = channels - self._is_muted = False - - self._input_device_index = input_device_index - self._push_callback_org = push_callback - - def _start_asyncio_loop(self) -> None: - self._asyncio_loop = asyncio.new_event_loop() - self._asyncio_loop.run_forever() - - def is_active(self) -> bool: - """ - is_active - returns the state of the stream - - Args: - None - - Returns: - True if the stream is active, False otherwise - """ - self._logger.debug("Microphone.is_active ENTER") - - if self._stream is None: - self._logger.error("stream is None") - self._logger.debug("Microphone.is_active LEAVE") - return False - - val = self._stream.is_active() - self._logger.info("is_active: %s", val) - self._logger.info("is_exiting: %s", self._exit.is_set()) - self._logger.debug("Microphone.is_active LEAVE") - return val - - def set_callback(self, push_callback: Callable) -> None: - """ - set_callback - sets the callback function to be called when data is received. - - Args: - push_callback (Callable): The callback function to be called when data is received. - This should be the websocket send function. - - Returns: - None - """ - self._push_callback_org = push_callback - - def start(self) -> bool: - """ - starts - starts the microphone stream - - Returns: - bool: True if the stream was started, False otherwise - """ - self._logger.debug("Microphone.start ENTER") - - self._logger.info("format: %s", self._format) - self._logger.info("channels: %d", self._channels) - self._logger.info("rate: %d", self._rate) - self._logger.info("chunk: %d", self._chunk) - # self._logger.info("input_device_id: %d", self._input_device_index) - - if self._push_callback_org is None: - self._logger.error("start failed. No callback set.") - self._logger.debug("Microphone.start LEAVE") - return False - - if inspect.iscoroutinefunction(self._push_callback_org): - self._logger.verbose("async/await callback - wrapping") - # Run our own asyncio loop. - self._asyncio_thread = threading.Thread(target=self._start_asyncio_loop) - self._asyncio_thread.start() - - self._push_callback = lambda data: ( - asyncio.run_coroutine_threadsafe( - self._push_callback_org(data), self._asyncio_loop - ).result() - if self._push_callback_org - else None - ) - else: - self._logger.verbose("regular threaded callback") - self._asyncio_thread = None - self._push_callback = self._push_callback_org - - if self._audio is not None: - self._stream = self._audio.open( - format=self._format, - channels=self._channels, - rate=self._rate, - input=True, - output=False, - frames_per_buffer=self._chunk, - input_device_index=self._input_device_index, - stream_callback=self._callback, - ) - - if self._stream is None: - self._logger.error("start failed. No stream created.") - self._logger.debug("Microphone.start LEAVE") - return False - - self._exit.clear() - if self._stream is not None: - self._stream.start_stream() - - self._logger.notice("start succeeded") - self._logger.debug("Microphone.start LEAVE") - return True - - def mute(self) -> bool: - """ - mute - mutes the microphone stream - - Returns: - bool: True if the stream was muted, False otherwise - """ - self._logger.verbose("Microphone.mute ENTER") - - if self._stream is None: - self._logger.error("mute failed. Library not initialized.") - self._logger.verbose("Microphone.mute LEAVE") - return False - - self._is_muted = True - - self._logger.notice("mute succeeded") - self._logger.verbose("Microphone.mute LEAVE") - return True - - def unmute(self) -> bool: - """ - unmute - unmutes the microphone stream - - Returns: - bool: True if the stream was unmuted, False otherwise - """ - self._logger.verbose("Microphone.unmute ENTER") - - if self._stream is None: - self._logger.error("unmute failed. Library not initialized.") - self._logger.verbose("Microphone.unmute LEAVE") - return False - - self._is_muted = False - - self._logger.notice("unmute succeeded") - self._logger.verbose("Microphone.unmute LEAVE") - return True - - def is_muted(self) -> bool: - """ - is_muted - returns the state of the stream - - Args: - None - - Returns: - True if the stream is muted, False otherwise - """ - self._logger.spam("Microphone.is_muted ENTER") - - if self._stream is None: - self._logger.spam("is_muted: stream is None") - self._logger.spam("Microphone.is_muted LEAVE") - return False - - val = self._is_muted - - self._logger.spam("is_muted: %s", val) - self._logger.spam("Microphone.is_muted LEAVE") - return val - - def finish(self) -> bool: - """ - finish - stops the microphone stream - - Returns: - bool: True if the stream was stopped, False otherwise - """ - self._logger.debug("Microphone.finish ENTER") - - self._logger.notice("signal exit") - self._exit.set() - - # Stop the stream. - if self._stream is not None: - self._logger.notice("stopping stream...") - self._stream.stop_stream() - self._stream.close() - self._logger.notice("stream stopped") - - # clean up the thread - if ( - # inspect.iscoroutinefunction(self._push_callback_org) - # and - self._asyncio_thread - is not None - ): - self._logger.notice("stopping _asyncio_loop...") - self._asyncio_loop.call_soon_threadsafe(self._asyncio_loop.stop) - self._asyncio_thread.join() - self._logger.notice("_asyncio_thread joined") - self._stream = None - self._asyncio_thread = None - - self._logger.notice("finish succeeded") - self._logger.debug("Microphone.finish LEAVE") - - return True - - def _callback( - self, input_data, frame_count, time_info, status_flags - ): # pylint: disable=unused-argument - """ - The callback used to process data in callback mode. - """ - # dynamic import of pyaudio as not to force the requirements on the SDK (and users) - import pyaudio # pylint: disable=import-outside-toplevel - - if self._exit.is_set(): - self._logger.notice("_callback exit is Set. stopping...") - return None, pyaudio.paAbort - - if input_data is None: - self._logger.warning("input_data is None") - return None, pyaudio.paContinue - - try: - if self._is_muted: - size = len(input_data) - input_data = b"\x00" * size - - self._push_callback(input_data) - except Exception as e: - self._logger.error("Error while sending: %s", str(e)) - raise - - return input_data, pyaudio.paContinue diff --git a/venv/Lib/site-packages/deepgram/audio/speaker/__init__.py b/venv/Lib/site-packages/deepgram/audio/speaker/__init__.py deleted file mode 100644 index f9adc8e5..00000000 --- a/venv/Lib/site-packages/deepgram/audio/speaker/__init__.py +++ /dev/null @@ -1,7 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .speaker import Speaker -from .errors import DeepgramSpeakerError -from .constants import LOGGING, CHANNELS, RATE, CHUNK, PLAYBACK_DELTA diff --git a/venv/Lib/site-packages/deepgram/audio/speaker/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/audio/speaker/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index 6bc2d7c2..00000000 Binary files a/venv/Lib/site-packages/deepgram/audio/speaker/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/audio/speaker/__pycache__/constants.cpython-312.pyc b/venv/Lib/site-packages/deepgram/audio/speaker/__pycache__/constants.cpython-312.pyc deleted file mode 100644 index 2359bf0a..00000000 Binary files a/venv/Lib/site-packages/deepgram/audio/speaker/__pycache__/constants.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/audio/speaker/__pycache__/errors.cpython-312.pyc b/venv/Lib/site-packages/deepgram/audio/speaker/__pycache__/errors.cpython-312.pyc deleted file mode 100644 index 76156b3f..00000000 Binary files a/venv/Lib/site-packages/deepgram/audio/speaker/__pycache__/errors.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/audio/speaker/__pycache__/speaker.cpython-312.pyc b/venv/Lib/site-packages/deepgram/audio/speaker/__pycache__/speaker.cpython-312.pyc deleted file mode 100644 index 6d944970..00000000 Binary files a/venv/Lib/site-packages/deepgram/audio/speaker/__pycache__/speaker.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/audio/speaker/constants.py b/venv/Lib/site-packages/deepgram/audio/speaker/constants.py deleted file mode 100644 index a033c721..00000000 --- a/venv/Lib/site-packages/deepgram/audio/speaker/constants.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from ...utils import verboselogs - -# Constants for speaker -LOGGING = verboselogs.WARNING -TIMEOUT = 0.050 -CHANNELS = 1 -RATE = 16000 -CHUNK = 8194 - -# Constants for speaker -PLAYBACK_DELTA = 2000 diff --git a/venv/Lib/site-packages/deepgram/audio/speaker/errors.py b/venv/Lib/site-packages/deepgram/audio/speaker/errors.py deleted file mode 100644 index 4d9b95ef..00000000 --- a/venv/Lib/site-packages/deepgram/audio/speaker/errors.py +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - - -# exceptions for speaker -class DeepgramSpeakerError(Exception): - """ - Exception raised for known errors related to Speaker library. - - Attributes: - message (str): The error message describing the exception. - """ - - def __init__(self, message: str): - super().__init__(message) - self.name = "DeepgramSpeakerError" - self.message = message - - def __str__(self): - return f"{self.name}: {self.message}" diff --git a/venv/Lib/site-packages/deepgram/audio/speaker/speaker.py b/venv/Lib/site-packages/deepgram/audio/speaker/speaker.py deleted file mode 100644 index e16d5898..00000000 --- a/venv/Lib/site-packages/deepgram/audio/speaker/speaker.py +++ /dev/null @@ -1,380 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -import asyncio -import inspect -import queue -import threading -from typing import Optional, Callable, Union, TYPE_CHECKING -import logging -from datetime import datetime - -import websockets - -from ...utils import verboselogs -from .constants import LOGGING, CHANNELS, RATE, CHUNK, TIMEOUT, PLAYBACK_DELTA - -from ..microphone import Microphone - -if TYPE_CHECKING: - import pyaudio - -HALF_SECOND = 0.5 - - -class Speaker: # pylint: disable=too-many-instance-attributes - """ - This implements a speaker for local audio output. This uses PyAudio under the hood. - """ - - _logger: verboselogs.VerboseLogger - - _audio: Optional["pyaudio.PyAudio"] = None - _stream: Optional["pyaudio.Stream"] = None - - _chunk: int - _rate: int - _channels: int - _output_device_index: Optional[int] = None - - # last time we received audio - _last_datagram: datetime = datetime.now() - _last_play_delta_in_ms: int - _lock_wait: threading.Lock - - _queue: queue.Queue - _exit: threading.Event - - _thread: Optional[threading.Thread] = None - # _asyncio_loop: asyncio.AbstractEventLoop - # _asyncio_thread: threading.Thread - _receiver_thread: Optional[threading.Thread] = None - _loop: Optional[asyncio.AbstractEventLoop] = None - - _push_callback_org: Optional[Callable] = None - _push_callback: Optional[Callable] = None - _pull_callback_org: Optional[Callable] = None - _pull_callback: Optional[Callable] = None - - _microphone: Optional[Microphone] = None - - def __init__( - self, - pull_callback: Optional[Callable] = None, - push_callback: Optional[Callable] = None, - verbose: int = LOGGING, - rate: int = RATE, - chunk: int = CHUNK, - channels: int = CHANNELS, - last_play_delta_in_ms: int = PLAYBACK_DELTA, - output_device_index: Optional[int] = None, - microphone: Optional[Microphone] = None, - ): # pylint: disable=too-many-positional-arguments - # dynamic import of pyaudio as not to force the requirements on the SDK (and users) - import pyaudio # pylint: disable=import-outside-toplevel - - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(verbose) - - self._exit = threading.Event() - self._queue = queue.Queue() - - self._last_datagram = datetime.now() - self._lock_wait = threading.Lock() - - self._microphone = microphone - - self._audio = pyaudio.PyAudio() - self._chunk = chunk - self._rate = rate - self._format = pyaudio.paInt16 - self._channels = channels - self._last_play_delta_in_ms = last_play_delta_in_ms - self._output_device_index = output_device_index - - self._push_callback_org = push_callback - self._pull_callback_org = pull_callback - - def set_push_callback(self, push_callback: Callable) -> None: - """ - set_push_callback - sets the callback function to be called when data is sent. - - Args: - push_callback (Callable): The callback function to be called when data is send. - This should be the websocket handle message function. - - Returns: - None - """ - self._push_callback_org = push_callback - - def set_pull_callback(self, pull_callback: Callable) -> None: - """ - set_pull_callback - sets the callback function to be called when data is received. - - Args: - pull_callback (Callable): The callback function to be called when data is received. - This should be the websocket recv function. - - Returns: - None - """ - self._pull_callback_org = pull_callback - - def start(self, active_loop: Optional[asyncio.AbstractEventLoop] = None) -> bool: - """ - starts - starts the Speaker stream - - Args: - socket (Union[SyncClientConnection, AsyncClientConnection]): The socket to receive audio data from. - - Returns: - bool: True if the stream was started, False otherwise - """ - self._logger.debug("Speaker.start ENTER") - - self._logger.info("format: %s", self._format) - self._logger.info("channels: %d", self._channels) - self._logger.info("rate: %d", self._rate) - self._logger.info("chunk: %d", self._chunk) - # self._logger.info("output_device_id: %d", self._output_device_index) - - # Automatically get the current running event loop - if inspect.iscoroutinefunction(self._push_callback_org) and active_loop is None: - self._logger.verbose("get default running asyncio loop") - self._loop = asyncio.get_running_loop() - - self._exit.clear() - self._queue = queue.Queue() - - if self._audio is not None: - self._stream = self._audio.open( - format=self._format, - channels=self._channels, - rate=self._rate, - input=False, - output=True, - frames_per_buffer=self._chunk, - output_device_index=self._output_device_index, - ) - - if self._stream is None: - self._logger.error("start failed. No stream created.") - self._logger.debug("Speaker.start LEAVE") - return False - - self._push_callback = self._push_callback_org - self._pull_callback = self._pull_callback_org - - # start the play thread - self._thread = threading.Thread( - target=self._play, args=(self._queue, self._stream, self._exit), daemon=True - ) - self._thread.start() - - # Start the stream - if self._stream is not None: - self._stream.start_stream() - - # Start the receiver thread within the start function - self._logger.verbose("Starting receiver thread...") - self._receiver_thread = threading.Thread(target=self._start_receiver) - self._receiver_thread.start() - - self._logger.notice("start succeeded") - self._logger.debug("Speaker.start LEAVE") - - return True - - def wait_for_complete_with_mute(self, mic: Microphone): - """ - This method will mute/unmute a Microphone and block until the speak is done playing sound. - """ - self._logger.debug("Speaker.wait_for_complete ENTER") - - if self._microphone is not None: - mic.mute() - self.wait_for_complete() - if self._microphone is not None: - mic.unmute() - - self._logger.debug("Speaker.wait_for_complete LEAVE") - - def wait_for_complete(self): - """ - This method will block until the speak is done playing sound. - """ - self._logger.debug("Speaker.wait_for_complete ENTER") - - delta_in_ms = float(self._last_play_delta_in_ms) - self._logger.debug("Last Play delta: %f", delta_in_ms) - - # set to now - with self._lock_wait: - self._last_datagram = datetime.now() - - while True: - # sleep for a bit - self._exit.wait(HALF_SECOND) - - # check if we should exit - if self._exit.is_set(): - self._logger.debug("Exiting wait_for_complete _exit is set") - break - - # check the time - with self._lock_wait: - delta = datetime.now() - self._last_datagram - diff_in_ms = delta.total_seconds() * 1000 - if diff_in_ms < delta_in_ms: - self._logger.debug("LastPlay delta is less than threshold") - continue - - # if we get here, we are done playing audio - self._logger.debug("LastPlay delta is greater than threshold. Exit wait!") - break - - self._logger.debug("Speaker.wait_for_complete LEAVE") - - def _start_receiver(self): - # Check if the socket is an asyncio WebSocket - if inspect.iscoroutinefunction(self._pull_callback_org): - self._logger.verbose("Starting asyncio receiver...") - asyncio.run_coroutine_threadsafe(self._start_asyncio_receiver(), self._loop) - else: - self._logger.verbose("Starting threaded receiver...") - self._start_threaded_receiver() - - async def _start_asyncio_receiver(self): - try: - while True: - if self._exit.is_set(): - self._logger.verbose("Exiting receiver thread...") - break - - message = await self._pull_callback() - if message is None: - self._logger.verbose("No message received...") - continue - - if isinstance(message, str): - self._logger.verbose("Received control message...") - await self._push_callback(message) - elif isinstance(message, bytes): - self._logger.verbose("Received audio data...") - await self._push_callback(message) - self.add_audio_to_queue(message) - except websockets.exceptions.ConnectionClosedOK as e: - self._logger.debug("send() exiting gracefully: %d", e.code) - except websockets.exceptions.ConnectionClosed as e: - if e.code in [1000, 1001]: - self._logger.debug("send() exiting gracefully: %d", e.code) - return - self._logger.error("_start_asyncio_receiver - ConnectionClosed: %s", str(e)) - except websockets.exceptions.WebSocketException as e: - self._logger.error( - "_start_asyncio_receiver- WebSocketException: %s", str(e) - ) - except Exception as e: # pylint: disable=broad-except - self._logger.error("_start_asyncio_receiver exception: %s", str(e)) - - def _start_threaded_receiver(self): - try: - while True: - if self._exit.is_set(): - self._logger.verbose("Exiting receiver thread...") - break - - message = self._pull_callback() - if message is None: - self._logger.verbose("No message received...") - continue - - if isinstance(message, str): - self._logger.verbose("Received control message...") - self._push_callback(message) - elif isinstance(message, bytes): - self._logger.verbose("Received audio data...") - self._push_callback(message) - self.add_audio_to_queue(message) - except Exception as e: # pylint: disable=broad-except - self._logger.notice("_start_threaded_receiver exception: %s", str(e)) - - def add_audio_to_queue(self, data: bytes) -> None: - """ - add_audio_to_queue - adds audio data to the Speaker queue - - Args: - data (bytes): The audio data to add to the queue - """ - self._queue.put(data) - - def finish(self) -> bool: - """ - finish - stops the Speaker stream - - Returns: - bool: True if the stream was stopped, False otherwise - """ - self._logger.debug("Speaker.finish ENTER") - - self._logger.notice("signal exit") - self._exit.set() - - if self._stream is not None: - self._logger.notice("stopping stream...") - self._stream.stop_stream() - self._stream.close() - self._logger.notice("stream stopped") - - if self._thread is not None: - self._logger.notice("joining _thread...") - self._thread.join() - self._logger.notice("thread stopped") - - if self._receiver_thread is not None: - self._logger.notice("stopping _receiver_thread...") - self._receiver_thread.join() - self._logger.notice("_receiver_thread joined") - - with self._queue.mutex: - self._queue.queue.clear() - - self._stream = None - self._thread = None - self._receiver_thread = None - - self._logger.notice("finish succeeded") - self._logger.debug("Speaker.finish LEAVE") - - return True - - def _play(self, audio_out, stream, stop): - """ - _play - plays audio data from the Speaker queue callback for portaudio - """ - while not stop.is_set(): - try: - if self._microphone is not None and self._microphone.is_muted(): - with self._lock_wait: - delta = datetime.now() - self._last_datagram - diff_in_ms = delta.total_seconds() * 1000 - if diff_in_ms > float(self._last_play_delta_in_ms): - self._logger.debug( - "LastPlay delta is greater than threshold. Unmute!" - ) - self._microphone.unmute() - - data = audio_out.get(True, TIMEOUT) - with self._lock_wait: - self._last_datagram = datetime.now() - if self._microphone is not None and not self._microphone.is_muted(): - self._logger.debug("New speaker sound detected. Mute!") - self._microphone.mute() - stream.write(data) - except queue.Empty: - pass - except Exception as e: # pylint: disable=broad-except - self._logger.error("_play exception: %s", str(e)) diff --git a/venv/Lib/site-packages/deepgram/billing.py b/venv/Lib/site-packages/deepgram/billing.py new file mode 100644 index 00000000..79bc0211 --- /dev/null +++ b/venv/Lib/site-packages/deepgram/billing.py @@ -0,0 +1,21 @@ +from ._types import Options, BalanceResponse, Balance +from ._utils import _request + + +class Billing: + _root = "/projects" + + def __init__(self, options: Options) -> None: + self.options = options + + async def list_balance(self, project_id: str) -> BalanceResponse: + """Returns a list of outstanding balances for the + specified project.""" + + return await _request(f'{self._root}/{project_id}/balances', self.options) + + + async def get_balance(self, project_id: str, balance_id: str) -> Balance: + """Returns a specific project based on the provided projectId.""" + + return await _request(f'{self._root}/{project_id}/balances/{balance_id}', self.options) \ No newline at end of file diff --git a/venv/Lib/site-packages/deepgram/client.py b/venv/Lib/site-packages/deepgram/client.py deleted file mode 100644 index 80c5d9c3..00000000 --- a/venv/Lib/site-packages/deepgram/client.py +++ /dev/null @@ -1,667 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from typing import Optional -from importlib import import_module -import os -import logging -import deprecation # type: ignore - -from . import __version__ -from .utils import verboselogs - -# common -# pylint: disable=unused-import -from .clients import ( - TextSource, - BufferSource, - StreamSource, - FileSource, - UrlSource, -) -from .clients import BaseResponse -from .clients import ( - Average, - Intent, - Intents, - IntentsInfo, - Segment, - SentimentInfo, - Sentiment, - Sentiments, - SummaryInfo, - Topic, - Topics, - TopicsInfo, -) -from .clients import ( - ModelInfo, - Hit, - Search, -) -from .clients import ( - OpenResponse, - CloseResponse, - UnhandledResponse, - ErrorResponse, -) -from .clients import ( - DeepgramError, - DeepgramTypeError, - DeepgramModuleError, - DeepgramApiError, - DeepgramUnknownApiError, -) - -# listen client -from .clients import ListenRouter, ReadRouter, SpeakRouter, AgentRouter - -# speech-to-text -from .clients import LiveClient, AsyncLiveClient # backward compat -from .clients import ( - ListenWebSocketClient, - AsyncListenWebSocketClient, -) -from .clients import ( - ListenWebSocketOptions, - LiveOptions, - LiveTranscriptionEvents, -) - -# live client responses -from .clients import ( - #### top level - LiveResultResponse, - ListenWSMetadataResponse, - SpeechStartedResponse, - UtteranceEndResponse, - #### common websocket response - # OpenResponse, - # CloseResponse, - # ErrorResponse, - # UnhandledResponse, - #### unique - ListenWSMetadata, - ListenWSAlternative, - ListenWSChannel, - ListenWSWord, -) - -# prerecorded -from .clients import ( - # common - # UrlSource, - # BufferSource, - # StreamSource, - # TextSource, - # FileSource, - # unique - PreRecordedStreamSource, - PrerecordedSource, - ListenRestSource, -) - -from .clients import ( - PreRecordedClient, - AsyncPreRecordedClient, -) # backward compat -from .clients import ( - ListenRESTClient, - AsyncListenRESTClient, -) -from .clients import ( - ListenRESTOptions, - PrerecordedOptions, -) - -# rest client responses -from .clients import ( - #### top level - AsyncPrerecordedResponse, - PrerecordedResponse, - SyncPrerecordedResponse, - #### shared - # Average, - # Intent, - # Intents, - # IntentsInfo, - # Segment, - # SentimentInfo, - # Sentiment, - # Sentiments, - # SummaryInfo, - # Topic, - # Topics, - # TopicsInfo, - #### between rest and websocket - # ModelInfo, - # Alternative, - # Hit, - # Search, - # Channel, - # Word, - # unique - Entity, - ListenRESTMetadata, - Paragraph, - Paragraphs, - ListenRESTResults, - Sentence, - Summaries, - SummaryV1, - SummaryV2, - Translation, - Utterance, - Warning, - ListenRESTAlternative, - ListenRESTChannel, - ListenRESTWord, -) - -# read -from .clients import ReadClient, AsyncReadClient -from .clients import AnalyzeClient, AsyncAnalyzeClient -from .clients import ( - AnalyzeOptions, - AnalyzeStreamSource, - AnalyzeSource, -) - -# read client responses -from .clients import ( - #### top level - AsyncAnalyzeResponse, - SyncAnalyzeResponse, - AnalyzeResponse, - #### shared - # Average, - # Intent, - # Intents, - # IntentsInfo, - # Segment, - # SentimentInfo, - # Sentiment, - # Sentiments, - # SummaryInfo, - # Topic, - # Topics, - # TopicsInfo, - #### unique - AnalyzeMetadata, - AnalyzeResults, - AnalyzeSummary, -) - -# speak -## speak REST -from .clients import ( - #### top level - SpeakRESTOptions, - SpeakOptions, # backward compat - #### common - # TextSource, - # BufferSource, - # StreamSource, - # FileSource, - #### unique - SpeakSource, - SpeakRestSource, - SpeakRESTSource, -) - -from .clients import ( - SpeakClient, # backward compat - SpeakRESTClient, - AsyncSpeakRESTClient, -) - -from .clients import ( - SpeakResponse, # backward compat - SpeakRESTResponse, -) - -## speak WebSocket -from .clients import SpeakWebSocketEvents, SpeakWebSocketMessage - -from .clients import ( - SpeakWSOptions, -) - -from .clients import ( - SpeakWebSocketClient, - AsyncSpeakWebSocketClient, - SpeakWSClient, - AsyncSpeakWSClient, -) - -from .clients import ( - #### top level - SpeakWSMetadataResponse, - FlushedResponse, - ClearedResponse, - WarningResponse, - #### common websocket response - # OpenResponse, - # CloseResponse, - # UnhandledResponse, - # ErrorResponse, -) - -# auth client classes -from .clients import AuthRESTClient, AsyncAuthRESTClient - -# auth client responses -from .clients import ( - GrantTokenResponse, -) - -# manage client classes/input -from .clients import ManageClient, AsyncManageClient -from .clients import ( - ProjectOptions, - KeyOptions, - ScopeOptions, - InviteOptions, - UsageRequestOptions, - UsageSummaryOptions, - UsageFieldsOptions, -) - -# manage client responses -from .clients import ( - #### top level - Message, - ProjectsResponse, - ModelResponse, - ModelsResponse, - MembersResponse, - KeyResponse, - KeysResponse, - ScopesResponse, - InvitesResponse, - UsageRequest, - UsageResponse, - UsageRequestsResponse, - UsageSummaryResponse, - UsageFieldsResponse, - BalancesResponse, - #### shared - Project, - STTDetails, - TTSMetadata, - TTSDetails, - Member, - Key, - Invite, - Config, - STTUsageDetails, - Callback, - TokenDetail, - SpeechSegment, - TTSUsageDetails, - STTTokens, - TTSTokens, - UsageSummaryResults, - Resolution, - UsageModel, - Balance, -) - -# on-prem -from .clients import ( - OnPremClient, - AsyncOnPremClient, - SelfHostedClient, - AsyncSelfHostedClient, -) - - -# agent -from .clients import AgentWebSocketEvents - -# websocket -from .clients import ( - AgentWebSocketClient, - AsyncAgentWebSocketClient, -) - -from .clients import ( - #### common websocket response - # OpenResponse, - # CloseResponse, - # ErrorResponse, - # UnhandledResponse, - #### unique - WelcomeResponse, - SettingsAppliedResponse, - ConversationTextResponse, - UserStartedSpeakingResponse, - AgentThinkingResponse, - FunctionCallRequest, - AgentStartedSpeakingResponse, - AgentAudioDoneResponse, - InjectionRefusedResponse, -) - -from .clients import ( - # top level - SettingsOptions, - UpdatePromptOptions, - UpdateSpeakOptions, - InjectAgentMessageOptions, - FunctionCallResponse, - AgentKeepAlive, - # sub level - Listen, - Speak, - Header, - Item, - Properties, - Parameters, - Function, - Think, - Provider, - Agent, - Input, - Output, - Audio, - Endpoint, -) - - -# client errors and options -from .options import DeepgramClientOptions, ClientOptionsFromEnv -from .errors import DeepgramApiKeyError - -# pylint: enable=unused-import - - -class Deepgram: # pylint: disable=broad-exception-raised - """ - The Deepgram class is no longer a class in version 3 of this SDK. - """ - - def __init__(self, *anything): - raise Exception( - """ - FATAL ERROR: - You are attempting to instantiate a Deepgram object, which is no longer a class in version 3 of this SDK. - - To fix this issue: - 1. You need to revert to the previous version 2 of the SDK: pip install deepgram-sdk==2.12.0 - 2. or, update your application's code to use version 3 of this SDK. See the README for more information. - - Things to consider: - - - This Version 3 of the SDK requires Python 3.10 or higher. - Older versions (3.9 and lower) of Python are nearing end-of-life: https://devguide.python.org/versions/ - Understand the risks of using a version of Python nearing EOL. - - - Version 2 of the SDK will receive maintenance updates in the form of security fixes only. - No new features will be added to version 2 of the SDK. - """ - ) - - -class DeepgramClient: - """ - Represents a client for interacting with the Deepgram API. - - This class provides a client for making requests to the Deepgram API with various configuration options. - - Attributes: - api_key (str): The Deepgram API key used for authentication. - config_options (DeepgramClientOptions): An optional configuration object specifying client options. - - Raises: - DeepgramApiKeyError: If the API key is missing or invalid. - - Methods: - listen: Returns a ListenClient instance for interacting with Deepgram's transcription services. - - manage: (Preferred) Returns a Threaded ManageClient instance for managing Deepgram resources. - selfhosted: (Preferred) Returns an Threaded SelfHostedClient instance for interacting with Deepgram's on-premises API. - - asyncmanage: Returns an (Async) ManageClient instance for managing Deepgram resources. - asyncselfhosted: Returns an (Async) SelfHostedClient instance for interacting with Deepgram's on-premises API. - """ - - _config: DeepgramClientOptions - _logger: verboselogs.VerboseLogger - - def __init__( - self, - api_key: str = "", - config: Optional[DeepgramClientOptions] = None, - ): - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - - if api_key == "" and config is not None: - self._logger.info("Attempting to set API key from config object") - api_key = config.api_key - if api_key == "": - self._logger.info("Attempting to set API key from environment variable") - api_key = os.getenv("DEEPGRAM_API_KEY", "") - if api_key == "": - self._logger.warning("WARNING: API key is missing") - - self.api_key = api_key - if config is None: # Use default configuration - self._config = DeepgramClientOptions(self.api_key) - else: - config.set_apikey(self.api_key) - self._config = config - - @property - def listen(self): - """ - Returns a Listen dot-notation router for interacting with Deepgram's transcription services. - """ - return ListenRouter(self._config) - - @property - def read(self): - """ - Returns a Read dot-notation router for interacting with Deepgram's read services. - """ - return ReadRouter(self._config) - - @property - def speak(self): - """ - Returns a Speak dot-notation router for interacting with Deepgram's speak services. - """ - return SpeakRouter(self._config) - - @property - @deprecation.deprecated( - deprecated_in="3.4.0", - removed_in="4.0.0", - current_version=__version__, - details="deepgram.asyncspeak is deprecated. Use deepgram.speak.asyncrest instead.", - ) - def asyncspeak(self): - """ - DEPRECATED: deepgram.asyncspeak is deprecated. Use deepgram.speak.asyncrest instead. - """ - return self.Version(self._config, "asyncspeak") - - @property - def manage(self): - """ - Returns a ManageClient instance for managing Deepgram resources. - """ - return self.Version(self._config, "manage") - - @property - def asyncmanage(self): - """ - Returns an AsyncManageClient instance for managing Deepgram resources. - """ - return self.Version(self._config, "asyncmanage") - - @property - def auth(self): - """ - Returns an AuthRESTClient instance for managing short-lived tokens. - """ - return self.Version(self._config, "auth") - - @property - def asyncauth(self): - """ - Returns an AsyncAuthRESTClient instance for managing short-lived tokens. - """ - return self.Version(self._config, "asyncauth") - - @property - @deprecation.deprecated( - deprecated_in="3.4.0", - removed_in="4.0.0", - current_version=__version__, - details="deepgram.onprem is deprecated. Use deepgram.speak.selfhosted instead.", - ) - def onprem(self): - """ - DEPRECATED: deepgram.onprem is deprecated. Use deepgram.speak.selfhosted instead. - """ - return self.Version(self._config, "selfhosted") - - @property - def selfhosted(self): - """ - Returns an SelfHostedClient instance for interacting with Deepgram's on-premises API. - """ - return self.Version(self._config, "selfhosted") - - @property - @deprecation.deprecated( - deprecated_in="3.4.0", - removed_in="4.0.0", - current_version=__version__, - details="deepgram.asynconprem is deprecated. Use deepgram.speak.asyncselfhosted instead.", - ) - def asynconprem(self): - """ - DEPRECATED: deepgram.asynconprem is deprecated. Use deepgram.speak.asyncselfhosted instead. - """ - return self.Version(self._config, "asyncselfhosted") - - @property - def asyncselfhosted(self): - """ - Returns an AsyncSelfHostedClient instance for interacting with Deepgram's on-premises API. - """ - return self.Version(self._config, "asyncselfhosted") - - @property - def agent(self): - """ - Returns a Agent dot-notation router for interacting with Deepgram's speak services. - """ - return AgentRouter(self._config) - - # INTERNAL CLASSES - class Version: - """ - Represents a version of the Deepgram API. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - _parent: str - - def __init__(self, config, parent: str): - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - - self._config = config - self._parent = parent - - # FUTURE VERSIONING: - # When v2 or v1.1beta1 or etc. This allows easy access to the latest version of the API. - # @property - # def latest(self): - # match self._parent: - # case "manage": - # return ManageClient(self._config) - # case "selfhosted": - # return SelfHostedClient(self._config) - # case _: - # raise DeepgramModuleError("Invalid parent") - - def v(self, version: str = ""): - # pylint: disable-msg=too-many-statements - """ - Returns a client for the specified version of the API. - """ - self._logger.debug("Version.v ENTER") - self._logger.info("version: %s", version) - if len(version) == 0: - self._logger.error("version is empty") - self._logger.debug("Version.v LEAVE") - raise DeepgramModuleError("Invalid module version") - - parent = "" - filename = "" - classname = "" - match self._parent: - case "manage": - parent = "manage" - filename = "client" - classname = "ManageClient" - case "asyncmanage": - parent = "manage" - filename = "async_client" - classname = "AsyncManageClient" - case "asyncspeak": - return AsyncSpeakRESTClient(self._config) - case "selfhosted": - parent = "selfhosted" - filename = "client" - classname = "SelfHostedClient" - case "asyncselfhosted": - parent = "selfhosted" - filename = "async_client" - classname = "AsyncSelfHostedClient" - case "auth": - parent = "auth" - filename = "client" - classname = "AuthRESTClient" - case "asyncauth": - parent = "auth" - filename = "async_client" - classname = "AsyncAuthRESTClient" - case _: - self._logger.error("parent unknown: %s", self._parent) - self._logger.debug("Version.v LEAVE") - raise DeepgramModuleError("Invalid parent type") - - # create class path - path = f"deepgram.clients.{parent}.v{version}.{filename}" - self._logger.info("path: %s", path) - self._logger.info("classname: %s", classname) - - # import class - mod = import_module(path) - if mod is None: - self._logger.error("module path is None") - self._logger.debug("Version.v LEAVE") - raise DeepgramModuleError("Unable to find package") - - my_class = getattr(mod, classname) - if my_class is None: - self._logger.error("my_class is None") - self._logger.debug("Version.v LEAVE") - raise DeepgramModuleError("Unable to find class") - - # instantiate class - my_class_instance = my_class(self._config) - self._logger.notice("Version.v succeeded") - self._logger.debug("Version.v LEAVE") - return my_class_instance - - # pylint: enable-msg=too-many-statements diff --git a/venv/Lib/site-packages/deepgram/clients/__init__.py b/venv/Lib/site-packages/deepgram/clients/__init__.py deleted file mode 100644 index c1bb5c5c..00000000 --- a/venv/Lib/site-packages/deepgram/clients/__init__.py +++ /dev/null @@ -1,379 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -# common -from .common import ( - TextSource, - BufferSource, - StreamSource, - FileSource, - UrlSource, -) -from .common import BaseResponse - -# common (shared between analze and prerecorded) -from .common import ( - Average, - Intent, - Intents, - IntentsInfo, - Segment, - SentimentInfo, - Sentiment, - Sentiments, - SummaryInfo, - Topic, - Topics, - TopicsInfo, -) - -# common (shared between listen rest and websocket) -from .common import ( - ModelInfo, - Hit, - Search, -) -from .common import ( - OpenResponse, - CloseResponse, - UnhandledResponse, - ErrorResponse, -) -from .common import ( - DeepgramError, - DeepgramTypeError, - DeepgramApiError, - DeepgramUnknownApiError, -) -from .errors import DeepgramModuleError - -from .listen_router import ListenRouter -from .read_router import ReadRouter -from .speak_router import SpeakRouter -from .agent_router import AgentRouter - -# listen -from .listen import LiveTranscriptionEvents - -## backward compat -from .prerecorded import ( - PreRecordedClient, - AsyncPreRecordedClient, -) -from .live import ( - LiveClient, - AsyncLiveClient, -) - -# speech-to-text rest -from .listen import ListenRESTClient, AsyncListenRESTClient - -## input -from .listen import ( - # common - # UrlSource, - # BufferSource, - # StreamSource, - # TextSource, - # FileSource, - # unique - PreRecordedStreamSource, - PrerecordedSource, - ListenRestSource, -) - -from .listen import ( - ListenRESTOptions, - PrerecordedOptions, -) - -## output -from .listen import ( - #### top level - AsyncPrerecordedResponse, - PrerecordedResponse, - SyncPrerecordedResponse, - #### shared - # Average, - # Intent, - # Intents, - # IntentsInfo, - # Segment, - # SentimentInfo, - # Sentiment, - # Sentiments, - # SummaryInfo, - # Topic, - # Topics, - # TopicsInfo, - #### between rest and websocket - # ModelInfo, - # Alternative, - # Hit, - # Search, - # Channel, - # Word, - # unique - Entity, - ListenRESTMetadata, - Paragraph, - Paragraphs, - ListenRESTResults, - Sentence, - Summaries, - SummaryV1, - SummaryV2, - Translation, - Utterance, - Warning, - ListenRESTAlternative, - ListenRESTChannel, - ListenRESTWord, -) - - -# speech-to-text websocket -from .listen import ListenWebSocketClient, AsyncListenWebSocketClient - -## input -from .listen import ( - ListenWebSocketOptions, - LiveOptions, -) - -## output -from .listen import ( - #### top level - LiveResultResponse, - ListenWSMetadataResponse, - SpeechStartedResponse, - UtteranceEndResponse, - #### common websocket response - # OpenResponse, - # CloseResponse, - # ErrorResponse, - # UnhandledResponse, - #### uniqye - ListenWSMetadata, - ListenWSWord, - ListenWSAlternative, - ListenWSChannel, -) - -## clients -from .listen import ( - ListenWebSocketClient, - AsyncListenWebSocketClient, -) - - -# read/analyze -from .analyze import ReadClient, AsyncReadClient -from .analyze import AnalyzeClient, AsyncAnalyzeClient -from .analyze import AnalyzeOptions -from .analyze import ( - # common - # UrlSource, - # TextSource, - # BufferSource, - # StreamSource, - # FileSource - # unique - AnalyzeStreamSource, - AnalyzeSource, -) -from .analyze import ( - #### top level - AsyncAnalyzeResponse, - SyncAnalyzeResponse, - AnalyzeResponse, - #### shared between analyze and pre-recorded - # Average, - # Intent, - # Intents, - # IntentsInfo, - # Segment, - # SentimentInfo, - # Sentiment, - # Sentiments, - # SummaryInfo, - # Topic, - # Topics, - # TopicsInfo, - #### unique - AnalyzeMetadata, - AnalyzeResults, - AnalyzeSummary, -) - -# text-to-speech -## text-to-speech REST -from .speak import ( - #### top level - SpeakRESTOptions, - SpeakOptions, - # common - # TextSource, - # BufferSource, - # StreamSource, - # FileSource, - # unique - SpeakSource, - SpeakRestSource, - SpeakRESTSource, -) - -from .speak import ( - SpeakClient, # backward compat - SpeakRESTClient, - AsyncSpeakRESTClient, -) - -from .speak import ( - SpeakResponse, # backward compat - SpeakRESTResponse, -) - -## text-to-speech WebSocket -from .speak import SpeakWebSocketEvents, SpeakWebSocketMessage - -from .speak import ( - SpeakWSOptions, -) - -from .speak import ( - SpeakWebSocketClient, - AsyncSpeakWebSocketClient, - SpeakWSClient, - AsyncSpeakWSClient, -) - -from .speak import ( - #### top level - SpeakWSMetadataResponse, - FlushedResponse, - ClearedResponse, - WarningResponse, - #### common websocket response - # OpenResponse, - # CloseResponse, - # UnhandledResponse, - # ErrorResponse, -) - -# manage -from .manage import ManageClient, AsyncManageClient -from .manage import ( - ProjectOptions, - KeyOptions, - ScopeOptions, - InviteOptions, - UsageRequestOptions, - UsageSummaryOptions, - UsageFieldsOptions, -) -from .manage import ( - #### top level - Message, - ProjectsResponse, - ModelResponse, - ModelsResponse, - MembersResponse, - KeyResponse, - KeysResponse, - ScopesResponse, - InvitesResponse, - UsageRequest, - UsageResponse, - UsageRequestsResponse, - UsageSummaryResponse, - UsageFieldsResponse, - BalancesResponse, - #### shared - Project, - STTDetails, - TTSMetadata, - TTSDetails, - Member, - Key, - Invite, - Config, - STTUsageDetails, - Callback, - TokenDetail, - SpeechSegment, - TTSUsageDetails, - STTTokens, - TTSTokens, - UsageSummaryResults, - Resolution, - UsageModel, - Balance, -) - -# auth -from .auth import AuthRESTClient, AsyncAuthRESTClient -from .auth import ( - GrantTokenResponse, -) - -# selfhosted -from .selfhosted import ( - OnPremClient, - AsyncOnPremClient, - SelfHostedClient, - AsyncSelfHostedClient, -) - -# agent -from .agent import AgentWebSocketEvents - -# websocket -from .agent import ( - AgentWebSocketClient, - AsyncAgentWebSocketClient, -) - -from .agent import ( - #### common websocket response - # OpenResponse, - # CloseResponse, - # ErrorResponse, - # UnhandledResponse, - #### unique - WelcomeResponse, - SettingsAppliedResponse, - ConversationTextResponse, - UserStartedSpeakingResponse, - AgentThinkingResponse, - FunctionCallRequest, - AgentStartedSpeakingResponse, - AgentAudioDoneResponse, - InjectionRefusedResponse, -) - -from .agent import ( - # top level - SettingsOptions, - UpdatePromptOptions, - UpdateSpeakOptions, - InjectAgentMessageOptions, - FunctionCallResponse, - AgentKeepAlive, - # sub level - Listen, - Speak, - Header, - Item, - Properties, - Parameters, - Function, - Think, - Provider, - Agent, - Input, - Output, - Audio, - Endpoint, -) diff --git a/venv/Lib/site-packages/deepgram/clients/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index beb885d9..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/__pycache__/agent_router.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/__pycache__/agent_router.cpython-312.pyc deleted file mode 100644 index 089f79e4..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/__pycache__/agent_router.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/__pycache__/errors.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/__pycache__/errors.cpython-312.pyc deleted file mode 100644 index c98cd106..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/__pycache__/errors.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/__pycache__/listen_router.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/__pycache__/listen_router.cpython-312.pyc deleted file mode 100644 index 055875f5..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/__pycache__/listen_router.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/__pycache__/read_router.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/__pycache__/read_router.cpython-312.pyc deleted file mode 100644 index a57b6217..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/__pycache__/read_router.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/__pycache__/speak_router.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/__pycache__/speak_router.cpython-312.pyc deleted file mode 100644 index 262d1dba..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/__pycache__/speak_router.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/agent/__init__.py b/venv/Lib/site-packages/deepgram/clients/agent/__init__.py deleted file mode 100644 index befd2ef8..00000000 --- a/venv/Lib/site-packages/deepgram/clients/agent/__init__.py +++ /dev/null @@ -1,54 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .enums import AgentWebSocketEvents - -# websocket -from .client import ( - AgentWebSocketClient, - AsyncAgentWebSocketClient, -) - -from .client import ( - #### common websocket response - OpenResponse, - CloseResponse, - ErrorResponse, - UnhandledResponse, - #### unique - WelcomeResponse, - SettingsAppliedResponse, - ConversationTextResponse, - UserStartedSpeakingResponse, - AgentThinkingResponse, - FunctionCallRequest, - AgentStartedSpeakingResponse, - AgentAudioDoneResponse, - InjectionRefusedResponse, -) - -from .client import ( - # top level - SettingsOptions, - UpdatePromptOptions, - UpdateSpeakOptions, - InjectAgentMessageOptions, - FunctionCallResponse, - AgentKeepAlive, - # sub level - Listen, - Speak, - Header, - Item, - Properties, - Parameters, - Function, - Think, - Provider, - Agent, - Input, - Output, - Audio, - Endpoint, -) diff --git a/venv/Lib/site-packages/deepgram/clients/agent/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/agent/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index 2c93d451..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/agent/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/agent/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/agent/__pycache__/client.cpython-312.pyc deleted file mode 100644 index 85705b20..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/agent/__pycache__/client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/agent/__pycache__/enums.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/agent/__pycache__/enums.cpython-312.pyc deleted file mode 100644 index b8660f1c..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/agent/__pycache__/enums.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/agent/client.py b/venv/Lib/site-packages/deepgram/clients/agent/client.py deleted file mode 100644 index e7c8eba9..00000000 --- a/venv/Lib/site-packages/deepgram/clients/agent/client.py +++ /dev/null @@ -1,98 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -# websocket -from .v1 import ( - AgentWebSocketClient as LatestAgentWebSocketClient, - AsyncAgentWebSocketClient as LatestAsyncAgentWebSocketClient, -) - -from .v1 import ( - #### common websocket response - BaseResponse as LatestBaseResponse, - OpenResponse as LatestOpenResponse, - CloseResponse as LatestCloseResponse, - ErrorResponse as LatestErrorResponse, - UnhandledResponse as LatestUnhandledResponse, - #### unique - WelcomeResponse as LatestWelcomeResponse, - SettingsAppliedResponse as LatestSettingsAppliedResponse, - ConversationTextResponse as LatestConversationTextResponse, - UserStartedSpeakingResponse as LatestUserStartedSpeakingResponse, - AgentThinkingResponse as LatestAgentThinkingResponse, - FunctionCallRequest as LatestFunctionCallRequest, - AgentStartedSpeakingResponse as LatestAgentStartedSpeakingResponse, - AgentAudioDoneResponse as LatestAgentAudioDoneResponse, - InjectionRefusedResponse as LatestInjectionRefusedResponse, -) - -from .v1 import ( - # top level - SettingsOptions as LatestSettingsOptions, - UpdatePromptOptions as LatestUpdatePromptOptions, - UpdateSpeakOptions as LatestUpdateSpeakOptions, - InjectAgentMessageOptions as LatestInjectAgentMessageOptions, - FunctionCallResponse as LatestFunctionCallResponse, - AgentKeepAlive as LatestAgentKeepAlive, - # sub level - Listen as LatestListen, - Speak as LatestSpeak, - Header as LatestHeader, - Item as LatestItem, - Properties as LatestProperties, - Parameters as LatestParameters, - Function as LatestFunction, - Think as LatestThink, - Provider as LatestProvider, - Agent as LatestAgent, - Input as LatestInput, - Output as LatestOutput, - Audio as LatestAudio, - Endpoint as LatestEndpoint, -) - - -# The vX/client.py points to the current supported version in the SDK. -# Older versions are supported in the SDK for backwards compatibility. - -AgentWebSocketClient = LatestAgentWebSocketClient -AsyncAgentWebSocketClient = LatestAsyncAgentWebSocketClient - -OpenResponse = LatestOpenResponse -CloseResponse = LatestCloseResponse -ErrorResponse = LatestErrorResponse -UnhandledResponse = LatestUnhandledResponse - -WelcomeResponse = LatestWelcomeResponse -SettingsAppliedResponse = LatestSettingsAppliedResponse -ConversationTextResponse = LatestConversationTextResponse -UserStartedSpeakingResponse = LatestUserStartedSpeakingResponse -AgentThinkingResponse = LatestAgentThinkingResponse -FunctionCallRequest = LatestFunctionCallRequest -AgentStartedSpeakingResponse = LatestAgentStartedSpeakingResponse -AgentAudioDoneResponse = LatestAgentAudioDoneResponse -InjectionRefusedResponse = LatestInjectionRefusedResponse - - -SettingsOptions = LatestSettingsOptions -UpdatePromptOptions = LatestUpdatePromptOptions -UpdateSpeakOptions = LatestUpdateSpeakOptions -InjectAgentMessageOptions = LatestInjectAgentMessageOptions -FunctionCallResponse = LatestFunctionCallResponse -AgentKeepAlive = LatestAgentKeepAlive - -Listen = LatestListen -Speak = LatestSpeak -Header = LatestHeader -Item = LatestItem -Properties = LatestProperties -Parameters = LatestParameters -Function = LatestFunction -Think = LatestThink -Provider = LatestProvider -Agent = LatestAgent -Input = LatestInput -Output = LatestOutput -Audio = LatestAudio -Endpoint = LatestEndpoint \ No newline at end of file diff --git a/venv/Lib/site-packages/deepgram/clients/agent/enums.py b/venv/Lib/site-packages/deepgram/clients/agent/enums.py deleted file mode 100644 index e0928dd2..00000000 --- a/venv/Lib/site-packages/deepgram/clients/agent/enums.py +++ /dev/null @@ -1,36 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from aenum import StrEnum - -# Constants mapping to events from the Deepgram API - - -class AgentWebSocketEvents(StrEnum): - """ - Enumerates the possible Agent API events that can be received from the Deepgram API - """ - - # server - Open: str = "Open" - Close: str = "Close" - AudioData: str = "AudioData" - Welcome: str = "Welcome" - SettingsApplied: str = "SettingsApplied" - ConversationText: str = "ConversationText" - UserStartedSpeaking: str = "UserStartedSpeaking" - AgentThinking: str = "AgentThinking" - FunctionCallRequest: str = "FunctionCallRequest" - AgentStartedSpeaking: str = "AgentStartedSpeaking" - AgentAudioDone: str = "AgentAudioDone" - Error: str = "Error" - Unhandled: str = "Unhandled" - - # client - Settings: str = "Settings" - UpdatePrompt: str = "UpdatePrompt" - UpdateSpeak: str = "UpdateSpeak" - InjectAgentMessage: str = "InjectAgentMessage" - InjectionRefused: str = "InjectionRefused" - AgentKeepAlive: str = "AgentKeepAlive" diff --git a/venv/Lib/site-packages/deepgram/clients/agent/v1/__init__.py b/venv/Lib/site-packages/deepgram/clients/agent/v1/__init__.py deleted file mode 100644 index cd115c9f..00000000 --- a/venv/Lib/site-packages/deepgram/clients/agent/v1/__init__.py +++ /dev/null @@ -1,58 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -# common websocket -from ...common import ( - OpenResponse, - CloseResponse, - UnhandledResponse, - ErrorResponse, -) - -# websocket -from .websocket import AgentWebSocketClient, AsyncAgentWebSocketClient - -from .websocket import ( - #### common websocket response - BaseResponse, - OpenResponse, - CloseResponse, - ErrorResponse, - UnhandledResponse, - #### unique - WelcomeResponse, - SettingsAppliedResponse, - ConversationTextResponse, - UserStartedSpeakingResponse, - AgentThinkingResponse, - FunctionCallRequest, - AgentStartedSpeakingResponse, - AgentAudioDoneResponse, - InjectionRefusedResponse, -) - -from .websocket import ( - # top level - SettingsOptions, - UpdatePromptOptions, - UpdateSpeakOptions, - InjectAgentMessageOptions, - FunctionCallResponse, - AgentKeepAlive, - # sub level - Listen, - Speak, - Header, - Item, - Properties, - Parameters, - Function, - Think, - Provider, - Agent, - Input, - Output, - Audio, - Endpoint, -) diff --git a/venv/Lib/site-packages/deepgram/clients/agent/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/agent/v1/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index fddc82a9..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/agent/v1/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/__init__.py b/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/__init__.py deleted file mode 100644 index f32c1bb7..00000000 --- a/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/__init__.py +++ /dev/null @@ -1,49 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .client import AgentWebSocketClient -from .async_client import AsyncAgentWebSocketClient - -from .response import ( - #### common websocket response - BaseResponse, - OpenResponse, - CloseResponse, - ErrorResponse, - UnhandledResponse, - #### unique - WelcomeResponse, - SettingsAppliedResponse, - ConversationTextResponse, - UserStartedSpeakingResponse, - AgentThinkingResponse, - FunctionCallRequest, - AgentStartedSpeakingResponse, - AgentAudioDoneResponse, - InjectionRefusedResponse, -) -from .options import ( - # top level - SettingsOptions, - UpdatePromptOptions, - UpdateSpeakOptions, - InjectAgentMessageOptions, - FunctionCallResponse, - AgentKeepAlive, - # sub level - Listen, - Speak, - Header, - Item, - Properties, - Parameters, - Function, - Think, - Provider, - Agent, - Input, - Output, - Audio, - Endpoint, -) diff --git a/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index 030ce7b5..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/__pycache__/async_client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/__pycache__/async_client.cpython-312.pyc deleted file mode 100644 index e69a55e7..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/__pycache__/async_client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/__pycache__/client.cpython-312.pyc deleted file mode 100644 index f840e5ae..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/__pycache__/client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/__pycache__/options.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/__pycache__/options.cpython-312.pyc deleted file mode 100644 index 484b9995..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/__pycache__/options.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/__pycache__/response.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/__pycache__/response.cpython-312.pyc deleted file mode 100644 index 45445333..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/__pycache__/response.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/async_client.py b/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/async_client.py deleted file mode 100644 index ae4822a5..00000000 --- a/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/async_client.py +++ /dev/null @@ -1,685 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -import asyncio -import json -import logging -from typing import Dict, Union, Optional, cast, Any, Callable -import threading - -from .....utils import verboselogs -from .....options import DeepgramClientOptions -from ...enums import AgentWebSocketEvents -from ....common import AbstractAsyncWebSocketClient -from ....common import DeepgramError - -from .response import ( - OpenResponse, - WelcomeResponse, - SettingsAppliedResponse, - ConversationTextResponse, - UserStartedSpeakingResponse, - AgentThinkingResponse, - FunctionCallRequest, - AgentStartedSpeakingResponse, - AgentAudioDoneResponse, - InjectionRefusedResponse, - CloseResponse, - ErrorResponse, - UnhandledResponse, -) -from .options import ( - SettingsOptions, - UpdatePromptOptions, - UpdateSpeakOptions, - InjectAgentMessageOptions, - FunctionCallResponse, - AgentKeepAlive, -) - -from .....audio.speaker import ( - Speaker, - RATE as SPEAKER_RATE, - CHANNELS as SPEAKER_CHANNELS, - PLAYBACK_DELTA as SPEAKER_PLAYBACK_DELTA, -) -from .....audio.microphone import ( - Microphone, - RATE as MICROPHONE_RATE, - CHANNELS as MICROPHONE_CHANNELS, -) - -ONE_SECOND = 1 -HALF_SECOND = 0.5 -DEEPGRAM_INTERVAL = 5 - - -class AsyncAgentWebSocketClient( - AbstractAsyncWebSocketClient -): # pylint: disable=too-many-instance-attributes - """ - Client for interacting with Deepgram's live transcription services over WebSockets. - - This class provides methods to establish a WebSocket connection for live transcription and handle real-time transcription events. - - Args: - config (DeepgramClientOptions): all the options for the client. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - _endpoint: str - - _event_handlers: Dict[AgentWebSocketEvents, list] - - _keep_alive_thread: Union[asyncio.Task, None] - - _kwargs: Optional[Dict] = None - _addons: Optional[Dict] = None - # note the distinction here. We can't use _config because it's already used in the parent - _settings: Optional[SettingsOptions] = None - _headers: Optional[Dict] = None - - _speaker_created: bool = False - _speaker: Optional[Speaker] = None - _microphone_created: bool = False - _microphone: Optional[Microphone] = None - - def __init__(self, config: DeepgramClientOptions): - if config is None: - raise DeepgramError("Config is required") - - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - - self._config = config - - # needs to be "wss://agent.deepgram.com/agent" - self._endpoint = "v1/agent/converse" - - # override the endpoint since it needs to be "wss://agent.deepgram.com/agent" - self._config.url = "agent.deepgram.com" - self._keep_alive_thread = None - - # init handlers - self._event_handlers = { - event: [] for event in AgentWebSocketEvents.__members__.values() - } - - if self._config.options.get("microphone_record") == "true": - self._logger.info("microphone_record is enabled") - rate = self._config.options.get("microphone_record_rate", MICROPHONE_RATE) - channels = self._config.options.get( - "microphone_record_channels", MICROPHONE_CHANNELS - ) - device_index = self._config.options.get("microphone_record_device_index") - - self._logger.debug("rate: %s", rate) - self._logger.debug("channels: %s", channels) - if device_index is not None: - self._logger.debug("device_index: %s", device_index) - - self._microphone_created = True - - if device_index is not None: - self._microphone = Microphone( - rate=rate, - channels=channels, - verbose=self._config.verbose, - input_device_index=device_index, - ) - else: - self._microphone = Microphone( - rate=rate, - channels=channels, - verbose=self._config.verbose, - ) - - if self._config.options.get("speaker_playback") == "true": - self._logger.info("speaker_playback is enabled") - rate = self._config.options.get("speaker_playback_rate", SPEAKER_RATE) - channels = self._config.options.get( - "speaker_playback_channels", SPEAKER_CHANNELS - ) - playback_delta_in_ms = self._config.options.get( - "speaker_playback_delta_in_ms", SPEAKER_PLAYBACK_DELTA - ) - device_index = self._config.options.get("speaker_playback_device_index") - - self._logger.debug("rate: %s", rate) - self._logger.debug("channels: %s", channels) - - self._speaker_created = True - - if device_index is not None: - self._logger.debug("device_index: %s", device_index) - - self._speaker = Speaker( - rate=rate, - channels=channels, - last_play_delta_in_ms=playback_delta_in_ms, - verbose=self._config.verbose, - output_device_index=device_index, - microphone=self._microphone, - ) - else: - self._speaker = Speaker( - rate=rate, - channels=channels, - last_play_delta_in_ms=playback_delta_in_ms, - verbose=self._config.verbose, - microphone=self._microphone, - ) - # call the parent constructor - super().__init__(self._config, self._endpoint) - - # pylint: disable=too-many-branches,too-many-statements - async def start( - self, - options: Optional[SettingsOptions] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - members: Optional[Dict] = None, - **kwargs, - ) -> bool: - """ - Starts the WebSocket connection for agent API. - """ - self._logger.debug("AsyncAgentWebSocketClient.start ENTER") - self._logger.info("settings: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - self._logger.info("members: %s", members) - self._logger.info("kwargs: %s", kwargs) - - if isinstance(options, SettingsOptions) and not options.check(): - self._logger.error("settings.check failed") - self._logger.debug("AsyncAgentWebSocketClient.start LEAVE") - raise DeepgramError("Fatal agent settings error") - - self._addons = addons - self._headers = headers - - # add "members" as members of the class - if members is not None: - self.__dict__.update(members) - - # set kwargs as members of the class - if kwargs is not None: - self._kwargs = kwargs - else: - self._kwargs = {} - - if isinstance(options, SettingsOptions): - self._logger.info("options is class") - self._settings = options - elif isinstance(options, dict): - self._logger.info("options is dict") - self._settings = SettingsOptions.from_dict(options) - elif isinstance(options, str): - self._logger.info("options is json") - self._settings = SettingsOptions.from_json(options) - else: - raise DeepgramError("Invalid options type") - - try: - # speaker substitutes the listening thread - if self._speaker is not None: - self._logger.notice("passing speaker to delegate_listening") - super().delegate_listening(self._speaker) - - # call parent start - if ( - await super().start( - {}, - self._addons, - self._headers, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - is False - ): - self._logger.error("AsyncAgentWebSocketClient.start failed") - self._logger.debug("AsyncAgentWebSocketClient.start LEAVE") - return False - - if self._speaker is not None: - self._logger.notice("speaker is delegate_listening. Starting speaker") - self._speaker.start() - - if self._speaker is not None and self._microphone is not None: - self._logger.notice( - "speaker is delegate_listening. Starting microphone" - ) - self._microphone.set_callback(self.send) - self._microphone.start() - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - # keepalive thread - if self._config.is_keep_alive_enabled(): - self._logger.notice("keepalive is enabled") - self._keep_alive_thread = asyncio.create_task(self._keep_alive()) - else: - self._logger.notice("keepalive is disabled") - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - # send the configurationsetting message - self._logger.notice("Sending Settings...") - ret_send_cs = await self.send(str(self._settings)) - if not ret_send_cs: - self._logger.error("Settings failed") - - err_error: ErrorResponse = ErrorResponse( - "Exception in AsyncAgentWebSocketClient.start", - "Settings failed to send", - "Exception", - ) - await self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.Error), - error=err_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - self._logger.debug("AgentWebSocketClient.start LEAVE") - return False - - self._logger.notice("start succeeded") - self._logger.debug("AsyncAgentWebSocketClient.start LEAVE") - return True - - except Exception as e: # pylint: disable=broad-except - self._logger.error( - "WebSocketException in AsyncAgentWebSocketClient.start: %s", e - ) - self._logger.debug("AsyncAgentWebSocketClient.start LEAVE") - if self._config.options.get("termination_exception_connect") is True: - raise e - return False - - # pylint: enable=too-many-branches,too-many-statements - - def on(self, event: AgentWebSocketEvents, handler: Callable) -> None: - """ - Registers event handlers for specific events. - """ - self._logger.info("event subscribed: %s", event) - if event in AgentWebSocketEvents.__members__.values() and callable(handler): - self._event_handlers[event].append(handler) - - async def _emit(self, event: AgentWebSocketEvents, *args, **kwargs) -> None: - """ - Emits events to the registered event handlers. - """ - self._logger.debug("AsyncAgentWebSocketClient._emit ENTER") - self._logger.debug("callback handlers for: %s", event) - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - self._logger.debug("callback handlers for: %s", event) - tasks = [] - for handler in self._event_handlers[event]: - task = asyncio.create_task(handler(self, *args, **kwargs)) - tasks.append(task) - - if tasks: - self._logger.debug("waiting for tasks to finish...") - await asyncio.gather(*tasks, return_exceptions=True) - tasks.clear() - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - self._logger.debug("AsyncAgentWebSocketClient._emit LEAVE") - - # pylint: disable=too-many-locals,too-many-statements - async def _process_text(self, message: str) -> None: - """ - Processes messages received over the WebSocket connection. - """ - self._logger.debug("AsyncAgentWebSocketClient._process_text ENTER") - - try: - self._logger.debug("Text data received") - if len(message) == 0: - self._logger.debug("message is empty") - self._logger.debug("AsyncAgentWebSocketClient._process_text LEAVE") - return - - data = json.loads(message) - response_type = data.get("type") - self._logger.debug("response_type: %s, data: %s", response_type, data) - - match response_type: - case AgentWebSocketEvents.Open: - open_result: OpenResponse = OpenResponse.from_json(message) - self._logger.verbose("OpenResponse: %s", open_result) - await self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.Open), - open=open_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case AgentWebSocketEvents.Welcome: - welcome_result: WelcomeResponse = WelcomeResponse.from_json(message) - self._logger.verbose("WelcomeResponse: %s", welcome_result) - await self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.Welcome), - welcome=welcome_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case AgentWebSocketEvents.SettingsApplied: - settings_applied_result: SettingsAppliedResponse = ( - SettingsAppliedResponse.from_json(message) - ) - self._logger.verbose( - "SettingsAppliedResponse: %s", settings_applied_result - ) - await self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.SettingsApplied), - settings_applied=settings_applied_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case AgentWebSocketEvents.ConversationText: - conversation_text_result: ConversationTextResponse = ( - ConversationTextResponse.from_json(message) - ) - self._logger.verbose( - "ConversationTextResponse: %s", conversation_text_result - ) - await self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.ConversationText), - conversation_text=conversation_text_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case AgentWebSocketEvents.UserStartedSpeaking: - user_started_speaking_result: UserStartedSpeakingResponse = ( - UserStartedSpeakingResponse.from_json(message) - ) - self._logger.verbose( - "UserStartedSpeakingResponse: %s", user_started_speaking_result - ) - await self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.UserStartedSpeaking), - user_started_speaking=user_started_speaking_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case AgentWebSocketEvents.AgentThinking: - agent_thinking_result: AgentThinkingResponse = ( - AgentThinkingResponse.from_json(message) - ) - self._logger.verbose( - "AgentThinkingResponse: %s", agent_thinking_result - ) - await self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.AgentThinking), - agent_thinking=agent_thinking_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case AgentWebSocketEvents.FunctionCallRequest: - function_call_request_result: FunctionCallRequest = ( - FunctionCallRequest.from_json(message) - ) - self._logger.verbose( - "FunctionCallRequest: %s", function_call_request_result - ) - await self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.FunctionCallRequest), - function_call_request=function_call_request_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case AgentWebSocketEvents.AgentStartedSpeaking: - agent_started_speaking_result: AgentStartedSpeakingResponse = ( - AgentStartedSpeakingResponse.from_json(message) - ) - self._logger.verbose( - "AgentStartedSpeakingResponse: %s", - agent_started_speaking_result, - ) - await self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.AgentStartedSpeaking), - agent_started_speaking=agent_started_speaking_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case AgentWebSocketEvents.AgentAudioDone: - agent_audio_done_result: AgentAudioDoneResponse = ( - AgentAudioDoneResponse.from_json(message) - ) - self._logger.verbose( - "AgentAudioDoneResponse: %s", agent_audio_done_result - ) - await self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.AgentAudioDone), - agent_audio_done=agent_audio_done_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case AgentWebSocketEvents.InjectionRefused: - injection_refused_result: InjectionRefusedResponse = ( - InjectionRefusedResponse.from_json(message) - ) - self._logger.verbose( - "InjectionRefused: %s", injection_refused_result - ) - await self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.InjectionRefused), - injection_refused=injection_refused_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case AgentWebSocketEvents.Close: - close_result: CloseResponse = CloseResponse.from_json(message) - self._logger.verbose("CloseResponse: %s", close_result) - await self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.Close), - close=close_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case AgentWebSocketEvents.Error: - err_error: ErrorResponse = ErrorResponse.from_json(message) - self._logger.verbose("ErrorResponse: %s", err_error) - await self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.Error), - error=err_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case _: - self._logger.warning( - "Unknown Message: response_type: %s, data: %s", - response_type, - data, - ) - unhandled_error: UnhandledResponse = UnhandledResponse( - type=AgentWebSocketEvents(AgentWebSocketEvents.Unhandled), - raw=message, - ) - await self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.Unhandled), - unhandled=unhandled_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - self._logger.notice("_process_text Succeeded") - self._logger.debug("AsyncAgentWebSocketClient._process_text LEAVE") - - except Exception as e: # pylint: disable=broad-except - self._logger.error( - "Exception in AsyncAgentWebSocketClient._process_text: %s", e - ) - e_error: ErrorResponse = ErrorResponse( - "Exception in AsyncAgentWebSocketClient._process_text", - f"{e}", - "Exception", - ) - await self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.Error), - error=e_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - # signal exit and close - await super()._signal_exit() - - self._logger.debug("AsyncAgentWebSocketClient._process_text LEAVE") - - if self._config.options.get("termination_exception") is True: - raise - return - - # pylint: enable=too-many-locals,too-many-statements - - async def _process_binary(self, message: bytes) -> None: - self._logger.debug("AsyncAgentWebSocketClient._process_binary ENTER") - self._logger.debug("Binary data received") - - await self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.AudioData), - data=message, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - self._logger.notice("_process_binary Succeeded") - self._logger.debug("AsyncAgentWebSocketClient._process_binary LEAVE") - - # pylint: disable=too-many-return-statements - async def _keep_alive(self) -> None: - """ - Sends keepalive messages to the WebSocket connection. - """ - self._logger.debug("AsyncAgentWebSocketClient._keep_alive ENTER") - - counter = 0 - while True: - try: - counter += 1 - await asyncio.sleep(ONE_SECOND) - - if self._exit_event.is_set(): - self._logger.notice("_keep_alive exiting gracefully") - self._logger.debug("AsyncAgentWebSocketClient._keep_alive LEAVE") - return - - # deepgram keepalive - if counter % DEEPGRAM_INTERVAL == 0: - await self.keep_alive() - - except Exception as e: # pylint: disable=broad-except - self._logger.error( - "Exception in AsyncAgentWebSocketClient._keep_alive: %s", e - ) - e_error: ErrorResponse = ErrorResponse( - "Exception in AsyncAgentWebSocketClient._keep_alive", - f"{e}", - "Exception", - ) - self._logger.error( - "Exception in AsyncAgentWebSocketClient._keep_alive: %s", str(e) - ) - await self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.Error), - error=e_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - # signal exit and close - await super()._signal_exit() - - self._logger.debug("AsyncAgentWebSocketClient._keep_alive LEAVE") - - if self._config.options.get("termination_exception") is True: - raise - return - - async def keep_alive(self) -> bool: - """ - Sends a KeepAlive message - """ - self._logger.spam("AsyncAgentWebSocketClient.keep_alive ENTER") - - self._logger.notice("Sending KeepAlive...") - ret = await self.send(json.dumps({"type": "KeepAlive"})) - - if not ret: - self._logger.error("keep_alive failed") - self._logger.spam("AsyncAgentWebSocketClient.keep_alive LEAVE") - return False - - self._logger.notice("keep_alive succeeded") - self._logger.spam("AsyncAgentWebSocketClient.keep_alive LEAVE") - - return True - - async def _close_message(self) -> bool: - # TODO: No known API close message # pylint: disable=fixme - # return await self.send(json.dumps({"type": "Close"})) - return True - - async def finish(self) -> bool: - """ - Closes the WebSocket connection gracefully. - """ - self._logger.debug("AsyncAgentWebSocketClient.finish ENTER") - - # stop the threads - self._logger.verbose("cancelling tasks...") - try: - # call parent finish - if await super().finish() is False: - self._logger.error("AsyncAgentWebSocketClient.finish failed") - - if self._microphone is not None and self._microphone_created: - self._microphone.finish() - self._microphone_created = False - - if self._speaker is not None and self._speaker_created: - self._speaker.finish() - self._speaker_created = False - - # Before cancelling, check if the tasks were created - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("before running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - tasks = [] - if self._keep_alive_thread is not None: - self._keep_alive_thread.cancel() - tasks.append(self._keep_alive_thread) - self._logger.notice("processing _keep_alive_thread cancel...") - - # Use asyncio.gather to wait for tasks to be cancelled - # Prevent indefinite waiting by setting a timeout - await asyncio.wait_for(asyncio.gather(*tasks), timeout=10) - self._logger.notice("threads joined") - - self._speaker = None - self._microphone = None - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - self._logger.notice("finish succeeded") - self._logger.spam("AsyncAgentWebSocketClient.finish LEAVE") - return True - - except asyncio.CancelledError as e: - self._logger.error("tasks cancelled error: %s", e) - self._logger.debug("AsyncAgentWebSocketClient.finish LEAVE") - return False - - except asyncio.TimeoutError as e: - self._logger.error("tasks cancellation timed out: %s", e) - self._logger.debug("AsyncAgentWebSocketClient.finish LEAVE") - return False diff --git a/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/client.py b/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/client.py deleted file mode 100644 index 8f7e2322..00000000 --- a/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/client.py +++ /dev/null @@ -1,669 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -import json -import logging -from typing import Dict, Union, Optional, cast, Any, Callable -import threading -import time - -from .....utils import verboselogs -from .....options import DeepgramClientOptions -from ...enums import AgentWebSocketEvents -from ....common import AbstractSyncWebSocketClient -from ....common import DeepgramError - -from .response import ( - OpenResponse, - WelcomeResponse, - SettingsAppliedResponse, - ConversationTextResponse, - UserStartedSpeakingResponse, - AgentThinkingResponse, - FunctionCallRequest, - AgentStartedSpeakingResponse, - AgentAudioDoneResponse, - InjectionRefusedResponse, - CloseResponse, - ErrorResponse, - UnhandledResponse, -) -from .options import ( - SettingsOptions, - UpdatePromptOptions, - UpdateSpeakOptions, - InjectAgentMessageOptions, - FunctionCallResponse, - AgentKeepAlive, -) - -from .....audio.speaker import ( - Speaker, - RATE as SPEAKER_RATE, - CHANNELS as SPEAKER_CHANNELS, - PLAYBACK_DELTA as SPEAKER_PLAYBACK_DELTA, -) -from .....audio.microphone import ( - Microphone, - RATE as MICROPHONE_RATE, - CHANNELS as MICROPHONE_CHANNELS, -) - -ONE_SECOND = 1 -HALF_SECOND = 0.5 -DEEPGRAM_INTERVAL = 5 - - -class AgentWebSocketClient( - AbstractSyncWebSocketClient -): # pylint: disable=too-many-instance-attributes - """ - Client for interacting with Deepgram's live transcription services over WebSockets. - - This class provides methods to establish a WebSocket connection for live transcription and handle real-time transcription events. - - Args: - config (DeepgramClientOptions): all the options for the client. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - _endpoint: str - - _event_handlers: Dict[AgentWebSocketEvents, list] - - _keep_alive_thread: Union[threading.Thread, None] - - _kwargs: Optional[Dict] = None - _addons: Optional[Dict] = None - # note the distinction here. We can't use _config because it's already used in the parent - _settings: Optional[SettingsOptions] = None - _headers: Optional[Dict] = None - - _speaker_created: bool = False - _speaker: Optional[Speaker] = None - _microphone_created: bool = False - _microphone: Optional[Microphone] = None - - def __init__(self, config: DeepgramClientOptions): - if config is None: - raise DeepgramError("Config is required") - - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - - self._config = config - - # needs to be "wss://agent.deepgram.com/agent" - self._endpoint = "v1/agent/converse" - - # override the endpoint since it needs to be "wss://agent.deepgram.com/agent" - self._config.url = "agent.deepgram.com" - - self._keep_alive_thread = None - - # init handlers - self._event_handlers = { - event: [] for event in AgentWebSocketEvents.__members__.values() - } - - if self._config.options.get("microphone_record") == "true": - self._logger.info("microphone_record is enabled") - rate = self._config.options.get("microphone_record_rate", MICROPHONE_RATE) - channels = self._config.options.get( - "microphone_record_channels", MICROPHONE_CHANNELS - ) - device_index = self._config.options.get("microphone_record_device_index") - - self._logger.debug("rate: %s", rate) - self._logger.debug("channels: %s", channels) - - self._microphone_created = True - - if device_index is not None: - self._logger.debug("device_index: %s", device_index) - self._microphone = Microphone( - rate=rate, - channels=channels, - verbose=self._config.verbose, - input_device_index=device_index, - ) - else: - self._microphone = Microphone( - rate=rate, - channels=channels, - verbose=self._config.verbose, - ) - - if self._config.options.get("speaker_playback") == "true": - self._logger.info("speaker_playback is enabled") - rate = self._config.options.get("speaker_playback_rate", SPEAKER_RATE) - channels = self._config.options.get( - "speaker_playback_channels", SPEAKER_CHANNELS - ) - playback_delta_in_ms = self._config.options.get( - "speaker_playback_delta_in_ms", SPEAKER_PLAYBACK_DELTA - ) - device_index = self._config.options.get("speaker_playback_device_index") - - self._logger.debug("rate: %s", rate) - self._logger.debug("channels: %s", channels) - - self._speaker_created = True - - if device_index is not None: - self._logger.debug("device_index: %s", device_index) - - self._speaker = Speaker( - rate=rate, - channels=channels, - last_play_delta_in_ms=playback_delta_in_ms, - verbose=self._config.verbose, - output_device_index=device_index, - microphone=self._microphone, - ) - else: - self._speaker = Speaker( - rate=rate, - channels=channels, - last_play_delta_in_ms=playback_delta_in_ms, - verbose=self._config.verbose, - microphone=self._microphone, - ) - - # call the parent constructor - super().__init__(self._config, self._endpoint) - - # pylint: disable=too-many-statements,too-many-branches - def start( - self, - options: Optional[SettingsOptions] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - members: Optional[Dict] = None, - **kwargs, - ) -> bool: - """ - Starts the WebSocket connection for agent API. - """ - self._logger.debug("AgentWebSocketClient.start ENTER") - self._logger.info("settings: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - self._logger.info("members: %s", members) - self._logger.info("kwargs: %s", kwargs) - - if isinstance(options, SettingsOptions) and not options.check(): - self._logger.error("settings.check failed") - self._logger.debug("AgentWebSocketClient.start LEAVE") - raise DeepgramError("Fatal agent settings error") - - self._addons = addons - self._headers = headers - - # add "members" as members of the class - if members is not None: - self.__dict__.update(members) - - # set kwargs as members of the class - if kwargs is not None: - self._kwargs = kwargs - else: - self._kwargs = {} - - if isinstance(options, SettingsOptions): - self._logger.info("options is class") - self._settings = options - elif isinstance(options, dict): - self._logger.info("options is dict") - self._settings = SettingsOptions.from_dict(options) - elif isinstance(options, str): - self._logger.info("options is json") - self._settings = SettingsOptions.from_json(options) - else: - raise DeepgramError("Invalid options type") - - try: - # speaker substitutes the listening thread - if self._speaker is not None: - self._logger.notice("passing speaker to delegate_listening") - super().delegate_listening(self._speaker) - - # call parent start - if ( - super().start( - {}, - self._addons, - self._headers, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - is False - ): - self._logger.error("AgentWebSocketClient.start failed") - self._logger.debug("AgentWebSocketClient.start LEAVE") - return False - - if self._speaker is not None: - self._logger.notice("speaker is delegate_listening. Starting speaker") - self._speaker.start() - - if self._speaker is not None and self._microphone is not None: - self._logger.notice( - "speaker is delegate_listening. Starting microphone" - ) - self._microphone.set_callback(self.send) - self._microphone.start() - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - # keepalive thread - if self._config.is_keep_alive_enabled(): - self._logger.notice("keepalive is enabled") - self._keep_alive_thread = threading.Thread(target=self._keep_alive) - self._keep_alive_thread.start() - else: - self._logger.notice("keepalive is disabled") - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - # send the Settings message - self._logger.notice("Sending Settings...") - ret_send_cs = self.send(str(self._settings)) - if not ret_send_cs: - self._logger.error("Settings failed") - - err_error: ErrorResponse = ErrorResponse( - "Exception in AgentWebSocketClient.start", - "Settings failed to send", - "Exception", - ) - self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.Error), - error=err_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - self._logger.debug("AgentWebSocketClient.start LEAVE") - return False - - self._logger.notice("start succeeded") - self._logger.debug("AgentWebSocketClient.start LEAVE") - return True - - except Exception as e: # pylint: disable=broad-except - self._logger.error( - "WebSocketException in AgentWebSocketClient.start: %s", e - ) - self._logger.debug("AgentWebSocketClient.start LEAVE") - if self._config.options.get("termination_exception_connect") is True: - raise e - return False - - # pylint: enable=too-many-statements,too-many-branches - - def on(self, event: AgentWebSocketEvents, handler: Callable) -> None: - """ - Registers event handlers for specific events. - """ - self._logger.info("event subscribed: %s", event) - if event in AgentWebSocketEvents.__members__.values() and callable(handler): - self._event_handlers[event].append(handler) - - def _emit(self, event: AgentWebSocketEvents, *args, **kwargs) -> None: - """ - Emits events to the registered event handlers. - """ - self._logger.debug("AgentWebSocketClient._emit ENTER") - self._logger.debug("callback handlers for: %s", event) - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - self._logger.debug("callback handlers for: %s", event) - for handler in self._event_handlers[event]: - handler(self, *args, **kwargs) - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - self._logger.debug("AgentWebSocketClient._emit LEAVE") - - # pylint: disable=too-many-return-statements,too-many-statements,too-many-locals,too-many-branches - def _process_text(self, message: str) -> None: - """ - Processes messages received over the WebSocket connection. - """ - self._logger.debug("AgentWebSocketClient._process_text ENTER") - - try: - self._logger.debug("Text data received") - if len(message) == 0: - self._logger.debug("message is empty") - self._logger.debug("AgentWebSocketClient._process_text LEAVE") - return - - data = json.loads(message) - response_type = data.get("type") - self._logger.debug("response_type: %s, data: %s", response_type, data) - - match response_type: - case AgentWebSocketEvents.Open: - open_result: OpenResponse = OpenResponse.from_json(message) - self._logger.verbose("OpenResponse: %s", open_result) - self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.Open), - open=open_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case AgentWebSocketEvents.Welcome: - welcome_result: WelcomeResponse = WelcomeResponse.from_json(message) - self._logger.verbose("WelcomeResponse: %s", welcome_result) - self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.Welcome), - welcome=welcome_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case AgentWebSocketEvents.SettingsApplied: - settings_applied_result: SettingsAppliedResponse = ( - SettingsAppliedResponse.from_json(message) - ) - self._logger.verbose( - "SettingsAppliedResponse: %s", settings_applied_result - ) - self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.SettingsApplied), - settings_applied=settings_applied_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case AgentWebSocketEvents.ConversationText: - conversation_text_result: ConversationTextResponse = ( - ConversationTextResponse.from_json(message) - ) - self._logger.verbose( - "ConversationTextResponse: %s", conversation_text_result - ) - self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.ConversationText), - conversation_text=conversation_text_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case AgentWebSocketEvents.UserStartedSpeaking: - user_started_speaking_result: UserStartedSpeakingResponse = ( - UserStartedSpeakingResponse.from_json(message) - ) - self._logger.verbose( - "UserStartedSpeakingResponse: %s", user_started_speaking_result - ) - self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.UserStartedSpeaking), - user_started_speaking=user_started_speaking_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case AgentWebSocketEvents.AgentThinking: - agent_thinking_result: AgentThinkingResponse = ( - AgentThinkingResponse.from_json(message) - ) - self._logger.verbose( - "AgentThinkingResponse: %s", agent_thinking_result - ) - self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.AgentThinking), - agent_thinking=agent_thinking_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case AgentWebSocketEvents.FunctionCallRequest: - function_call_request_result: FunctionCallRequest = ( - FunctionCallRequest.from_json(message) - ) - self._logger.verbose( - "FunctionCallRequest: %s", function_call_request_result - ) - self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.FunctionCallRequest), - function_call_request=function_call_request_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case AgentWebSocketEvents.AgentStartedSpeaking: - agent_started_speaking_result: AgentStartedSpeakingResponse = ( - AgentStartedSpeakingResponse.from_json(message) - ) - self._logger.verbose( - "AgentStartedSpeakingResponse: %s", - agent_started_speaking_result, - ) - self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.AgentStartedSpeaking), - agent_started_speaking=agent_started_speaking_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case AgentWebSocketEvents.AgentAudioDone: - agent_audio_done_result: AgentAudioDoneResponse = ( - AgentAudioDoneResponse.from_json(message) - ) - self._logger.verbose( - "AgentAudioDoneResponse: %s", agent_audio_done_result - ) - self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.AgentAudioDone), - agent_audio_done=agent_audio_done_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case AgentWebSocketEvents.InjectionRefused: - injection_refused_result: InjectionRefusedResponse = ( - InjectionRefusedResponse.from_json(message) - ) - self._logger.verbose( - "InjectionRefused: %s", injection_refused_result - ) - self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.InjectionRefused), - injection_refused=injection_refused_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case AgentWebSocketEvents.Close: - close_result: CloseResponse = CloseResponse.from_json(message) - self._logger.verbose("CloseResponse: %s", close_result) - self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.Close), - close=close_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case AgentWebSocketEvents.Error: - err_error: ErrorResponse = ErrorResponse.from_json(message) - self._logger.verbose("ErrorResponse: %s", err_error) - self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.Error), - error=err_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case _: - self._logger.warning( - "Unknown Message: response_type: %s, data: %s", - response_type, - data, - ) - unhandled_error: UnhandledResponse = UnhandledResponse( - type=AgentWebSocketEvents(AgentWebSocketEvents.Unhandled), - raw=message, - ) - self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.Unhandled), - unhandled=unhandled_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - self._logger.notice("_process_text Succeeded") - self._logger.debug("SpeakStreamClient._process_text LEAVE") - - except Exception as e: # pylint: disable=broad-except - self._logger.error("Exception in AgentWebSocketClient._process_text: %s", e) - e_error: ErrorResponse = ErrorResponse( - "Exception in AgentWebSocketClient._process_text", - f"{e}", - "Exception", - ) - self._logger.error( - "Exception in AgentWebSocketClient._process_text: %s", str(e) - ) - self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.Error), - error=e_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - # signal exit and close - super()._signal_exit() - - self._logger.debug("AgentWebSocketClient._process_text LEAVE") - - if self._config.options.get("termination_exception") is True: - raise - return - - # pylint: enable=too-many-return-statements,too-many-statements - - def _process_binary(self, message: bytes) -> None: - self._logger.debug("AgentWebSocketClient._process_binary ENTER") - self._logger.debug("Binary data received") - - self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.AudioData), - data=message, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - self._logger.notice("_process_binary Succeeded") - self._logger.debug("AgentWebSocketClient._process_binary LEAVE") - - # pylint: disable=too-many-return-statements - def _keep_alive(self) -> None: - """ - Sends keepalive messages to the WebSocket connection. - """ - self._logger.debug("AgentWebSocketClient._keep_alive ENTER") - - counter = 0 - while True: - try: - counter += 1 - self._exit_event.wait(timeout=ONE_SECOND) - - if self._exit_event.is_set(): - self._logger.notice("_keep_alive exiting gracefully") - self._logger.debug("AgentWebSocketClient._keep_alive LEAVE") - return - - # deepgram keepalive - if counter % DEEPGRAM_INTERVAL == 0: - self.keep_alive() - - except Exception as e: # pylint: disable=broad-except - self._logger.error( - "Exception in AgentWebSocketClient._keep_alive: %s", e - ) - e_error: ErrorResponse = ErrorResponse( - "Exception in AgentWebSocketClient._keep_alive", - f"{e}", - "Exception", - ) - self._logger.error( - "Exception in AgentWebSocketClient._keep_alive: %s", str(e) - ) - self._emit( - AgentWebSocketEvents(AgentWebSocketEvents.Error), - error=e_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - # signal exit and close - super()._signal_exit() - - self._logger.debug("AgentWebSocketClient._keep_alive LEAVE") - - if self._config.options.get("termination_exception") is True: - raise - return - - def keep_alive(self) -> bool: - """ - Sends a KeepAlive message - """ - self._logger.spam("AgentWebSocketClient.keep_alive ENTER") - - self._logger.notice("Sending KeepAlive...") - ret = self.send(json.dumps({"type": "KeepAlive"})) - - if not ret: - self._logger.error("keep_alive failed") - self._logger.spam("AgentWebSocketClient.keep_alive LEAVE") - return False - - self._logger.notice("keep_alive succeeded") - self._logger.spam("AgentWebSocketClient.keep_alive LEAVE") - - return True - - def _close_message(self) -> bool: - # TODO: No known API close message # pylint: disable=fixme - # return self.send(json.dumps({"type": "Close"})) - return True - - # closes the WebSocket connection gracefully - def finish(self) -> bool: - """ - Closes the WebSocket connection gracefully. - """ - self._logger.spam("AgentWebSocketClient.finish ENTER") - - # call parent finish - if super().finish() is False: - self._logger.error("AgentWebSocketClient.finish failed") - - if self._microphone is not None and self._microphone_created: - self._microphone.finish() - self._microphone_created = False - - if self._speaker is not None and self._speaker_created: - self._speaker.finish() - self._speaker_created = False - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("before running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - # stop the threads - self._logger.verbose("cancelling tasks...") - if self._keep_alive_thread is not None: - self._keep_alive_thread.join() - self._keep_alive_thread = None - self._logger.notice("processing _keep_alive_thread thread joined") - - if self._listen_thread is not None: - self._listen_thread.join() - self._listen_thread = None - self._logger.notice("listening thread joined") - - self._speaker = None - self._microphone = None - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("before running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - self._logger.notice("finish succeeded") - self._logger.spam("AgentWebSocketClient.finish LEAVE") - return True diff --git a/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/options.py b/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/options.py deleted file mode 100644 index ffdaa5c1..00000000 --- a/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/options.py +++ /dev/null @@ -1,368 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from typing import List, Optional, Union, Any, Tuple, Dict -import logging - -from dataclasses import dataclass, field -from dataclasses_json import config as dataclass_config - -from deepgram.utils import verboselogs - -from ...enums import AgentWebSocketEvents -from ....common import BaseResponse - - -# ConfigurationSettings - - -@dataclass -class Header(BaseResponse): - """ - This class defines a single key/value pair for a header. - """ - - key: str - value: str - - -@dataclass -class Item(BaseResponse): - """ - This class defines a single item in a list of items. - """ - - type: str - description: str - - -@dataclass -class Properties(BaseResponse): - """ - This class defines the properties which is just a list of items. - """ - - item: Item - - def __getitem__(self, key): - _dict = self.to_dict() - if "item" in _dict: - _dict["item"] = [Item.from_dict(item) for item in _dict["item"]] - return _dict[key] - - -@dataclass -class Parameters(BaseResponse): - """ - This class defines the parameters for a function. - """ - - type: str - properties: Properties - required: List[str] - - def __getitem__(self, key): - _dict = self.to_dict() - if "properties" in _dict: - _dict["properties"] = _dict["properties"].copy() - return _dict[key] - -class Provider(dict): - """ - Generic attribute class for provider objects. - """ - def __getattr__(self, name): - try: - return self[name] - except KeyError: - # pylint: disable=raise-missing-from - raise AttributeError(name) - def __setattr__(self, name, value): - self[name] = value - - -@dataclass -class Endpoint(BaseResponse): - """ - Define a custom endpoint for the agent. - """ - - method: Optional[str] = field(default="POST") - url: str = field(default="") - headers: Optional[List[Header]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "headers" in _dict: - _dict["headers"] = [ - Header.from_dict(headers) for headers in _dict["headers"] - ] - return _dict[key] - - -@dataclass -class Function(BaseResponse): - """ - This class defines a function for the Think model. - """ - - name: str - description: str - url: str - method: str - headers: Optional[List[Header]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - parameters: Optional[Parameters] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - endpoint: Optional[Endpoint] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "parameters" in _dict and isinstance(_dict["parameters"], dict): - _dict["parameters"] = Parameters.from_dict(_dict["parameters"]) - if "headers" in _dict and isinstance(_dict["headers"], list): - _dict["headers"] = [Header.from_dict(header) for header in _dict["headers"]] - if "endpoint" in _dict and isinstance(_dict["endpoint"], dict): - _dict["endpoint"] = Endpoint.from_dict(_dict["endpoint"]) - return _dict[key] - - -@dataclass -class Think(BaseResponse): - """ - This class defines any configuration settings for the Think model. - """ - - provider: Provider = field(default_factory=Provider) - functions: Optional[List[Function]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - endpoint: Optional[Endpoint] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - prompt: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __post_init__(self): - if not isinstance(self.provider, Provider): - self.provider = Provider(self.provider) - - def __getitem__(self, key): - _dict = self.to_dict() - if "functions" in _dict and isinstance(_dict["functions"], list): - _dict["functions"] = [ - Function.from_dict(function) for function in _dict["functions"] - ] - if "endpoint" in _dict and isinstance(_dict["endpoint"], dict): - _dict["endpoint"] = Endpoint.from_dict(_dict["endpoint"]) - return _dict[key] - - -@dataclass -class Listen(BaseResponse): - """ - This class defines any configuration settings for the Listen model. - """ - - provider: Provider = field(default_factory=Provider) - - def __post_init__(self): - if not isinstance(self.provider, Provider): - self.provider = Provider(self.provider) - - def __getitem__(self, key): - _dict = self.to_dict() - return _dict[key] - - -@dataclass -class Speak(BaseResponse): - """ - This class defines any configuration settings for the Speak model. - """ - - provider: Provider = field(default_factory=Provider) - endpoint: Optional[Endpoint] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __post_init__(self): - if not isinstance(self.provider, Provider): - self.provider = Provider(self.provider) - - def __getitem__(self, key): - _dict = self.to_dict() - if "endpoint" in _dict and isinstance(_dict["endpoint"], dict): - _dict["endpoint"] = Endpoint.from_dict(_dict["endpoint"]) - return _dict[key] - - -@dataclass -class Agent(BaseResponse): - """ - This class defines any configuration settings for the Agent model. - """ - - language: str = field(default="en") - listen: Listen = field(default_factory=Listen) - think: Think = field(default_factory=Think) - speak: Speak = field(default_factory=Speak) - greeting: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "listen" in _dict and isinstance(_dict["listen"], dict): - _dict["listen"] = Listen.from_dict(_dict["listen"]) - if "think" in _dict and isinstance(_dict["think"], dict): - _dict["think"] = Think.from_dict(_dict["think"]) - if "speak" in _dict and isinstance(_dict["speak"], dict): - _dict["speak"] = Speak.from_dict(_dict["speak"]) - return _dict[key] -@dataclass -class Input(BaseResponse): - """ - This class defines any configuration settings for the input audio. - """ - - encoding: Optional[str] = field(default="linear16") - sample_rate: int = field(default=16000) - - -@dataclass -class Output(BaseResponse): - """ - This class defines any configuration settings for the output audio. - """ - - encoding: Optional[str] = field(default="linear16") - sample_rate: Optional[int] = field(default=16000) - bitrate: Optional[int] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - container: Optional[str] = field(default="none") - - -@dataclass -class Audio(BaseResponse): - """ - This class defines any configuration settings for the audio. - """ - - input: Optional[Input] = field(default_factory=Input) - output: Optional[Output] = field(default_factory=Output) - - def __getitem__(self, key): - _dict = self.to_dict() - if "input" in _dict and isinstance(_dict["input"], dict): - _dict["input"] = Input.from_dict(_dict["input"]) - if "output" in _dict and isinstance(_dict["output"], dict): - _dict["output"] = Output.from_dict(_dict["output"]) - return _dict[key] - -@dataclass -class SettingsOptions(BaseResponse): - """ - The client should send a Settings message immediately after opening the websocket and before sending any audio. - """ - - experimental: Optional[bool] = field(default=False) - type: str = str(AgentWebSocketEvents.Settings) - audio: Audio = field(default_factory=Audio) - agent: Agent = field(default_factory=Agent) - - def __getitem__(self, key): - _dict = self.to_dict() - if "audio" in _dict and isinstance(_dict["audio"], dict): - _dict["audio"] = Audio.from_dict(_dict["audio"]) - if "agent" in _dict and isinstance(_dict["agent"], dict): - _dict["agent"] = Agent.from_dict(_dict["agent"]) - - def check(self): - """ - Check the options for any deprecated or soon-to-be-deprecated options. - """ - logger = verboselogs.VerboseLogger(__name__) - logger.addHandler(logging.StreamHandler()) - prev = logger.level - logger.setLevel(verboselogs.ERROR) - - # do we need to check anything here? - - logger.setLevel(prev) - - return True - - -# UpdatePrompt - - -@dataclass -class UpdatePromptOptions(BaseResponse): - """ - The client can send an UpdatePrompt message to provide a new prompt to the Think model in the middle of a conversation. - """ - - type: str = str(AgentWebSocketEvents.UpdatePrompt) - prompt: str = field(default="") - - -# UpdateSpeak - - -@dataclass -class UpdateSpeakOptions(BaseResponse): - """ - The client can send an UpdateSpeak message to change the Speak model in the middle of a conversation. - """ - - type: str = str(AgentWebSocketEvents.UpdateSpeak) - speak: Speak = field(default_factory=Speak) - - -# InjectAgentMessage - - -@dataclass -class InjectAgentMessageOptions(BaseResponse): - """ - The client can send an InjectAgentMessage to immediately trigger an agent statement. If the injection request arrives while the user is speaking, or while the server is in the middle of sending audio for an agent response, then the request will be ignored and the server will reply with an InjectionRefused. - """ - - type: str = str(AgentWebSocketEvents.InjectAgentMessage) - message: str = field(default="") - - -# Function Call Response - - -@dataclass -class FunctionCallResponse(BaseResponse): - """ - TheFunctionCallResponse message is a JSON command that the client should reply with every time there is a FunctionCallRequest received. - """ - - type: str = "FunctionCallResponse" - function_call_id: str = field(default="") - output: str = field(default="") - - -# Agent Keep Alive - - -@dataclass -class AgentKeepAlive(BaseResponse): - """ - The KeepAlive message is a JSON command that you can use to ensure that the server does not close the connection. - """ - - type: str = "KeepAlive" diff --git a/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/response.py b/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/response.py deleted file mode 100644 index c0dc226d..00000000 --- a/venv/Lib/site-packages/deepgram/clients/agent/v1/websocket/response.py +++ /dev/null @@ -1,109 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from typing import List, Optional, Dict, Any - -from dataclasses import dataclass - -# common websocket response -from ....common import ( - BaseResponse, - OpenResponse, - CloseResponse, - ErrorResponse, - UnhandledResponse, -) - -# unique - - -@dataclass -class WelcomeResponse(BaseResponse): - """ - The server will send a Welcome message as soon as the websocket opens. - """ - - type: str - request_id: str - - -@dataclass -class SettingsAppliedResponse(BaseResponse): - """ - The server will send a SettingsApplied message as soon as the settings are applied. - """ - - type: str - - -@dataclass -class ConversationTextResponse(BaseResponse): - """ - The server will send a ConversationText message every time the agent hears the user say something, and every time the agent speaks something itself. - """ - - type: str - role: str - content: str - - -@dataclass -class UserStartedSpeakingResponse(BaseResponse): - """ - The server will send a UserStartedSpeaking message every time the user begins a new utterance. - """ - - type: str - - -@dataclass -class AgentThinkingResponse(BaseResponse): - """ - The server will send an AgentThinking message to inform the client of a non-verbalized agent thought. - You will ONLY receive this message if you have set `experimental` to true. - """ - - type: str - content: str - - -@dataclass -class FunctionCallRequest(BaseResponse): - """ - The FunctionCallRequest message is used to call a function from the server to the client. - """ - - type: str - function_name: str - function_call_id: str - input: str - - -@dataclass -class AgentStartedSpeakingResponse(BaseResponse): - """ - The server will send an AgentStartedSpeaking message when it begins streaming an agent audio response to the client for playback. - """ - - total_latency: float - tts_latency: float - ttt_latency: float - - -@dataclass -class AgentAudioDoneResponse(BaseResponse): - """ - The server will send an AgentAudioDone message immediately after it sends the last audio message in a piece of agent speech. - """ - - type: str - - -@dataclass -class InjectionRefusedResponse(BaseResponse): - """ - The server will send an InjectionRefused message when an InjectAgentMessage request is ignored because it arrived while the user was speaking or while the server was sending audio for an agent response. - """ - - type: str diff --git a/venv/Lib/site-packages/deepgram/clients/agent_router.py b/venv/Lib/site-packages/deepgram/clients/agent_router.py deleted file mode 100644 index 90d82f3a..00000000 --- a/venv/Lib/site-packages/deepgram/clients/agent_router.py +++ /dev/null @@ -1,130 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from importlib import import_module -import logging - -from ..utils import verboselogs -from ..options import DeepgramClientOptions -from .errors import DeepgramModuleError - - -class AgentRouter: - """ - Represents a client for interacting with the Deepgram API. - - This class provides a client for making requests to the Deepgram API with various configuration options. - - Attributes: - config_options (DeepgramClientOptions): An optional configuration object specifying client options. - - Raises: - DeepgramApiKeyError: If the API key is missing or invalid. - - Methods: - read: (Preferred) Returns an Threaded AnalyzeClient instance for interacting with Deepgram's read transcription services. - asyncread: Returns an (Async) AnalyzeClient instance for interacting with Deepgram's read transcription services. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - - def __init__(self, config: DeepgramClientOptions): - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - self._config = config - - @property - def websocket(self): - """ - Returns an AgentWebSocketClient instance for interacting with Deepgram's Agent API. - """ - return self.Version(self._config, "websocket") - - @property - def asyncwebsocket(self): - """ - Returns an AsyncAgentWebSocketClient instance for interacting with Deepgram's Agent API. - """ - return self.Version(self._config, "asyncwebsocket") - - # INTERNAL CLASSES - class Version: - """ - Represents a version of the Deepgram API. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - _parent: str - - def __init__(self, config, parent: str): - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - self._config = config - self._parent = parent - - # FUTURE VERSIONING: - # When v2 or v1.1beta1 or etc. This allows easy access to the latest version of the API. - # @property - # def latest(self): - # match self._parent: - # case "analyze": - # return AnalyzeClient(self._config) - # case _: - # raise DeepgramModuleError("Invalid parent") - - def v(self, version: str = ""): - """ - Returns a specific version of the Deepgram API. - """ - self._logger.debug("Version.v ENTER") - self._logger.info("version: %s", version) - if len(version) == 0: - self._logger.error("version is empty") - self._logger.debug("Version.v LEAVE") - raise DeepgramModuleError("Invalid module version") - - parent = "" - file_name = "" - class_name = "" - match self._parent: - case "websocket": - parent = "websocket" - file_name = "client" - class_name = "AgentWebSocketClient" - case "asyncwebsocket": - parent = "websocket" - file_name = "async_client" - class_name = "AsyncAgentWebSocketClient" - case _: - self._logger.error("parent unknown: %s", self._parent) - self._logger.debug("Version.v LEAVE") - raise DeepgramModuleError("Invalid parent type") - - # create class path - path = f"deepgram.clients.agent.v{version}.{parent}.{file_name}" - self._logger.info("path: %s", path) - self._logger.info("class_name: %s", class_name) - - # import class - mod = import_module(path) - if mod is None: - self._logger.error("module path is None") - self._logger.debug("Version.v LEAVE") - raise DeepgramModuleError("Unable to find package") - - my_class = getattr(mod, class_name) - if my_class is None: - self._logger.error("my_class is None") - self._logger.debug("Version.v LEAVE") - raise DeepgramModuleError("Unable to find class") - - # instantiate class - my_class = my_class(self._config) - self._logger.notice("Version.v succeeded") - self._logger.debug("Version.v LEAVE") - return my_class diff --git a/venv/Lib/site-packages/deepgram/clients/analyze/__init__.py b/venv/Lib/site-packages/deepgram/clients/analyze/__init__.py deleted file mode 100644 index 71708c58..00000000 --- a/venv/Lib/site-packages/deepgram/clients/analyze/__init__.py +++ /dev/null @@ -1,40 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .client import AnalyzeClient, AsyncAnalyzeClient -from .client import ReadClient, AsyncReadClient -from .client import AnalyzeOptions -from .client import ( - # common - UrlSource, - TextSource, - BufferSource, - StreamSource, - FileSource, - # unique - AnalyzeStreamSource, - AnalyzeSource, -) -from .client import ( - AsyncAnalyzeResponse, - SyncAnalyzeResponse, - AnalyzeResponse, - # shared - Average, - Intent, - Intents, - IntentsInfo, - Segment, - SentimentInfo, - Sentiment, - Sentiments, - SummaryInfo, - Topic, - Topics, - TopicsInfo, - # unique - AnalyzeMetadata, - AnalyzeResults, - AnalyzeSummary, -) diff --git a/venv/Lib/site-packages/deepgram/clients/analyze/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/analyze/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index 99215418..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/analyze/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/analyze/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/analyze/__pycache__/client.cpython-312.pyc deleted file mode 100644 index 62732bef..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/analyze/__pycache__/client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/analyze/client.py b/venv/Lib/site-packages/deepgram/clients/analyze/client.py deleted file mode 100644 index 80dc3fad..00000000 --- a/venv/Lib/site-packages/deepgram/clients/analyze/client.py +++ /dev/null @@ -1,87 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .v1.client import AnalyzeClient as AnalyzeClientLatest -from .v1.async_client import AsyncAnalyzeClient as AsyncAnalyzeClientLatest -from .v1.options import ( - # common - AnalyzeOptions as AnalyzeOptionsLatest, - UrlSource as UrlSourceLatest, - TextSource as TextSourceLatest, - BufferSource as BufferSourceLatest, - StreamSource as StreamSourceLatest, - FileSource as FileSourceLatest, - # unique - AnalyzeStreamSource as AnalyzeStreamSourceLatest, - AnalyzeSource as AnalyzeSourceLatest, -) -from .v1.response import ( - SyncAnalyzeResponse as SyncAnalyzeResponseLatest, - AnalyzeResponse as AnalyzeResponseLatest, - AsyncAnalyzeResponse as AsyncAnalyzeResponseLatest, - # shared - Average as AverageLatest, - Intent as IntentLatest, - Intents as IntentsLatest, - IntentsInfo as IntentsInfoLatest, - Segment as SegmentLatest, - SentimentInfo as SentimentInfoLatest, - Sentiment as SentimentLatest, - Sentiments as SentimentsLatest, - SummaryInfo as SummaryInfoLatest, - Topic as TopicLatest, - Topics as TopicsLatest, - TopicsInfo as TopicsInfoLatest, - # unique - Results as ResultsLatest, - Metadata as MetadataLatest, - Summary as SummaryLatest, -) - -# The client.py points to the current supported version in the SDK. -# Older versions are supported in the SDK for backwards compatibility. - -# common -UrlSource = UrlSourceLatest -TextSource = TextSourceLatest -BufferSource = BufferSourceLatest -StreamSource = StreamSourceLatest -FileSource = FileSourceLatest - -AnalyzeStreamSource = AnalyzeStreamSourceLatest -AnalyzeSource = AnalyzeSourceLatest - -# input -AnalyzeOptions = AnalyzeOptionsLatest - -# responses -SyncAnalyzeResponse = SyncAnalyzeResponseLatest -AnalyzeResponse = AnalyzeResponseLatest -AsyncAnalyzeResponse = AsyncAnalyzeResponseLatest -# shared -Average = AverageLatest -Intent = IntentLatest -Intents = IntentsLatest -IntentsInfo = IntentsInfoLatest -Segment = SegmentLatest -SentimentInfo = SentimentInfoLatest -Sentiment = SentimentLatest -Sentiments = SentimentsLatest -SummaryInfo = SummaryInfoLatest -Topic = TopicLatest -Topics = TopicsLatest -TopicsInfo = TopicsInfoLatest -# unique -AnalyzeResults = ResultsLatest -AnalyzeMetadata = MetadataLatest -AnalyzeSummary = SummaryLatest - -# clients -AnalyzeClient = AnalyzeClientLatest -AsyncAnalyzeClient = AsyncAnalyzeClientLatest - - -# aliases -ReadClient = AnalyzeClientLatest -AsyncReadClient = AsyncAnalyzeClientLatest diff --git a/venv/Lib/site-packages/deepgram/clients/analyze/v1/__init__.py b/venv/Lib/site-packages/deepgram/clients/analyze/v1/__init__.py deleted file mode 100644 index 8ffd0b46..00000000 --- a/venv/Lib/site-packages/deepgram/clients/analyze/v1/__init__.py +++ /dev/null @@ -1,46 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .client import AnalyzeClient -from .async_client import AsyncAnalyzeClient - -# common -from .options import ( - UrlSource, - TextSource, - BufferSource, - StreamSource, - FileSource, -) - -# analyze - -from .options import ( - AnalyzeOptions, - AnalyzeStreamSource, - AnalyzeSource, -) - -from .response import ( - AsyncAnalyzeResponse, - SyncAnalyzeResponse, - AnalyzeResponse, - # shared - Average, - Intent, - Intents, - IntentsInfo, - Segment, - SentimentInfo, - Sentiment, - Sentiments, - SummaryInfo, - Topic, - Topics, - TopicsInfo, - # unique - Metadata, - Results, - Summary, -) diff --git a/venv/Lib/site-packages/deepgram/clients/analyze/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/analyze/v1/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index 6c31fa0f..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/analyze/v1/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/analyze/v1/__pycache__/async_client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/analyze/v1/__pycache__/async_client.cpython-312.pyc deleted file mode 100644 index 51fac841..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/analyze/v1/__pycache__/async_client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/analyze/v1/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/analyze/v1/__pycache__/client.cpython-312.pyc deleted file mode 100644 index bc7f5661..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/analyze/v1/__pycache__/client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/analyze/v1/__pycache__/helpers.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/analyze/v1/__pycache__/helpers.cpython-312.pyc deleted file mode 100644 index d3d7422a..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/analyze/v1/__pycache__/helpers.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/analyze/v1/__pycache__/options.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/analyze/v1/__pycache__/options.cpython-312.pyc deleted file mode 100644 index 4b7d6b88..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/analyze/v1/__pycache__/options.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/analyze/v1/__pycache__/response.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/analyze/v1/__pycache__/response.cpython-312.pyc deleted file mode 100644 index d5661b7a..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/analyze/v1/__pycache__/response.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/analyze/v1/async_client.py b/venv/Lib/site-packages/deepgram/clients/analyze/v1/async_client.py deleted file mode 100644 index 5c3e569b..00000000 --- a/venv/Lib/site-packages/deepgram/clients/analyze/v1/async_client.py +++ /dev/null @@ -1,346 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -import logging -from typing import Dict, Union, Optional - -import httpx - -from ....utils import verboselogs -from ....options import DeepgramClientOptions -from ...common import AbstractAsyncRestClient -from ...common import DeepgramError, DeepgramTypeError - -from .helpers import is_buffer_source, is_readstream_source, is_url_source -from .options import ( - AnalyzeOptions, - UrlSource, - FileSource, -) -from .response import AsyncAnalyzeResponse, AnalyzeResponse - - -class AsyncAnalyzeClient(AbstractAsyncRestClient): - """ - A client class for handling text data. - Provides methods for transcribing text from URLs and files. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - - def __init__(self, config: DeepgramClientOptions): - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - self._config = config - super().__init__(config) - - # pylint: disable=too-many-positional-arguments - - async def analyze_url( - self, - source: UrlSource, - options: Optional[Union[AnalyzeOptions, Dict]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/read", - **kwargs, - ) -> Union[AsyncAnalyzeResponse, AnalyzeResponse]: - """ - Analyze text from a URL source. - - Args: - source (UrlSource): The URL source of the text to ingest. - options (AnalyzeOptions): Additional options for the ingest (default is None). - endpoint (str): The API endpoint for the ingest (default is "v1/read"). - - Returns: - AnalyzeResponse: An object containing the result. - - Raises: - DeepgramTypeError: Raised for known API errors. - """ - self._logger.debug("AsyncAnalyzeClient.analyze_url ENTER") - - if ( - isinstance(options, dict) - and "callback" in options - and options["callback"] is not None - ) or (isinstance(options, AnalyzeOptions) and options.callback is not None): - self._logger.debug("AsyncAnalyzeClient.analyze_url LEAVE") - return await self.analyze_url_callback( - source, - callback=options["callback"], - options=options, - headers=headers, - addons=addons, - timeout=timeout, - endpoint=endpoint, - **kwargs, - ) - - url = f"{self._config.url}/{endpoint}" - if is_url_source(source): - body = source - else: - self._logger.error("Unknown transcription source type") - self._logger.debug("AsyncAnalyzeClient.analyze_url LEAVE") - raise DeepgramTypeError("Unknown transcription source type") - - if isinstance(options, AnalyzeOptions) and not options.check(): - self._logger.error("options.check failed") - self._logger.debug("AsyncAnalyzeClient.analyze_url LEAVE") - raise DeepgramError("Fatal transcription options error") - - self._logger.info("url: %s", url) - self._logger.info("source: %s", source) - if isinstance(options, AnalyzeOptions): - self._logger.info("AnalyzeOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.post( - url, - options=options, - addons=addons, - headers=headers, - json=body, - timeout=timeout, - **kwargs, - ) - self._logger.info("json: %s", result) - res = AnalyzeResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("analyze_url succeeded") - self._logger.debug("AsyncAnalyzeClient.analyze_url LEAVE") - return res - - async def analyze_url_callback( - self, - source: UrlSource, - callback: str, - options: Optional[Union[AnalyzeOptions, Dict]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/read", - **kwargs, - ) -> AsyncAnalyzeResponse: - """ - Transcribes audio from a URL source and sends the result to a callback URL. - - Args: - source (UrlSource): The URL source of the audio to transcribe. - callback (str): The callback URL where the transcription results will be sent. - options (AnalyzeOptions): Additional options for the transcription (default is None). - endpoint (str): The API endpoint for the transcription (default is "v1/read"). - - Returns: - AsyncAnalyzeResponse: An object containing the request_id or an error message. - - Raises: - DeepgramTypeError: Raised for known API errors. - """ - self._logger.debug("AnalyzeClient.analyze_url_callback ENTER") - - url = f"{self._config.url}/{endpoint}" - if options is None: - options = {} - if isinstance(options, AnalyzeOptions): - options.callback = callback - else: - options["callback"] = callback - if is_url_source(source): - body = source - else: - self._logger.error("Unknown transcription source type") - self._logger.debug("AnalyzeClient.analyze_url_callback LEAVE") - raise DeepgramTypeError("Unknown transcription source type") - - if isinstance(options, AnalyzeOptions) and not options.check(): - self._logger.error("options.check failed") - self._logger.debug("AnalyzeClient.analyze_url_callback LEAVE") - raise DeepgramError("Fatal transcription options error") - - self._logger.info("url: %s", url) - self._logger.info("source: %s", source) - if isinstance(options, AnalyzeOptions): - self._logger.info("AnalyzeOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.post( - url, - options=options, - addons=addons, - headers=headers, - json=body, - timeout=timeout, - **kwargs, - ) - self._logger.info("json: %s", result) - res = AsyncAnalyzeResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("analyze_url_callback succeeded") - self._logger.debug("AnalyzeClient.analyze_url_callback LEAVE") - return res - - async def analyze_text( - self, - source: FileSource, - options: Optional[Union[AnalyzeOptions, Dict]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/read", - **kwargs, - ) -> Union[AsyncAnalyzeResponse, AnalyzeResponse]: - """ - Analyze text from a local file source. - - Args: - source (TextSource): The local file source of the text to ingest. - options (AnalyzeOptions): Additional options for the ingest (default is None). - endpoint (str): The API endpoint for the transcription (default is "v1/read"). - - Returns: - AnalyzeResponse: An object containing the transcription result or an error message. - - Raises: - DeepgramTypeError: Raised for known API errors. - """ - self._logger.debug("AsyncAnalyzeClient.analyze_text ENTER") - - if ( - isinstance(options, dict) - and "callback" in options - and options["callback"] is not None - ) or (isinstance(options, AnalyzeOptions) and options.callback is not None): - self._logger.debug("AsyncAnalyzeClient.analyze_text LEAVE") - return await self.analyze_text_callback( - source, - callback=options["callback"], - options=options, - headers=headers, - addons=addons, - timeout=timeout, - endpoint=endpoint, - **kwargs, - ) - - url = f"{self._config.url}/{endpoint}" - if is_buffer_source(source): - body = source["buffer"] # type: ignore - elif is_readstream_source(source): - body = source["stream"] # type: ignore - else: - self._logger.error("Unknown transcription source type") - self._logger.debug("AsyncAnalyzeClient.analyze_text LEAVE") - raise DeepgramTypeError("Unknown transcription source type") - - if isinstance(options, AnalyzeOptions) and not options.check(): - self._logger.error("options.check failed") - self._logger.debug("AsyncAnalyzeClient.analyze_text LEAVE") - raise DeepgramError("Fatal transcription options error") - - self._logger.info("url: %s", url) - if isinstance(options, AnalyzeOptions): - self._logger.info("AnalyzeOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.post( - url, - options=options, - addons=addons, - headers=headers, - content=body, - timeout=timeout, - **kwargs, - ) - self._logger.info("json: %s", result) - res = AnalyzeResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("analyze_text succeeded") - self._logger.debug("AsyncAnalyzeClient.analyze_text LEAVE") - return res - - async def analyze_text_callback( - self, - source: FileSource, - callback: str, - options: Optional[Union[AnalyzeOptions, Dict]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/read", - **kwargs, - ) -> AsyncAnalyzeResponse: - """ - Transcribes audio from a local file source and sends the result to a callback URL. - - Args: - source (TextSource): The local file source of the audio to transcribe. - callback (str): The callback URL where the transcription results will be sent. - options (AnalyzeOptions): Additional options for the transcription (default is None). - endpoint (str): The API endpoint for the transcription (default is "v1/read"). - - Returns: - AsyncAnalyzeResponse: An object containing the request_id or an error message. - - Raises: - DeepgramTypeError: Raised for known API errors. - """ - self._logger.debug("AnalyzeClient.analyze_text_callback ENTER") - - url = f"{self._config.url}/{endpoint}" - if options is None: - options = {} - if isinstance(options, AnalyzeOptions): - options.callback = callback - else: - options["callback"] = callback - if is_buffer_source(source): - body = source["buffer"] # type: ignore - elif is_readstream_source(source): - body = source["stream"] # type: ignore - else: - self._logger.error("Unknown transcription source type") - self._logger.debug("AnalyzeClient.analyze_text_callback LEAVE") - raise DeepgramTypeError("Unknown transcription source type") - - if isinstance(options, AnalyzeOptions) and not options.check(): - self._logger.error("options.check failed") - self._logger.debug("AnalyzeClient.analyze_text_callback LEAVE") - raise DeepgramError("Fatal transcription options error") - - self._logger.info("url: %s", url) - if isinstance(options, AnalyzeOptions): - self._logger.info("AnalyzeOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.post( - url, - options=options, - addons=addons, - headers=headers, - json=body, - timeout=timeout, - **kwargs, - ) - self._logger.info("json: %s", result) - res = AsyncAnalyzeResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("analyze_text_callback succeeded") - self._logger.debug("AnalyzeClient.analyze_text_callback LEAVE") - return res - - # pylint: enable=too-many-positional-arguments diff --git a/venv/Lib/site-packages/deepgram/clients/analyze/v1/client.py b/venv/Lib/site-packages/deepgram/clients/analyze/v1/client.py deleted file mode 100644 index a90145ed..00000000 --- a/venv/Lib/site-packages/deepgram/clients/analyze/v1/client.py +++ /dev/null @@ -1,346 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -import logging -from typing import Dict, Union, Optional - -import httpx - -from ....utils import verboselogs -from ....options import DeepgramClientOptions -from ...common import AbstractSyncRestClient -from ...common import DeepgramError, DeepgramTypeError - -from .helpers import is_buffer_source, is_readstream_source, is_url_source -from .options import ( - AnalyzeOptions, - UrlSource, - FileSource, -) -from .response import AsyncAnalyzeResponse, AnalyzeResponse - - -class AnalyzeClient(AbstractSyncRestClient): - """ - A client class for handling text data. - Provides methods for transcribing text from URLs, files, etc. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - - def __init__(self, config: DeepgramClientOptions): - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - self._config = config - super().__init__(config) - - # pylint: disable=too-many-positional-arguments - - def analyze_url( - self, - source: UrlSource, - options: Optional[Union[AnalyzeOptions, Dict]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/read", - **kwargs, - ) -> Union[AnalyzeResponse, AsyncAnalyzeResponse]: - """ - Analyze text from a URL source. - - Args: - source (UrlSource): The URL source of the text to ingest. - options (AnalyzeOptions): Additional options for the ingest (default is None). - endpoint (str): The API endpoint for the ingest (default is "v1/read"). - - Returns: - AnalyzeResponse: An object containing the result. - - Raises: - DeepgramTypeError: Raised for known API errors. - """ - self._logger.debug("AnalyzeClient.analyze_url ENTER") - - if ( - isinstance(options, dict) - and "callback" in options - and options["callback"] is not None - ) or (isinstance(options, AnalyzeOptions) and options.callback is not None): - self._logger.debug("AnalyzeClient.analyze_url LEAVE") - return self.analyze_url_callback( - source, - callback=options["callback"], - options=options, - addons=addons, - headers=headers, - timeout=timeout, - endpoint=endpoint, - **kwargs, - ) - - url = f"{self._config.url}/{endpoint}" - if is_url_source(source): - body = source - else: - self._logger.error("Unknown transcription source type") - self._logger.debug("AnalyzeClient.analyze_url LEAVE") - raise DeepgramTypeError("Unknown transcription source type") - - if isinstance(options, AnalyzeOptions) and not options.check(): - self._logger.error("options.check failed") - self._logger.debug("AnalyzeClient.analyze_url LEAVE") - raise DeepgramError("Fatal transcription options error") - - self._logger.info("url: %s", url) - self._logger.info("source: %s", source) - if isinstance(options, AnalyzeOptions): - self._logger.info("AnalyzeOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.post( - url, - options=options, - addons=addons, - headers=headers, - json=body, - timeout=timeout, - **kwargs, - ) - self._logger.info("json: %s", result) - res = AnalyzeResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("analyze_url succeeded") - self._logger.debug("AnalyzeClient.analyze_url LEAVE") - return res - - def analyze_url_callback( - self, - source: UrlSource, - callback: str, - options: Optional[Union[AnalyzeOptions, Dict]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/read", - **kwargs, - ) -> AsyncAnalyzeResponse: - """ - Transcribes audio from a URL source and sends the result to a callback URL. - - Args: - source (UrlSource): The URL source of the audio to transcribe. - callback (str): The callback URL where the transcription results will be sent. - options (AnalyzeOptions): Additional options for the transcription (default is None). - endpoint (str): The API endpoint for the transcription (default is "v1/read"). - - Returns: - AsyncAnalyzeResponse: An object containing the request_id or an error message. - - Raises: - DeepgramTypeError: Raised for known API errors. - """ - self._logger.debug("AnalyzeClient.analyze_url_callback ENTER") - - url = f"{self._config.url}/{endpoint}" - if options is None: - options = {} - if isinstance(options, AnalyzeOptions): - options.callback = callback - else: - options["callback"] = callback - if is_url_source(source): - body = source - else: - self._logger.error("Unknown transcription source type") - self._logger.debug("AnalyzeClient.analyze_url_callback LEAVE") - raise DeepgramTypeError("Unknown transcription source type") - - if isinstance(options, AnalyzeOptions) and not options.check(): - self._logger.error("options.check failed") - self._logger.debug("AnalyzeClient.analyze_url_callback LEAVE") - raise DeepgramError("Fatal transcription options error") - - self._logger.info("url: %s", url) - self._logger.info("source: %s", source) - if isinstance(options, AnalyzeOptions): - self._logger.info("AnalyzeOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.post( - url, - options=options, - addons=addons, - headers=headers, - json=body, - timeout=timeout, - **kwargs, - ) - self._logger.info("json: %s", result) - res = AsyncAnalyzeResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("analyze_url_callback succeeded") - self._logger.debug("AnalyzeClient.analyze_url_callback LEAVE") - return res - - def analyze_text( - self, - source: FileSource, - options: Optional[Union[AnalyzeOptions, Dict]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/read", - **kwargs, - ) -> Union[AnalyzeResponse, AsyncAnalyzeResponse]: - """ - Analyze text from a local file source. - - Args: - source (TextSource): The local file source of the text to ingest. - options (AnalyzeOptions): Additional options for the ingest (default is None). - endpoint (str): The API endpoint for the transcription (default is "v1/read"). - - Returns: - AnalyzeResponse: An object containing the transcription result or an error message. - - Raises: - DeepgramTypeError: Raised for known API errors. - """ - self._logger.debug("AnalyzeClient.analyze_text ENTER") - - if ( - isinstance(options, dict) - and "callback" in options - and options["callback"] is not None - ) or (isinstance(options, AnalyzeOptions) and options.callback is not None): - self._logger.debug("AnalyzeClient.analyze_text LEAVE") - return self.analyze_text_callback( - source, - callback=options["callback"], - options=options, - addons=addons, - headers=headers, - timeout=timeout, - endpoint=endpoint, - **kwargs, - ) - - url = f"{self._config.url}/{endpoint}" - if is_buffer_source(source): - body = source["buffer"] # type: ignore - elif is_readstream_source(source): - body = source["stream"] # type: ignore - else: - self._logger.error("Unknown transcription source type") - self._logger.debug("AnalyzeClient.analyze_text LEAVE") - raise DeepgramTypeError("Unknown transcription source type") - - if isinstance(options, AnalyzeOptions) and not options.check(): - self._logger.error("options.check failed") - self._logger.debug("AnalyzeClient.analyze_text LEAVE") - raise DeepgramError("Fatal transcription options error") - - self._logger.info("url: %s", url) - if isinstance(options, AnalyzeOptions): - self._logger.info("AnalyzeOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.post( - url, - options=options, - addons=addons, - headers=headers, - content=body, - timeout=timeout, - **kwargs, - ) - self._logger.info("json: %s", result) - res = AnalyzeResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("analyze_text succeeded") - self._logger.debug("AnalyzeClient.analyze_text LEAVE") - return res - - def analyze_text_callback( - self, - source: FileSource, - callback: str, - options: Optional[Union[AnalyzeOptions, Dict]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/read", - **kwargs, - ) -> AsyncAnalyzeResponse: - """ - Transcribes audio from a local file source and sends the result to a callback URL. - - Args: - source (TextSource): The local file source of the audio to transcribe. - callback (str): The callback URL where the transcription results will be sent. - options (AnalyzeOptions): Additional options for the transcription (default is None). - endpoint (str): The API endpoint for the transcription (default is "v1/read"). - - Returns: - AsyncAnalyzeResponse: An object containing the request_id or an error message. - - Raises: - DeepgramTypeError: Raised for known API errors. - """ - self._logger.debug("AnalyzeClient.analyze_file_callback ENTER") - - url = f"{self._config.url}/{endpoint}" - if options is None: - options = {} - if isinstance(options, AnalyzeOptions): - options.callback = callback - else: - options["callback"] = callback - if is_buffer_source(source): - body = source["buffer"] # type: ignore - elif is_readstream_source(source): - body = source["stream"] # type: ignore - else: - self._logger.error("Unknown transcription source type") - self._logger.debug("AnalyzeClient.analyze_file_callback LEAVE") - raise DeepgramTypeError("Unknown transcription source type") - - if isinstance(options, AnalyzeOptions) and not options.check(): - self._logger.error("options.check failed") - self._logger.debug("AnalyzeClient.analyze_file_callback LEAVE") - raise DeepgramError("Fatal transcription options error") - - self._logger.info("url: %s", url) - if isinstance(options, AnalyzeOptions): - self._logger.info("AnalyzeOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.post( - url, - options=options, - addons=addons, - headers=headers, - json=body, - timeout=timeout, - **kwargs, - ) - self._logger.info("json: %s", result) - res = AsyncAnalyzeResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("analyze_file_callback succeeded") - self._logger.debug("AnalyzeClient.analyze_file_callback LEAVE") - return res - - # pylint: enable=too-many-positional-arguments diff --git a/venv/Lib/site-packages/deepgram/clients/analyze/v1/helpers.py b/venv/Lib/site-packages/deepgram/clients/analyze/v1/helpers.py deleted file mode 100644 index ef6746b3..00000000 --- a/venv/Lib/site-packages/deepgram/clients/analyze/v1/helpers.py +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .options import AnalyzeSource - - -def is_buffer_source(provided_source: AnalyzeSource) -> bool: - """ - Check if the provided source is a buffer source. - """ - return "buffer" in provided_source - - -def is_readstream_source(provided_source: AnalyzeSource) -> bool: - """ - Check if the provided source is a readstream source. - """ - return "stream" in provided_source - - -def is_url_source(provided_source: AnalyzeSource) -> bool: - """ - Check if the provided source is a url source. - """ - return "url" in provided_source diff --git a/venv/Lib/site-packages/deepgram/clients/analyze/v1/options.py b/venv/Lib/site-packages/deepgram/clients/analyze/v1/options.py deleted file mode 100644 index d6999c66..00000000 --- a/venv/Lib/site-packages/deepgram/clients/analyze/v1/options.py +++ /dev/null @@ -1,83 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -import logging -from typing import List, Union, Optional - -from dataclasses import dataclass, field -from dataclasses_json import config as dataclass_config - -from ....utils import verboselogs -from ...common import ( - TextSource, - FileSource, - BufferSource, - StreamSource, - UrlSource, - BaseResponse, -) - - -@dataclass -class AnalyzeOptions(BaseResponse): # pylint: disable=too-many-instance-attributes - """ - Contains all the options for the AnalyzeOptions. - - Reference: - https://developers.deepgram.com/reference/text-intelligence-apis - """ - - callback: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - callback_method: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - custom_intent: Optional[Union[List[str], str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - custom_intent_mode: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - custom_topic: Optional[Union[List[str], str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - custom_topic_mode: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - intents: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - language: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - sentiment: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - summarize: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - topics: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def check(self): - """ - Check the options for the AnalyzeOptions. - """ - logger = verboselogs.VerboseLogger(__name__) - logger.addHandler(logging.StreamHandler()) - prev = logger.level - logger.setLevel(verboselogs.ERROR) - - # no op at the moment - - logger.setLevel(prev) - - return True - - -# unique -AnalyzeSource = Union[UrlSource, FileSource] -AnalyzeStreamSource = StreamSource diff --git a/venv/Lib/site-packages/deepgram/clients/analyze/v1/response.py b/venv/Lib/site-packages/deepgram/clients/analyze/v1/response.py deleted file mode 100644 index 5d678cba..00000000 --- a/venv/Lib/site-packages/deepgram/clients/analyze/v1/response.py +++ /dev/null @@ -1,143 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from typing import List, Optional, Dict, Any - -from dataclasses import dataclass, field -from dataclasses_json import config as dataclass_config - -from ...common import ( - BaseResponse, - Average, - Intent, - Intents, - IntentsInfo, - Segment, - SentimentInfo, - Sentiment, - Sentiments, - SummaryInfo, - Topic, - Topics, - TopicsInfo, -) - - -# Async Analyze Response Types: - - -@dataclass -class AsyncAnalyzeResponse(BaseResponse): - """ - Async Analyze Response - """ - - request_id: str = "" - - -# Analyze Response Types: - - -@dataclass -class Metadata(BaseResponse): - """ - Metadata - """ - - request_id: str = "" - created: str = "" - language: str = "" - intents_info: Optional[IntentsInfo] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - sentiment_info: Optional[SentimentInfo] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - summary_info: Optional[SummaryInfo] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - topics_info: Optional[TopicsInfo] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "intents_info" in _dict: - _dict["intents_info"] = IntentsInfo.from_dict(_dict["intents_info"]) - if "sentiment_info" in _dict: - _dict["sentiment_info"] = SentimentInfo.from_dict(_dict["sentiment_info"]) - if "summary_info" in _dict: - _dict["summary_info"] = SummaryInfo.from_dict(_dict["summary_info"]) - if "topics_info" in _dict: - _dict["topics_info"] = TopicsInfo.from_dict(_dict["topics_info"]) - return _dict[key] - - -@dataclass -class Summary(BaseResponse): - """ - Summary - """ - - text: str = "" - - -@dataclass -class Results(BaseResponse): - """ - Results - """ - - summary: Optional[Summary] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - sentiments: Optional[Sentiments] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - topics: Optional[Topics] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - intents: Optional[Intents] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "summary" in _dict: - _dict["summary"] = Summary.from_dict(_dict["summary"]) - if "sentiments" in _dict: - _dict["sentiments"] = Sentiments.from_dict(_dict["sentiments"]) - if "topics" in _dict: - _dict["topics"] = Topics.from_dict(_dict["topics"]) - if "intents" in _dict: - _dict["intents"] = Intents.from_dict(_dict["intents"]) - return _dict[key] - - -# Analyze Response Result: - - -@dataclass -class AnalyzeResponse(BaseResponse): - """ - Analyze Response - """ - - metadata: Optional[Metadata] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - results: Optional[Results] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "metadata" in _dict: - _dict["metadata"] = Metadata.from_dict(_dict["metadata"]) - if "results" in _dict: - _dict["results"] = Results.from_dict(_dict["results"]) - return _dict[key] - - -SyncAnalyzeResponse = AnalyzeResponse diff --git a/venv/Lib/site-packages/deepgram/clients/auth/__init__.py b/venv/Lib/site-packages/deepgram/clients/auth/__init__.py deleted file mode 100644 index d5ac419c..00000000 --- a/venv/Lib/site-packages/deepgram/clients/auth/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .client import AuthRESTClient -from .client import AsyncAuthRESTClient -from .client import ( - GrantTokenResponse, -) \ No newline at end of file diff --git a/venv/Lib/site-packages/deepgram/clients/auth/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/auth/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index 14183396..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/auth/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/auth/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/auth/__pycache__/client.cpython-312.pyc deleted file mode 100644 index 1026cca2..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/auth/__pycache__/client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/auth/client.py b/venv/Lib/site-packages/deepgram/clients/auth/client.py deleted file mode 100644 index 2e74f243..00000000 --- a/venv/Lib/site-packages/deepgram/clients/auth/client.py +++ /dev/null @@ -1,11 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .v1.client import AuthRESTClient as AuthRESTClientLatest -from .v1.async_client import AsyncAuthRESTClient as AsyncAuthRESTClientLatest -from .v1.response import GrantTokenResponse as GrantTokenResponseLatest - -AuthRESTClient = AuthRESTClientLatest -AsyncAuthRESTClient = AsyncAuthRESTClientLatest -GrantTokenResponse = GrantTokenResponseLatest diff --git a/venv/Lib/site-packages/deepgram/clients/auth/v1/__init__.py b/venv/Lib/site-packages/deepgram/clients/auth/v1/__init__.py deleted file mode 100644 index f449c80a..00000000 --- a/venv/Lib/site-packages/deepgram/clients/auth/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT -from .client import AuthRESTClient -from .async_client import AsyncAuthRESTClient -from .response import ( - GrantTokenResponse, -) \ No newline at end of file diff --git a/venv/Lib/site-packages/deepgram/clients/auth/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/auth/v1/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index de213b97..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/auth/v1/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/auth/v1/__pycache__/async_client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/auth/v1/__pycache__/async_client.cpython-312.pyc deleted file mode 100644 index 00523bd3..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/auth/v1/__pycache__/async_client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/auth/v1/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/auth/v1/__pycache__/client.cpython-312.pyc deleted file mode 100644 index ba6f42e2..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/auth/v1/__pycache__/client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/auth/v1/__pycache__/response.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/auth/v1/__pycache__/response.cpython-312.pyc deleted file mode 100644 index bed1d3f6..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/auth/v1/__pycache__/response.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/auth/v1/async_client.py b/venv/Lib/site-packages/deepgram/clients/auth/v1/async_client.py deleted file mode 100644 index 43ecb490..00000000 --- a/venv/Lib/site-packages/deepgram/clients/auth/v1/async_client.py +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -import logging - -from ....utils import verboselogs -from ....options import DeepgramClientOptions -from ...common import AbstractAsyncRestClient -from .response import GrantTokenResponse - - -class AsyncAuthRESTClient(AbstractAsyncRestClient): - """ - A client class for handling authentication endpoints. - Provides method for generating a temporary JWT token. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - _endpoint: str - - def __init__(self, config: DeepgramClientOptions): - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - self._config = config - self._endpoint = "v1/auth/grant" - super().__init__(config) - - async def grant_token(self): - """ - Generates a temporary JWT with a 30 second TTL. - - Returns: - GrantTokenResponse: An object containing the authentication token and its expiration time. - - Raises: - DeepgramTypeError: Raised for known API errors. - """ - self._logger.debug("AuthRestClient.grant_token ENTER") - - url = f"{self._config.url}/{self._endpoint}" - self._logger.info("url: %s", url) - result = await self.post(url, headers={"Authorization": f"Token {self._config.api_key}"}) - self._logger.info("json: %s", result) - res = GrantTokenResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("grant_token succeeded") - self._logger.debug("AuthRestClient.grant_token LEAVE") - return res diff --git a/venv/Lib/site-packages/deepgram/clients/auth/v1/client.py b/venv/Lib/site-packages/deepgram/clients/auth/v1/client.py deleted file mode 100644 index c75815da..00000000 --- a/venv/Lib/site-packages/deepgram/clients/auth/v1/client.py +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -import logging - -from ....utils import verboselogs -from ....options import DeepgramClientOptions -from ...common import AbstractSyncRestClient -from .response import GrantTokenResponse - - -class AuthRESTClient(AbstractSyncRestClient): - """ - A client class for handling authentication endpoints. - Provides method for generating a temporary JWT token. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - _endpoint: str - - def __init__(self, config: DeepgramClientOptions): - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - self._config = config - self._endpoint = "v1/auth/grant" - super().__init__(config) - - def grant_token(self): - """ - Generates a temporary JWT with a 30 second TTL. - - Returns: - GrantTokenResponse: An object containing the authentication token and its expiration time. - - Raises: - DeepgramTypeError: Raised for known API errors. - """ - self._logger.debug("AuthRestClient.grant_token ENTER") - - url = f"{self._config.url}/{self._endpoint}" - self._logger.info("url: %s", url) - result = self.post(url, headers={"Authorization": f"Token {self._config.api_key}"}) - self._logger.info("json: %s", result) - res = GrantTokenResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("grant_token succeeded") - self._logger.debug("AuthRestClient.grant_token LEAVE") - return res diff --git a/venv/Lib/site-packages/deepgram/clients/auth/v1/response.py b/venv/Lib/site-packages/deepgram/clients/auth/v1/response.py deleted file mode 100644 index cf72f357..00000000 --- a/venv/Lib/site-packages/deepgram/clients/auth/v1/response.py +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from dataclasses import dataclass, field -from dataclasses_json import config as dataclass_config - -from ...common import ( - BaseResponse, -) - -@dataclass -class GrantTokenResponse(BaseResponse): - """ - The response object for the authentication grant token endpoint. - """ - access_token: str = field( - metadata=dataclass_config(field_name='access_token'), - default="", - ) - expires_in: int = field( - metadata=dataclass_config(field_name='expires_in'), - default=30, - ) \ No newline at end of file diff --git a/venv/Lib/site-packages/deepgram/clients/common/__init__.py b/venv/Lib/site-packages/deepgram/clients/common/__init__.py deleted file mode 100644 index 58c449d9..00000000 --- a/venv/Lib/site-packages/deepgram/clients/common/__init__.py +++ /dev/null @@ -1,85 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .v1 import ( - DeepgramError, - DeepgramTypeError, - DeepgramApiError, - DeepgramUnknownApiError, -) - -from .v1 import AbstractAsyncRestClient -from .v1 import AbstractSyncRestClient -from .v1 import AbstractAsyncWebSocketClient -from .v1 import AbstractSyncWebSocketClient - -from .v1 import ( - TextSource as TextSourceLatest, - BufferSource as BufferSourceLatest, - StreamSource as StreamSourceLatest, - FileSource as FileSourceLatest, - UrlSource as UrlSourceLatest, -) - -# shared -from .v1 import ( - BaseResponse as BaseResponseLatest, - ModelInfo as ModelInfoLatest, - Hit as HitLatest, - Search as SearchLatest, -) - -# rest -from .v1 import ( - Average as AverageLatest, - Intent as IntentLatest, - Intents as IntentsLatest, - IntentsInfo as IntentsInfoLatest, - Segment as SegmentLatest, - SentimentInfo as SentimentInfoLatest, - Sentiment as SentimentLatest, - Sentiments as SentimentsLatest, - SummaryInfo as SummaryInfoLatest, - Topic as TopicLatest, - Topics as TopicsLatest, - TopicsInfo as TopicsInfoLatest, -) - -# websocket -from .v1 import ( - OpenResponse as OpenResponseLatest, - CloseResponse as CloseResponseLatest, - ErrorResponse as ErrorResponseLatest, - UnhandledResponse as UnhandledResponseLatest, -) - -# export -UrlSource = UrlSourceLatest -TextSource = TextSourceLatest -BufferSource = BufferSourceLatest -StreamSource = StreamSourceLatest -FileSource = FileSourceLatest - -BaseResponse = BaseResponseLatest -ModelInfo = ModelInfoLatest -Hit = HitLatest -Search = SearchLatest - -Average = AverageLatest -Intent = IntentLatest -Intents = IntentsLatest -IntentsInfo = IntentsInfoLatest -Segment = SegmentLatest -SentimentInfo = SentimentInfoLatest -Sentiment = SentimentLatest -Sentiments = SentimentsLatest -SummaryInfo = SummaryInfoLatest -Topic = TopicLatest -Topics = TopicsLatest -TopicsInfo = TopicsInfoLatest - -OpenResponse = OpenResponseLatest -CloseResponse = CloseResponseLatest -ErrorResponse = ErrorResponseLatest -UnhandledResponse = UnhandledResponseLatest diff --git a/venv/Lib/site-packages/deepgram/clients/common/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/common/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index ff399e7d..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/common/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/__init__.py b/venv/Lib/site-packages/deepgram/clients/common/v1/__init__.py deleted file mode 100644 index 7603fc0a..00000000 --- a/venv/Lib/site-packages/deepgram/clients/common/v1/__init__.py +++ /dev/null @@ -1,53 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .enums import Sentiment - -from .errors import ( - DeepgramError, - DeepgramTypeError, - DeepgramApiError, - DeepgramUnknownApiError, -) -from .abstract_async_rest import AbstractAsyncRestClient -from .abstract_sync_rest import AbstractSyncRestClient -from .abstract_async_websocket import AbstractAsyncWebSocketClient -from .abstract_sync_websocket import AbstractSyncWebSocketClient - -from .options import ( - TextSource, - BufferSource, - StreamSource, - FileSource, - UrlSource, -) - -from .shared_response import ( - BaseResponse, - ModelInfo, - Hit, - Search, -) - -from .rest_response import ( - Average, - Intent, - Intents, - IntentsInfo, - Segment, - SentimentInfo, - Sentiment, - Sentiments, - SummaryInfo, - Topic, - Topics, - TopicsInfo, -) - -from .websocket_response import ( - OpenResponse, - CloseResponse, - ErrorResponse, - UnhandledResponse, -) diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index a18590e1..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/abstract_async_rest.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/abstract_async_rest.cpython-312.pyc deleted file mode 100644 index 2ae39d89..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/abstract_async_rest.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/abstract_async_websocket.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/abstract_async_websocket.cpython-312.pyc deleted file mode 100644 index 2d96fb92..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/abstract_async_websocket.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/abstract_sync_rest.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/abstract_sync_rest.cpython-312.pyc deleted file mode 100644 index d2d061a3..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/abstract_sync_rest.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/abstract_sync_websocket.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/abstract_sync_websocket.cpython-312.pyc deleted file mode 100644 index 37873036..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/abstract_sync_websocket.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/enums.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/enums.cpython-312.pyc deleted file mode 100644 index 31e0753b..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/enums.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/errors.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/errors.cpython-312.pyc deleted file mode 100644 index 82d51d5f..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/errors.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/helpers.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/helpers.cpython-312.pyc deleted file mode 100644 index d89c8b97..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/helpers.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/options.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/options.cpython-312.pyc deleted file mode 100644 index 8e97737a..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/options.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/rest_response.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/rest_response.cpython-312.pyc deleted file mode 100644 index f1676a71..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/rest_response.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/shared_response.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/shared_response.cpython-312.pyc deleted file mode 100644 index 00b23e1c..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/shared_response.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/websocket_events.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/websocket_events.cpython-312.pyc deleted file mode 100644 index 475240ab..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/websocket_events.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/websocket_response.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/websocket_response.cpython-312.pyc deleted file mode 100644 index 663b2c53..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/common/v1/__pycache__/websocket_response.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/abstract_async_rest.py b/venv/Lib/site-packages/deepgram/clients/common/v1/abstract_async_rest.py deleted file mode 100644 index 3c0d8056..00000000 --- a/venv/Lib/site-packages/deepgram/clients/common/v1/abstract_async_rest.py +++ /dev/null @@ -1,383 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -import json -import io -from typing import Dict, Optional, List, Union - -import httpx - -from .helpers import append_query_params -from ....options import DeepgramClientOptions -from .errors import DeepgramError, DeepgramApiError, DeepgramUnknownApiError - - -class AbstractAsyncRestClient: - """ - An abstract base class for a RESTful HTTP client. - - This class provides common HTTP methods (GET, POST, PUT, PATCH, DELETE) for making asynchronous HTTP requests. - It handles error responses and provides basic JSON parsing. - - Args: - url (Dict): The base URL for the RESTful API, including any path segments. - headers (Optional[Dict[str, Any]]): Optional HTTP headers to include in requests. - params (Optional[Dict[str, Any]]): Optional query parameters to include in requests. - timeout (Optional[httpx.Timeout]): Optional timeout configuration for requests. - - Exceptions: - DeepgramApiError: Raised for known API errors. - DeepgramUnknownApiError: Raised for unknown API errors. - """ - - _config: DeepgramClientOptions - - def __init__(self, config: DeepgramClientOptions): - if config is None: - raise DeepgramError("Config are required") - self._config = config - - # pylint: disable=too-many-positional-arguments - - async def get( - self, - url: str, - options: Optional[Dict] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ) -> str: - """ - Make a GET request to the specified URL. - """ - return await self._handle_request( - "GET", - url, - params=options, - addons=addons, - headers=headers, - timeout=timeout, - **kwargs, - ) - - async def post_raw( - self, - url: str, - options: Optional[Dict] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ) -> httpx.Response: - """ - Make a POST request to the specified URL and return response in raw bytes. - """ - return await self._handle_request_raw( - "POST", - url, - params=options, - addons=addons, - headers=headers, - timeout=timeout, - **kwargs, - ) - - async def post_memory( - self, - url: str, - file_result: List, - options: Optional[Dict] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ) -> Dict[str, Union[str, io.BytesIO]]: - """ - Make a POST request to the specified URL and return response in memory. - """ - return await self._handle_request_memory( - "POST", - url, - file_result=file_result, - params=options, - addons=addons, - headers=headers, - timeout=timeout, - **kwargs, - ) - - async def post( - self, - url: str, - options: Optional[Dict] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ) -> str: - """ - Make a POST request to the specified URL. - """ - return await self._handle_request( - "POST", - url, - params=options, - addons=addons, - headers=headers, - timeout=timeout, - **kwargs, - ) - - async def put( - self, - url: str, - options: Optional[Dict] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ) -> str: - """ - Make a PUT request to the specified URL. - """ - return await self._handle_request( - "PUT", - url, - params=options, - addons=addons, - headers=headers, - timeout=timeout, - **kwargs, - ) - - async def patch( - self, - url: str, - options: Optional[Dict] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ) -> str: - """ - Make a PATCH request to the specified URL. - """ - return await self._handle_request( - "PATCH", - url, - params=options, - addons=addons, - headers=headers, - timeout=timeout, - **kwargs, - ) - - async def delete( - self, - url: str, - options: Optional[Dict] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ) -> str: - """ - Make a DELETE request to the specified URL. - """ - return await self._handle_request( - "DELETE", - url, - params=options, - addons=addons, - headers=headers, - timeout=timeout, - **kwargs, - ) - - # pylint: disable-msg=too-many-locals,too-many-branches,too-many-locals - async def _handle_request( - self, - method: str, - url: str, - params: Optional[Dict] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ) -> str: - _url = url - if params is not None: - _url = append_query_params(_url, params) - if addons is not None: - _url = append_query_params(_url, addons) - _headers = self._config.headers - if headers is not None: - _headers.update(headers) - if timeout is None: - timeout = httpx.Timeout(30.0, connect=10.0) - - try: - transport = kwargs.get("transport") - async with httpx.AsyncClient( - timeout=timeout, transport=transport - ) as client: - if transport: - kwargs.pop("transport") - response = await client.request( - method, _url, headers=_headers, **kwargs - ) - response.raise_for_status() - - # throw exception if response is None or response.text is None - if response is None or response.text is None: - raise DeepgramError( - "Response is not available yet. Please try again later." - ) - - return response.text - - except httpx.HTTPError as e1: - if isinstance(e1, httpx.HTTPStatusError): - status_code = e1.response.status_code or 500 - try: - json_object = json.loads(e1.response.text) - raise DeepgramApiError( - json_object.get("err_msg"), - str(status_code), - json.dumps(json_object), - ) from e1 - except json.decoder.JSONDecodeError as e2: - raise DeepgramUnknownApiError(e2.msg, str(status_code)) from e2 - except ValueError as e2: - raise DeepgramUnknownApiError(str(e2), str(status_code)) from e2 - else: - raise # pylint: disable-msg=try-except-raise - except Exception: # pylint: disable-msg=try-except-raise - raise - - # pylint: enable-msg=too-many-locals,too-many-branches,too-many-locals - - # pylint: disable-msg=too-many-locals,too-many-branches - async def _handle_request_memory( - self, - method: str, - url: str, - file_result: List, - params: Optional[Dict] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ) -> Dict[str, Union[str, io.BytesIO]]: - _url = url - if params is not None: - _url = append_query_params(_url, params) - if addons is not None: - _url = append_query_params(_url, addons) - _headers = self._config.headers - if headers is not None: - _headers.update(headers) - if timeout is None: - timeout = httpx.Timeout(30.0, connect=10.0) - - try: - transport = kwargs.get("transport") - async with httpx.AsyncClient( - timeout=timeout, transport=transport - ) as client: - if transport: - kwargs.pop("transport") - response = await client.request( - method, _url, headers=_headers, **kwargs - ) - response.raise_for_status() - - ret: Dict[str, Union[str, io.BytesIO]] = {} - for item in file_result: - if item in response.headers: - ret[item] = response.headers[item] - continue - tmp_item = f"dg-{item}" - if tmp_item in response.headers: - ret[item] = response.headers[tmp_item] - continue - tmp_item = f"x-dg-{item}" - if tmp_item in response.headers: - ret[item] = response.headers[tmp_item] - ret["stream"] = io.BytesIO(response.content) - return ret - - except httpx.HTTPError as e1: - if isinstance(e1, httpx.HTTPStatusError): - status_code = e1.response.status_code or 500 - try: - json_object = json.loads(e1.response.text) - raise DeepgramApiError( - json_object.get("err_msg"), - str(status_code), - json.dumps(json_object), - ) from e1 - except json.decoder.JSONDecodeError as e2: - raise DeepgramUnknownApiError(e2.msg, str(status_code)) from e2 - except ValueError as e2: - raise DeepgramUnknownApiError(str(e2), str(status_code)) from e2 - else: - raise # pylint: disable-msg=try-except-raise - except Exception: # pylint: disable-msg=try-except-raise - raise - - # pylint: enable-msg=too-many-locals,too-many-branches - - # pylint: disable-msg=too-many-locals,too-many-branches - async def _handle_request_raw( - self, - method: str, - url: str, - params: Optional[Dict] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ) -> httpx.Response: - _url = url - if params is not None: - _url = append_query_params(_url, params) - if addons is not None: - _url = append_query_params(_url, addons) - _headers = self._config.headers - if headers is not None: - _headers.update(headers) - if timeout is None: - timeout = httpx.Timeout(30.0, connect=10.0) - - try: - transport = kwargs.get("transport") - client = httpx.AsyncClient(timeout=timeout, transport=transport) - if transport: - kwargs.pop("transport") - req = client.build_request(method, _url, headers=_headers, **kwargs) - return await client.send(req, stream=True) - - except httpx.HTTPError as e1: - if isinstance(e1, httpx.HTTPStatusError): - status_code = e1.response.status_code or 500 - try: - json_object = json.loads(e1.response.text) - raise DeepgramApiError( - json_object.get("err_msg"), - str(status_code), - json.dumps(json_object), - ) from e1 - except json.decoder.JSONDecodeError as e2: - raise DeepgramUnknownApiError(e2.msg, str(status_code)) from e2 - except ValueError as e2: - raise DeepgramUnknownApiError(str(e2), str(status_code)) from e2 - else: - raise # pylint: disable-msg=try-except-raise - except Exception: # pylint: disable-msg=try-except-raise - raise - - # pylint: enable-msg=too-many-locals,too-many-branches - # pylint: enable=too-many-positional-arguments diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/abstract_async_websocket.py b/venv/Lib/site-packages/deepgram/clients/common/v1/abstract_async_websocket.py deleted file mode 100644 index 5f374ae3..00000000 --- a/venv/Lib/site-packages/deepgram/clients/common/v1/abstract_async_websocket.py +++ /dev/null @@ -1,537 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT -import asyncio -import json -import logging -from typing import Dict, Union, Optional, cast, Any, Callable -from datetime import datetime -import threading -from abc import ABC, abstractmethod - -import websockets - -try: - # Websockets versions >= 13 - from websockets.asyncio.client import connect, ClientConnection - - WS_ADDITIONAL_HEADERS_KEY = "additional_headers" -except ImportError: - # Backward compatibility with websockets versions 12 - from websockets.legacy.client import ( # type: ignore - connect, - WebSocketClientProtocol as ClientConnection, - ) - - WS_ADDITIONAL_HEADERS_KEY = "extra_headers" - -from ....audio import Speaker -from ....utils import verboselogs -from ....options import DeepgramClientOptions -from .helpers import convert_to_websocket_url, append_query_params -from .errors import DeepgramError - -from .websocket_response import ( - OpenResponse, - CloseResponse, - ErrorResponse, -) -from .websocket_events import WebSocketEvents - - -ONE_SECOND = 1 -HALF_SECOND = 0.5 -DEEPGRAM_INTERVAL = 5 -PING_INTERVAL = 20 - - -class AbstractAsyncWebSocketClient(ABC): # pylint: disable=too-many-instance-attributes - """ - Abstract class for using WebSockets. - - This class provides methods to establish a WebSocket connection generically for - use in all WebSocket clients. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - _endpoint: str - _websocket_url: str - - _socket: Optional[ClientConnection] = None - - _listen_thread: Union[asyncio.Task, None] - _delegate: Optional[Speaker] = None - - _kwargs: Optional[Dict] = None - _addons: Optional[Dict] = None - _options: Optional[Dict] = None - _headers: Optional[Dict] = None - - def __init__(self, config: DeepgramClientOptions, endpoint: str = ""): - if config is None: - raise DeepgramError("Config is required") - if endpoint == "": - raise DeepgramError("endpoint is required") - - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - - self._config = config - self._endpoint = endpoint - - self._listen_thread = None - - # events - self._exit_event = asyncio.Event() - - # set websocket url - self._websocket_url = convert_to_websocket_url(self._config.url, self._endpoint) - - def delegate_listening(self, delegate: Speaker) -> None: - """ - Delegate the listening thread to the Speaker object. - """ - self._delegate = delegate - - # pylint: disable=too-many-branches,too-many-statements - async def start( - self, - options: Optional[Any] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> bool: - """ - Starts the WebSocket connection for live transcription. - """ - self._logger.debug("AbstractAsyncWebSocketClient.start ENTER") - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - self._logger.info("kwargs: %s", kwargs) - - self._addons = addons - self._headers = headers - - # set kwargs - if kwargs is not None: - self._kwargs = kwargs - else: - self._kwargs = {} - - if not isinstance(options, dict): - self._logger.error("options is not a dict") - self._logger.debug("AbstractSyncWebSocketClient.start LEAVE") - return False - - # set options - if options is not None: - self._options = options - else: - self._options = {} - - combined_options = self._options.copy() - if self._addons is not None: - self._logger.info("merging addons to options") - combined_options.update(self._addons) - self._logger.info("new options: %s", combined_options) - self._logger.debug("combined_options: %s", combined_options) - - combined_headers = self._config.headers.copy() - if self._headers is not None: - self._logger.info("merging headers to options") - combined_headers.update(self._headers) - self._logger.info("new headers: %s", combined_headers) - self._logger.debug("combined_headers: %s", combined_headers) - - url_with_params = append_query_params(self._websocket_url, combined_options) - - try: - ws_connect_kwargs: Dict = { - "ping_interval": PING_INTERVAL, - WS_ADDITIONAL_HEADERS_KEY: combined_headers, - } - - self._socket = await connect( - url_with_params, - **ws_connect_kwargs, - ) - self._exit_event.clear() - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - # delegate the listening thread to external object - if self._delegate is not None: - self._logger.notice("_delegate is enabled. this is usually the speaker") - self._delegate.set_pull_callback(self._socket.recv) - self._delegate.set_push_callback(self._process_message) - else: - self._logger.notice("create _listening thread") - self._listen_thread = asyncio.create_task(self._listening()) - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - # push open event - await self._emit( - WebSocketEvents(WebSocketEvents.Open), - OpenResponse(type=WebSocketEvents.Open), - ) - - self._logger.notice("start succeeded") - self._logger.debug("AbstractAsyncWebSocketClient.start LEAVE") - return True - except websockets.exceptions.ConnectionClosed as e: - self._logger.error( - "ConnectionClosed in AbstractAsyncWebSocketClient.start: %s", e - ) - self._logger.debug("AbstractAsyncWebSocketClient.start LEAVE") - if self._config.options.get("termination_exception_connect", False): - raise - return False - except websockets.exceptions.WebSocketException as e: - self._logger.error( - "WebSocketException in AbstractAsyncWebSocketClient.start: %s", e - ) - self._logger.debug("AbstractAsyncWebSocketClient.start LEAVE") - if self._config.options.get("termination_exception_connect", False): - raise - return False - except Exception as e: # pylint: disable=broad-except - self._logger.error( - "WebSocketException in AbstractAsyncWebSocketClient.start: %s", e - ) - self._logger.debug("AbstractAsyncWebSocketClient.start LEAVE") - if self._config.options.get("termination_exception_connect", False): - raise - return False - - async def is_connected(self) -> bool: - """ - Returns the connection status of the WebSocket. - """ - return self._socket is not None - - # pylint: enable=too-many-branches,too-many-statements - - @abstractmethod - def on(self, event: WebSocketEvents, handler: Callable) -> None: - """ - Registers an event handler for the WebSocket connection. - """ - raise NotImplementedError("no on method") - - @abstractmethod - async def _emit(self, event: WebSocketEvents, *args, **kwargs) -> None: - """ - Emits an event to the WebSocket connection. - """ - raise NotImplementedError("no _emit method") - - # pylint: disable=too-many-return-statements,too-many-statements,too-many-locals,too-many-branches - async def _listening(self) -> None: - """ - Listens for messages from the WebSocket connection. - """ - self._logger.debug("AbstractAsyncWebSocketClient._listening ENTER") - - while True: - try: - if self._exit_event.is_set(): - self._logger.notice("_listening exiting gracefully") - self._logger.debug("AbstractAsyncWebSocketClient._listening LEAVE") - return - - if self._socket is None: - self._logger.warning("socket is empty") - self._logger.debug("AbstractAsyncWebSocketClient._listening LEAVE") - return - - message = await self._socket.recv() - - if message is None: - self._logger.info("message is None") - continue - - self._logger.spam("data type: %s", type(message)) - - if isinstance(message, bytes): - self._logger.debug("Binary data received") - await self._process_binary(message) - else: - self._logger.debug("Text data received") - await self._process_text(message) - - self._logger.notice("_listening Succeeded") - self._logger.debug("AbstractAsyncWebSocketClient._listening LEAVE") - - except websockets.exceptions.ConnectionClosedOK as e: - # signal exit and close - await self._signal_exit() - - self._logger.notice(f"_listening({e.code}) exiting gracefully") - self._logger.debug("AbstractAsyncWebSocketClient._listening LEAVE") - return - - except websockets.exceptions.ConnectionClosed as e: - if e.code in [1000, 1001]: - # signal exit and close - await self._signal_exit() - - self._logger.notice(f"_listening({e.code}) exiting gracefully") - self._logger.debug("AbstractAsyncWebSocketClient._listening LEAVE") - return - - # we need to explicitly call self._signal_exit() here because we are hanging on a recv() - # note: this is different than the speak websocket client - self._logger.error( - "ConnectionClosed in AbstractAsyncWebSocketClient._listening with code %s: %s", - e.code, - e.reason, - ) - cc_error: ErrorResponse = ErrorResponse( - "ConnectionClosed in AbstractAsyncWebSocketClient._listening", - f"{e}", - "ConnectionClosed", - ) - await self._emit( - WebSocketEvents(WebSocketEvents.Error), - error=cc_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - # signal exit and close - await self._signal_exit() - - self._logger.debug("AbstractAsyncWebSocketClient._listening LEAVE") - - if self._config.options.get("termination_exception_connect") is True: - raise - return - - except websockets.exceptions.WebSocketException as e: - self._logger.error( - "WebSocketException in AbstractAsyncWebSocketClient._listening: %s", - e, - ) - ws_error: ErrorResponse = ErrorResponse( - "WebSocketException in AbstractAsyncWebSocketClient._listening", - f"{e}", - "WebSocketException", - ) - await self._emit( - WebSocketEvents(WebSocketEvents.Error), - error=ws_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - # signal exit and close - await self._signal_exit() - - self._logger.debug("AbstractAsyncWebSocketClient._listening LEAVE") - - if self._config.options.get("termination_exception_connect") is True: - raise - return - - except Exception as e: # pylint: disable=broad-except - self._logger.error( - "Exception in AbstractAsyncWebSocketClient._listening: %s", e - ) - e_error: ErrorResponse = ErrorResponse( - "Exception in AbstractAsyncWebSocketClient._listening", - f"{e}", - "Exception", - ) - await self._emit( - WebSocketEvents(WebSocketEvents.Error), - error=e_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - # signal exit and close - await self._signal_exit() - - self._logger.debug("AbstractAsyncWebSocketClient._listening LEAVE") - - if self._config.options.get("termination_exception_connect") is True: - raise - return - - # pylint: enable=too-many-return-statements,too-many-statements,too-many-locals,too-many-branches - - async def _process_message(self, message: Union[str, bytes]) -> None: - if isinstance(message, bytes): - await self._process_binary(message) - else: - await self._process_text(message) - - @abstractmethod - async def _process_text(self, message: str) -> None: - raise NotImplementedError("no _process_text method") - - @abstractmethod - async def _process_binary(self, message: bytes) -> None: - raise NotImplementedError("no _process_binary method") - - @abstractmethod - async def _close_message(self) -> bool: - raise NotImplementedError("no _close_message method") - - # pylint: disable=too-many-return-statements,too-many-branches - - async def send(self, data: Union[str, bytes]) -> bool: - """ - Sends data over the WebSocket connection. - """ - self._logger.spam("AbstractAsyncWebSocketClient.send ENTER") - - if self._exit_event.is_set(): - self._logger.notice("send exiting gracefully") - self._logger.debug("AbstractAsyncWebSocketClient.send LEAVE") - return False - - if not await self.is_connected(): - self._logger.notice("is_connected is False") - self._logger.debug("AbstractAsyncWebSocketClient.send LEAVE") - return False - - if self._socket is not None: - try: - await self._socket.send(data) - except websockets.exceptions.ConnectionClosedOK as e: - self._logger.notice(f"send() exiting gracefully: {e.code}") - self._logger.debug("AbstractAsyncWebSocketClient.send LEAVE") - if self._config.options.get("termination_exception_send") is True: - raise - return True - except websockets.exceptions.ConnectionClosed as e: - if e.code in [1000, 1001]: - self._logger.notice(f"send({e.code}) exiting gracefully") - self._logger.debug("AbstractAsyncWebSocketClient.send LEAVE") - if self._config.options.get("termination_exception_send") is True: - raise - return True - - self._logger.error("send() failed - ConnectionClosed: %s", str(e)) - self._logger.spam("AbstractAsyncWebSocketClient.send LEAVE") - if self._config.options.get("termination_exception_send") is True: - raise - return False - except websockets.exceptions.WebSocketException as e: - self._logger.error("send() failed - WebSocketException: %s", str(e)) - self._logger.spam("AbstractAsyncWebSocketClient.send LEAVE") - if self._config.options.get("termination_exception_send") is True: - raise - return False - except Exception as e: # pylint: disable=broad-except - self._logger.error("send() failed - Exception: %s", str(e)) - self._logger.spam("AbstractAsyncWebSocketClient.send LEAVE") - if self._config.options.get("termination_exception_send") is True: - raise - return False - - self._logger.spam("send() succeeded") - self._logger.spam("AbstractAsyncWebSocketClient.send LEAVE") - return True - - self._logger.spam("send() failed. socket is None") - self._logger.spam("AbstractAsyncWebSocketClient.send LEAVE") - return False - - # pylint: enable=too-many-return-statements,too-many-branches - - async def finish(self) -> bool: - """ - Closes the WebSocket connection gracefully. - """ - self._logger.debug("AbstractAsyncWebSocketClient.finish ENTER") - - # signal exit - await self._signal_exit() - - # stop the threads - self._logger.verbose("cancelling tasks...") - try: - # Before cancelling, check if the tasks were created - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("before running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - tasks = [] - if self._listen_thread is not None: - self._listen_thread.cancel() - tasks.append(self._listen_thread) - self._logger.notice("processing _listen_thread cancel...") - - # Use asyncio.gather to wait for tasks to be cancelled - await asyncio.gather(*filter(None, tasks)) - self._logger.notice("threads joined") - - # debug the threads - for thread in threading.enumerate(): - if thread is not None and thread.name is not None: - self._logger.debug("after running thread: %s", thread.name) - else: - self._logger.debug("after running thread: unknown_thread_name") - self._logger.debug("number of active threads: %s", threading.active_count()) - - self._logger.notice("finish succeeded") - self._logger.spam("AbstractAsyncWebSocketClient.finish LEAVE") - return True - - except asyncio.CancelledError as e: - self._logger.error("tasks cancelled error: %s", e) - self._logger.debug("AbstractAsyncWebSocketClient.finish LEAVE") - return True - - async def _signal_exit(self) -> None: - # send close event - self._logger.verbose("closing socket...") - if self._socket is not None: - self._logger.verbose("send Close...") - try: - # if the socket connection is closed, the following line might throw an error - await self._close_message() - except websockets.exceptions.ConnectionClosedOK as e: - self._logger.notice("_signal_exit - ConnectionClosedOK: %s", e.code) - except websockets.exceptions.ConnectionClosed as e: - self._logger.error("_signal_exit - ConnectionClosed: %s", e.code) - except websockets.exceptions.WebSocketException as e: - self._logger.error("_signal_exit - WebSocketException: %s", str(e)) - except Exception as e: # pylint: disable=broad-except - self._logger.error("_signal_exit - Exception: %s", str(e)) - - # push close event - try: - await self._emit( - WebSocketEvents(WebSocketEvents.Close), - close=CloseResponse(type=WebSocketEvents.Close), - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - except Exception as e: # pylint: disable=broad-except - self._logger.error("_emit - Exception: %s", e) - - # wait for task to send - await asyncio.sleep(0.5) - - # signal exit - self._exit_event.set() - - # closes the WebSocket connection gracefully - self._logger.verbose("clean up socket...") - if self._socket is not None: - self._logger.verbose("socket.wait_closed...") - try: - await self._socket.close() - except websockets.exceptions.WebSocketException as e: - self._logger.error("socket.wait_closed failed: %s", e) - - self._socket = None diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/abstract_sync_rest.py b/venv/Lib/site-packages/deepgram/clients/common/v1/abstract_sync_rest.py deleted file mode 100644 index cbfd40ef..00000000 --- a/venv/Lib/site-packages/deepgram/clients/common/v1/abstract_sync_rest.py +++ /dev/null @@ -1,375 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -import json -import io -from typing import Dict, Optional, List, Union - -import httpx - -from .helpers import append_query_params -from ....options import DeepgramClientOptions -from .errors import DeepgramError, DeepgramApiError, DeepgramUnknownApiError - - -class AbstractSyncRestClient: - """ - An abstract base class for a RESTful HTTP client. - - This class provides common HTTP methods (GET, POST, PUT, PATCH, DELETE) for making asynchronous HTTP requests. - It handles error responses and provides basic JSON parsing. - - Args: - url (Dict): The base URL for the RESTful API, including any path segments. - headers (Optional[Dict[str, Any]]): Optional HTTP headers to include in requests. - params (Optional[Dict[str, Any]]): Optional query parameters to include in requests. - timeout (Optional[httpx.Timeout]): Optional timeout configuration for requests. - - Exceptions: - DeepgramApiError: Raised for known API errors. - DeepgramUnknownApiError: Raised for unknown API errors. - """ - - _config: DeepgramClientOptions - - def __init__(self, config: DeepgramClientOptions): - if config is None: - raise DeepgramError("Config are required") - self._config = config - - # pylint: disable=too-many-positional-arguments - - def get( - self, - url: str, - options: Optional[Dict] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ) -> str: - """ - Make a GET request to the specified URL. - """ - return self._handle_request( - "GET", - url, - params=options, - addons=addons, - headers=headers, - timeout=timeout, - **kwargs, - ) - - def post_raw( - self, - url: str, - options: Optional[Dict] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ) -> httpx.Response: - """ - Make a POST request to the specified URL and return response in raw bytes. - """ - return self._handle_request_raw( - "POST", - url, - params=options, - addons=addons, - headers=headers, - timeout=timeout, - **kwargs, - ) - - def post_memory( - self, - url: str, - file_result: List, - options: Optional[Dict] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ) -> Dict[str, Union[str, io.BytesIO]]: - """ - Make a POST request to the specified URL and return response in memory. - """ - return self._handle_request_memory( - "POST", - url, - file_result=file_result, - params=options, - addons=addons, - headers=headers, - timeout=timeout, - **kwargs, - ) - - def post( - self, - url: str, - options: Optional[Dict] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ) -> str: - """ - Make a POST request to the specified URL. - """ - return self._handle_request( - "POST", - url, - params=options, - addons=addons, - headers=headers, - timeout=timeout, - **kwargs, - ) - - def put( - self, - url: str, - options: Optional[Dict] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ) -> str: - """ - Make a PUT request to the specified URL. - """ - return self._handle_request( - "PUT", - url, - params=options, - addons=addons, - headers=headers, - timeout=timeout, - **kwargs, - ) - - def patch( - self, - url: str, - options: Optional[Dict] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ) -> str: - """ - Make a PATCH request to the specified URL. - """ - return self._handle_request( - "PATCH", - url, - params=options, - addons=addons, - headers=headers, - timeout=timeout, - **kwargs, - ) - - def delete( - self, - url: str, - options: Optional[Dict] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ) -> str: - """ - Make a DELETE request to the specified URL. - """ - return self._handle_request( - "DELETE", - url, - params=options, - addons=addons, - headers=headers, - timeout=timeout, - **kwargs, - ) - - # pylint: disable-msg=too-many-locals,too-many-branches - def _handle_request( - self, - method: str, - url: str, - params: Optional[Dict] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ) -> str: - _url = url - if params is not None: - _url = append_query_params(_url, params) - if addons is not None: - _url = append_query_params(_url, addons) - _headers = self._config.headers - if headers is not None: - _headers.update(headers) - if timeout is None: - timeout = httpx.Timeout(30.0, connect=10.0) - - try: - transport = kwargs.get("transport") - with httpx.Client(timeout=timeout, transport=transport) as client: - if transport: - kwargs.pop("transport") - response = client.request(method, _url, headers=_headers, **kwargs) - response.raise_for_status() - - # throw exception if response is None or response.text is None - if response is None or response.text is None: - raise DeepgramError( - "Response is not available yet. Please try again later." - ) - - return response.text - - except httpx.HTTPError as e1: - if isinstance(e1, httpx.HTTPStatusError): - status_code = e1.response.status_code or 500 - try: - json_object = json.loads(e1.response.text) - raise DeepgramApiError( - json_object.get("err_msg"), - str(status_code), - json.dumps(json_object), - ) from e1 - except json.decoder.JSONDecodeError as e2: - raise DeepgramUnknownApiError(e2.msg, str(status_code)) from e2 - except ValueError as e2: - raise DeepgramUnknownApiError(str(e2), str(status_code)) from e2 - else: - raise # pylint: disable-msg=try-except-raise - except Exception: # pylint: disable-msg=try-except-raise - raise - - # pylint: enable-msg=too-many-locals,too-many-branches - - # pylint: disable-msg=too-many-branches,too-many-locals - def _handle_request_memory( - self, - method: str, - url: str, - file_result: List, - params: Optional[Dict] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ) -> Dict[str, Union[str, io.BytesIO]]: - _url = url - if params is not None: - _url = append_query_params(_url, params) - if addons is not None: - _url = append_query_params(_url, addons) - _headers = self._config.headers - if headers is not None: - _headers.update(headers) - if timeout is None: - timeout = httpx.Timeout(30.0, connect=10.0) - - try: - transport = kwargs.get("transport") - with httpx.Client(timeout=timeout, transport=transport) as client: - if transport: - kwargs.pop("transport") - response = client.request(method, _url, headers=_headers, **kwargs) - response.raise_for_status() - - ret: Dict[str, Union[str, io.BytesIO]] = {} - for item in file_result: - if item in response.headers: - ret[item] = response.headers[item] - continue - tmp_item = f"dg-{item}" - if tmp_item in response.headers: - ret[item] = response.headers[tmp_item] - continue - tmp_item = f"x-dg-{item}" - if tmp_item in response.headers: - ret[item] = response.headers[tmp_item] - ret["stream"] = io.BytesIO(response.content) - return ret - - except httpx.HTTPError as e1: - if isinstance(e1, httpx.HTTPStatusError): - status_code = e1.response.status_code or 500 - try: - json_object = json.loads(e1.response.text) - raise DeepgramApiError( - json_object.get("err_msg"), - str(status_code), - json.dumps(json_object), - ) from e1 - except json.decoder.JSONDecodeError as e2: - raise DeepgramUnknownApiError(e2.msg, str(status_code)) from e2 - except ValueError as e2: - raise DeepgramUnknownApiError(str(e2), str(status_code)) from e2 - else: - raise # pylint: disable-msg=try-except-raise - except Exception: # pylint: disable-msg=try-except-raise - raise - - # pylint: disable-msg=too-many-branches,too-many-locals - - # pylint: disable-msg=too-many-branches,too-many-locals - def _handle_request_raw( - self, - method: str, - url: str, - params: Optional[Dict] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ) -> httpx.Response: - _url = url - if params is not None: - _url = append_query_params(_url, params) - if addons is not None: - _url = append_query_params(_url, addons) - _headers = self._config.headers - if headers is not None: - _headers.update(headers) - if timeout is None: - timeout = httpx.Timeout(30.0, connect=10.0) - - try: - transport = kwargs.get("transport") - client = httpx.Client(timeout=timeout, transport=transport) - if transport: - kwargs.pop("transport") - req = client.build_request(method, _url, headers=_headers, **kwargs) - return client.send(req, stream=True) - - except httpx.HTTPError as e1: - if isinstance(e1, httpx.HTTPStatusError): - status_code = e1.response.status_code or 500 - try: - json_object = json.loads(e1.response.text) - raise DeepgramApiError( - json_object.get("err_msg"), - str(status_code), - json.dumps(json_object), - ) from e1 - except json.decoder.JSONDecodeError as e2: - raise DeepgramUnknownApiError(e2.msg, str(status_code)) from e2 - except ValueError as e2: - raise DeepgramUnknownApiError(str(e2), str(status_code)) from e2 - else: - raise # pylint: disable-msg=try-except-raise - except Exception: # pylint: disable-msg=try-except-raise - raise - - # pylint: enable-msg=too-many-branches,too-many-locals - # pylint: enable=too-many-positional-arguments diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/abstract_sync_websocket.py b/venv/Lib/site-packages/deepgram/clients/common/v1/abstract_sync_websocket.py deleted file mode 100644 index 23433a09..00000000 --- a/venv/Lib/site-packages/deepgram/clients/common/v1/abstract_sync_websocket.py +++ /dev/null @@ -1,527 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT -import json -import time -import logging -from typing import Dict, Union, Optional, cast, Any, Callable, Type -from datetime import datetime -import threading -from abc import ABC, abstractmethod - -from websockets.sync.client import connect, ClientConnection -import websockets - -from ....audio import Speaker -from ....utils import verboselogs -from ....options import DeepgramClientOptions -from .helpers import convert_to_websocket_url, append_query_params -from .errors import DeepgramError - -from .websocket_response import ( - OpenResponse, - CloseResponse, - ErrorResponse, -) -from .websocket_events import WebSocketEvents - - -ONE_SECOND = 1 -HALF_SECOND = 0.5 -DEEPGRAM_INTERVAL = 5 -PING_INTERVAL = 20 - - -class AbstractSyncWebSocketClient(ABC): # pylint: disable=too-many-instance-attributes - """ - Abstract class for using WebSockets. - - This class provides methods to establish a WebSocket connection generically for - use in all WebSocket clients. - - Args: - config (DeepgramClientOptions): all the options for the client - endpoint (str): the endpoint to connect to - thread_cls (Type[threading.Thread]): optional thread class to use for creating threads, - defaults to threading.Thread. Useful for custom thread management like ContextVar support. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - _endpoint: str - _websocket_url: str - - _socket: Optional[ClientConnection] = None - _exit_event: threading.Event - _lock_send: threading.Lock - - _listen_thread: Union[threading.Thread, None] - _delegate: Optional[Speaker] = None - - _thread_cls: Type[threading.Thread] - - _kwargs: Optional[Dict] = None - _addons: Optional[Dict] = None - _options: Optional[Dict] = None - _headers: Optional[Dict] = None - - def __init__( - self, - config: DeepgramClientOptions, - endpoint: str = "", - thread_cls: Type[threading.Thread] = threading.Thread, - ): - if config is None: - raise DeepgramError("Config is required") - if endpoint == "": - raise DeepgramError("endpoint is required") - - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - - self._config = config - self._endpoint = endpoint - self._lock_send = threading.Lock() - - self._listen_thread = None - - self._thread_cls = thread_cls - - # exit - self._exit_event = threading.Event() - - # set websocket url - self._websocket_url = convert_to_websocket_url(self._config.url, self._endpoint) - - def delegate_listening(self, delegate: Speaker) -> None: - """ - Delegate the listening thread to the main thread. - """ - self._delegate = delegate - - # pylint: disable=too-many-statements,too-many-branches - def start( - self, - options: Optional[Any] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> bool: - """ - Starts the WebSocket connection for live transcription. - """ - self._logger.debug("AbstractSyncWebSocketClient.start ENTER") - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - self._logger.info("kwargs: %s", kwargs) - - self._addons = addons - self._headers = headers - - # set kwargs - if kwargs is not None: - self._kwargs = kwargs - else: - self._kwargs = {} - - if not isinstance(options, dict): - self._logger.error("options is not a dict") - self._logger.debug("AbstractSyncWebSocketClient.start LEAVE") - return False - - # set options - if options is not None: - self._options = options - else: - self._options = {} - - combined_options = self._options.copy() - if self._addons is not None: - self._logger.info("merging addons to options") - combined_options.update(self._addons) - self._logger.info("new options: %s", combined_options) - self._logger.debug("combined_options: %s", combined_options) - - combined_headers = self._config.headers.copy() - if self._headers is not None: - self._logger.info("merging headers to options") - combined_headers.update(self._headers) - self._logger.info("new headers: %s", combined_headers) - self._logger.debug("combined_headers: %s", combined_headers) - - url_with_params = append_query_params(self._websocket_url, combined_options) - try: - self._socket = connect(url_with_params, additional_headers=combined_headers) - self._exit_event.clear() - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - # delegate the listening thread to external object - if self._delegate is not None: - self._logger.notice("_delegate is enabled. this is usually the speaker") - self._delegate.set_pull_callback(self._socket.recv) - self._delegate.set_push_callback(self._process_message) - else: - self._logger.notice("create _listening thread") - self._listen_thread = self._thread_cls(target=self._listening) - self._listen_thread.start() - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - # push open event - self._emit( - WebSocketEvents(WebSocketEvents.Open), - OpenResponse(type=WebSocketEvents.Open), - ) - - self._logger.notice("start succeeded") - self._logger.debug("AbstractSyncWebSocketClient.start LEAVE") - return True - except websockets.exceptions.ConnectionClosed as e: - self._logger.error( - "ConnectionClosed in AbstractSyncWebSocketClient.start: %s", e - ) - self._logger.debug("AbstractSyncWebSocketClient.start LEAVE") - if self._config.options.get("termination_exception_connect", False): - raise e - return False - except websockets.exceptions.WebSocketException as e: - self._logger.error( - "WebSocketException in AbstractSyncWebSocketClient.start: %s", e - ) - self._logger.debug("AbstractSyncWebSocketClient.start LEAVE") - if self._config.options.get("termination_exception_connect", False): - raise e - return False - except Exception as e: # pylint: disable=broad-except - self._logger.error( - "WebSocketException in AbstractSyncWebSocketClient.start: %s", e - ) - self._logger.debug("AbstractSyncWebSocketClient.start LEAVE") - if self._config.options.get("termination_exception_connect", False): - raise e - return False - - def is_connected(self) -> bool: - """ - Returns the connection status of the WebSocket. - """ - return self._socket is not None - - # pylint: enable=too-many-statements,too-many-branches - - @abstractmethod - def on(self, event: WebSocketEvents, handler: Callable) -> None: - """ - Registers an event handler for the WebSocket connection. - """ - raise NotImplementedError("no on method") - - @abstractmethod - def _emit(self, event: WebSocketEvents, *args, **kwargs) -> None: - """ - Emits an event to the WebSocket connection. - """ - raise NotImplementedError("no _emit method") - - # pylint: disable=too-many-return-statements,too-many-statements,too-many-locals,too-many-branches - def _listening( - self, - ) -> None: - """ - Listens for messages from the WebSocket connection. - """ - self._logger.debug("AbstractSyncWebSocketClient._listening ENTER") - - while True: - try: - if self._exit_event.is_set(): - self._logger.notice("_listening exiting gracefully") - self._logger.debug("AbstractSyncWebSocketClient._listening LEAVE") - return - - if self._socket is None: - self._logger.warning("socket is empty") - self._logger.debug("AbstractSyncWebSocketClient._listening LEAVE") - return - - message = self._socket.recv() - - if message is None: - self._logger.info("message is None") - continue - - self._logger.spam("data type: %s", type(message)) - - if isinstance(message, bytes): - self._logger.debug("Binary data received") - self._process_binary(message) - else: - self._logger.debug("Text data received") - self._process_text(message) - - self._logger.notice("_listening Succeeded") - self._logger.debug("AbstractSyncWebSocketClient._listening LEAVE") - - except websockets.exceptions.ConnectionClosedOK as e: - # signal exit and close - self._signal_exit() - - self._logger.notice(f"_listening({e.code}) exiting gracefully") - self._logger.debug("AbstractSyncWebSocketClient._listening LEAVE") - return - - except websockets.exceptions.ConnectionClosed as e: - if e.code in [1000, 1001]: - # signal exit and close - self._signal_exit() - - self._logger.notice(f"_listening({e.code}) exiting gracefully") - self._logger.debug("AbstractSyncWebSocketClient._listening LEAVE") - return - - # we need to explicitly call self._signal_exit() here because we are hanging on a recv() - # note: this is different than the speak websocket client - self._logger.error( - "ConnectionClosed in AbstractSyncWebSocketClient._listening with code %s: %s", - e.code, - e.reason, - ) - cc_error: ErrorResponse = ErrorResponse( - "ConnectionClosed in AbstractSyncWebSocketClient._listening", - f"{e}", - "ConnectionClosed", - ) - self._emit( - WebSocketEvents(WebSocketEvents.Error), - cc_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - # signal exit and close - self._signal_exit() - - self._logger.debug("AbstractSyncWebSocketClient._listening LEAVE") - - if self._config.options.get("termination_exception_connect") is True: - raise - return - - except websockets.exceptions.WebSocketException as e: - self._logger.error( - "WebSocketException in AbstractSyncWebSocketClient._listening with: %s", - e, - ) - ws_error: ErrorResponse = ErrorResponse( - "WebSocketException in AbstractSyncWebSocketClient._listening", - f"{e}", - "WebSocketException", - ) - self._emit( - WebSocketEvents(WebSocketEvents.Error), - ws_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - # signal exit and close - self._signal_exit() - - self._logger.debug("AbstractSyncWebSocketClient._listening LEAVE") - - if self._config.options.get("termination_exception_connect") is True: - raise - return - - except Exception as e: # pylint: disable=broad-except - self._logger.error( - "Exception in AbstractSyncWebSocketClient._listening: %s", e - ) - e_error: ErrorResponse = ErrorResponse( - "Exception in AbstractSyncWebSocketClient._listening", - f"{e}", - "Exception", - ) - self._emit( - WebSocketEvents(WebSocketEvents.Error), - e_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - # signal exit and close - self._signal_exit() - - self._logger.debug("AbstractSyncWebSocketClient._listening LEAVE") - - if self._config.options.get("termination_exception_connect") is True: - raise - return - - # pylint: enable=too-many-return-statements,too-many-statements,too-many-locals,too-many-branches - - def _process_message(self, message: Union[str, bytes]) -> None: - if isinstance(message, bytes): - self._process_binary(message) - else: - self._process_text(message) - - @abstractmethod - def _process_text(self, message: str) -> None: - raise NotImplementedError("no _process_text method") - - @abstractmethod - def _process_binary(self, message: bytes) -> None: - raise NotImplementedError("no _process_binary method") - - @abstractmethod - def _close_message(self) -> bool: - raise NotImplementedError("no _close_message method") - - # pylint: disable=too-many-return-statements,too-many-branches - def send(self, data: Union[str, bytes]) -> bool: - """ - Sends data over the WebSocket connection. - """ - self._logger.spam("AbstractSyncWebSocketClient.send ENTER") - - if self._exit_event.is_set(): - self._logger.notice("send exiting gracefully") - self._logger.debug("AbstractSyncWebSocketClient.send LEAVE") - return False - - if not self.is_connected(): - self._logger.notice("is_connected is False") - self._logger.debug("AbstractSyncWebSocketClient.send LEAVE") - return False - - if self._socket is not None: - with self._lock_send: - try: - self._socket.send(data) - except websockets.exceptions.ConnectionClosedOK as e: - self._logger.notice(f"send() exiting gracefully: {e.code}") - self._logger.debug("AbstractSyncWebSocketClient.send LEAVE") - if self._config.options.get("termination_exception_send") is True: - raise - return True - except websockets.exceptions.ConnectionClosed as e: - if e.code in [1000, 1001]: - self._logger.notice(f"send({e.code}) exiting gracefully") - self._logger.debug("AbstractSyncWebSocketClient.send LEAVE") - if ( - self._config.options.get("termination_exception_send") - == "true" - ): - raise - return True - self._logger.error("send() failed - ConnectionClosed: %s", str(e)) - self._logger.spam("AbstractSyncWebSocketClient.send LEAVE") - if self._config.options.get("termination_exception_send") is True: - raise - return False - except websockets.exceptions.WebSocketException as e: - self._logger.error("send() failed - WebSocketException: %s", str(e)) - self._logger.spam("AbstractSyncWebSocketClient.send LEAVE") - if self._config.options.get("termination_exception_send") is True: - raise - return False - except Exception as e: # pylint: disable=broad-except - self._logger.error("send() failed - Exception: %s", str(e)) - self._logger.spam("AbstractSyncWebSocketClient.send LEAVE") - if self._config.options.get("termination_exception_send") is True: - raise - return False - - self._logger.spam("send() succeeded") - self._logger.spam("AbstractSyncWebSocketClient.send LEAVE") - return True - - self._logger.spam("send() failed. socket is None") - self._logger.spam("AbstractSyncWebSocketClient.send LEAVE") - return False - - # pylint: enable=too-many-return-statements,too-many-branches - - def finish(self) -> bool: - """ - Closes the WebSocket connection gracefully. - """ - self._logger.spam("AbstractSyncWebSocketClient.finish ENTER") - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("before running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - # signal exit - self._signal_exit() - - # stop the threads - self._logger.verbose("cancelling tasks...") - if self._listen_thread is not None: - self._listen_thread.join() - self._listen_thread = None - self._logger.notice("listening thread joined") - - # debug the threads - for thread in threading.enumerate(): - if thread is not None and thread.name is not None: - self._logger.debug("before running thread: %s", thread.name) - else: - self._logger.debug("after running thread: unknown_thread_name") - self._logger.debug("number of active threads: %s", threading.active_count()) - - self._logger.notice("finish succeeded") - self._logger.spam("AbstractSyncWebSocketClient.finish LEAVE") - return True - - # signals the WebSocket connection to exit - def _signal_exit(self) -> None: - # closes the WebSocket connection gracefully - self._logger.notice("closing socket...") - if self._socket is not None: - self._logger.notice("sending Close...") - try: - # if the socket connection is closed, the following line might throw an error - self._close_message() - except websockets.exceptions.ConnectionClosedOK as e: - self._logger.notice("_signal_exit - ConnectionClosedOK: %s", e.code) - except websockets.exceptions.ConnectionClosed as e: - self._logger.error("_signal_exit - ConnectionClosed: %s", e.code) - except websockets.exceptions.WebSocketException as e: - self._logger.error("_signal_exit - WebSocketException: %s", str(e)) - except Exception as e: # pylint: disable=broad-except - self._logger.error("_signal_exit - Exception: %s", str(e)) - - # push close event - try: - self._emit( - WebSocketEvents(WebSocketEvents.Close), - CloseResponse(type=WebSocketEvents.Close), - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - except Exception as e: # pylint: disable=broad-except - self._logger.error("_signal_exit - Exception: %s", e) - - # wait for task to send - time.sleep(0.5) - - # signal exit - self._exit_event.set() - - # closes the WebSocket connection gracefully - self._logger.verbose("clean up socket...") - if self._socket is not None: - self._logger.verbose("socket.wait_closed...") - try: - self._socket.close() - except websockets.exceptions.WebSocketException as e: - self._logger.error("socket.wait_closed failed: %s", e) - - self._socket = None diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/enums.py b/venv/Lib/site-packages/deepgram/clients/common/v1/enums.py deleted file mode 100644 index a25893e9..00000000 --- a/venv/Lib/site-packages/deepgram/clients/common/v1/enums.py +++ /dev/null @@ -1,18 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from aenum import StrEnum - -# Constants mapping to events from the Deepgram API - - -class Sentiment(StrEnum): - """ - Sentiment values. - """ - - UNKNOWN: str = "" - NEGATIVE: str = "negative" - NEUTRAL: str = "neutral" - POSITIVE: str = "positive" diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/errors.py b/venv/Lib/site-packages/deepgram/clients/common/v1/errors.py deleted file mode 100644 index e0b5ac8e..00000000 --- a/venv/Lib/site-packages/deepgram/clients/common/v1/errors.py +++ /dev/null @@ -1,77 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - - -class DeepgramError(Exception): - """ - Exception raised for unknown errors related to the Deepgram API. - - Attributes: - message (str): The error message describing the exception. - """ - - def __init__(self, message: str): - super().__init__(message) - self.name = "DeepgramError" - self.message = message - - def __str__(self): - return f"{self.name}: {self.message}" - - -class DeepgramTypeError(Exception): - """ - Exception raised for unknown errors related to unknown Types for Transcription. - - Attributes: - message (str): The error message describing the exception. - """ - - def __init__(self, message: str): - super().__init__(message) - self.name = "DeepgramTypeError" - self.message = message - - def __str__(self): - return f"{self.name}: {self.message}" - - -class DeepgramApiError(Exception): - """ - Exception raised for known errors (in json response format) related to the Deepgram API. - - Attributes: - message (str): The error message describing the exception. - status (str): The HTTP status associated with the API error. - original_error (str - json): The original error that was raised. - """ - - def __init__(self, message: str, status: str, original_error=None): - super().__init__(message) - self.name = "DeepgramApiError" - self.status = status - self.message = message - self.original_error = original_error - - def __str__(self): - return f"{self.name}: {self.message} (Status: {self.status})" - - -class DeepgramUnknownApiError(DeepgramApiError): - """ - Exception raised for unknown errors related to the Deepgram API. - - Attributes: - message (str): The error message describing the exception. - status (str): The HTTP status associated with the API error. - """ - - def __init__(self, message: str, status: str): - super().__init__(message, status) - self.name = "DeepgramUnknownApiError" - self.status = status - self.message = message - - def __str__(self): - return f"{self.name}: {self.message} (Status: {self.status})" diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/helpers.py b/venv/Lib/site-packages/deepgram/clients/common/v1/helpers.py deleted file mode 100644 index c7429acd..00000000 --- a/venv/Lib/site-packages/deepgram/clients/common/v1/helpers.py +++ /dev/null @@ -1,53 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from urllib.parse import urlparse, urlunparse, parse_qs, urlencode -from typing import Dict, Optional -import re - - -# This function appends query parameters to a URL -def append_query_params(url: str, params: Optional[Dict] = None): - """ - Appends query parameters to a URL - """ - parsed_url = urlparse(url) - query_params = parse_qs(parsed_url.query) - - if params is not None: - for key, value in params.items(): - if value is None: - continue - if isinstance(value, bool): - value = str(value).lower() - if isinstance(value, list): - for item in value: - query_params[key] = query_params.get(key, []) + [str(item)] - else: - query_params[key] = [str(value)] - - updated_query_string = urlencode(query_params, doseq=True) - updated_url = parsed_url._replace(query=updated_query_string).geturl() - return updated_url - - -# This function converts a URL to a WebSocket URL -def convert_to_websocket_url(base_url: str, endpoint: str): - """ - Converts a URL to a WebSocket URL - """ - use_ssl = True # Default to true - if re.match(r"^https?://", base_url, re.IGNORECASE): - if "http://" in base_url: - use_ssl = False # Override to false if http:// is found - base_url = base_url.replace("https://", "").replace("http://", "") - if not re.match(r"^wss?://", base_url, re.IGNORECASE): - if use_ssl: - base_url = "wss://" + base_url - else: - base_url = "ws://" + base_url - parsed_url = urlparse(base_url) - domain = parsed_url.netloc - websocket_url = urlunparse((parsed_url.scheme, domain, endpoint, "", "", "")) - return websocket_url diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/options.py b/venv/Lib/site-packages/deepgram/clients/common/v1/options.py deleted file mode 100644 index c2db15d9..00000000 --- a/venv/Lib/site-packages/deepgram/clients/common/v1/options.py +++ /dev/null @@ -1,65 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from io import BufferedReader -from typing import Union -from typing_extensions import TypedDict - - -class StreamSource(TypedDict): - """ - Represents a data source for reading binary data from a stream-like source. - - This class is used to specify a source of binary data that can be read from - a stream, such as an audio file in .wav format. - - Attributes: - stream (BufferedReader): A BufferedReader object for reading binary data. - """ - - stream: BufferedReader - - -class UrlSource(TypedDict): - """ - Represents a data source for specifying the location of a file via a URL. - - This class is used to specify a hosted file URL, typically pointing to an - externally hosted file, such as an audio file hosted on a server or the internet. - - Attributes: - url (str): The URL pointing to the hosted file. - """ - - url: str - - -class BufferSource(TypedDict): - """ - Represents a data source for handling raw binary data. - - This class is used to specify raw binary data, such as audio data in its - binary form, which can be captured from a microphone or generated synthetically. - - Attributes: - buffer (bytes): The binary data. - """ - - buffer: bytes - - -class TextSource(TypedDict): - """ - Represents a data source for reading binary data from a text-like source. - - This class is used to specify a source of text data that can be read from. - - Attributes: - text (str): A string for reading text data. - """ - - text: str - - -FileSource = Union[TextSource, BufferSource, StreamSource] diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/rest_response.py b/venv/Lib/site-packages/deepgram/clients/common/v1/rest_response.py deleted file mode 100644 index 22ca09eb..00000000 --- a/venv/Lib/site-packages/deepgram/clients/common/v1/rest_response.py +++ /dev/null @@ -1,181 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from typing import List, Optional, Dict, Any - -from dataclasses import dataclass, field -from dataclasses_json import config as dataclass_config - -from .enums import Sentiment -from .shared_response import BaseResponse - - -# Analyze Response Types: - - -@dataclass -class IntentsInfo(BaseResponse): - """ - Intents Info - """ - - model_uuid: str = "" - input_tokens: int = 0 - output_tokens: int = 0 - - -@dataclass -class SentimentInfo(BaseResponse): - """ - Sentiment Info - """ - - model_uuid: str = "" - input_tokens: int = 0 - output_tokens: int = 0 - - -@dataclass -class SummaryInfo(BaseResponse): - """ - Summary Info - """ - - model_uuid: str = "" - input_tokens: int = 0 - output_tokens: int = 0 - - -@dataclass -class TopicsInfo(BaseResponse): - """ - Topics Info - """ - - model_uuid: str = "" - input_tokens: int = 0 - output_tokens: int = 0 - - -@dataclass -class Average(BaseResponse): - """ - Average - """ - - sentiment: Sentiment - sentiment_score: float = 0 - - def __getitem__(self, key): - _dict = self.to_dict() - if "sentiment" in _dict: - _dict["sentiment"] = Sentiment.from_dict(_dict["sentiment"]) - return _dict[key] - - -@dataclass -class Topic(BaseResponse): - """ - Topic - """ - - topic: str = "" - confidence_score: float = 0 - - -@dataclass -class Intent(BaseResponse): - """ - Intent - """ - - intent: str = "" - confidence_score: float = 0 - - -@dataclass -class Segment(BaseResponse): - """ - Segment - """ - - text: str = "" - start_word: int = 0 - end_word: int = 0 - sentiment: Optional[Sentiment] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - sentiment_score: Optional[float] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - intents: Optional[List[Intent]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - topics: Optional[List[Topic]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "sentiment" in _dict: - _dict["sentiment"] = Sentiment.from_dict(_dict["sentiment"]) - if "intents" in _dict: - _dict["intents"] = Intent.from_dict(_dict["intents"]) - if "topics" in _dict: - _dict["topics"] = Topic.from_dict(_dict["topics"]) - return _dict[key] - - -@dataclass -class Sentiments(BaseResponse): - """ - Sentiments - """ - - average: Average - segments: List[Segment] = field(default_factory=list) - - def __getitem__(self, key): - _dict = self.to_dict() - if "segments" in _dict: - _dict["segments"] = [ - Segment.from_dict(segments) for segments in _dict["segments"] - ] - if "average" in _dict: - _dict["average"] = Average.from_dict(_dict["average"]) - return _dict[key] - - -@dataclass -class Topics(BaseResponse): - """ - Topics - """ - - segments: List[Segment] = field(default_factory=list) - - def __getitem__(self, key): - _dict = self.to_dict() - if "segments" in _dict: - _dict["segments"] = [ - Segment.from_dict(segments) for segments in _dict["segments"] - ] - return _dict[key] - - -@dataclass -class Intents(BaseResponse): - """ - Intents - """ - - segments: List[Segment] = field(default_factory=list) - - def __getitem__(self, key): - _dict = self.to_dict() - if "segments" in _dict: - _dict["segments"] = [ - Segment.from_dict(segments) for segments in _dict["segments"] - ] - return _dict[key] diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/shared_response.py b/venv/Lib/site-packages/deepgram/clients/common/v1/shared_response.py deleted file mode 100644 index 5342380e..00000000 --- a/venv/Lib/site-packages/deepgram/clients/common/v1/shared_response.py +++ /dev/null @@ -1,86 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from typing import List, Optional, Dict, Any - - -from dataclasses import dataclass, field -from dataclasses_json import config as dataclass_config, DataClassJsonMixin - - -# base class - - -@dataclass -class BaseResponse(DataClassJsonMixin): - """ - BaseResponse class used to define the common methods and properties for all response classes. - """ - - def __getitem__(self, key): - _dict = self.to_dict() - return _dict[key] - - def __setitem__(self, key, val): - self.__dict__[key] = val - - def __str__(self) -> str: - return self.to_json(indent=4) - - def eval(self, key: str) -> str: - """ - This method is used to evaluate a key in the response object using a dot notation style method. - """ - keys = key.split(".") - result: Dict[Any, Any] = self.to_dict() - for k in keys: - if isinstance(result, dict) and k in result: - result = result[k] - elif isinstance(result, list) and k.isdigit() and int(k) < len(result): - result = result[int(k)] - else: - return "" - return str(result) - - -# shared classes - - -@dataclass -class ModelInfo(BaseResponse): - """ - ModelInfo object - """ - - name: str = "" - version: str = "" - arch: str = "" - - -@dataclass -class Hit(BaseResponse): - """ - The hit information for the response. - """ - - confidence: float = 0 - start: float = 0 - end: float = 0 - snippet: Optional[str] = "" - - -@dataclass -class Search(BaseResponse): - """ - The search information for the response. - """ - - query: str = "" - hits: List[Hit] = field(default_factory=list) - - def __getitem__(self, key): - _dict = self.to_dict() - if "hits" in _dict: - _dict["hits"] = [Hit.from_dict(hits) for hits in _dict["hits"]] - return _dict[key] diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/websocket_events.py b/venv/Lib/site-packages/deepgram/clients/common/v1/websocket_events.py deleted file mode 100644 index 4ab36a16..00000000 --- a/venv/Lib/site-packages/deepgram/clients/common/v1/websocket_events.py +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from aenum import StrEnum - -# Constants mapping to events from the Deepgram API - - -class WebSocketEvents(StrEnum): - """ - Enumerates the possible events that can be received from the Deepgram API - """ - - Open: str = "Open" - Close: str = "Close" - Warning: str = "Warning" - Error: str = "Error" - Unhandled: str = "Unhandled" diff --git a/venv/Lib/site-packages/deepgram/clients/common/v1/websocket_response.py b/venv/Lib/site-packages/deepgram/clients/common/v1/websocket_response.py deleted file mode 100644 index 63d7c016..00000000 --- a/venv/Lib/site-packages/deepgram/clients/common/v1/websocket_response.py +++ /dev/null @@ -1,64 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from typing import List, Optional, Dict, Any - -from dataclasses import dataclass, field -from dataclasses_json import config as dataclass_config - -from .shared_response import BaseResponse - - -# Result Message - - -@dataclass -class OpenResponse(BaseResponse): - """ - Open Message from the Deepgram Platform - """ - - type: str = "" - - -# Close Message - - -@dataclass -class CloseResponse(BaseResponse): - """ - Close Message from the Deepgram Platform - """ - - type: str = "" - - -# Error Message - - -@dataclass -class ErrorResponse(BaseResponse): - """ - Error Message from the Deepgram Platform - """ - - description: str = "" - message: str = "" - type: str = "" - variant: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - -# Unhandled Message - - -@dataclass -class UnhandledResponse(BaseResponse): - """ - Unhandled Message from the Deepgram Platform - """ - - type: str = "" - raw: str = "" diff --git a/venv/Lib/site-packages/deepgram/clients/errors.py b/venv/Lib/site-packages/deepgram/clients/errors.py deleted file mode 100644 index 197b3c7e..00000000 --- a/venv/Lib/site-packages/deepgram/clients/errors.py +++ /dev/null @@ -1,16 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - - -class DeepgramModuleError(Exception): - """ - Base class for exceptions raised for a missing Deepgram module. - - Attributes: - message (str): The error message describing the exception. - """ - - def __init__(self, message: str): - super().__init__(message) - self.name = "DeepgramModuleError" diff --git a/venv/Lib/site-packages/deepgram/clients/listen/__init__.py b/venv/Lib/site-packages/deepgram/clients/listen/__init__.py deleted file mode 100644 index 3a3285f5..00000000 --- a/venv/Lib/site-packages/deepgram/clients/listen/__init__.py +++ /dev/null @@ -1,108 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .enums import LiveTranscriptionEvents - -# backward compat -from .client import ( - PreRecordedClient, - AsyncPreRecordedClient, - LiveClient, - AsyncLiveClient, -) - -# rest -# common -from .client import ( - UrlSource, - TextSource, - BufferSource, - StreamSource, - FileSource, -) - -## input -from .client import ( - ListenRESTOptions, - PrerecordedOptions, - PreRecordedStreamSource, - PrerecordedSource, - ListenRestSource, -) - -## output -from .client import ( - # top level - AsyncPrerecordedResponse, - PrerecordedResponse, - SyncPrerecordedResponse, - # shared - Average, - Intent, - Intents, - IntentsInfo, - Segment, - SentimentInfo, - Sentiment, - Sentiments, - SummaryInfo, - Topic, - Topics, - TopicsInfo, - # between rest and websocket - ModelInfo, - Hit, - Search, - # unique - Entity, - ListenRESTMetadata, - Paragraph, - Paragraphs, - ListenRESTResults, - Sentence, - Summaries, - SummaryV1, - SummaryV2, - Translation, - Utterance, - Warning, - ListenRESTAlternative, - ListenRESTChannel, - ListenRESTWord, -) - - -# websocket -## input -from .client import ( - ListenWebSocketOptions, - LiveOptions, -) - -## output -from .client import ( - # top level - LiveResultResponse, - ListenWSMetadataResponse, - SpeechStartedResponse, - UtteranceEndResponse, - # common websocket response - OpenResponse, - CloseResponse, - ErrorResponse, - UnhandledResponse, - # unique - ListenWSMetadata, - ListenWSWord, - ListenWSAlternative, - ListenWSChannel, -) - -# clients -from .client import ( - ListenRESTClient, - AsyncListenRESTClient, - ListenWebSocketClient, - AsyncListenWebSocketClient, -) diff --git a/venv/Lib/site-packages/deepgram/clients/listen/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/listen/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index e7adb4e6..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/listen/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/listen/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/listen/__pycache__/client.cpython-312.pyc deleted file mode 100644 index c27dff6b..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/listen/__pycache__/client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/listen/__pycache__/enums.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/listen/__pycache__/enums.cpython-312.pyc deleted file mode 100644 index 1ca1a755..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/listen/__pycache__/enums.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/listen/client.py b/venv/Lib/site-packages/deepgram/clients/listen/client.py deleted file mode 100644 index 29b61bed..00000000 --- a/venv/Lib/site-packages/deepgram/clients/listen/client.py +++ /dev/null @@ -1,180 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -# rest -from .v1 import ( - ListenRESTClient as ListenRESTClientLatest, - AsyncListenRESTClient as AsyncListenRESTClientLatest, -) -from .v1 import ( - PrerecordedOptions as PrerecordedOptionsLatest, - ListenRESTOptions as ListenRESTOptionsLatest, -) - -from .v1 import ( - UrlSource as UrlSourceLatest, - TextSource as TextSourceLatest, - BufferSource as BufferSourceLatest, - StreamSource as StreamSourceLatest, - FileSource as FileSourceLatest, - PreRecordedStreamSource as PreRecordedStreamSourceLatest, - PrerecordedSource as PrerecordedSourceLatest, - ListenRestSource as ListenRestSourceLatest, -) -from .v1 import ( - AsyncPrerecordedResponse as AsyncPrerecordedResponseLatest, - PrerecordedResponse as PrerecordedResponseLatest, - SyncPrerecordedResponse as SyncPrerecordedResponseLatest, - # shared - Average as AverageLatest, - Intent as IntentLatest, - Intents as IntentsLatest, - IntentsInfo as IntentsInfoLatest, - Segment as SegmentLatest, - SentimentInfo as SentimentInfoLatest, - Sentiment as SentimentLatest, - Sentiments as SentimentsLatest, - SummaryInfo as SummaryInfoLatest, - Topic as TopicLatest, - Topics as TopicsLatest, - TopicsInfo as TopicsInfoLatest, - # between rest and websocket - ModelInfo as ModelInfoLatest, - Hit as HitLatest, - Search as SearchLatest, - # unique - ListenRESTMetadata as ListenRESTMetadataLatest, - Entity as EntityLatest, - Paragraph as ParagraphLatest, - Paragraphs as ParagraphsLatest, - ListenRESTResults as ListenRESTResultsLatest, - Sentence as SentenceLatest, - Summaries as SummariesLatest, - SummaryV1 as SummaryV1Latest, - SummaryV2 as SummaryV2Latest, - Translation as TranslationLatest, - Utterance as UtteranceLatest, - Warning as WarningLatest, - ListenRESTAlternative as ListenRESTAlternativeLatest, - ListenRESTChannel as ListenRESTChannelLatest, - ListenRESTWord as ListenRESTWordLatest, -) - -# websocket -from .v1 import ( - ListenWebSocketClient as ListenWebSocketClientLatest, - AsyncListenWebSocketClient as AsyncListenWebSocketClientLatest, -) -from .v1 import ( - LiveOptions as LiveOptionsLatest, - ListenWebSocketOptions as ListenWebSocketOptionsLatest, -) -from .v1 import ( - OpenResponse as OpenResponseLatest, - LiveResultResponse as LiveResultResponseLatest, - ListenWSMetadataResponse as ListenWSMetadataResponseLatest, - SpeechStartedResponse as SpeechStartedResponseLatest, - UtteranceEndResponse as UtteranceEndResponseLatest, - CloseResponse as CloseResponseLatest, - ErrorResponse as ErrorResponseLatest, - UnhandledResponse as UnhandledResponseLatest, - ListenWSMetadata as ListenWSMetadataLatest, - ListenWSAlternative as ListenWSAlternativeLatest, - ListenWSChannel as ListenWSChannelLatest, - ListenWSWord as ListenWSWordLatest, -) - -# The vX/client.py points to the current supported version in the SDK. -# Older versions are supported in the SDK for backwards compatibility. - -# shared -Average = AverageLatest -Intent = IntentLatest -Intents = IntentsLatest -IntentsInfo = IntentsInfoLatest -Segment = SegmentLatest -SentimentInfo = SentimentInfoLatest -Sentiment = SentimentLatest -Sentiments = SentimentsLatest -SummaryInfo = SummaryInfoLatest -Topic = TopicLatest -Topics = TopicsLatest -TopicsInfo = TopicsInfoLatest - -# between rest and websocket -Hit = HitLatest -ModelInfo = ModelInfoLatest -Search = SearchLatest - -# websocket common -OpenResponse = OpenResponseLatest -CloseResponse = CloseResponseLatest -ErrorResponse = ErrorResponseLatest -UnhandledResponse = UnhandledResponseLatest - - -# backward compat -PreRecordedClient = ListenRESTClientLatest -AsyncPreRecordedClient = AsyncListenRESTClientLatest -LiveClient = ListenWebSocketClientLatest -AsyncLiveClient = ListenWebSocketClientLatest - -# rest -## common -UrlSource = UrlSourceLatest -TextSource = TextSourceLatest -BufferSource = BufferSourceLatest -StreamSource = StreamSourceLatest -FileSource = FileSourceLatest - -# input -ListenRESTOptions = ListenRESTOptionsLatest -PrerecordedOptions = PrerecordedOptionsLatest -PreRecordedStreamSource = PreRecordedStreamSourceLatest -PrerecordedSource = PrerecordedSourceLatest -ListenRestSource = ListenRestSourceLatest - -## output -AsyncPrerecordedResponse = AsyncPrerecordedResponseLatest -PrerecordedResponse = PrerecordedResponseLatest -SyncPrerecordedResponse = SyncPrerecordedResponseLatest -# unique -Entity = EntityLatest -ListenRESTMetadata = ListenRESTMetadataLatest -Paragraph = ParagraphLatest -Paragraphs = ParagraphsLatest -ListenRESTResults = ListenRESTResultsLatest -Sentence = SentenceLatest -Summaries = SummariesLatest -SummaryV1 = SummaryV1Latest -SummaryV2 = SummaryV2Latest -Translation = TranslationLatest -Utterance = UtteranceLatest -Warning = WarningLatest -ListenRESTAlternative = ListenRESTAlternativeLatest -ListenRESTChannel = ListenRESTChannelLatest -ListenRESTWord = ListenRESTWordLatest - -# websocket -## input -ListenWebSocketOptions = ListenWebSocketOptionsLatest -LiveOptions = LiveOptionsLatest - -## output -LiveResultResponse = LiveResultResponseLatest -ListenWSMetadataResponse = ListenWSMetadataResponseLatest -SpeechStartedResponse = SpeechStartedResponseLatest -UtteranceEndResponse = UtteranceEndResponseLatest - -## unique -ListenWSMetadata = ListenWSMetadataLatest -ListenWSAlternative = ListenWSAlternativeLatest -ListenWSChannel = ListenWSChannelLatest -ListenWSWord = ListenWSWordLatest - -# clients -ListenRESTClient = ListenRESTClientLatest -AsyncListenRESTClient = AsyncListenRESTClientLatest -ListenWebSocketClient = ListenWebSocketClientLatest -AsyncListenWebSocketClient = AsyncListenWebSocketClientLatest diff --git a/venv/Lib/site-packages/deepgram/clients/listen/enums.py b/venv/Lib/site-packages/deepgram/clients/listen/enums.py deleted file mode 100644 index 8e39ae02..00000000 --- a/venv/Lib/site-packages/deepgram/clients/listen/enums.py +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from aenum import StrEnum - -# Constants mapping to events from the Deepgram API - - -class LiveTranscriptionEvents(StrEnum): - """ - Enumerates the possible events that can be received from the Deepgram API - """ - - Open: str = "Open" - Close: str = "Close" - Transcript: str = "Results" - Metadata: str = "Metadata" - UtteranceEnd: str = "UtteranceEnd" - SpeechStarted: str = "SpeechStarted" - Finalize: str = "Finalize" - Error: str = "Error" - Unhandled: str = "Unhandled" - Warning: str = "Warning" diff --git a/venv/Lib/site-packages/deepgram/clients/listen/v1/__init__.py b/venv/Lib/site-packages/deepgram/clients/listen/v1/__init__.py deleted file mode 100644 index d1b2f3a6..00000000 --- a/venv/Lib/site-packages/deepgram/clients/listen/v1/__init__.py +++ /dev/null @@ -1,131 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -# backward compat -from .rest import ( - ListenRESTClient as PreRecordedClient, - AsyncListenRESTClient as AsyncPreRecordedClient, -) -from .websocket import ( - ListenWebSocketClient as LiveClient, - AsyncListenWebSocketClient as AsyncLiveClient, -) - -# shared -from ...common import ( - Average, - Intent, - Intents, - IntentsInfo, - Segment, - SentimentInfo, - Sentiment, - Sentiments, - SummaryInfo, - Topic, - Topics, - TopicsInfo, -) - -# between rest and websocket -from ...common import ( - ModelInfo, - Hit, - Search, -) - -# common websocket -from ...common import ( - OpenResponse, - CloseResponse, - UnhandledResponse, - ErrorResponse, -) - -# rest -from .rest import ListenRESTClient, AsyncListenRESTClient -from .rest import ListenRESTOptions, PrerecordedOptions -from .rest import ( - # common - UrlSource, - BufferSource, - StreamSource, - TextSource, - FileSource, - # unique - PreRecordedStreamSource, - PrerecordedSource, - ListenRestSource, -) -from .rest import ( - #### top level - AsyncPrerecordedResponse, - PrerecordedResponse, - SyncPrerecordedResponse, - #### shared - # Average, - # Intent, - # Intents, - # IntentsInfo, - # Segment, - # SentimentInfo, - # Sentiment, - # Sentiments, - # SummaryInfo, - # Topic, - # Topics, - # TopicsInfo, - #### between rest and websocket - # ModelInfo, - # Alternative, - # Hit, - # Search, - # Channel, - # Word, - #### unique - Entity, - Metadata as ListenRESTMetadata, - Paragraph, - Paragraphs, - Results as ListenRESTResults, - Sentence, - Summaries, - SummaryV1, - SummaryV2, - Translation, - Utterance, - Warning, - ListenRESTAlternative, - ListenRESTChannel, - ListenRESTWord, -) - -# websocket -from .websocket import ListenWebSocketClient, AsyncListenWebSocketClient -from .websocket import LiveOptions, ListenWebSocketOptions -from .websocket import ( - #### top level - LiveResultResponse, - MetadataResponse as ListenWSMetadataResponse, - SpeechStartedResponse, - UtteranceEndResponse, - #### common websocket response - # BaseResponse, - # OpenResponse, - # CloseResponse, - # ErrorResponse, - # UnhandledResponse, - #### between rest and websocket - # ModelInfo, - # Alternative, - # Hit, - # Search, - # Channel, - # Word, - #### unique - Metadata as ListenWSMetadata, - ListenWSWord, - ListenWSAlternative, - ListenWSChannel, -) diff --git a/venv/Lib/site-packages/deepgram/clients/listen/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/listen/v1/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index c55a8662..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/listen/v1/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/__init__.py b/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/__init__.py deleted file mode 100644 index 8106a2dd..00000000 --- a/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/__init__.py +++ /dev/null @@ -1,59 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .client import ListenRESTClient -from .async_client import AsyncListenRESTClient -from .options import ( - ListenRESTOptions, - PrerecordedOptions, - # common - UrlSource, - BufferSource, - StreamSource, - TextSource, - FileSource, - # unique - PreRecordedStreamSource, - PrerecordedSource, - ListenRestSource, -) -from .response import ( - # top level - AsyncPrerecordedResponse, - PrerecordedResponse, - SyncPrerecordedResponse, - # shared - Average, - Intent, - Intents, - IntentsInfo, - Segment, - SentimentInfo, - Sentiment, - Sentiments, - SummaryInfo, - Topic, - Topics, - TopicsInfo, - # between rest and websocket - ModelInfo, - Hit, - Search, - # unique - Entity, - Metadata, - Paragraph, - Paragraphs, - Results, - Sentence, - Summaries, - SummaryV1, - SummaryV2, - Translation, - Utterance, - Warning, - ListenRESTAlternative, - ListenRESTChannel, - ListenRESTWord, -) diff --git a/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index 78704582..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/__pycache__/async_client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/__pycache__/async_client.cpython-312.pyc deleted file mode 100644 index 48b20530..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/__pycache__/async_client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/__pycache__/client.cpython-312.pyc deleted file mode 100644 index 63b2780d..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/__pycache__/client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/__pycache__/helpers.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/__pycache__/helpers.cpython-312.pyc deleted file mode 100644 index 054b6367..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/__pycache__/helpers.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/__pycache__/options.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/__pycache__/options.cpython-312.pyc deleted file mode 100644 index 52170ed1..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/__pycache__/options.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/__pycache__/response.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/__pycache__/response.cpython-312.pyc deleted file mode 100644 index eece8567..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/__pycache__/response.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/async_client.py b/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/async_client.py deleted file mode 100644 index ef9360a4..00000000 --- a/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/async_client.py +++ /dev/null @@ -1,347 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -import logging -from typing import Dict, Union, Optional - -import httpx - -from .....utils import verboselogs -from .....options import DeepgramClientOptions -from ....common import AbstractAsyncRestClient -from ....common import DeepgramError, DeepgramTypeError - -from .helpers import is_buffer_source, is_readstream_source, is_url_source -from .options import ( - ListenRESTOptions, - PrerecordedOptions, - FileSource, - UrlSource, -) -from .response import AsyncPrerecordedResponse, PrerecordedResponse - - -class AsyncListenRESTClient(AbstractAsyncRestClient): - """ - A client class for handling pre-recorded audio data. - Provides methods for transcribing audio from URLs and files. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - - def __init__(self, config: DeepgramClientOptions): - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - self._config = config - super().__init__(config) - - # pylint: disable=too-many-positional-arguments - - async def transcribe_url( - self, - source: UrlSource, - options: Optional[Union[Dict, ListenRESTOptions]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/listen", - **kwargs, - ) -> Union[AsyncPrerecordedResponse, PrerecordedResponse]: - """ - Transcribes audio from a URL source. - - Args: - source (UrlSource): The URL source of the audio to transcribe. - options (ListenRESTOptions): Additional options for the transcription (default is None). - endpoint (str): The API endpoint for the transcription (default is "v1/listen"). - - Returns: - PrerecordedResponse: An object containing the transcription result. - - Raises: - DeepgramTypeError: Raised for known API errors. - """ - self._logger.debug("ListenRESTClient.transcribe_url ENTER") - - if ( - isinstance(options, dict) - and "callback" in options - and options["callback"] is not None - ) or (isinstance(options, ListenRESTOptions) and options.callback is not None): - self._logger.debug("ListenRESTClient.transcribe_url LEAVE") - return await self.transcribe_url_callback( - source, - callback=options["callback"], - options=options, - addons=addons, - headers=headers, - timeout=timeout, - endpoint=endpoint, - **kwargs, - ) - - url = f"{self._config.url}/{endpoint}" - if is_url_source(source): - body = source - else: - self._logger.error("Unknown transcription source type") - self._logger.debug("ListenRESTClient.transcribe_url LEAVE") - raise DeepgramTypeError("Unknown transcription source type") - - if isinstance(options, ListenRESTOptions) and not options.check(): - self._logger.error("options.check failed") - self._logger.debug("ListenRESTClient.transcribe_url LEAVE") - raise DeepgramError("Fatal transcription options error") - - self._logger.info("url: %s", url) - self._logger.info("source: %s", source) - if isinstance(options, ListenRESTOptions): - self._logger.info("ListenRESTOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.post( - url, - options=options, - addons=addons, - headers=headers, - json=body, - timeout=timeout, - **kwargs, - ) - self._logger.info("json: %s", result) - res = PrerecordedResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("transcribe_url succeeded") - self._logger.debug("ListenRESTClient.transcribe_url LEAVE") - return res - - async def transcribe_url_callback( - self, - source: UrlSource, - callback: str, - options: Optional[Union[Dict, ListenRESTOptions]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/listen", - **kwargs, - ) -> AsyncPrerecordedResponse: - """ - Transcribes audio from a URL source and sends the result to a callback URL. - - Args: - source (UrlSource): The URL source of the audio to transcribe. - callback (str): The callback URL where the transcription results will be sent. - options (ListenRESTOptions): Additional options for the transcription (default is None). - endpoint (str): The API endpoint for the transcription (default is "v1/listen"). - - Returns: - AsyncPrerecordedResponse: An object containing the request_id or an error message. - - Raises: - DeepgramTypeError: Raised for known API errors. - """ - self._logger.debug("ListenRESTClient.transcribe_url_callback ENTER") - - url = f"{self._config.url}/{endpoint}" - if options is None: - options = {} - if isinstance(options, ListenRESTOptions): - options.callback = callback - else: - options["callback"] = callback - if is_url_source(source): - body = source - else: - self._logger.error("Unknown transcription source type") - self._logger.debug("ListenRESTClient.transcribe_url_callback LEAVE") - raise DeepgramTypeError("Unknown transcription source type") - - if isinstance(options, ListenRESTOptions) and not options.check(): - self._logger.error("options.check failed") - self._logger.debug("ListenRESTClient.transcribe_url_callback LEAVE") - raise DeepgramError("Fatal transcription options error") - - self._logger.info("url: %s", url) - self._logger.info("source: %s", source) - if isinstance(options, ListenRESTOptions): - self._logger.info("ListenRESTOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.post( - url, - options=options, - addons=addons, - headers=headers, - json=body, - timeout=timeout, - **kwargs, - ) - self._logger.info("json: %s", result) - res = AsyncPrerecordedResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("transcribe_url_callback succeeded") - self._logger.debug("ListenRESTClient.transcribe_url_callback LEAVE") - return res - - async def transcribe_file( - self, - source: FileSource, - options: Optional[Union[Dict, ListenRESTOptions]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/listen", - **kwargs, - ) -> Union[AsyncPrerecordedResponse, PrerecordedResponse]: - """ - Transcribes audio from a local file source. - - Args: - source (FileSource): The local file source of the audio to transcribe. - options (ListenRESTOptions): Additional options for the transcription (default is None). - endpoint (str): The API endpoint for the transcription (default is "v1/listen"). - - Returns: - PrerecordedResponse: An object containing the transcription result or an error message. - - Raises: - DeepgramTypeError: Raised for known API errors. - """ - self._logger.debug("ListenRESTClient.transcribe_file ENTER") - - if ( - isinstance(options, dict) - and "callback" in options - and options["callback"] is not None - ) or (isinstance(options, ListenRESTOptions) and options.callback is not None): - self._logger.debug("ListenRESTClient.transcribe_file LEAVE") - return await self.transcribe_file_callback( - source, - callback=options["callback"], - options=options, - addons=addons, - headers=headers, - timeout=timeout, - endpoint=endpoint, - **kwargs, - ) - - url = f"{self._config.url}/{endpoint}" - if is_buffer_source(source): - body = source["buffer"] # type: ignore - elif is_readstream_source(source): - body = source["stream"] # type: ignore - else: - self._logger.error("Unknown transcription source type") - self._logger.debug("ListenRESTClient.transcribe_file LEAVE") - raise DeepgramTypeError("Unknown transcription source type") - - if isinstance(options, ListenRESTOptions) and not options.check(): - self._logger.error("options.check failed") - self._logger.debug("ListenRESTClient.transcribe_file LEAVE") - raise DeepgramError("Fatal transcription options error") - - self._logger.info("url: %s", url) - if isinstance(options, ListenRESTOptions): - self._logger.info("ListenRESTOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.post( - url, - options=options, - addons=addons, - headers=headers, - content=body, - timeout=timeout, - **kwargs, - ) - self._logger.info("json: %s", result) - res = PrerecordedResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("transcribe_file succeeded") - self._logger.debug("ListenRESTClient.transcribe_file LEAVE") - return res - - async def transcribe_file_callback( - self, - source: FileSource, - callback: str, - options: Optional[Union[Dict, ListenRESTOptions]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/listen", - **kwargs, - ) -> AsyncPrerecordedResponse: - """ - Transcribes audio from a local file source and sends the result to a callback URL. - - Args: - source (FileSource): The local file source of the audio to transcribe. - callback (str): The callback URL where the transcription results will be sent. - options (ListenRESTOptions): Additional options for the transcription (default is None). - endpoint (str): The API endpoint for the transcription (default is "v1/listen"). - - Returns: - AsyncPrerecordedResponse: An object containing the request_id or an error message. - - Raises: - DeepgramTypeError: Raised for known API errors. - """ - self._logger.debug("ListenRESTClient.transcribe_file_callback ENTER") - - url = f"{self._config.url}/{endpoint}" - if options is None: - options = {} - if isinstance(options, ListenRESTOptions): - options.callback = callback - else: - options["callback"] = callback - if is_buffer_source(source): - body = source["buffer"] # type: ignore - elif is_readstream_source(source): - body = source["stream"] # type: ignore - else: - self._logger.error("Unknown transcription source type") - self._logger.debug("ListenRESTClient.transcribe_file_callback LEAVE") - raise DeepgramTypeError("Unknown transcription source type") - - if isinstance(options, ListenRESTOptions) and not options.check(): - self._logger.error("options.check failed") - self._logger.debug("ListenRESTClient.transcribe_file_callback LEAVE") - raise DeepgramError("Fatal transcription options error") - - self._logger.info("url: %s", url) - if isinstance(options, ListenRESTOptions): - self._logger.info("ListenRESTOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.post( - url, - options=options, - addons=addons, - headers=headers, - content=body, - timeout=timeout, - **kwargs, - ) - self._logger.info("json: %s", result) - res = AsyncPrerecordedResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("transcribe_file_callback succeeded") - self._logger.debug("ListenRESTClient.transcribe_file_callback LEAVE") - return res - - # pylint: enable=too-many-positional-arguments diff --git a/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/client.py b/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/client.py deleted file mode 100644 index 3accab56..00000000 --- a/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/client.py +++ /dev/null @@ -1,348 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -import logging -from typing import Dict, Union, Optional - -import httpx - -from .....utils import verboselogs -from .....options import DeepgramClientOptions -from ....common import AbstractSyncRestClient -from ....common import DeepgramError, DeepgramTypeError - -from .helpers import is_buffer_source, is_readstream_source, is_url_source -from .options import ( - ListenRESTOptions, - PrerecordedOptions, - FileSource, - UrlSource, -) -from .response import AsyncPrerecordedResponse, PrerecordedResponse - - -class ListenRESTClient(AbstractSyncRestClient): - """ - A client class for handling pre-recorded audio data. - Provides methods for transcribing audio from URLs and files. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - - def __init__(self, config: DeepgramClientOptions): - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - self._config = config - super().__init__(config) - - # pylint: disable=too-many-positional-arguments - - def transcribe_url( - self, - source: UrlSource, - options: Optional[Union[Dict, ListenRESTOptions]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/listen", - **kwargs, - ) -> Union[AsyncPrerecordedResponse, PrerecordedResponse]: - """ - Transcribes audio from a URL source. - - Args: - source (UrlSource): The URL source of the audio to transcribe. - options (ListenRESTOptions): Additional options for the transcription (default is None). - endpoint (str): The API endpoint for the transcription (default is "v1/listen"). - - Returns: - PrerecordedResponse: An object containing the transcription result. - - Raises: - DeepgramTypeError: Raised for known API errors. - """ - self._logger.debug("ListenRESTClient.transcribe_url ENTER") - - if ( - isinstance(options, dict) - and "callback" in options - and options["callback"] is not None - ) or (isinstance(options, ListenRESTOptions) and options.callback is not None): - self._logger.debug("ListenRESTClient.transcribe_url LEAVE") - return self.transcribe_url_callback( - source, - callback=options["callback"], - options=options, - addons=addons, - headers=headers, - timeout=timeout, - endpoint=endpoint, - **kwargs, - ) - - url = f"{self._config.url}/{endpoint}" - if is_url_source(source): - body = source - else: - self._logger.error("Unknown transcription source type") - self._logger.debug("ListenRESTClient.transcribe_url LEAVE") - raise DeepgramTypeError("Unknown transcription source type") - - if isinstance(options, ListenRESTOptions) and not options.check(): - self._logger.error("options.check failed") - self._logger.debug("ListenRESTClient.transcribe_url LEAVE") - raise DeepgramError("Fatal transcription options error") - - self._logger.info("url: %s", url) - self._logger.info("source: %s", source) - if isinstance(options, ListenRESTOptions): - self._logger.info("ListenRESTOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.post( - url, - options=options, - addons=addons, - headers=headers, - json=body, - timeout=timeout, - **kwargs, - ) - self._logger.info("json: %s", result) - res = PrerecordedResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("transcribe_url succeeded") - self._logger.debug("ListenRESTClient.transcribe_url LEAVE") - return res - - def transcribe_url_callback( - self, - source: UrlSource, - callback: str, - options: Optional[Union[Dict, ListenRESTOptions]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/listen", - **kwargs, - ) -> AsyncPrerecordedResponse: - """ - Transcribes audio from a URL source and sends the result to a callback URL. - - Args: - source (UrlSource): The URL source of the audio to transcribe. - callback (str): The callback URL where the transcription results will be sent. - options (ListenRESTOptions): Additional options for the transcription (default is None). - endpoint (str): The API endpoint for the transcription (default is "v1/listen"). - - Returns: - AsyncPrerecordedResponse: An object containing the request_id or an error message. - - Raises: - DeepgramTypeError: Raised for known API errors. - """ - self._logger.debug("ListenRESTClient.transcribe_url_callback ENTER") - - url = f"{self._config.url}/{endpoint}" - if options is None: - options = {} - if isinstance(options, ListenRESTOptions): - options.callback = callback - else: - options["callback"] = callback - if is_url_source(source): - body = source - else: - self._logger.error("Unknown transcription source type") - self._logger.debug("ListenRESTClient.transcribe_url_callback LEAVE") - raise DeepgramTypeError("Unknown transcription source type") - - if isinstance(options, ListenRESTOptions) and not options.check(): - self._logger.error("options.check failed") - self._logger.debug("ListenRESTClient.transcribe_url_callback LEAVE") - raise DeepgramError("Fatal transcription options error") - - self._logger.info("url: %s", url) - self._logger.info("source: %s", source) - if isinstance(options, ListenRESTOptions): - self._logger.info("ListenRESTOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.post( - url, - options=options, - addons=addons, - headers=headers, - json=body, - timeout=timeout, - **kwargs, - ) - self._logger.info("json: %s", result) - res = AsyncPrerecordedResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("transcribe_url_callback succeeded") - self._logger.debug("ListenRESTClient.transcribe_url_callback LEAVE") - return res - - def transcribe_file( - self, - source: FileSource, - options: Optional[Union[Dict, ListenRESTOptions]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/listen", - **kwargs, - ) -> Union[AsyncPrerecordedResponse, PrerecordedResponse]: - """ - Transcribes audio from a local file source. - - Args: - source (FileSource): The local file source of the audio to transcribe. - options (ListenRESTOptions): Additional options for the transcription (default is None). - endpoint (str): The API endpoint for the transcription (default is "v1/listen"). - - Returns: - PrerecordedResponse: An object containing the transcription result or an error message. - - Raises: - DeepgramTypeError: Raised for known API errors. - """ - self._logger.debug("ListenRESTClient.transcribe_file ENTER") - - if ( - isinstance(options, dict) - and "callback" in options - and options["callback"] is not None - ) or (isinstance(options, ListenRESTOptions) and options.callback is not None): - self._logger.debug("ListenRESTClient.transcribe_file LEAVE") - return self.transcribe_file_callback( - source, - callback=options["callback"], - options=options, - addons=addons, - headers=headers, - timeout=timeout, - endpoint=endpoint, - **kwargs, - ) - - url = f"{self._config.url}/{endpoint}" - - if is_buffer_source(source): - body = source["buffer"] # type: ignore - elif is_readstream_source(source): - body = source["stream"] # type: ignore - else: - self._logger.error("Unknown transcription source type") - self._logger.debug("ListenRESTClient.transcribe_file LEAVE") - raise DeepgramTypeError("Unknown transcription source type") - - if isinstance(options, ListenRESTOptions) and not options.check(): - self._logger.error("options.check failed") - self._logger.debug("ListenRESTClient.transcribe_file LEAVE") - raise DeepgramError("Fatal transcription options error") - - self._logger.info("url: %s", url) - if isinstance(options, ListenRESTOptions): - self._logger.info("ListenRESTOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.post( - url, - options=options, - addons=addons, - headers=headers, - content=body, - timeout=timeout, - **kwargs, - ) - self._logger.info("json: %s", result) - res = PrerecordedResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("transcribe_file succeeded") - self._logger.debug("ListenRESTClient.transcribe_file LEAVE") - return res - - def transcribe_file_callback( - self, - source: FileSource, - callback: str, - options: Optional[Union[Dict, ListenRESTOptions]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/listen", - **kwargs, - ) -> AsyncPrerecordedResponse: - """ - Transcribes audio from a local file source and sends the result to a callback URL. - - Args: - source (FileSource): The local file source of the audio to transcribe. - callback (str): The callback URL where the transcription results will be sent. - options (ListenRESTOptions): Additional options for the transcription (default is None). - endpoint (str): The API endpoint for the transcription (default is "v1/listen"). - - Returns: - AsyncPrerecordedResponse: An object containing the request_id or an error message. - - Raises: - DeepgramTypeError: Raised for known API errors. - """ - self._logger.debug("ListenRESTClient.transcribe_file_callback ENTER") - - url = f"{self._config.url}/{endpoint}" - if options is None: - options = {} - if isinstance(options, ListenRESTOptions): - options.callback = callback - else: - options["callback"] = callback - if is_buffer_source(source): - body = source["buffer"] # type: ignore - elif is_readstream_source(source): - body = source["stream"] # type: ignore - else: - self._logger.error("Unknown transcription source type") - self._logger.debug("ListenRESTClient.transcribe_file_callback LEAVE") - raise DeepgramTypeError("Unknown transcription source type") - - if isinstance(options, ListenRESTOptions) and not options.check(): - self._logger.error("options.check failed") - self._logger.debug("ListenRESTClient.transcribe_file_callback LEAVE") - raise DeepgramError("Fatal transcription options error") - - self._logger.info("url: %s", url) - if isinstance(options, ListenRESTOptions): - self._logger.info("ListenRESTOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.post( - url, - options=options, - addons=addons, - headers=headers, - content=body, - timeout=timeout, - **kwargs, - ) - self._logger.info("json: %s", result) - res = AsyncPrerecordedResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("transcribe_file_callback succeeded") - self._logger.debug("ListenRESTClient.transcribe_file_callback LEAVE") - return res - - # pylint: enable=too-many-positional-arguments diff --git a/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/helpers.py b/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/helpers.py deleted file mode 100644 index 2def898f..00000000 --- a/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/helpers.py +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .options import PrerecordedSource - - -def is_buffer_source(provided_source: PrerecordedSource) -> bool: - """ - Check if the provided source is a buffer source. - """ - return "buffer" in provided_source - - -def is_readstream_source(provided_source: PrerecordedSource) -> bool: - """ - Check if the provided source is a readstream source. - """ - return "stream" in provided_source - - -def is_url_source(provided_source: PrerecordedSource) -> bool: - """ - Check if the provided source is a URL source. - """ - return "url" in provided_source diff --git a/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/options.py b/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/options.py deleted file mode 100644 index 1c44d54e..00000000 --- a/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/options.py +++ /dev/null @@ -1,181 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from typing import Union, List, Optional -import logging - -from dataclasses import dataclass, field -from dataclasses_json import config as dataclass_config - -from deepgram.utils import verboselogs -from ....common import ( - TextSource, - StreamSource, - BufferSource, - FileSource, - UrlSource, - BaseResponse, -) - - -@dataclass -class PrerecordedOptions(BaseResponse): # pylint: disable=too-many-instance-attributes - """ - Contains all the options for the PrerecordedClient. - - Reference: - https://developers.deepgram.com/reference/pre-recorded - """ - - alternatives: Optional[int] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - channels: Optional[int] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - callback: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - callback_method: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - custom_intent: Optional[Union[List[str], str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - custom_intent_mode: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - custom_topic: Optional[Union[List[str], str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - custom_topic_mode: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - detect_entities: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - detect_language: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - detect_topics: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - diarize: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - diarize_version: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - dictation: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - encoding: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - extra: Optional[Union[List[str], str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - filler_words: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - intents: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - keyterm: Optional[List[str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - keywords: Optional[Union[List[str], str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - language: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - measurements: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - model: Optional[str] = field( - default="None", metadata=dataclass_config(exclude=lambda f: f is None) - ) - multichannel: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - numerals: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - paragraphs: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - profanity_filter: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - punctuate: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - redact: Optional[Union[List[str], bool, str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - replace: Optional[Union[List[str], str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - sample_rate: Optional[int] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - search: Optional[Union[List[str], str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - sentiment: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - smart_format: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - summarize: Optional[Union[bool, str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - tag: Optional[List[str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - tier: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - topics: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - utt_split: Optional[float] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - utterances: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - version: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def check(self): - """ - Check the options for any deprecated fields or values. - """ - logger = verboselogs.VerboseLogger(__name__) - logger.addHandler(logging.StreamHandler()) - prev = logger.level - logger.setLevel(verboselogs.ERROR) - - if self.tier: - logger.error( - "WARNING: Tier is deprecated. Will be removed in a future version." - ) - - logger.setLevel(prev) - - return True - - -ListenRESTOptions = PrerecordedOptions - -# unique -PrerecordedSource = Union[UrlSource, FileSource] -ListenRestSource = PrerecordedSource - -# PrerecordedSource for backwards compatibility -PreRecordedStreamSource = StreamSource diff --git a/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/response.py b/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/response.py deleted file mode 100644 index e24e9c2f..00000000 --- a/venv/Lib/site-packages/deepgram/clients/listen/v1/rest/response.py +++ /dev/null @@ -1,470 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from typing import List, Optional, Dict, Any - -from dataclasses import dataclass, field -from dataclasses_json import config as dataclass_config - -# between analyze and listen -from ....common import ( - BaseResponse, - Average, - Intent, - Intents, - IntentsInfo, - Segment, - SentimentInfo, - Sentiment, - Sentiments, - SummaryInfo, - Topic, - Topics, - TopicsInfo, -) - -# between rest and websocket -from ....common import ( - ModelInfo, - Hit, - Search, -) - -# Async Prerecorded Response Types: - - -@dataclass -class AsyncPrerecordedResponse(BaseResponse): - """ - The response object for the async prerecorded API. - """ - - request_id: str = "" - - -# Prerecorded Response Types: - - -@dataclass -class Metadata(BaseResponse): # pylint: disable=too-many-instance-attributes - """ - The metadata for the response. - """ - - transaction_key: str = "" - request_id: str = "" - sha256: str = "" - created: str = "" - duration: float = 0 - channels: int = 0 - models: Optional[List[str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - # pylint: disable=used-before-assignment - warnings: Optional[List[Warning]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - # pylint: enable=used-before-assignment - model_info: Optional[Dict[str, ModelInfo]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - summary_info: Optional[SummaryInfo] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - intents_info: Optional[IntentsInfo] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - sentiment_info: Optional[SentimentInfo] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - topics_info: Optional[TopicsInfo] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - extra: Optional[Dict] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "models" in _dict: - _dict["models"] = [str(models) for models in _dict["models"]] - if "warnings" in _dict: - _dict["warnings"] = [ - Warning.from_dict(warnings) for warnings in _dict["warnings"] - ] - if "model_info" in _dict: - _dict["model_info"] = [ - ModelInfo.from_dict(model_info) - for _, model_info in _dict["model_info"].items() - ] - if "summary_info" in _dict: - _dict["summary_info"] = SummaryInfo.from_dict(_dict["summary_info"]) - if "intents_info" in _dict: - _dict["intents_info"] = IntentsInfo.from_dict(_dict["intents_info"]) - if "sentiment_info" in _dict: - _dict["sentiment_info"] = SentimentInfo.from_dict(_dict["sentiment_info"]) - if "topics_info" in _dict: - _dict["topics_info"] = TopicsInfo.from_dict(_dict["topics_info"]) - if "extra" in _dict: - _dict["extra"] = [str(extra) for _, extra in _dict["extra"].items()] - return _dict[key] - - -@dataclass -class SummaryV1(BaseResponse): - """ - The summary information for the response. - """ - - summary: str = "" - start_word: float = 0 - end_word: float = 0 - - -Summaries = SummaryV1 - - -@dataclass -class SummaryV2(BaseResponse): - """ - The summary information for the response. - """ - - result: str = "" - short: str = "" - - -Summary = SummaryV2 - - -@dataclass -class ListenRESTWord(BaseResponse): # pylint: disable=too-many-instance-attributes - """ - The word information for the response. - """ - - word: str = "" - start: float = 0 - end: float = 0 - confidence: float = 0 - punctuated_word: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - speaker: Optional[int] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - language: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - speaker_confidence: Optional[float] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - sentiment: Optional[Sentiment] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - sentiment_score: Optional[float] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "sentiment" in _dict: - _dict["sentiment"] = Sentiment.from_dict(_dict["sentiment"]) - return _dict[key] - - -@dataclass -class Sentence(BaseResponse): - """ - The sentence information for the response. - """ - - text: str = "" - start: float = 0 - end: float = 0 - sentiment: Optional[Sentiment] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - sentiment_score: Optional[float] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "sentiment" in _dict: - _dict["sentiment"] = Sentiment.from_dict(_dict["sentiment"]) - return _dict[key] - - -@dataclass -class Paragraph(BaseResponse): - """ - The paragraph information for the response. - """ - - sentences: List[Sentence] = field(default_factory=list) - start: float = 0 - end: float = 0 - num_words: int = 0 - speaker: Optional[int] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - sentiment: Optional[Sentiment] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - sentiment_score: Optional[float] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "sentences" in _dict: - _dict["sentences"] = [ - Sentence.from_dict(sentences) for sentences in _dict["sentences"] - ] - if "sentiment" in _dict: - _dict["sentiment"] = Sentiment.from_dict(_dict["sentiment"]) - return _dict[key] - - -@dataclass -class Paragraphs(BaseResponse): - """ - The paragraphs information for the response. - """ - - transcript: Optional[str] = "" - paragraphs: Optional[List[Paragraph]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "paragraphs" in _dict: - _dict["paragraphs"] = [ - Paragraph.from_dict(paragraphs) for paragraphs in _dict["paragraphs"] - ] - return _dict[key] - - -@dataclass -class Translation(BaseResponse): - """ - The translation information for the response. - """ - - language: Optional[str] = "" - translation: Optional[str] = "" - - -@dataclass -class Warning(BaseResponse): # pylint: disable=used-before-assignment,redefined-builtin - """ - The warning information for the response. - """ - - parameter: str = "" - type: str = "" - message: str = "" - - -@dataclass -class Utterance(BaseResponse): # pylint: disable=too-many-instance-attributes - """ - The utterance information for the response. - """ - - start: float = 0 - end: float = 0 - confidence: float = 0 - channel: int = 0 - transcript: str = "" - words: List[ListenRESTWord] = field(default_factory=list) - speaker: Optional[int] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - sentiment: Optional[Sentiment] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - sentiment_score: Optional[float] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - id: str = "" - - def __getitem__(self, key): - _dict = self.to_dict() - if "words" in _dict: - _dict["words"] = [ - ListenRESTWord.from_dict(words) for words in _dict["words"] - ] - if "sentiment" in _dict: - _dict["sentiment"] = Sentiment.from_dict(_dict["sentiment"]) - return _dict[key] - - -@dataclass -class Entity(BaseResponse): - """ - The entity information for the response. - """ - - label: str = "" - value: str = "" - confidence: float = 0 - start_word: float = 0 - end_word: float = 0 - - -@dataclass -class ListenRESTAlternative( - BaseResponse -): # pylint: disable=too-many-instance-attributes - """ - The alternative information for the response. - """ - - transcript: str = "" - confidence: float = 0 - words: List[ListenRESTWord] = field(default_factory=list) - summaries: Optional[List[SummaryV1]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - paragraphs: Optional[Paragraphs] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - entities: Optional[List[Entity]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - translations: Optional[List[Translation]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - languages: Optional[List[str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "words" in _dict: - _dict["words"] = [ - ListenRESTWord.from_dict(words) for words in _dict["words"] - ] - if "summaries" in _dict: - _dict["summaries"] = [ - SummaryV1.from_dict(summaries) for summaries in _dict["summaries"] - ] - if "paragraphs" in _dict: - _dict["paragraphs"] = Paragraphs.from_dict(_dict["paragraphs"]) - if "entities" in _dict: - _dict["entities"] = [ - Entity.from_dict(entities) for entities in _dict["entities"] - ] - if "translations" in _dict: - _dict["translations"] = [ - Translation.from_dict(translations) - for translations in _dict["translations"] - ] - return _dict[key] - - -@dataclass -class ListenRESTChannel(BaseResponse): - """ - The channel information for the response. - """ - - search: Optional[List[Search]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - alternatives: List[ListenRESTAlternative] = field(default_factory=list) - detected_language: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - language_confidence: Optional[float] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "search" in _dict: - _dict["search"] = [Search.from_dict(search) for search in _dict["search"]] - if "alternatives" in _dict: - _dict["alternatives"] = [ - ListenRESTAlternative.from_dict(alternatives) - for alternatives in _dict["alternatives"] - ] - return _dict[key] - - -@dataclass -class Results(BaseResponse): - """ - The results information for the response. - """ - - channels: Optional[List[ListenRESTChannel]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - utterances: Optional[List[Utterance]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - summary: Optional[SummaryV2] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - sentiments: Optional[Sentiments] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - topics: Optional[Topics] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - intents: Optional[Intents] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "channels" in _dict: - _dict["channels"] = [ - ListenRESTChannel.from_dict(channels) for channels in _dict["channels"] - ] - if "utterances" in _dict: - _dict["utterances"] = [ - Utterance.from_dict(utterances) for utterances in _dict["utterances"] - ] - if "summary" in _dict: - _dict["summary"] = SummaryV2.from_dict(_dict["summary"]) - if "sentiments" in _dict: - _dict["sentiments"] = Sentiments.from_dict(_dict["sentiments"]) - if "topics" in _dict: - _dict["topics"] = Topics.from_dict(_dict["topics"]) - if "intents" in _dict: - _dict["intents"] = Intents.from_dict(_dict["intents"]) - return _dict[key] - - -# Prerecorded Response Result: - - -@dataclass -class PrerecordedResponse(BaseResponse): - """ - The response object for the prerecorded API. - """ - - metadata: Optional[Metadata] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - results: Optional[Results] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "metadata" in _dict: - _dict["metadata"] = Metadata.from_dict(_dict["metadata"]) - if "results" in _dict: - _dict["results"] = Results.from_dict(_dict["results"]) - return _dict[key] - - -SyncPrerecordedResponse = PrerecordedResponse diff --git a/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/__init__.py b/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/__init__.py deleted file mode 100644 index 9f6891d8..00000000 --- a/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/__init__.py +++ /dev/null @@ -1,31 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .client import ListenWebSocketClient -from .async_client import AsyncListenWebSocketClient -from .options import LiveOptions, ListenWebSocketOptions - -# unique websocket response -from .response import ( - #### top level - LiveResultResponse, - MetadataResponse, - SpeechStartedResponse, - UtteranceEndResponse, - #### common websocket response - BaseResponse, - OpenResponse, - CloseResponse, - ErrorResponse, - UnhandledResponse, - #### between rest and websocket - ModelInfo, - Hit, - Search, - #### unique - Metadata, - ListenWSWord, - ListenWSAlternative, - ListenWSChannel, -) diff --git a/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index 11c364e0..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/__pycache__/async_client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/__pycache__/async_client.cpython-312.pyc deleted file mode 100644 index b112e190..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/__pycache__/async_client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/__pycache__/client.cpython-312.pyc deleted file mode 100644 index 77674929..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/__pycache__/client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/__pycache__/options.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/__pycache__/options.cpython-312.pyc deleted file mode 100644 index 5765297e..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/__pycache__/options.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/__pycache__/response.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/__pycache__/response.cpython-312.pyc deleted file mode 100644 index 5850286e..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/__pycache__/response.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/async_client.py b/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/async_client.py deleted file mode 100644 index 0ed81c0c..00000000 --- a/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/async_client.py +++ /dev/null @@ -1,587 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT -import asyncio -import json -import logging -from typing import Dict, Union, Optional, cast, Any, Callable -from datetime import datetime -import threading - -from .....utils import verboselogs -from .....options import DeepgramClientOptions -from ...enums import LiveTranscriptionEvents -from ....common import AbstractAsyncWebSocketClient -from ....common import DeepgramError - -from .response import ( - OpenResponse, - LiveResultResponse, - MetadataResponse, - SpeechStartedResponse, - UtteranceEndResponse, - CloseResponse, - ErrorResponse, - UnhandledResponse, -) -from .options import ListenWebSocketOptions - -ONE_SECOND = 1 -HALF_SECOND = 0.5 -DEEPGRAM_INTERVAL = 5 -PING_INTERVAL = 20 - - -class AsyncListenWebSocketClient( - AbstractAsyncWebSocketClient -): # pylint: disable=too-many-instance-attributes - """ - Client for interacting with Deepgram's live transcription services over WebSockets. - - This class provides methods to establish a WebSocket connection for live transcription and handle real-time transcription events. - - Args: - config (DeepgramClientOptions): all the options for the client. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - _endpoint: str - - _event_handlers: Dict[LiveTranscriptionEvents, list] - - _keep_alive_thread: Union[asyncio.Task, None] - _flush_thread: Union[asyncio.Task, None] - _last_datagram: Optional[datetime] = None - - _kwargs: Optional[Dict] = None - _addons: Optional[Dict] = None - _options: Optional[Dict] = None - _headers: Optional[Dict] = None - - def __init__(self, config: DeepgramClientOptions): - if config is None: - raise DeepgramError("Config is required") - - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - - self._config = config - self._endpoint = "v1/listen" - - self._flush_thread = None - self._keep_alive_thread = None - - # auto flush - self._last_datagram = None - self._lock_flush = threading.Lock() - - # init handlers - self._event_handlers = { - event: [] for event in LiveTranscriptionEvents.__members__.values() - } - - # call the parent constructor - super().__init__(self._config, self._endpoint) - - # pylint: disable=too-many-branches,too-many-statements - async def start( - self, - options: Optional[Union[ListenWebSocketOptions, Dict]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - members: Optional[Dict] = None, - **kwargs, - ) -> bool: - """ - Starts the WebSocket connection for live transcription. - """ - self._logger.debug("AsyncListenWebSocketClient.start ENTER") - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - self._logger.info("members: %s", members) - self._logger.info("kwargs: %s", kwargs) - - if isinstance(options, ListenWebSocketOptions) and not options.check(): - self._logger.error("options.check failed") - self._logger.debug("AsyncListenWebSocketClient.start LEAVE") - raise DeepgramError("Fatal transcription options error") - - self._addons = addons - self._headers = headers - - # add "members" as members of the class - if members is not None: - self.__dict__.update(members) - - # set kwargs as members of the class - if kwargs is not None: - self._kwargs = kwargs - else: - self._kwargs = {} - - if isinstance(options, ListenWebSocketOptions): - self._logger.info("ListenWebSocketOptions switching class -> dict") - self._options = options.to_dict() - elif options is not None: - self._options = options - else: - self._options = {} - - try: - # call parent start - if ( - await super().start( - self._options, - self._addons, - self._headers, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - is False - ): - self._logger.error("AsyncListenWebSocketClient.start failed") - self._logger.debug("AsyncListenWebSocketClient.start LEAVE") - return False - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - # keepalive thread - if self._config.is_keep_alive_enabled(): - self._logger.notice("keepalive is enabled") - self._keep_alive_thread = asyncio.create_task(self._keep_alive()) - else: - self._logger.notice("keepalive is disabled") - - # flush thread - if self._config.is_auto_flush_reply_enabled(): - self._logger.notice("autoflush is enabled") - self._flush_thread = asyncio.create_task(self._flush()) - else: - self._logger.notice("autoflush is disabled") - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - self._logger.notice("start succeeded") - self._logger.debug("AsyncListenWebSocketClient.start LEAVE") - return True - - except Exception as e: # pylint: disable=broad-except - self._logger.error( - "WebSocketException in AsyncListenWebSocketClient.start: %s", e - ) - self._logger.debug("AsyncListenWebSocketClient.start LEAVE") - if self._config.options.get("termination_exception_connect") is True: - raise - return False - - # pylint: enable=too-many-branches,too-many-statements - - def on(self, event: LiveTranscriptionEvents, handler: Callable) -> None: - """ - Registers event handlers for specific events. - """ - self._logger.info("event subscribed: %s", event) - if event in LiveTranscriptionEvents.__members__.values() and callable(handler): - self._event_handlers[event].append(handler) - - # triggers the registered event handlers for a specific event - async def _emit(self, event: LiveTranscriptionEvents, *args, **kwargs) -> None: - """ - Emits events to the registered event handlers. - """ - self._logger.debug("AsyncListenWebSocketClient._emit ENTER") - self._logger.debug("callback handlers for: %s", event) - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - tasks = [] - for handler in self._event_handlers[event]: - task = asyncio.create_task(handler(self, *args, **kwargs)) - tasks.append(task) - - if tasks: - self._logger.debug("waiting for tasks to finish...") - await asyncio.gather(*tasks, return_exceptions=True) - tasks.clear() - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - self._logger.debug("AsyncListenWebSocketClient._emit LEAVE") - - async def _process_text(self, message: str) -> None: - """ - Processes messages received over the WebSocket connection. - """ - self._logger.debug("AsyncListenWebSocketClient._process_text ENTER") - - try: - self._logger.debug("Text data received") - if len(message) == 0: - self._logger.debug("message is empty") - self._logger.debug("AsyncListenWebSocketClient._process_text LEAVE") - return - - data = json.loads(message) - response_type = data.get("type") - self._logger.debug("response_type: %s, data: %s", response_type, data) - - match response_type: - case LiveTranscriptionEvents.Open: - open_result: OpenResponse = OpenResponse.from_json(message) - self._logger.verbose("OpenResponse: %s", open_result) - await self._emit( - LiveTranscriptionEvents(LiveTranscriptionEvents.Open), - open=open_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case LiveTranscriptionEvents.Transcript: - msg_result: LiveResultResponse = LiveResultResponse.from_json( - message - ) - self._logger.verbose("LiveResultResponse: %s", msg_result) - - # auto flush - if self._config.is_inspecting_listen(): - inspect_res = await self._inspect(msg_result) - if not inspect_res: - self._logger.error("inspect_res failed") - - await self._emit( - LiveTranscriptionEvents(LiveTranscriptionEvents.Transcript), - result=msg_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case LiveTranscriptionEvents.Metadata: - meta_result: MetadataResponse = MetadataResponse.from_json(message) - self._logger.verbose("MetadataResponse: %s", meta_result) - await self._emit( - LiveTranscriptionEvents(LiveTranscriptionEvents.Metadata), - metadata=meta_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case LiveTranscriptionEvents.SpeechStarted: - ss_result: SpeechStartedResponse = SpeechStartedResponse.from_json( - message - ) - self._logger.verbose("SpeechStartedResponse: %s", ss_result) - await self._emit( - LiveTranscriptionEvents(LiveTranscriptionEvents.SpeechStarted), - speech_started=ss_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case LiveTranscriptionEvents.UtteranceEnd: - ue_result: UtteranceEndResponse = UtteranceEndResponse.from_json( - message - ) - self._logger.verbose("UtteranceEndResponse: %s", ue_result) - await self._emit( - LiveTranscriptionEvents(LiveTranscriptionEvents.UtteranceEnd), - utterance_end=ue_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case LiveTranscriptionEvents.Close: - close_result: CloseResponse = CloseResponse.from_json(message) - self._logger.verbose("CloseResponse: %s", close_result) - await self._emit( - LiveTranscriptionEvents(LiveTranscriptionEvents.Close), - close=close_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case LiveTranscriptionEvents.Error: - err_error: ErrorResponse = ErrorResponse.from_json(message) - self._logger.verbose("ErrorResponse: %s", err_error) - await self._emit( - LiveTranscriptionEvents(LiveTranscriptionEvents.Error), - error=err_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case _: - self._logger.warning( - "Unknown Message: response_type: %s, data: %s", - response_type, - data, - ) - unhandled_error: UnhandledResponse = UnhandledResponse( - type=LiveTranscriptionEvents(LiveTranscriptionEvents.Unhandled), - raw=message, - ) - await self._emit( - LiveTranscriptionEvents(LiveTranscriptionEvents.Unhandled), - unhandled=unhandled_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - self._logger.notice("_process_text Succeeded") - self._logger.debug("AsyncListenWebSocketClient._process_text LEAVE") - - except Exception as e: # pylint: disable=broad-except - self._logger.error( - "Exception in AsyncListenWebSocketClient._process_text: %s", e - ) - e_error: ErrorResponse = ErrorResponse( - "Exception in AsyncListenWebSocketClient._process_text", - f"{e}", - "Exception", - ) - await self._emit( - LiveTranscriptionEvents(LiveTranscriptionEvents.Error), - error=e_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - # signal exit and close - await super()._signal_exit() - - self._logger.debug("AsyncListenWebSocketClient._process_text LEAVE") - - if self._config.options.get("termination_exception") is True: - raise - return - - # pylint: enable=too-many-return-statements,too-many-statements - - async def _process_binary(self, message: bytes) -> None: - raise NotImplementedError("no _process_binary method should be called") - - # pylint: disable=too-many-return-statements - async def _keep_alive(self) -> None: - """ - Sends keepalive messages to the WebSocket connection. - """ - self._logger.debug("AsyncListenWebSocketClient._keep_alive ENTER") - - counter = 0 - while True: - try: - counter += 1 - await asyncio.sleep(ONE_SECOND) - - if self._exit_event.is_set(): - self._logger.notice("_keep_alive exiting gracefully") - self._logger.debug("AsyncListenWebSocketClient._keep_alive LEAVE") - return - - # deepgram keepalive - if counter % DEEPGRAM_INTERVAL == 0: - await self.keep_alive() - - except Exception as e: # pylint: disable=broad-except - self._logger.error( - "Exception in AsyncListenWebSocketClient._keep_alive: %s", e - ) - e_error: ErrorResponse = ErrorResponse( - "Exception in AsyncListenWebSocketClient._keep_alive", - f"{e}", - "Exception", - ) - self._logger.error( - "Exception in AsyncListenWebSocketClient._keep_alive: %s", str(e) - ) - await self._emit( - LiveTranscriptionEvents(LiveTranscriptionEvents.Error), - error=e_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - # signal exit and close - await super()._signal_exit() - - self._logger.debug("AsyncListenWebSocketClient._keep_alive LEAVE") - - if self._config.options.get("termination_exception") is True: - raise - return - - ## pylint: disable=too-many-return-statements,too-many-statements - async def _flush(self) -> None: - self._logger.debug("AsyncListenWebSocketClient._flush ENTER") - - delta_in_ms_str = self._config.options.get("auto_flush_reply_delta") - if delta_in_ms_str is None: - self._logger.error("auto_flush_reply_delta is None") - self._logger.debug("AsyncListenWebSocketClient._flush LEAVE") - return - delta_in_ms = float(delta_in_ms_str) - - while True: - try: - await asyncio.sleep(HALF_SECOND) - - if self._exit_event.is_set(): - self._logger.notice("_flush exiting gracefully") - self._logger.debug("AsyncListenWebSocketClient._flush LEAVE") - return - - if self._last_datagram is None: - self._logger.debug("AutoFlush last_datagram is None") - continue - - delta = datetime.now() - self._last_datagram - diff_in_ms = delta.total_seconds() * 1000 - self._logger.debug("AutoFlush delta: %f", diff_in_ms) - if diff_in_ms < delta_in_ms: - self._logger.debug("AutoFlush delta is less than threshold") - continue - - self._last_datagram = None - await self.finalize() - - except Exception as e: # pylint: disable=broad-except - self._logger.error( - "Exception in AsyncListenWebSocketClient._flush: %s", e - ) - e_error: ErrorResponse = ErrorResponse( - "Exception in AsyncListenWebSocketClient._flush", - f"{e}", - "Exception", - ) - self._logger.error( - "Exception in AsyncListenWebSocketClient._flush: %s", str(e) - ) - await self._emit( - LiveTranscriptionEvents(LiveTranscriptionEvents.Error), - error=e_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - # signal exit and close - await super()._signal_exit() - - self._logger.debug("AsyncListenWebSocketClient._flush LEAVE") - - if self._config.options.get("termination_exception") is True: - raise - return - - # pylint: enable=too-many-return-statements - - async def keep_alive(self) -> bool: - """ - Sends a KeepAlive message - """ - self._logger.spam("AsyncListenWebSocketClient.keep_alive ENTER") - - self._logger.notice("Sending KeepAlive...") - ret = await self.send(json.dumps({"type": "KeepAlive"})) - - if not ret: - self._logger.error("keep_alive failed") - self._logger.spam("AsyncListenWebSocketClient.keep_alive LEAVE") - return False - - self._logger.notice("keep_alive succeeded") - self._logger.spam("AsyncListenWebSocketClient.keep_alive LEAVE") - - return True - - async def finalize(self) -> bool: - """ - Finalizes the Transcript connection by flushing it - """ - self._logger.spam("AsyncListenWebSocketClient.finalize ENTER") - - self._logger.notice("Sending Finalize...") - ret = await self.send(json.dumps({"type": "Finalize"})) - - if not ret: - self._logger.error("finalize failed") - self._logger.spam("AsyncListenWebSocketClient.finalize LEAVE") - return False - - self._logger.notice("finalize succeeded") - self._logger.spam("AsyncListenWebSocketClient.finalize LEAVE") - - return True - - async def _close_message(self) -> bool: - return await self.send(json.dumps({"type": "CloseStream"})) - - async def finish(self) -> bool: - """ - Closes the WebSocket connection gracefully. - """ - self._logger.debug("AsyncListenWebSocketClient.finish ENTER") - - # stop the threads - self._logger.verbose("cancelling tasks...") - try: - # call parent finish - if await super().finish() is False: - self._logger.error("AsyncListenWebSocketClient.finish failed") - - # Before cancelling, check if the tasks were created - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("before running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - tasks = [] - if self._keep_alive_thread is not None: - self._keep_alive_thread.cancel() - tasks.append(self._keep_alive_thread) - self._logger.notice("processing _keep_alive_thread cancel...") - - if self._flush_thread is not None: - self._flush_thread.cancel() - tasks.append(self._flush_thread) - self._logger.notice("processing _flush_thread cancel...") - - # Use asyncio.gather to wait for tasks to be cancelled - # Prevent indefinite waiting by setting a timeout - await asyncio.wait_for(asyncio.gather(*tasks), timeout=10) - self._logger.notice("threads joined") - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - self._logger.notice("finish succeeded") - self._logger.spam("AsyncListenWebSocketClient.finish LEAVE") - return True - - except asyncio.CancelledError as e: - self._logger.error("tasks cancelled error: %s", e) - self._logger.debug("AsyncListenWebSocketClient.finish LEAVE") - return False - - except asyncio.TimeoutError as e: - self._logger.error("tasks cancellation timed out: %s", e) - self._logger.debug("AsyncListenWebSocketClient.finish LEAVE") - return False - - async def _inspect(self, msg_result: LiveResultResponse) -> bool: - # auto flush_inspect is generically used to track any messages you might want to snoop on - # place additional logic here to inspect messages of interest - - # for auto flush functionality - # set the last datagram - sentence = msg_result.channel.alternatives[0].transcript - if len(sentence) == 0: - return True - - if msg_result.is_final: - self._logger.debug("AutoFlush is_final received") - self._last_datagram = None - else: - self._last_datagram = datetime.now() - self._logger.debug( - "AutoFlush interim received: %s", - str(self._last_datagram), - ) - - return True diff --git a/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/client.py b/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/client.py deleted file mode 100644 index e6633689..00000000 --- a/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/client.py +++ /dev/null @@ -1,590 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT -import json -import time -import logging -from typing import Dict, Union, Optional, cast, Any, Callable, Type -from datetime import datetime -import threading - -from .....utils import verboselogs -from .....options import DeepgramClientOptions -from ...enums import LiveTranscriptionEvents -from ....common import AbstractSyncWebSocketClient -from ....common import DeepgramError - -from .response import ( - OpenResponse, - LiveResultResponse, - MetadataResponse, - SpeechStartedResponse, - UtteranceEndResponse, - CloseResponse, - ErrorResponse, - UnhandledResponse, -) -from .options import ListenWebSocketOptions - -ONE_SECOND = 1 -HALF_SECOND = 0.5 -DEEPGRAM_INTERVAL = 5 -PING_INTERVAL = 20 - - -class ListenWebSocketClient( - AbstractSyncWebSocketClient -): # pylint: disable=too-many-instance-attributes - """ - Client for interacting with Deepgram's live transcription services over WebSockets. - - This class provides methods to establish a WebSocket connection for live transcription and handle real-time transcription events. - - Args: - config (DeepgramClientOptions): all the options for the client. - thread_cls (Type[threading.Thread]): optional thread class to use for creating threads, - defaults to threading.Thread. Useful for custom thread management like ContextVar support. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - _endpoint: str - - _lock_flush: threading.Lock - _event_handlers: Dict[LiveTranscriptionEvents, list] - - _keep_alive_thread: Union[threading.Thread, None] - _flush_thread: Union[threading.Thread, None] - _last_datagram: Optional[datetime] = None - - _thread_cls: Type[threading.Thread] - - _kwargs: Optional[Dict] = None - _addons: Optional[Dict] = None - _options: Optional[Dict] = None - _headers: Optional[Dict] = None - - def __init__( - self, - config: DeepgramClientOptions, - thread_cls: Type[threading.Thread] = threading.Thread, - ): - if config is None: - raise DeepgramError("Config is required") - - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - - self._config = config - self._endpoint = "v1/listen" - - self._flush_thread = None - self._keep_alive_thread = None - - # auto flush - self._last_datagram = None - self._lock_flush = threading.Lock() - - self._thread_cls = thread_cls - - # init handlers - self._event_handlers = { - event: [] for event in LiveTranscriptionEvents.__members__.values() - } - - # call the parent constructor - super().__init__( - config=self._config, - endpoint=self._endpoint, - thread_cls=self._thread_cls, - ) - - # pylint: disable=too-many-statements,too-many-branches - def start( - self, - options: Optional[Union[ListenWebSocketOptions, Dict]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - members: Optional[Dict] = None, - **kwargs, - ) -> bool: - """ - Starts the WebSocket connection for live transcription. - """ - self._logger.debug("ListenWebSocketClient.start ENTER") - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - self._logger.info("members: %s", members) - self._logger.info("kwargs: %s", kwargs) - - if isinstance(options, ListenWebSocketOptions) and not options.check(): - self._logger.error("options.check failed") - self._logger.debug("ListenWebSocketClient.start LEAVE") - raise DeepgramError("Fatal transcription options error") - - self._addons = addons - self._headers = headers - - # add "members" as members of the class - if members is not None: - self.__dict__.update(members) - - # set kwargs as members of the class - if kwargs is not None: - self._kwargs = kwargs - else: - self._kwargs = {} - - if isinstance(options, ListenWebSocketOptions): - self._logger.info("ListenWebSocketOptions switching class -> dict") - self._options = options.to_dict() - elif options is not None: - self._options = options - else: - self._options = {} - - try: - # call parent start - if ( - super().start( - self._options, - self._addons, - self._headers, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - is False - ): - self._logger.error("ListenWebSocketClient.start failed") - self._logger.debug("ListenWebSocketClient.start LEAVE") - return False - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - # keepalive thread - if self._config.is_keep_alive_enabled(): - self._logger.notice("keepalive is enabled") - self._keep_alive_thread = self._thread_cls(target=self._keep_alive) - self._keep_alive_thread.start() - else: - self._logger.notice("keepalive is disabled") - - # flush thread - if self._config.is_auto_flush_reply_enabled(): - self._logger.notice("autoflush is enabled") - self._flush_thread = self._thread_cls(target=self._flush) - self._flush_thread.start() - else: - self._logger.notice("autoflush is disabled") - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - self._logger.notice("start succeeded") - self._logger.debug("ListenWebSocketClient.start LEAVE") - return True - - except Exception as e: # pylint: disable=broad-except - self._logger.error( - "WebSocketException in ListenWebSocketClient.start: %s", e - ) - self._logger.debug("ListenWebSocketClient.start LEAVE") - if self._config.options.get("termination_exception_connect") is True: - raise e - return False - - # pylint: enable=too-many-statements,too-many-branches - - def on( - self, event: LiveTranscriptionEvents, handler: Callable - ) -> None: # registers event handlers for specific events - """ - Registers event handlers for specific events. - """ - self._logger.info("event subscribed: %s", event) - if event in LiveTranscriptionEvents.__members__.values() and callable(handler): - self._event_handlers[event].append(handler) - - def _emit(self, event: LiveTranscriptionEvents, *args, **kwargs) -> None: - """ - Emits events to the registered event handlers. - """ - self._logger.debug("ListenWebSocketClient._emit ENTER") - self._logger.debug("callback handlers for: %s", event) - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - self._logger.debug("callback handlers for: %s", event) - for handler in self._event_handlers[event]: - handler(self, *args, **kwargs) - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - self._logger.debug("ListenWebSocketClient._emit LEAVE") - - # pylint: disable=too-many-return-statements,too-many-statements,too-many-locals,too-many-branches - def _process_text(self, message: str) -> None: - """ - Processes messages received over the WebSocket connection. - """ - self._logger.debug("ListenWebSocketClient._process_text ENTER") - - try: - if len(message) == 0: - self._logger.debug("message is empty") - self._logger.debug("ListenWebSocketClient._process_text LEAVE") - return - - data = json.loads(message) - response_type = data.get("type") - self._logger.debug("response_type: %s, data: %s", response_type, data) - - match response_type: - case LiveTranscriptionEvents.Open: - open_result: OpenResponse = OpenResponse.from_json(message) - self._logger.verbose("OpenResponse: %s", open_result) - self._emit( - LiveTranscriptionEvents(LiveTranscriptionEvents.Open), - open=open_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case LiveTranscriptionEvents.Transcript: - msg_result: LiveResultResponse = LiveResultResponse.from_json( - message - ) - self._logger.verbose("LiveResultResponse: %s", msg_result) - - # auto flush - if self._config.is_inspecting_listen(): - inspect_res = self._inspect(msg_result) - if not inspect_res: - self._logger.error("inspect_res failed") - - self._emit( - LiveTranscriptionEvents(LiveTranscriptionEvents.Transcript), - result=msg_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case LiveTranscriptionEvents.Metadata: - meta_result: MetadataResponse = MetadataResponse.from_json(message) - self._logger.verbose("MetadataResponse: %s", meta_result) - self._emit( - LiveTranscriptionEvents(LiveTranscriptionEvents.Metadata), - metadata=meta_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case LiveTranscriptionEvents.SpeechStarted: - ss_result: SpeechStartedResponse = SpeechStartedResponse.from_json( - message - ) - self._logger.verbose("SpeechStartedResponse: %s", ss_result) - self._emit( - LiveTranscriptionEvents(LiveTranscriptionEvents.SpeechStarted), - speech_started=ss_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case LiveTranscriptionEvents.UtteranceEnd: - ue_result: UtteranceEndResponse = UtteranceEndResponse.from_json( - message - ) - self._logger.verbose("UtteranceEndResponse: %s", ue_result) - self._emit( - LiveTranscriptionEvents(LiveTranscriptionEvents.UtteranceEnd), - utterance_end=ue_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case LiveTranscriptionEvents.Close: - close_result: CloseResponse = CloseResponse.from_json(message) - self._logger.verbose("CloseResponse: %s", close_result) - self._emit( - LiveTranscriptionEvents(LiveTranscriptionEvents.Close), - close=close_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case LiveTranscriptionEvents.Error: - err_error: ErrorResponse = ErrorResponse.from_json(message) - self._logger.verbose("ErrorResponse: %s", err_error) - self._emit( - LiveTranscriptionEvents(LiveTranscriptionEvents.Error), - error=err_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case _: - self._logger.warning( - "Unknown Message: response_type: %s, data: %s", - response_type, - data, - ) - unhandled_error: UnhandledResponse = UnhandledResponse( - type=LiveTranscriptionEvents(LiveTranscriptionEvents.Unhandled), - raw=message, - ) - self._emit( - LiveTranscriptionEvents(LiveTranscriptionEvents.Unhandled), - unhandled=unhandled_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - self._logger.notice("_process_text Succeeded") - self._logger.debug("SpeakStreamClient._process_text LEAVE") - - except Exception as e: # pylint: disable=broad-except - self._logger.error( - "Exception in ListenWebSocketClient._process_text: %s", e - ) - e_error: ErrorResponse = ErrorResponse( - "Exception in ListenWebSocketClient._process_text", - f"{e}", - "Exception", - ) - self._logger.error( - "Exception in ListenWebSocketClient._process_text: %s", str(e) - ) - self._emit( - LiveTranscriptionEvents(LiveTranscriptionEvents.Error), - e_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - # signal exit and close - super()._signal_exit() - - self._logger.debug("ListenWebSocketClient._process_text LEAVE") - - if self._config.options.get("termination_exception") is True: - raise - return - - # pylint: enable=too-many-return-statements,too-many-statements - - def _process_binary(self, message: bytes) -> None: - raise NotImplementedError("no _process_binary method should be called") - - # pylint: disable=too-many-return-statements - def _keep_alive(self) -> None: - self._logger.debug("ListenWebSocketClient._keep_alive ENTER") - - counter = 0 - while True: - try: - counter += 1 - self._exit_event.wait(timeout=ONE_SECOND) - - if self._exit_event.is_set(): - self._logger.notice("_keep_alive exiting gracefully") - self._logger.debug("ListenWebSocketClient._keep_alive LEAVE") - return - - # deepgram keepalive - if counter % DEEPGRAM_INTERVAL == 0: - self.keep_alive() - - except Exception as e: # pylint: disable=broad-except - self._logger.error( - "Exception in ListenWebSocketClient._keep_alive: %s", e - ) - e_error: ErrorResponse = ErrorResponse( - "Exception in ListenWebSocketClient._keep_alive", - f"{e}", - "Exception", - ) - self._logger.error( - "Exception in ListenWebSocketClient._keep_alive: %s", str(e) - ) - self._emit( - LiveTranscriptionEvents(LiveTranscriptionEvents.Error), - e_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - # signal exit and close - super()._signal_exit() - - self._logger.debug("ListenWebSocketClient._keep_alive LEAVE") - - if self._config.options.get("termination_exception") is True: - raise - return - - ## pylint: disable=too-many-return-statements,too-many-statements - def _flush(self) -> None: - self._logger.debug("ListenWebSocketClient._flush ENTER") - - delta_in_ms_str = self._config.options.get("auto_flush_reply_delta") - if delta_in_ms_str is None: - self._logger.error("auto_flush_reply_delta is None") - self._logger.debug("ListenWebSocketClient._flush LEAVE") - return - delta_in_ms = float(delta_in_ms_str) - - _flush_event = threading.Event() - while True: - try: - _flush_event.wait(timeout=HALF_SECOND) - - if self._exit_event.is_set(): - self._logger.notice("_flush exiting gracefully") - self._logger.debug("ListenWebSocketClient._flush LEAVE") - return - - with self._lock_flush: - if self._last_datagram is None: - self._logger.debug("AutoFlush last_datagram is None") - continue - - delta = datetime.now() - self._last_datagram - diff_in_ms = delta.total_seconds() * 1000 - self._logger.debug("AutoFlush delta: %f", diff_in_ms) - if diff_in_ms < delta_in_ms: - self._logger.debug("AutoFlush delta is less than threshold") - continue - - with self._lock_flush: - self._last_datagram = None - self.finalize() - - except Exception as e: # pylint: disable=broad-except - self._logger.error("Exception in ListenWebSocketClient._flush: %s", e) - e_error: ErrorResponse = ErrorResponse( - "Exception in ListenWebSocketClient._flush", - f"{e}", - "Exception", - ) - self._logger.error( - "Exception in ListenWebSocketClient._flush: %s", str(e) - ) - self._emit( - LiveTranscriptionEvents(LiveTranscriptionEvents.Error), - e_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - # signal exit and close - super()._signal_exit() - - self._logger.debug("ListenWebSocketClient._flush LEAVE") - - if self._config.options.get("termination_exception") is True: - raise - return - - # pylint: enable=too-many-return-statements - - def keep_alive(self) -> bool: - """ - Sends a KeepAlive message - """ - self._logger.spam("ListenWebSocketClient.keep_alive ENTER") - - self._logger.notice("Sending KeepAlive...") - ret = self.send(json.dumps({"type": "KeepAlive"})) - - if not ret: - self._logger.error("keep_alive failed") - self._logger.spam("ListenWebSocketClient.keep_alive LEAVE") - return False - - self._logger.notice("keep_alive succeeded") - self._logger.spam("ListenWebSocketClient.keep_alive LEAVE") - - return True - - def finalize(self) -> bool: - """ - Finalizes the Transcript connection by flushing it - """ - self._logger.spam("ListenWebSocketClient.finalize ENTER") - - self._logger.notice("Sending Finalize...") - ret = self.send(json.dumps({"type": "Finalize"})) - - if not ret: - self._logger.error("finalize failed") - self._logger.spam("ListenWebSocketClient.finalize LEAVE") - return False - - self._logger.notice("finalize succeeded") - self._logger.spam("ListenWebSocketClient.finalize LEAVE") - - return True - - def _close_message(self) -> bool: - return self.send(json.dumps({"type": "CloseStream"})) - - # closes the WebSocket connection gracefully - def finish(self) -> bool: - """ - Closes the WebSocket connection gracefully. - """ - self._logger.spam("ListenWebSocketClient.finish ENTER") - - # call parent finish - if super().finish() is False: - self._logger.error("ListenWebSocketClient.finish failed") - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("before running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - # stop the threads - self._logger.verbose("cancelling tasks...") - if self._flush_thread is not None: - self._flush_thread.join() - self._flush_thread = None - self._logger.notice("processing _flush_thread thread joined") - - if self._keep_alive_thread is not None: - self._keep_alive_thread.join() - self._keep_alive_thread = None - self._logger.notice("processing _keep_alive_thread thread joined") - - if self._listen_thread is not None: - self._listen_thread.join() - self._listen_thread = None - self._logger.notice("listening thread joined") - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("before running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - self._logger.notice("finish succeeded") - self._logger.spam("ListenWebSocketClient.finish LEAVE") - return True - - def _inspect(self, msg_result: LiveResultResponse) -> bool: - # auto flush_inspect is generically used to track any messages you might want to snoop on - # place additional logic here to inspect messages of interest - - # for auto flush functionality - # set the last datagram - sentence = msg_result.channel.alternatives[0].transcript - if len(sentence) == 0: - return True - - if msg_result.is_final: - with self._lock_flush: - self._logger.debug("AutoFlush is_final received") - self._last_datagram = None - else: - with self._lock_flush: - self._last_datagram = datetime.now() - self._logger.debug( - "AutoFlush interim received: %s", - str(self._last_datagram), - ) - - return True diff --git a/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/options.py b/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/options.py deleted file mode 100644 index 97b14105..00000000 --- a/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/options.py +++ /dev/null @@ -1,153 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from typing import List, Optional, Union -import logging - -from dataclasses import dataclass, field -from dataclasses_json import config as dataclass_config - -from deepgram.utils import verboselogs - -from ....common import BaseResponse - - -@dataclass -class LiveOptions(BaseResponse): # pylint: disable=too-many-instance-attributes - """ - Live Transcription Options for the Deepgram Platform. - - Please see the documentation for more information on each option: - https://developers.deepgram.com/reference/streaming - """ - - alternatives: Optional[int] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - callback: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - callback_method: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - channels: Optional[int] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - diarize: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - diarize_version: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - dictation: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - encoding: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - # pylint: disable=W0511 - # TODO: endpointing's current type previous was `Optional[str]` which is incorrect - # for backward compatibility we are keeping it as `Optional[Union[str, bool, int]]` - # since it gets translated to a string to be placed as a query parameter, will keep `str` for now - # but will change this to `Optional[Union[bool, int]]` in a future release - endpointing: Optional[Union[str, bool, int]] = field( - default=None, - metadata=dataclass_config(exclude=lambda f: f is None), - ) - # pylint: enable=W0511 - extra: Optional[Union[List[str], str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - filler_words: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - interim_results: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - keywords: Optional[Union[List[str], str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - keyterm: Optional[List[str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - language: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - model: Optional[str] = field( - default="None", metadata=dataclass_config(exclude=lambda f: f is None) - ) - multichannel: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - no_delay: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - numerals: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - punctuate: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - profanity_filter: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - redact: Optional[Union[List[str], bool, str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - replace: Optional[Union[List[str], str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - sample_rate: Optional[int] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - search: Optional[Union[List[str], str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - smart_format: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - tag: Optional[List[str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - tier: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - utterance_end_ms: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - vad_events: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - version: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def check(self): - """ - Check the options for any deprecated or soon-to-be-deprecated options. - """ - logger = verboselogs.VerboseLogger(__name__) - logger.addHandler(logging.StreamHandler()) - prev = logger.level - logger.setLevel(verboselogs.ERROR) - - if self.tier: - logger.warning( - "WARNING: Tier is deprecated. Will be removed in a future version." - ) - - if isinstance(self.endpointing, str): - logger.warning( - "WARNING: endpointing's current type previous was `Optional[str]` which is incorrect" - " for backward compatibility we are keeping it as `Optional[Union[str, bool, int]]`" - " since it gets translated to a string to be placed as a query parameter, will keep `str` for now" - " but will change this to `Optional[Union[bool, int]]` in a future release" - ) - - logger.setLevel(prev) - - return True - - -ListenWebSocketOptions = LiveOptions diff --git a/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/response.py b/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/response.py deleted file mode 100644 index 5a086b0c..00000000 --- a/venv/Lib/site-packages/deepgram/clients/listen/v1/websocket/response.py +++ /dev/null @@ -1,217 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from typing import List, Optional, Dict, Any - -from dataclasses import dataclass, field -from dataclasses_json import config as dataclass_config - -# common websocket response -from ....common import ( - BaseResponse, - OpenResponse, - CloseResponse, - ErrorResponse, - UnhandledResponse, -) - -# between rest and websocket -from ....common import ( - ModelInfo, - Hit, - Search, -) - - -# unique - - -@dataclass -class ListenWSWord(BaseResponse): - """ - Word object - """ - - word: str = "" - start: float = 0 - end: float = 0 - confidence: float = 0 - punctuated_word: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - speaker: Optional[int] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - language: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - -@dataclass -class ListenWSAlternative(BaseResponse): - """ - Alternative object - """ - - transcript: str = "" - confidence: float = 0 - words: List[ListenWSWord] = field(default_factory=list) - languages: Optional[List[str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "words" in _dict: - _dict["words"] = [ListenWSWord.from_dict(words) for words in _dict["words"]] - return _dict[key] - - -@dataclass -class ListenWSChannel(BaseResponse): - """ - Channel object - """ - - search: Optional[List[Search]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - alternatives: List[ListenWSAlternative] = field(default_factory=list) - - def __getitem__(self, key): - _dict = self.to_dict() - if "search" in _dict: - _dict["search"] = [Search.from_dict(search) for search in _dict["search"]] - if "alternatives" in _dict: - _dict["alternatives"] = [ - ListenWSAlternative.from_dict(alternatives) - for alternatives in _dict["alternatives"] - ] - return _dict[key] - - -@dataclass -class Metadata(BaseResponse): - """ - Metadata object - """ - - model_info: ModelInfo - request_id: str = "" - model_uuid: str = "" - extra: Optional[Dict[str, str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "model_info" in _dict: - _dict["model_info"] = [ - ModelInfo.from_dict(model_info) for model_info in _dict["model_info"] - ] - if "extra" in _dict: - _dict["extra"] = [str(extra) for _, extra in _dict["extra"].items()] - return _dict[key] - - -# live result messages - - -@dataclass -class LiveResultResponse(BaseResponse): # pylint: disable=too-many-instance-attributes - """ - Result Message from the Deepgram Platform - """ - - channel: ListenWSChannel - metadata: Metadata - type: str = "" - channel_index: List[int] = field(default_factory=list) - duration: float = 0 - start: float = 0 - is_final: bool = False - from_finalize: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - speech_final: bool = False - - def __getitem__(self, key): - _dict = self.to_dict() - if "channel" in _dict: - _dict["channel"] = [ - ListenWSChannel.from_dict(channel) for channel in _dict["channel"] - ] - if "metadata" in _dict: - _dict["metadata"] = [ - Metadata.from_dict(metadata) for metadata in _dict["metadata"] - ] - return _dict[key] - - -# Metadata Message - - -@dataclass -class MetadataResponse(BaseResponse): # pylint: disable=too-many-instance-attributes - """ - Metadata Message from the Deepgram Platform - """ - - type: str = "" - transaction_key: str = "" - request_id: str = "" - sha256: str = "" - created: str = "" - duration: float = 0 - channels: int = 0 - models: Optional[List[str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - model_info: Optional[Dict[str, ModelInfo]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - extra: Optional[Dict] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "models" in _dict: - _dict["models"] = [str(models) for models in _dict["models"]] - if "model_info" in _dict: - _dict["model_info"] = [ - ModelInfo.from_dict(model_info) - for _, model_info in _dict["model_info"].items() - ] - if "extra" in _dict: - _dict["extra"] = [str(extra) for _, extra in _dict["extra"].items()] - return _dict[key] - - -# Speech Started Message - - -@dataclass -class SpeechStartedResponse(BaseResponse): - """ - SpeechStartedResponse Message from the Deepgram Platform - """ - - type: str = "" - channel: List[int] = field(default_factory=list) - timestamp: float = 0 - - -# Utterance End Message - - -@dataclass -class UtteranceEndResponse(BaseResponse): - """ - UtteranceEnd Message from the Deepgram Platform - """ - - type: str = "" - channel: List[int] = field(default_factory=list) - last_word_end: float = 0 diff --git a/venv/Lib/site-packages/deepgram/clients/listen_router.py b/venv/Lib/site-packages/deepgram/clients/listen_router.py deleted file mode 100644 index 7bc88bfe..00000000 --- a/venv/Lib/site-packages/deepgram/clients/listen_router.py +++ /dev/null @@ -1,225 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from importlib import import_module -import logging -import deprecation # type: ignore - -from .. import __version__ -from .listen.v1 import ( - PreRecordedClient, - AsyncPreRecordedClient, - LiveClient, - AsyncLiveClient, -) -from ..utils import verboselogs -from ..options import DeepgramClientOptions -from .errors import DeepgramModuleError - - -class ListenRouter: - """ - Represents a client for interacting with the Deepgram API. - - This class provides a client for making requests to the Deepgram API with various configuration options. - - Attributes: - config_options (DeepgramClientOptions): An optional configuration object specifying client options. - - Raises: - DeepgramApiKeyError: If the API key is missing or invalid. - - Methods: - live: (Preferred) Returns a Threaded LiveClient instance for interacting with Deepgram's transcription services. - prerecorded: (Preferred) Returns an Threaded PreRecordedClient instance for interacting with Deepgram's prerecorded transcription services. - - asynclive: Returns an (Async) LiveClient instance for interacting with Deepgram's transcription services. - asyncprerecorded: Returns an (Async) PreRecordedClient instance for interacting with Deepgram's prerecorded transcription services. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - - def __init__(self, config: DeepgramClientOptions): - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - self._config = config - - @property - @deprecation.deprecated( - deprecated_in="3.4.0", - removed_in="4.0.0", - current_version=__version__, - details="deepgram.listen.prerecorded is deprecated. Use deepgram.listen.rest instead.", - ) - def prerecorded(self): - """ - DEPRECATED: deepgram.listen.prerecorded is deprecated. Use deepgram.listen.rest instead. - """ - return self.Version(self._config, "prerecorded") - - @property - @deprecation.deprecated( - deprecated_in="3.4.0", - removed_in="4.0.0", - current_version=__version__, - details="deepgram.listen.asyncprerecorded is deprecated. Use deepgram.listen.asyncrest instead.", - ) - def asyncprerecorded(self): - """ - DEPRECATED: deepgram.listen.asyncprerecorded is deprecated. Use deepgram.listen.asyncrest instead. - """ - return self.Version(self._config, "asyncprerecorded") - - @property - @deprecation.deprecated( - deprecated_in="3.4.0", - removed_in="4.0.0", - current_version=__version__, - details="deepgram.listen.live is deprecated. Use deepgram.listen.websocket instead.", - ) - def live(self): - """ - DEPRECATED: deepgram.listen.live is deprecated. Use deepgram.listen.websocket instead. - """ - return self.Version(self._config, "live") - - @property - @deprecation.deprecated( - deprecated_in="3.4.0", - removed_in="4.0.0", - current_version=__version__, - details="deepgram.listen.asynclive is deprecated. Use deepgram.listen.asyncwebsocket instead.", - ) - def asynclive(self): - """ - DEPRECATED: deepgram.listen.asynclive is deprecated. Use deepgram.listen.asyncwebsocket instead. - """ - return self.Version(self._config, "asynclive") - - @property - def rest(self): - """ - Returns a ListenRESTClient instance for interacting with Deepgram's prerecorded transcription services. - """ - return self.Version(self._config, "rest") - - @property - def asyncrest(self): - """ - Returns an AsyncListenRESTClient instance for interacting with Deepgram's prerecorded transcription services. - """ - return self.Version(self._config, "asyncrest") - - @property - def websocket(self): - """ - Returns a ListenWebSocketClient instance for interacting with Deepgram's transcription services. - """ - return self.Version(self._config, "websocket") - - @property - def asyncwebsocket(self): - """ - Returns an AsyncListenWebSocketClient instance for interacting with Deepgram's transcription services. - """ - return self.Version(self._config, "asyncwebsocket") - - # INTERNAL CLASSES - class Version: - """ - Represents a version of the Deepgram API. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - _parent: str - - def __init__(self, config, parent: str): - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - self._config = config - self._parent = parent - - # FUTURE VERSIONING: - # When v2 or v1.1beta1 or etc. This allows easy access to the latest version of the API. - # @property - # def latest(self): - # match self._parent: - # case "live": - # return LiveClient(self._config) - # case "prerecorded": - # return PreRecordedClient(self._config) - # case _: - # raise DeepgramModuleError("Invalid parent") - - def v(self, version: str = ""): - """ - Returns a specific version of the Deepgram API. - """ - self._logger.debug("Version.v ENTER") - self._logger.info("version: %s", version) - if len(version) == 0: - self._logger.error("version is empty") - self._logger.debug("Version.v LEAVE") - raise DeepgramModuleError("Invalid module version") - - protocol = "" - file_name = "" - class_name = "" - match self._parent: - case "live": - return LiveClient(self._config) - case "asynclive": - return AsyncLiveClient(self._config) - case "prerecorded": - return PreRecordedClient(self._config) - case "asyncprerecorded": - return AsyncPreRecordedClient(self._config) - case "websocket": - protocol = "websocket" - file_name = "client" - class_name = "ListenWebSocketClient" - case "asyncwebsocket": - protocol = "websocket" - file_name = "async_client" - class_name = "AsyncListenWebSocketClient" - case "rest": - protocol = "rest" - file_name = "client" - class_name = "ListenRESTClient" - case "asyncrest": - protocol = "rest" - file_name = "async_client" - class_name = "AsyncListenRESTClient" - case _: - self._logger.error("parent unknown: %s", self._parent) - self._logger.debug("Version.v LEAVE") - raise DeepgramModuleError("Invalid parent type") - - # create class path - path = f"deepgram.clients.listen.v{version}.{protocol}.{file_name}" - self._logger.info("path: %s", path) - self._logger.info("class_name: %s", class_name) - - # import class - mod = import_module(path) - if mod is None: - self._logger.error("module path is None") - self._logger.debug("Version.v LEAVE") - raise DeepgramModuleError("Unable to find package") - - my_class = getattr(mod, class_name) - if my_class is None: - self._logger.error("my_class is None") - self._logger.debug("Version.v LEAVE") - raise DeepgramModuleError("Unable to find class") - - # instantiate class - my_class = my_class(self._config) - self._logger.notice("Version.v succeeded") - self._logger.debug("Version.v LEAVE") - return my_class diff --git a/venv/Lib/site-packages/deepgram/clients/live/__init__.py b/venv/Lib/site-packages/deepgram/clients/live/__init__.py deleted file mode 100644 index e71ab007..00000000 --- a/venv/Lib/site-packages/deepgram/clients/live/__init__.py +++ /dev/null @@ -1,20 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .v1 import LiveTranscriptionEvents - -from .v1 import LiveClient -from .v1 import AsyncLiveClient -from .v1 import LiveOptions -from .v1 import ( - OpenResponse, - LiveResultResponse, - ListenWSMetadataResponse, - MetadataResponse, # backwards compat - SpeechStartedResponse, - UtteranceEndResponse, - CloseResponse, - ErrorResponse, - UnhandledResponse, -) diff --git a/venv/Lib/site-packages/deepgram/clients/live/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/live/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index bc6282d3..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/live/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/live/v1/__init__.py b/venv/Lib/site-packages/deepgram/clients/live/v1/__init__.py deleted file mode 100644 index 273c4d3b..00000000 --- a/venv/Lib/site-packages/deepgram/clients/live/v1/__init__.py +++ /dev/null @@ -1,20 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .enums import LiveTranscriptionEvents - -from .client import LiveClient -from .client import AsyncLiveClient -from .client import LiveOptions -from .client import ( - OpenResponse, - LiveResultResponse, - ListenWSMetadataResponse, - MetadataResponse, # backwards compat - SpeechStartedResponse, - UtteranceEndResponse, - CloseResponse, - ErrorResponse, - UnhandledResponse, -) diff --git a/venv/Lib/site-packages/deepgram/clients/live/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/live/v1/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index f7331b8b..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/live/v1/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/live/v1/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/live/v1/__pycache__/client.cpython-312.pyc deleted file mode 100644 index acd1fa8f..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/live/v1/__pycache__/client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/live/v1/__pycache__/enums.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/live/v1/__pycache__/enums.cpython-312.pyc deleted file mode 100644 index ef59bebb..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/live/v1/__pycache__/enums.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/live/v1/client.py b/venv/Lib/site-packages/deepgram/clients/live/v1/client.py deleted file mode 100644 index fd75c948..00000000 --- a/venv/Lib/site-packages/deepgram/clients/live/v1/client.py +++ /dev/null @@ -1,38 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from ...listen.v1 import ListenWebSocketClient as LiveClientLatest -from ...listen.v1 import AsyncListenWebSocketClient as AsyncLiveClientLatest -from ...listen.v1 import LiveOptions as LiveOptionsLatest -from ...listen.v1 import ( - OpenResponse as OpenResponseLatest, - LiveResultResponse as LiveResultResponseLatest, - ListenWSMetadataResponse as ListenWSMetadataResponseLatest, - SpeechStartedResponse as SpeechStartedResponseLatest, - UtteranceEndResponse as UtteranceEndResponseLatest, - CloseResponse as CloseResponseLatest, - ErrorResponse as ErrorResponseLatest, - UnhandledResponse as UnhandledResponseLatest, -) - -# The vX/client.py points to the current supported version in the SDK. -# Older versions are supported in the SDK for backwards compatibility. - - -# input -LiveOptions = LiveOptionsLatest -OpenResponse = OpenResponseLatest -LiveResultResponse = LiveResultResponseLatest -ListenWSMetadataResponse = ListenWSMetadataResponseLatest -MetadataResponse = ListenWSMetadataResponseLatest -SpeechStartedResponse = SpeechStartedResponseLatest -UtteranceEndResponse = UtteranceEndResponseLatest -CloseResponse = CloseResponseLatest -ErrorResponse = ErrorResponseLatest -UnhandledResponse = UnhandledResponseLatest - - -# clients -LiveClient = LiveClientLatest -AsyncLiveClient = AsyncLiveClientLatest diff --git a/venv/Lib/site-packages/deepgram/clients/live/v1/enums.py b/venv/Lib/site-packages/deepgram/clients/live/v1/enums.py deleted file mode 100644 index ee98540f..00000000 --- a/venv/Lib/site-packages/deepgram/clients/live/v1/enums.py +++ /dev/null @@ -1,5 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from ...listen import LiveTranscriptionEvents diff --git a/venv/Lib/site-packages/deepgram/clients/manage/__init__.py b/venv/Lib/site-packages/deepgram/clients/manage/__init__.py deleted file mode 100644 index 8a4287ae..00000000 --- a/venv/Lib/site-packages/deepgram/clients/manage/__init__.py +++ /dev/null @@ -1,53 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .client import ManageClient -from .client import AsyncManageClient -from .client import ( - ProjectOptions, - KeyOptions, - ScopeOptions, - InviteOptions, - UsageRequestOptions, - UsageSummaryOptions, - UsageFieldsOptions, -) -from .client import ( - #### top level - Message, - ProjectsResponse, - ModelResponse, - ModelsResponse, - MembersResponse, - KeyResponse, - KeysResponse, - ScopesResponse, - InvitesResponse, - UsageRequest, - UsageResponse, - UsageRequestsResponse, - UsageSummaryResponse, - UsageFieldsResponse, - BalancesResponse, - #### shared - Project, - STTDetails, - TTSMetadata, - TTSDetails, - Member, - Key, - Invite, - Config, - STTUsageDetails, - Callback, - TokenDetail, - SpeechSegment, - TTSUsageDetails, - STTTokens, - TTSTokens, - UsageSummaryResults, - Resolution, - UsageModel, - Balance, -) diff --git a/venv/Lib/site-packages/deepgram/clients/manage/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/manage/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index e5dc96be..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/manage/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/manage/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/manage/__pycache__/client.cpython-312.pyc deleted file mode 100644 index fb98e9b9..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/manage/__pycache__/client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/manage/client.py b/venv/Lib/site-packages/deepgram/clients/manage/client.py deleted file mode 100644 index 8238cd7a..00000000 --- a/venv/Lib/site-packages/deepgram/clients/manage/client.py +++ /dev/null @@ -1,110 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .v1.client import ManageClient as ManageClientLatest -from .v1.async_client import AsyncManageClient as AsyncManageClientLatest - -# input -from .v1.options import ( - ProjectOptions as ProjectOptionsLatest, - KeyOptions as KeyOptionsLatest, - ScopeOptions as ScopeOptionsLatest, - InviteOptions as InviteOptionsLatest, - UsageRequestOptions as UsageRequestOptionsLatest, - UsageSummaryOptions as UsageSummaryOptionsLatest, - UsageFieldsOptions as UsageFieldsOptionsLatest, -) - -# responses -from .v1.response import ( - Message as MessageLatest, - ProjectsResponse as ProjectsResponseLatest, - ModelResponse as ModelResponseLatest, - ModelsResponse as ModelsResponseLatest, - MembersResponse as MembersResponseLatest, - KeyResponse as KeyResponseLatest, - KeysResponse as KeysResponseLatest, - ScopesResponse as ScopesResponseLatest, - InvitesResponse as InvitesResponseLatest, - UsageRequest as UsageRequestLatest, - UsageResponse as UsageResponseLatest, - UsageRequestsResponse as UsageRequestsResponseLatest, - UsageSummaryResponse as UsageSummaryResponseLatest, - UsageFieldsResponse as UsageFieldsResponseLatest, - BalancesResponse as BalancesResponseLatest, - Project as ProjectLatest, - STTDetails as STTDetailsLatest, - TTSMetadata as TTSMetadataLatest, - TTSDetails as TTSDetailsLatest, - Member as MemberLatest, - Key as KeyLatest, - Invite as InviteLatest, - Config as ConfigLatest, - STTUsageDetails as STTUsageDetailsLatest, - Callback as CallbackLatest, - TokenDetail as TokenDetailLatest, - SpeechSegment as SpeechSegmentLatest, - TTSUsageDetails as TTSUsageDetailsLatest, - STTTokens as STTTokensLatest, - TTSTokens as TTSTokensLatest, - UsageSummaryResults as UsageSummaryResultsLatest, - Resolution as ResolutionLatest, - UsageModel as UsageModelLatest, - Balance as BalanceLatest, -) - - -# The client.py points to the current supported version in the SDK. -# Older versions are supported in the SDK for backwards compatibility. - - -# input -ProjectOptions = ProjectOptionsLatest -KeyOptions = KeyOptionsLatest -ScopeOptions = ScopeOptionsLatest -InviteOptions = InviteOptionsLatest -UsageRequestOptions = UsageRequestOptionsLatest -UsageSummaryOptions = UsageSummaryOptionsLatest -UsageFieldsOptions = UsageFieldsOptionsLatest - - -# responses -Message = MessageLatest -ProjectsResponse = ProjectsResponseLatest -ModelResponse = ModelResponseLatest -ModelsResponse = ModelsResponseLatest -MembersResponse = MembersResponseLatest -KeyResponse = KeyResponseLatest -KeysResponse = KeysResponseLatest -ScopesResponse = ScopesResponseLatest -InvitesResponse = InvitesResponseLatest -UsageRequest = UsageRequestLatest -UsageResponse = UsageResponseLatest -UsageRequestsResponse = UsageRequestsResponseLatest -UsageSummaryResponse = UsageSummaryResponseLatest -UsageFieldsResponse = UsageFieldsResponseLatest -BalancesResponse = BalancesResponseLatest -Project = ProjectLatest -STTDetails = STTDetailsLatest -TTSMetadata = TTSMetadataLatest -TTSDetails = TTSDetailsLatest -Member = MemberLatest -Key = KeyLatest -Invite = InviteLatest -Config = ConfigLatest -STTUsageDetails = STTUsageDetailsLatest -Callback = CallbackLatest -TokenDetail = TokenDetailLatest -SpeechSegment = SpeechSegmentLatest -TTSUsageDetails = TTSUsageDetailsLatest -STTTokens = STTTokensLatest -TTSTokens = TTSTokensLatest -UsageSummaryResults = UsageSummaryResultsLatest -Resolution = ResolutionLatest -UsageModel = UsageModelLatest -Balance = BalanceLatest - -# clients -ManageClient = ManageClientLatest -AsyncManageClient = AsyncManageClientLatest diff --git a/venv/Lib/site-packages/deepgram/clients/manage/v1/__init__.py b/venv/Lib/site-packages/deepgram/clients/manage/v1/__init__.py deleted file mode 100644 index 0373a56e..00000000 --- a/venv/Lib/site-packages/deepgram/clients/manage/v1/__init__.py +++ /dev/null @@ -1,54 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .client import ManageClient -from .async_client import AsyncManageClient -from .options import ( - ProjectOptions, - KeyOptions, - ScopeOptions, - InviteOptions, - UsageRequestOptions, - UsageSummaryOptions, - UsageFieldsOptions, -) - -from .response import ( - #### top level - Message, - ProjectsResponse, - ModelResponse, - ModelsResponse, - MembersResponse, - KeyResponse, - KeysResponse, - ScopesResponse, - InvitesResponse, - UsageRequest, - UsageResponse, - UsageRequestsResponse, - UsageSummaryResponse, - UsageFieldsResponse, - BalancesResponse, - #### shared - Project, - STTDetails, - TTSMetadata, - TTSDetails, - Member, - Key, - Invite, - Config, - STTUsageDetails, - Callback, - TokenDetail, - SpeechSegment, - TTSUsageDetails, - STTTokens, - TTSTokens, - UsageSummaryResults, - Resolution, - UsageModel, - Balance, -) diff --git a/venv/Lib/site-packages/deepgram/clients/manage/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/manage/v1/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index 4ff685e7..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/manage/v1/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/manage/v1/__pycache__/async_client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/manage/v1/__pycache__/async_client.cpython-312.pyc deleted file mode 100644 index ab73f9ff..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/manage/v1/__pycache__/async_client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/manage/v1/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/manage/v1/__pycache__/client.cpython-312.pyc deleted file mode 100644 index 7b4e6409..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/manage/v1/__pycache__/client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/manage/v1/__pycache__/options.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/manage/v1/__pycache__/options.cpython-312.pyc deleted file mode 100644 index 8c1d5b02..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/manage/v1/__pycache__/options.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/manage/v1/__pycache__/response.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/manage/v1/__pycache__/response.cpython-312.pyc deleted file mode 100644 index 68e93332..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/manage/v1/__pycache__/response.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/manage/v1/async_client.py b/venv/Lib/site-packages/deepgram/clients/manage/v1/async_client.py deleted file mode 100644 index 99fea77a..00000000 --- a/venv/Lib/site-packages/deepgram/clients/manage/v1/async_client.py +++ /dev/null @@ -1,1176 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -import logging -from typing import Dict, Union, Optional -import json - -import httpx - -from ....utils import verboselogs -from ....options import DeepgramClientOptions -from ...common import AbstractAsyncRestClient, DeepgramError - -from .response import ( - Message, - Project, - ProjectsResponse, - MembersResponse, - Key, - KeyResponse, - KeysResponse, - ScopesResponse, - InvitesResponse, - UsageRequest, - UsageRequestsResponse, - UsageSummaryResponse, - UsageFieldsResponse, - Balance, - BalancesResponse, - ModelResponse, - ModelsResponse, -) -from .options import ( - ProjectOptions, - ModelOptions, - KeyOptions, - ScopeOptions, - InviteOptions, - UsageRequestOptions, - UsageSummaryOptions, - UsageFieldsOptions, -) - - -class AsyncManageClient( - AbstractAsyncRestClient -): # pylint: disable=too-many-public-methods,too-many-lines - """ - A client for managing Deepgram projects and associated resources via the Deepgram API. - - This class provides methods for performing various operations on Deepgram projects, including: - - Retrieving project details - - Updating project settings - - Managing project members and scopes - - Handling project invitations - - Monitoring project usage and balances - - Args: - config (DeepgramClientOptions): all the options for the client. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - _endpoint: str - - def __init__(self, config: DeepgramClientOptions): - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - self._config = config - self._endpoint = "v1/projects" - super().__init__(config) - - # pylint: disable=too-many-positional-arguments - - # projects - async def list_projects( - self, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> ProjectsResponse: - """ - Please see get_projects for more information. - """ - return await self.get_projects( - timeout=timeout, addons=addons, headers=headers, **kwargs - ) - - async def get_projects( - self, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> ProjectsResponse: - """ - Gets a list of projects for the authenticated user. - - Reference: - https://developers.deepgram.com/reference/get-projects - """ - self._logger.debug("ManageClient.get_projects ENTER") - url = f"{self._config.url}/{self._endpoint}" - self._logger.info("url: %s", url) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.get( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("result: %s", result) - res = ProjectsResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_projects succeeded") - self._logger.debug("ManageClient.get_projects LEAVE") - return res - - async def get_project( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Project: - """ - Gets details for a specific project. - - Reference: - https://developers.deepgram.com/reference/get-project - """ - self._logger.debug("ManageClient.get_project ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.get( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("result: %s", result) - res = Project.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_project succeeded") - self._logger.debug("ManageClient.get_project LEAVE") - return res - - async def update_project_option( - self, - project_id: str, - options: Union[Dict, ProjectOptions], - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Message: - """ - Updates a project's settings. - - Reference: - https://developers.deepgram.com/reference/update-project - """ - self._logger.debug("ManageClient.update_project_option ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - if isinstance(options, ProjectOptions): - self._logger.info("ProjectOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.patch( - url, json=options, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("result: %s", result) - res = Message.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("update_project_option succeeded") - self._logger.debug("ManageClient.update_project_option LEAVE") - return res - - async def update_project( - self, - project_id: str, - name="", - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Message: - """ - Updates a project's settings. - - Reference: - https://developers.deepgram.com/reference/update-project - """ - self._logger.debug("ManageClient.update_project ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}" - options = { - "name": name, - } - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.patch( - url, json=options, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("result: %s", result) - res = Message.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("update_project succeeded") - self._logger.debug("ManageClient.update_project LEAVE") - return res - - async def delete_project( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Message: - """ - Deletes a project. - - Reference: - https://developers.deepgram.com/reference/delete-project - """ - self._logger.debug("ManageClient.delete_project ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}" - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.delete( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("result: %s", result) - res = Message.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("delete_project succeeded") - self._logger.debug("ManageClient.delete_project LEAVE") - return res - - async def list_project_models( - self, - project_id: str, - options: Optional[Union[Dict, ModelOptions]] = None, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> ModelsResponse: - """ - Please see get_project_models. - """ - return await self.get_project_models( - project_id, - options=options, - timeout=timeout, - addons=addons, - headers=headers, - **kwargs, - ) - - async def get_project_models( - self, - project_id: str, - options: Optional[Union[Dict, ModelOptions]] = None, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> ModelsResponse: - """ - Gets models for a specific project. - - Reference: - https://developers.deepgram.com/reference/get-project - https://developers.deepgram.com/reference/get-model - - Args: - project_id (str): The ID of the project. - timeout (Optional[httpx.Timeout]): The timeout setting for the request. - addons (Optional[Dict]): Additional options for the request. - headers (Optional[Dict]): Headers to include in the request. - **kwargs: Additional keyword arguments. - - Returns: - ModelsResponse: A response object containing the model details. - """ - self._logger.debug("ManageClient.get_project_models ENTER") - - if options is None: - options = ModelOptions() - - url = f"{self._config.url}/{self._endpoint}/{project_id}/models" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - if isinstance(options, ModelOptions): - self._logger.info("ModelOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.get( - url, json=options, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = ModelsResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_project_models succeeded") - self._logger.debug("ManageClient.get_project_models LEAVE") - return res - - async def get_project_model( - self, - project_id: str, - model_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> ModelResponse: - """ - Gets a single model for a specific project. - - Reference: - https://developers.deepgram.com/reference/get-project - https://developers.deepgram.com/reference/get-model - - Args: - project_id (str): The ID of the project. - model_id (str): The ID of the model. - timeout (Optional[httpx.Timeout]): The timeout setting for the request. - addons (Optional[Dict]): Additional options for the request. - headers (Optional[Dict]): Headers to include in the request. - **kwargs: Additional keyword arguments. - - Returns: - ModelResponse: A response object containing the model details. - """ - self._logger.debug("ManageClient.get_project_model ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/models/{model_id}" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("model_id: %s", model_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.get( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = ModelResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_project_model succeeded") - self._logger.debug("ManageClient.get_project_model LEAVE") - return res - - # models - async def list_models( - self, - options: Optional[Union[Dict, ModelOptions]] = None, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> ModelsResponse: - """ - Please see get_models for more information. - """ - return await self.get_models( - options=options, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - - async def get_models( - self, - options: Optional[Union[Dict, ModelOptions]] = None, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> ModelsResponse: - """ - Gets all models available. - - Reference: - https://developers.deepgram.com/reference/get-model - - Args: - timeout (Optional[httpx.Timeout]): The timeout setting for the request. - addons (Optional[Dict]): Additional options for the request. - headers (Optional[Dict]): Headers to include in the request. - **kwargs: Additional keyword arguments. - - Returns: - ModelsResponse: A response object containing the model details. - """ - self._logger.debug("ManageClient.get_models ENTER") - - if options is None: - options = ModelOptions() - - url = f"{self._config.url}/v1/models" - self._logger.info("url: %s", url) - if isinstance(options, ModelOptions): - self._logger.info("ModelOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.get( - url, json=options, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("result: %s", result) - res = ModelsResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_models succeeded") - self._logger.debug("ManageClient.get_models LEAVE") - return res - - async def get_model( - self, - model_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> ModelResponse: - """ - Gets information for a specific model. - - Reference: - https://developers.deepgram.com/reference/get-model - - Args: - model_id (str): The ID of the model. - timeout (Optional[httpx.Timeout]): The timeout setting for the request. - addons (Optional[Dict]): Additional options for the request. - headers (Optional[Dict]): Headers to include in the request. - **kwargs: Additional keyword arguments. - - Returns: - ModelResponse: A response object containing the model details. - """ - self._logger.debug("ManageClient.get_model ENTER") - url = f"{self._config.url}/v1/models/{model_id}" - self._logger.info("url: %s", url) - self._logger.info("model_id: %s", model_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.get( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("result: %s", result) - res = ModelResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_model succeeded") - self._logger.debug("ManageClient.get_model LEAVE") - return res - - # keys - async def list_keys( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> KeysResponse: - """ - Please see get_keys for more information. - """ - return await self.get_keys( - project_id, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - - async def get_keys( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> KeysResponse: - """ - Gets a list of keys for a project. - - Reference: - https://developers.deepgram.com/reference/list-keys - """ - self._logger.debug("ManageClient.get_keys ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/keys" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.get( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("result: %s", result) - res = KeysResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_keys succeeded") - self._logger.debug("ManageClient.get_keys LEAVE") - return res - - async def get_key( - self, - project_id: str, - key_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> KeyResponse: - """ - Gets details for a specific key. - - Reference: - https://developers.deepgram.com/reference/get-key - """ - self._logger.debug("ManageClient.get_key ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/keys/{key_id}" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("key_id: %s", key_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.get( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("result: %s", result) - res = KeyResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_key succeeded") - self._logger.debug("ManageClient.get_key LEAVE") - return res - - async def create_key( - self, - project_id: str, - options: Union[Dict, KeyOptions], - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Key: - """ - Creates a new key. - - Reference: - https://developers.deepgram.com/reference/create-key - """ - self._logger.debug("ManageClient.create_key ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/keys" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - if isinstance(options, KeyOptions): - self._logger.info("KeyOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.post( - url, json=options, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("result: %s", result) - res = Key.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("create_key succeeded") - self._logger.debug("ManageClient.create_key LEAVE") - return res - - async def delete_key( - self, - project_id: str, - key_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Message: - """ - Deletes a key. - - Reference: - https://developers.deepgram.com/reference/delete-key - """ - self._logger.debug("ManageClient.delete_key ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/keys/{key_id}" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("key_id: %s", key_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.delete( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("result: %s", result) - res = Message.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("delete_key succeeded") - self._logger.debug("ManageClient.delete_key LEAVE") - return res - - # members - async def list_members( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> MembersResponse: - """ - Please see get_members for more information. - """ - return await self.get_members( - project_id, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - - async def get_members( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> MembersResponse: - """ - Gets a list of members for a project. - - Reference: - https://developers.deepgram.com/reference/get-members - """ - self._logger.debug("ManageClient.get_members ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/members" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.get( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("result: %s", result) - res = MembersResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_members succeeded") - self._logger.debug("ManageClient.get_members LEAVE") - return res - - async def remove_member( - self, - project_id: str, - member_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Message: - """ - Removes a member from a project. - - Reference: - https://developers.deepgram.com/reference/remove-member - """ - self._logger.debug("ManageClient.remove_member ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/members/{member_id}" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("member_id: %s", member_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.delete( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("result: %s", result) - res = Message.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("remove_member succeeded") - self._logger.debug("ManageClient.remove_member LEAVE") - return res - - # scopes - async def get_member_scopes( - self, - project_id: str, - member_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> ScopesResponse: - """ - Gets a list of scopes for a member. - - Reference: - https://developers.deepgram.com/reference/get-member-scopes - """ - self._logger.debug("ManageClient.get_member_scopes ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/members/{member_id}/scopes" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("member_id: %s", member_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.get( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("result: %s", result) - res = ScopesResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_member_scopes succeeded") - self._logger.debug("ManageClient.get_member_scopes LEAVE") - return res - - async def update_member_scope( - self, - project_id: str, - member_id: str, - options: Union[Dict, ScopeOptions], - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Message: - """ - Updates a member's scopes. - - Reference: - https://developers.deepgram.com/reference/update-scope - """ - self._logger.debug("ManageClient.update_member_scope ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/members/{member_id}/scopes" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - if isinstance(options, ScopeOptions): - self._logger.info("ScopeOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.put( - url, json=options, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("result: %s", result) - res = Message.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("update_member_scope succeeded") - self._logger.debug("ManageClient.update_member_scope LEAVE") - return res - - # invites - async def list_invites( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> InvitesResponse: - """ - Please see get_invites for more information. - """ - return await self.get_invites( - project_id, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - - async def get_invites( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> InvitesResponse: - """ - Gets a list of invites for a project. - - Reference: - https://developers.deepgram.com/reference/list-invites - """ - self._logger.debug("ManageClient.get_invites ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/invites" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.get( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("result: %s", result) - res = InvitesResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_invites succeeded") - self._logger.debug("ManageClient.get_invites LEAVE") - return res - - async def send_invite_options( - self, - project_id: str, - options: Union[Dict, InviteOptions], - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Message: - """ - Sends an invite to a project. - - Reference: - https://developers.deepgram.com/reference/send-invite - """ - self._logger.debug("ManageClient.send_invite_options ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/invites" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - if isinstance(options, InviteOptions): - self._logger.info("InviteOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.post( - url, json=options, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("result: %s", result) - res = Message.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("send_invite_options succeeded") - self._logger.debug("ManageClient.send_invite_options LEAVE") - return res - - async def send_invite( - self, - project_id: str, - email: str, - scope="member", - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Message: - """ - Sends an invite to a project. - - Reference: - https://developers.deepgram.com/reference/send-invite - """ - self._logger.debug("ManageClient.send_invite ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/invites" - options = { - "email": email, - "scope": scope, - } - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.post( - url, json=options, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("result: %s", result) - res = Message.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("send_invite succeeded") - self._logger.debug("ManageClient.send_invite LEAVE") - return res - - async def delete_invite( - self, - project_id: str, - email: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Message: - """ - Deletes an invite from a project. - - Reference: - https://developers.deepgram.com/reference/delete-invite - """ - self._logger.debug("ManageClient.delete_invite ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/invites/{email}" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("email: %s", email) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.delete( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("result: %s", result) - res = Message.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("delete_invite succeeded") - self._logger.debug("ManageClient.delete_invite LEAVE") - return res - - async def leave_project( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Message: - """ - Leaves a project. - - Reference: - https://developers.deepgram.com/reference/leave-project - """ - self._logger.debug("ManageClient.leave_project ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/leave" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.delete( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("result: %s", result) - res = Message.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("leave_project succeeded") - self._logger.debug("ManageClient.leave_project LEAVE") - return res - - # usage - async def get_usage_requests( - self, - project_id: str, - options: Union[Dict, UsageRequestOptions], - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> UsageRequestsResponse: - """ - Gets a list of usage requests for a project. - - Reference: - https://developers.deepgram.com/reference/get-all-requests - """ - self._logger.debug("ManageClient.get_usage_requests ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/requests" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - if isinstance(options, UsageRequestOptions): - self._logger.info("UsageRequestOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.get( - url, - options=options, - timeout=timeout, - addons=addons, - headers=headers, - **kwargs, - ) - self._logger.info("result: %s", result) - res = UsageRequestsResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_usage_requests succeeded") - self._logger.debug("ManageClient.get_usage_requests LEAVE") - return res - - async def get_usage_request( - self, - project_id: str, - request_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> UsageRequest: - """ - Gets details for a specific usage request. - - Reference: - https://developers.deepgram.com/reference/get-request - """ - self._logger.debug("ManageClient.get_usage_request ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/requests/{request_id}" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("request_id: %s", request_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.get( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("result: %s", result) - - # convert str to JSON to check response field - json_result = json.loads(result) - if json_result.get("response") is None: - raise DeepgramError( - "Response is not available yet. Please try again later." - ) - - res = UsageRequest.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_usage_request succeeded") - self._logger.debug("ManageClient.get_usage_request LEAVE") - return res - - async def get_usage_summary( - self, - project_id: str, - options: Union[Dict, UsageSummaryOptions], - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> UsageSummaryResponse: - """ - Gets a summary of usage for a project. - - Reference: - https://developers.deepgram.com/reference/summarize-usage - """ - self._logger.debug("ManageClient.get_usage_summary ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/usage" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - if isinstance(options, UsageSummaryOptions): - self._logger.info("UsageSummaryOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.get( - url, - options=options, - timeout=timeout, - addons=addons, - headers=headers, - **kwargs, - ) - self._logger.info("result: %s", result) - res = UsageSummaryResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_usage_summary succeeded") - self._logger.debug("ManageClient.get_usage_summary LEAVE") - return res - - async def get_usage_fields( - self, - project_id: str, - options: Union[Dict, UsageFieldsOptions], - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> UsageFieldsResponse: - """ - Gets a list of usage fields for a project. - - Reference: - https://developers.deepgram.com/reference/get-fields - """ - self._logger.debug("ManageClient.get_usage_fields ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/usage/fields" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - if isinstance(options, UsageFieldsOptions): - self._logger.info("UsageFieldsOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.get( - url, - options=options, - timeout=timeout, - addons=addons, - headers=headers, - **kwargs, - ) - self._logger.info("result: %s", result) - res = UsageFieldsResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_usage_fields succeeded") - self._logger.debug("ManageClient.get_usage_fields LEAVE") - return res - - # balances - async def list_balances( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> BalancesResponse: - """ - Please see get_balances for more information. - """ - return await self.get_balances( - project_id, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - - async def get_balances( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> BalancesResponse: - """ - Gets a list of balances for a project. - - Reference: - https://developers.deepgram.com/reference/get-all-balances - """ - self._logger.debug("ManageClient.get_balances ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/balances" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.get( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("result: %s", result) - res = BalancesResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_balances succeeded") - self._logger.debug("ManageClient.get_balances LEAVE") - return res - - async def get_balance( - self, - project_id: str, - balance_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Balance: - """ - Gets details for a specific balance. - - Reference: - https://developers.deepgram.com/reference/get-balance - """ - self._logger.debug("ManageClient.get_balance ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/balances/{balance_id}" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("balance_id: %s", balance_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = await self.get( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("result: %s", result) - res = Balance.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_balance succeeded") - self._logger.debug("ManageClient.get_balance LEAVE") - return res - - # pylint: enable=too-many-positional-arguments diff --git a/venv/Lib/site-packages/deepgram/clients/manage/v1/client.py b/venv/Lib/site-packages/deepgram/clients/manage/v1/client.py deleted file mode 100644 index a2b6e94c..00000000 --- a/venv/Lib/site-packages/deepgram/clients/manage/v1/client.py +++ /dev/null @@ -1,1179 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -import logging -from typing import Dict, Union, Optional -import json - -import httpx - -from ....utils import verboselogs -from ....options import DeepgramClientOptions -from ...common import AbstractSyncRestClient, DeepgramError - -from .response import ( - Message, - Project, - ProjectsResponse, - MembersResponse, - Key, - KeyResponse, - KeysResponse, - ScopesResponse, - InvitesResponse, - UsageRequest, - UsageRequestsResponse, - UsageSummaryResponse, - UsageFieldsResponse, - Balance, - BalancesResponse, - ModelResponse, - ModelsResponse, -) -from .options import ( - ProjectOptions, - ModelOptions, - KeyOptions, - ScopeOptions, - InviteOptions, - UsageRequestOptions, - UsageSummaryOptions, - UsageFieldsOptions, -) - - -class ManageClient( - AbstractSyncRestClient -): # pylint: disable=too-many-public-methods,too-many-lines - """ - A client for managing Deepgram projects and associated resources via the Deepgram API. - - This class provides methods for performing various operations on Deepgram projects, including: - - Retrieving project details - - Updating project settings - - Managing project members and scopes - - Handling project invitations - - Monitoring project usage and balances - - Args: - config (DeepgramClientOptions): all the options for the client. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - _endpoint: str - - def __init__(self, config: DeepgramClientOptions): - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - - self._config = config - self._endpoint = "v1/projects" - super().__init__(config) - - # projects - def list_projects( - self, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> ProjectsResponse: - """ - List all projects for the current user. - """ - return self.get_projects( - timeout=timeout, addons=addons, headers=headers, **kwargs - ) - - # pylint: disable=too-many-positional-arguments - - def get_projects( - self, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> ProjectsResponse: - """ - Gets a list of projects for the authenticated user. - - Reference: - https://developers.deepgram.com/reference/get-projects - """ - self._logger.debug("ManageClient.get_projects ENTER") - url = f"{self._config.url}/{self._endpoint}" - self._logger.info("url: %s", url) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.get( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = ProjectsResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_projects succeeded") - self._logger.debug("ManageClient.get_projects LEAVE") - return res - - def get_project( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Project: - """ - Gets details for a specific project. - - Reference: - https://developers.deepgram.com/reference/get-project - """ - self._logger.debug("ManageClient.get_project ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.get( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = Project.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_project succeeded") - self._logger.debug("ManageClient.get_project LEAVE") - return res - - def update_project_option( - self, - project_id: str, - options: Union[Dict, ProjectOptions], - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Message: - """ - Updates a project's settings. - - Reference: - https://developers.deepgram.com/reference/update-project - """ - self._logger.debug("ManageClient.update_project_option ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - if isinstance(options, ProjectOptions): - self._logger.info("ProjectOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.patch( - url, json=options, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = Message.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("update_project_option succeeded") - self._logger.debug("ManageClient.update_project_option LEAVE") - return res - - def update_project( - self, - project_id: str, - name: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Message: - """ - Updates a project's settings. - - Reference: - https://developers.deepgram.com/reference/update-project - """ - self._logger.debug("ManageClient.update_project ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}" - options = { - "name": name, - } - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.patch( - url, json=options, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = Message.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("update_project succeeded") - self._logger.debug("ManageClient.update_project LEAVE") - return res - - def delete_project( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Message: - """ - Deletes a project. - - Reference: - https://developers.deepgram.com/reference/delete-project - """ - self._logger.debug("ManageClient.delete_project ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}" - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.delete( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = Message.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("delete_project succeeded") - self._logger.debug("ManageClient.delete_project LEAVE") - return res - - def list_project_models( - self, - project_id: str, - options: Optional[Union[Dict, ModelOptions]] = None, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> ModelsResponse: - """ - Please see get_project_models. - """ - return self.get_project_models( - project_id, - options=options, - timeout=timeout, - addons=addons, - headers=headers, - **kwargs, - ) - - def get_project_models( - self, - project_id: str, - options: Optional[Union[Dict, ModelOptions]] = None, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> ModelsResponse: - """ - Gets models for a specific project. - - Reference: - https://developers.deepgram.com/reference/get-project - https://developers.deepgram.com/reference/get-model - - Args: - project_id (str): The ID of the project. - options (Optional[Union[Dict, ModelOptions]]): The options for the request. - timeout (Optional[httpx.Timeout]): The timeout setting for the request. - addons (Optional[Dict]): Additional options for the request. - headers (Optional[Dict]): Headers to include in the request. - **kwargs: Additional keyword arguments. - - Returns: - ModelsResponse: A response object containing the model details. - """ - self._logger.debug("ManageClient.get_project_models ENTER") - - if options is None: - options = ModelOptions() - - url = f"{self._config.url}/{self._endpoint}/{project_id}/models" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - if isinstance(options, ModelOptions): - self._logger.info("ModelOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.get( - url, json=options, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = ModelsResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_project_models succeeded") - self._logger.debug("ManageClient.get_project_models LEAVE") - return res - - def get_project_model( - self, - project_id: str, - model_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> ModelResponse: - """ - Gets a single model for a specific project. - - Reference: - https://developers.deepgram.com/reference/get-project - https://developers.deepgram.com/reference/get-model - - Args: - project_id (str): The ID of the project. - model_id (str): The ID of the model. - timeout (Optional[httpx.Timeout]): The timeout setting for the request. - addons (Optional[Dict]): Additional options for the request. - headers (Optional[Dict]): Headers to include in the request. - **kwargs: Additional keyword arguments. - - Returns: - ModelResponse: A response object containing the model details. - """ - self._logger.debug("ManageClient.get_project_model ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/models/{model_id}" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("model_id: %s", model_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.get( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = ModelResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_project_model succeeded") - self._logger.debug("ManageClient.get_project_model LEAVE") - return res - - # models - def list_models( - self, - options: Optional[Union[Dict, ModelOptions]] = None, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> ModelsResponse: - """ - Please see get_models for more information. - """ - return self.get_models( - options=options, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - - def get_models( - self, - options: Optional[Union[Dict, ModelOptions]] = None, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> ModelsResponse: - """ - Gets all models available. - - Reference: - https://developers.deepgram.com/reference/get-model - - Args: - options (Optional[Union[Dict, ModelOptions]]): The options for the request. - timeout (Optional[httpx.Timeout]): The timeout setting for the request. - addons (Optional[Dict]): Additional options for the request. - headers (Optional[Dict]): Headers to include in the request. - **kwargs: Additional keyword arguments. - - Returns: - ModelsResponse: A response object containing the model details. - """ - self._logger.debug("ManageClient.get_models ENTER") - - if options is None: - options = ModelOptions() - - url = f"{self._config.url}/v1/models" - self._logger.info("url: %s", url) - if isinstance(options, ModelOptions): - self._logger.info("ModelOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.get( - url, json=options, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = ModelsResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_models succeeded") - self._logger.debug("ManageClient.get_models LEAVE") - return res - - def get_model( - self, - model_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> ModelResponse: - """ - Gets information for a specific model. - - Reference: - https://developers.deepgram.com/reference/get-model - - Args: - model_id (str): The ID of the model. - timeout (Optional[httpx.Timeout]): The timeout setting for the request. - addons (Optional[Dict]): Additional options for the request. - headers (Optional[Dict]): Headers to include in the request. - **kwargs: Additional keyword arguments. - - Returns: - ModelResponse: A response object containing the model details. - """ - self._logger.debug("ManageClient.get_model ENTER") - url = f"{self._config.url}/v1/models/{model_id}" - self._logger.info("url: %s", url) - self._logger.info("model_id: %s", model_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.get( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = ModelResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_model succeeded") - self._logger.debug("ManageClient.get_model LEAVE") - return res - - # keys - def list_keys( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> KeysResponse: - """ - Please see get_keys for more information. - """ - return self.get_keys( - project_id, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - - def get_keys( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> KeysResponse: - """ - Gets a list of keys for a project. - - Reference: - https://developers.deepgram.com/reference/list-keys - """ - self._logger.debug("ManageClient.get_keys ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/keys" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.get( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = KeysResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_keys succeeded") - self._logger.debug("ManageClient.get_keys LEAVE") - return res - - def get_key( - self, - project_id: str, - key_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> KeyResponse: - """ - Gets details for a specific key. - - Reference: - https://developers.deepgram.com/reference/get-key - """ - self._logger.debug("ManageClient.get_key ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/keys/{key_id}" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("key_id: %s", key_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.get( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = KeyResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_key succeeded") - self._logger.debug("ManageClient.get_key LEAVE") - return res - - def create_key( - self, - project_id: str, - options: Union[Dict, KeyOptions], - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Key: - """ - Creates a new key. - - Reference: - https://developers.deepgram.com/reference/create-key - """ - self._logger.debug("ManageClient.create_key ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/keys" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - if isinstance(options, KeyOptions): - self._logger.info("KeyOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.post( - url, json=options, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = Key.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("create_key succeeded") - self._logger.debug("ManageClient.create_key LEAVE") - return res - - def delete_key( - self, - project_id: str, - key_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Message: - """ - Deletes a key. - - Reference: - https://developers.deepgram.com/reference/delete-key - """ - self._logger.debug("ManageClient.delete_key ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/keys/{key_id}" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("key_id: %s", key_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.delete( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = Message.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("delete_key succeeded") - self._logger.debug("ManageClient.delete_key LEAVE") - return res - - # members - def list_members( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> MembersResponse: - """ - Please see get_members for more information. - """ - return self.get_members( - project_id, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - - def get_members( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> MembersResponse: - """ - Gets a list of members for a project. - - Reference: - https://developers.deepgram.com/reference/get-members - """ - self._logger.debug("ManageClient.get_members ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/members" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.get( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = MembersResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_members succeeded") - self._logger.debug("ManageClient.get_members LEAVE") - return res - - def remove_member( - self, - project_id: str, - member_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Message: - """ - Removes a member from a project. - - Reference: - https://developers.deepgram.com/reference/remove-member - """ - self._logger.debug("ManageClient.remove_member ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/members/{member_id}" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("member_id: %s", member_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.delete( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = Message.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("remove_member succeeded") - self._logger.debug("ManageClient.remove_member LEAVE") - return res - - # scopes - def get_member_scopes( - self, - project_id: str, - member_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> ScopesResponse: - """ - Gets a list of scopes for a member. - - Reference: - https://developers.deepgram.com/reference/get-member-scopes - """ - self._logger.debug("ManageClient.get_member_scopes ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/members/{member_id}/scopes" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("member_id: %s", member_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.get( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = ScopesResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_member_scopes succeeded") - self._logger.debug("ManageClient.get_member_scopes LEAVE") - return res - - def update_member_scope( - self, - project_id: str, - member_id: str, - options: Union[Dict, ScopeOptions], - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Message: - """ - Updates a member's scopes. - - Reference: - https://developers.deepgram.com/reference/update-scope - """ - self._logger.debug("ManageClient.update_member_scope ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/members/{member_id}/scopes" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - if isinstance(options, ScopeOptions): - self._logger.info("ScopeOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.put( - url, json=options, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = Message.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("update_member_scope succeeded") - self._logger.debug("ManageClient.update_member_scope LEAVE") - return res - - # invites - def list_invites( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> InvitesResponse: - """ - Please see get_invites for more information. - """ - return self.get_invites( - project_id, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - - def get_invites( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> InvitesResponse: - """ - Gets a list of invites for a project. - - Reference: - https://developers.deepgram.com/reference/list-invites - """ - self._logger.debug("ManageClient.get_invites ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/invites" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.get( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = InvitesResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_invites succeeded") - self._logger.debug("ManageClient.get_invites LEAVE") - return res - - def send_invite_options( - self, - project_id: str, - options: Union[Dict, InviteOptions], - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Message: - """ - Sends an invite to a project. - - Reference: - https://developers.deepgram.com/reference/send-invite - """ - self._logger.debug("ManageClient.send_invite_options ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/invites" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - if isinstance(options, InviteOptions): - self._logger.info("InviteOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.post( - url, json=options, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = Message.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("send_invite_options succeeded") - self._logger.debug("ManageClient.send_invite_options LEAVE") - return res - - def send_invite( - self, - project_id: str, - email: str, - scope="member", - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Message: - """ - Sends an invite to a project. - - Reference: - https://developers.deepgram.com/reference/send-invite - """ - self._logger.debug("ManageClient.send_invite ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/invites" - options = { - "email": email, - "scope": scope, - } - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.post( - url, json=options, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = Message.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("send_invite succeeded") - self._logger.debug("ManageClient.send_invite LEAVE") - return res - - def delete_invite( - self, - project_id: str, - email: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Message: - """ - Deletes an invite from a project. - - Reference: - https://developers.deepgram.com/reference/delete-invite - """ - self._logger.debug("ManageClient.delete_invite ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/invites/{email}" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("email: %s", email) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.delete( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = Message.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("delete_invite succeeded") - self._logger.debug("ManageClient.delete_invite LEAVE") - return res - - def leave_project( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Message: - """ - Leaves a project. - - Reference: - https://developers.deepgram.com/reference/leave-project - """ - self._logger.debug("ManageClient.leave_project ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/leave" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.delete( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = Message.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("leave_project succeeded") - self._logger.debug("ManageClient.leave_project LEAVE") - return res - - # usage - def get_usage_requests( - self, - project_id: str, - options: Union[Dict, UsageRequestOptions], - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> UsageRequestsResponse: - """ - Gets a list of usage requests for a project. - - Reference: - https://developers.deepgram.com/reference/get-all-requests - """ - self._logger.debug("ManageClient.get_usage_requests ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/requests" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - if isinstance(options, UsageRequestOptions): - self._logger.info("UsageRequestOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.get( - url, - options=options, - timeout=timeout, - addons=addons, - headers=headers, - **kwargs, - ) - self._logger.info("json: %s", result) - res = UsageRequestsResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_usage_requests succeeded") - self._logger.debug("ManageClient.get_usage_requests LEAVE") - return res - - def get_usage_request( - self, - project_id: str, - request_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> UsageRequest: - """ - Gets details for a specific usage request. - - Reference: - https://developers.deepgram.com/reference/get-request - """ - self._logger.debug("ManageClient.get_usage_request ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/requests/{request_id}" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("request_id: %s", request_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.get( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - - # convert str to JSON to check response field - json_result = json.loads(result) - if json_result.get("response") is None: - raise DeepgramError( - "Response is not available yet. Please try again later." - ) - - res = UsageRequest.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_usage_request succeeded") - self._logger.debug("ManageClient.get_usage_request LEAVE") - return res - - def get_usage_summary( - self, - project_id: str, - options: Union[Dict, UsageSummaryOptions], - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> UsageSummaryResponse: - """ - Gets a summary of usage for a project. - - Reference: - https://developers.deepgram.com/reference/summarize-usage - """ - self._logger.debug("ManageClient.get_usage_summary ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/usage" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - if isinstance(options, UsageSummaryOptions): - self._logger.info("UsageSummaryOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.get( - url, - options=options, - timeout=timeout, - addons=addons, - headers=headers, - **kwargs, - ) - self._logger.info("json: %s", result) - res = UsageSummaryResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_usage_summary succeeded") - self._logger.debug("ManageClient.get_usage_summary LEAVE") - return res - - def get_usage_fields( - self, - project_id: str, - options: Union[Dict, UsageFieldsOptions], - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> UsageFieldsResponse: - """ - Gets a list of usage fields for a project. - - Reference: - https://developers.deepgram.com/reference/get-fields - """ - self._logger.debug("ManageClient.get_usage_fields ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/usage/fields" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - if isinstance(options, UsageFieldsOptions): - self._logger.info("UsageFieldsOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.get( - url, - options=options, - timeout=timeout, - addons=addons, - headers=headers, - **kwargs, - ) - self._logger.info("json: %s", result) - res = UsageFieldsResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_usage_fields succeeded") - self._logger.debug("ManageClient.get_usage_fields LEAVE") - return res - - # balances - def list_balances( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> BalancesResponse: - """ - Please see get_balances for more information. - """ - return self.get_balances( - project_id, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - - def get_balances( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> BalancesResponse: - """ - Gets a list of balances for a project. - - Reference: - https://developers.deepgram.com/reference/get-all-balances - """ - self._logger.debug("ManageClient.get_balances ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/balances" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.get( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = BalancesResponse.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_balances succeeded") - self._logger.debug("ManageClient.get_balances LEAVE") - return res - - def get_balance( - self, - project_id: str, - balance_id: str, - timeout: Optional[httpx.Timeout] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - **kwargs, - ) -> Balance: - """ - Gets details for a specific balance. - - Reference: - https://developers.deepgram.com/reference/get-balance - """ - self._logger.debug("ManageClient.get_balance ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/balances/{balance_id}" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("balance_id: %s", balance_id) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - result = self.get( - url, timeout=timeout, addons=addons, headers=headers, **kwargs - ) - self._logger.info("json: %s", result) - res = Balance.from_json(result) - self._logger.verbose("result: %s", res) - self._logger.notice("get_balance succeeded") - self._logger.debug("ManageClient.get_balance LEAVE") - return res - - # pylint: enable=too-many-positional-arguments diff --git a/venv/Lib/site-packages/deepgram/clients/manage/v1/options.py b/venv/Lib/site-packages/deepgram/clients/manage/v1/options.py deleted file mode 100644 index 34fbf876..00000000 --- a/venv/Lib/site-packages/deepgram/clients/manage/v1/options.py +++ /dev/null @@ -1,177 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from typing import List, Optional - -from dataclasses import dataclass, field -from dataclasses_json import config as dataclass_config - -from ...common import BaseResponse - -# Input - - -@dataclass -class ProjectOptions(BaseResponse): - """ - Project Options - """ - - name: str = "" - - -@dataclass -class ModelOptions(BaseResponse): - """ - Model Options - """ - - include_outdated: bool = False - - -@dataclass -class KeyOptions(BaseResponse): - """ - Key Options - """ - - comment: Optional[str] = "" - expiration_date: Optional[str] = field( - default="", metadata=dataclass_config(exclude=lambda f: f == "") - ) - time_to_live_in_seconds: Optional[int] = field( - default=-1, metadata=dataclass_config(exclude=lambda f: f == -1) - ) - scopes: List[str] = field(default_factory=list) - tags: Optional[List[str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if _dict["scopes"] is not None: - _dict["scopes"] = [str(scopes) for scopes in _dict["scopes"]] - if _dict["tags"] is not None: - _dict["tags"] = [str(tags) for tags in _dict["tags"]] - return _dict[key] - - -@dataclass -class ScopeOptions(BaseResponse): - """ - Scope Options - """ - - scope: str = "" - - -@dataclass -class InviteOptions(BaseResponse): - """ - Invite Options - """ - - email: str = "" - scope: str = "" - - -@dataclass -class UsageRequestOptions(BaseResponse): - """ - Usage Request Options - """ - - start: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - end: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - limit: Optional[int] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - status: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - -@dataclass -class UsageSummaryOptions(BaseResponse): # pylint: disable=too-many-instance-attributes - """ - Usage Summary Options - """ - - start: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - end: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - accessor: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - tag: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - method: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - model: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - multichannel: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - interim_results: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - punctuate: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - ner: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - utterances: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - replace: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - profanity_filter: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - keywords: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - detect_topics: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - diarize: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - search: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - redact: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - alternatives: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - numerals: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - smart_format: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - -@dataclass -class UsageFieldsOptions(BaseResponse): - """ - Usage Fields Options - """ - - start: Optional[str] = "" - end: Optional[str] = "" diff --git a/venv/Lib/site-packages/deepgram/clients/manage/v1/response.py b/venv/Lib/site-packages/deepgram/clients/manage/v1/response.py deleted file mode 100644 index ef6824f4..00000000 --- a/venv/Lib/site-packages/deepgram/clients/manage/v1/response.py +++ /dev/null @@ -1,682 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from typing import List, Optional, Dict, Any - -from dataclasses import dataclass, field -from dataclasses_json import config as dataclass_config - -from ...common import ( - BaseResponse, -) - - -# Result Message - - -@dataclass -class Message(BaseResponse): - """ - Message from the Deepgram Platform - """ - - message: str = "" - - -# Projects - - -@dataclass -class Project(BaseResponse): - """ - Project object - """ - - project_id: str = "" - name: str = "" - - -@dataclass -class ProjectsResponse(BaseResponse): - """ - Projects Response object - """ - - projects: List[Project] = field(default_factory=list) - - def __getitem__(self, key): - _dict = self.to_dict() - if "projects" in _dict: - _dict["projects"] = [ - Project.from_dict(projects) for projects in _dict["projects"] - ] - return _dict[key] - - -# Models - - -@dataclass -class STTDetails(BaseResponse): # pylint: disable=too-many-instance-attributes - """ - STTDetails class used to define the properties of the Speech-to-Text model response object. - """ - - name: str = "" - canonical_name: str = "" - architecture: str = "" - languages: List[str] = field(default_factory=list) - version: str = "" - uuid: str = "" - batch: bool = False - streaming: bool = False - formatted_output: bool = False - - def __getitem__(self, key): - _dict = self.to_dict() - if "languages" in _dict: - _dict["languages"] = [str(languages) for languages in _dict["languages"]] - return _dict[key] - - -@dataclass -class TTSMetadata(BaseResponse): - """ - TTSMetadata class used to define the properties for a given STT or TTS model. - """ - - accent: str = "" - color: str = "" - image: str = "" - sample: str = "" - tags: Optional[List[str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - -@dataclass -class TTSDetails(BaseResponse): - """ - TTSDetails class used to define the properties of the Text-to-Speech model response object. - """ - - name: str = "" - canonical_name: str = "" - architecture: str = "" - languages: List[str] = field(default_factory=list) - version: str = "" - uuid: str = "" - metadata: Optional[TTSMetadata] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "metadata" in _dict: - _dict["metadata"] = [ - TTSMetadata.from_dict(metadata) for metadata in _dict["metadata"] - ] - return _dict[key] - - -# responses - - -@dataclass -class ModelResponse(BaseResponse): - """ - ModelResponse class used to define the properties of a single model. - """ - - name: str = "" - canonical_name: str = "" - architecture: str = "" - language: str = "" - version: str = "" - uuid: str = "" - metadata: Optional[TTSMetadata] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "metadata" in _dict: - _dict["metadata"] = [ - TTSMetadata.from_dict(metadata) for metadata in _dict["metadata"] - ] - return _dict[key] - - -@dataclass -class ModelsResponse(BaseResponse): - """ - ModelsResponse class used to obtain a list of models. - """ - - stt: List[STTDetails] = field(default_factory=list) - tts: List[TTSDetails] = field(default_factory=list) - - def __getitem__(self, key): - _dict = self.to_dict() - if "stt" in _dict: - _dict["stt"] = [STTDetails.from_dict(stt) for stt in _dict["stt"]] - if "tts" in _dict: - _dict["tts"] = [TTSDetails.from_dict(tts) for tts in _dict["tts"]] - return _dict[key] - - -# Members - - -@dataclass -class Member(BaseResponse): - """ - Member object - """ - - email: str = "" - first_name: str = "" - last_name: str = "" - member_id: str = "" - - -@dataclass -class MembersResponse(BaseResponse): - """ - Members Response object - """ - - members: List[Member] = field(default_factory=list) - - def __getitem__(self, key): - _dict = self.to_dict() - if "members" in _dict: - _dict["members"] = [ - Member.from_dict(members) for members in _dict["members"] - ] - return _dict[key] - - -# Keys - - -@dataclass -class Key(BaseResponse): - """ - Key object - """ - - api_key_id: str = "" - key: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - comment: Optional[str] = "" - created: str = "" - scopes: List[str] = field(default_factory=list) - expiration_date: str = field( - default="", metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "scopes" in _dict: - _dict["scopes"] = [str(scopes) for scopes in _dict["scopes"]] - return _dict[key] - - -@dataclass -class KeyResponse(BaseResponse): - """ - Key Response object - """ - - api_key: Key - member: Member - - def __getitem__(self, key): - _dict = self.to_dict() - if "api_key" in _dict: - _dict["api_key"] = Key.from_dict(_dict["api_key"]) - if "member" in _dict: - _dict["member"] = Member.from_dict(_dict["member"]) - return _dict[key] - - -@dataclass -class KeysResponse(BaseResponse): - """ - Keys Response object - """ - - api_keys: List[KeyResponse] = field(default_factory=list) - - def __getitem__(self, key): - _dict = self.to_dict() - if "api_keys" in _dict: - _dict["api_keys"] = [ - KeyResponse.from_dict(api_keys) for api_keys in _dict["api_keys"] - ] - return _dict[key] - - -# Scopes - - -@dataclass -class ScopesResponse(BaseResponse): - """ - Scopes Response object - """ - - scopes: List[str] = field(default_factory=list) - - def __getitem__(self, key): - _dict = self.to_dict() - if "scopes" in _dict: - _dict["scopes"] = [str(scopes) for scopes in _dict["scopes"]] - return _dict[key] - - -# Invites - - -@dataclass -class Invite(BaseResponse): - """ - Invite object - """ - - email: str = "" - scope: str = "" - - -@dataclass -class InvitesResponse(BaseResponse): - """ - Invites Response object - """ - - invites: List[Invite] = field(default_factory=list) - - def __getitem__(self, key): - _dict = self.to_dict() - if "invites" in _dict: - _dict["invites"] = [ - Invite.from_dict(invites) for invites in _dict["invites"] - ] - return _dict[key] - - -# Usage - - -@dataclass -class Config(BaseResponse): # pylint: disable=too-many-instance-attributes - """ - Config object - """ - - language: str = "" - model: str = "" - punctuate: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - utterances: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - diarize: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - smart_format: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - interim_results: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - topics: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - intents: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - sentiment: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - summarize: Optional[bool] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - -@dataclass -class STTUsageDetails(BaseResponse): # pylint: disable=too-many-instance-attributes - """ - Details object - """ - - config: Config - usd: float = 0 - duration: Optional[float] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - total_audio: Optional[float] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - channels: Optional[int] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - streams: Optional[int] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - method: str = "" - tier: Optional[str] = "" - models: List[str] = field(default_factory=list) - tags: Optional[List[str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - features: List[str] = field(default_factory=list) - - def __getitem__(self, key): - _dict = self.to_dict() - if "models" in _dict: - _dict["models"] = [str(models) for models in _dict["models"]] - if "tags" in _dict: - _dict["tags"] = [str(tags) for tags in _dict["tags"]] - if "features" in _dict: - _dict["features"] = [str(features) for features in _dict["features"]] - if "config" in _dict: - _dict["config"] = Config.from_dict(_dict["config"]) - return _dict[key] - - -@dataclass -class Callback(BaseResponse): - """ - Callback object - """ - - attempts: int = 0 - code: int = 0 - completed: str = "" - - -@dataclass -class TokenDetail(BaseResponse): - """ - Token Detail object - """ - - feature: str = "" - input: int = 0 - model: str = "" - output: int = 0 - - -@dataclass -class SpeechSegment(BaseResponse): - """ - Speech Segment object - """ - - characters: int = 0 - model: str = "" - tier: str = "" - - -@dataclass -class TTSUsageDetails(BaseResponse): - """ - TTS Details object - """ - - duration: float = 0 - speech_segments: List[SpeechSegment] = field(default_factory=list) - # pylint: disable=fixme - # TODO: audio_metadata: None - # pylint: enable=fixme - - def __getitem__(self, key): - _dict = self.to_dict() - if "speech_segments" in _dict: - _dict["speech_segments"] = [ - SpeechSegment.from_dict(speech_segments) - for speech_segments in _dict["speech_segments"] - ] - return _dict[key] - - -@dataclass -class UsageResponse(BaseResponse): - """ - UsageResponse object - """ - - details: Optional[STTUsageDetails] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - code: int = 0 - completed: str = "" - message: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - tts_details: Optional[TTSUsageDetails] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - token_details: List[TokenDetail] = field( - default_factory=list, metadata=dataclass_config(exclude=lambda f: f is list) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "details" in _dict: - _dict["details"] = STTUsageDetails.from_dict(_dict["details"]) - if "tts_details" in _dict: - _dict["tts_details"] = TTSUsageDetails.from_dict(_dict["tts_details"]) - if "token_details" in _dict: - _dict["token_details"] = [ - TokenDetail.from_dict(token_details) - for token_details in _dict["token_details"] - ] - return _dict[key] - - -@dataclass -class UsageRequest(BaseResponse): # pylint: disable=too-many-instance-attributes - """ - Usage Request object - """ - - response: UsageResponse - project_uuid: str = "" - request_id: str = "" - created: str = "" - path: str = "" - api_key_id: str = "" - callback: Optional[Callback] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - accessor: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "response" in _dict: - _dict["response"] = UsageResponse.from_dict(_dict["response"]) - if "callback" in _dict: - _dict["callback"] = Callback.from_dict(_dict["callback"]) - return _dict[key] - - -@dataclass -class UsageRequestsResponse(BaseResponse): - """ - Usage Requests Response object - """ - - page: int = 0 - limit: int = 0 - requests: List[UsageRequest] = field(default_factory=list) - - def __getitem__(self, key): - _dict = self.to_dict() - if "requests" in _dict: - _dict["requests"] = [ - UsageRequest.from_dict(requests) for requests in _dict["requests"] - ] - return _dict[key] - - -@dataclass -class STTTokens(BaseResponse): - """ - STTTokens object - """ - - tokens_in: int = 0 - out: int = 0 - - -@dataclass -class TTSTokens(BaseResponse): - """ - TTSTokens object - """ - - characters: int = 0 - requests: int = 0 - - -@dataclass -class UsageSummaryResults(BaseResponse): - """ - Results object - """ - - tokens: STTTokens - tts: TTSTokens - start: str = "" - end: str = "" - hours: int = 0 - total_hours: int = 0 - requests: int = 0 - - def __getitem__(self, key): - _dict = self.to_dict() - if "tokens" in _dict: - _dict["tokens"] = STTTokens.from_dict(_dict["tokens"]) - if "tts" in _dict: - _dict["tts"] = TTSTokens.from_dict(_dict["tts"]) - return _dict[key] - - -@dataclass -class Resolution(BaseResponse): - """ - Resolution object - """ - - units: str = "" - amount: int = 0 - - -@dataclass -class UsageSummaryResponse(BaseResponse): - """ - Usage Summary Response object - """ - - resolution: Resolution - start: str = "" - end: str = "" - results: List[UsageSummaryResults] = field(default_factory=list) - - def __getitem__(self, key): - _dict = self.to_dict() - if "resolution" in _dict: - _dict["resolution"] = Resolution.from_dict(_dict["resolution"]) - if "results" in _dict: - _dict["results"] = [ - UsageSummaryResults.from_dict(results) for results in _dict["results"] - ] - return _dict[key] - - -@dataclass -class UsageModel(BaseResponse): - """ - Usage Model object - """ - - name: str = "" - language: str = "" - version: str = "" - model_id: str = "" - - -@dataclass -class UsageFieldsResponse(BaseResponse): - """ - Usage Fields Response object - """ - - tags: Optional[List[str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - models: List[UsageModel] = field(default_factory=list) - processing_methods: List[str] = field(default_factory=list) - features: List[str] = field(default_factory=list) - languages: Optional[List[str]] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - if "tags" in _dict: - _dict["tags"] = [str(tags) for tags in _dict["tags"]] - if "models" in _dict: - _dict["models"] = [ - UsageModel.from_dict(models) for models in _dict["models"] - ] - if "processing_methods" in _dict: - _dict["processing_methods"] = [ - str(processing_methods) - for processing_methods in _dict["processing_methods"] - ] - if "features" in _dict: - _dict["features"] = [str(features) for features in _dict["features"]] - if "languages" in _dict: - _dict["languages"] = [str(languages) for languages in _dict["languages"]] - return _dict[key] - - -# Billing - - -@dataclass -class Balance(BaseResponse): - """ - Balance object - """ - - balance_id: str = "" - amount: str = "" - units: str = "" - purchase_order_id: str = "" - - -@dataclass -class BalancesResponse(BaseResponse): - """ - Balances Response object - """ - - balances: List[Balance] = field(default_factory=list) - - def __getitem__(self, key): - _dict = self.to_dict() - if "balances" in _dict: - _dict["balances"] = [ - Balance.from_dict(balances) for balances in _dict["balances"] - ] - return _dict[key] diff --git a/venv/Lib/site-packages/deepgram/clients/prerecorded/__init__.py b/venv/Lib/site-packages/deepgram/clients/prerecorded/__init__.py deleted file mode 100644 index 9156a65c..00000000 --- a/venv/Lib/site-packages/deepgram/clients/prerecorded/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .v1 import PreRecordedClient -from .v1 import AsyncPreRecordedClient -from .v1 import PrerecordedOptions -from .v1 import ( - UrlSource, - FileSource, - PreRecordedStreamSource, - PrerecordedSource, -) -from .v1 import ( - AsyncPrerecordedResponse, - PrerecordedResponse, - SyncPrerecordedResponse, -) diff --git a/venv/Lib/site-packages/deepgram/clients/prerecorded/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/prerecorded/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index 60230a41..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/prerecorded/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/prerecorded/v1/__init__.py b/venv/Lib/site-packages/deepgram/clients/prerecorded/v1/__init__.py deleted file mode 100644 index 03095cc9..00000000 --- a/venv/Lib/site-packages/deepgram/clients/prerecorded/v1/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .client import PreRecordedClient -from .client import AsyncPreRecordedClient -from .client import PrerecordedOptions -from .client import ( - UrlSource, - FileSource, - PreRecordedStreamSource, - PrerecordedSource, -) -from .client import ( - AsyncPrerecordedResponse, - PrerecordedResponse, - SyncPrerecordedResponse, -) diff --git a/venv/Lib/site-packages/deepgram/clients/prerecorded/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/prerecorded/v1/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index e277fb61..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/prerecorded/v1/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/prerecorded/v1/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/prerecorded/v1/__pycache__/client.cpython-312.pyc deleted file mode 100644 index ef84cd9a..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/prerecorded/v1/__pycache__/client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/prerecorded/v1/__pycache__/errors.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/prerecorded/v1/__pycache__/errors.cpython-312.pyc deleted file mode 100644 index 4756fa70..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/prerecorded/v1/__pycache__/errors.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/prerecorded/v1/client.py b/venv/Lib/site-packages/deepgram/clients/prerecorded/v1/client.py deleted file mode 100644 index 0a8819d3..00000000 --- a/venv/Lib/site-packages/deepgram/clients/prerecorded/v1/client.py +++ /dev/null @@ -1,37 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from ...listen import PreRecordedClient as PreRecordedClientLatest -from ...listen import AsyncPreRecordedClient as AsyncPreRecordedClientLatest -from ...listen import ( - PrerecordedOptions as PrerecordedOptionsLatest, - UrlSource as UrlSourceLatest, - FileSource as FileSourceLatest, - PreRecordedStreamSource as PreRecordedStreamSourceLatest, - PrerecordedSource as PrerecordedSourceLatest, -) -from ...listen import ( - AsyncPrerecordedResponse as AsyncPrerecordedResponseLatest, - PrerecordedResponse as PrerecordedResponseLatest, - SyncPrerecordedResponse as SyncPrerecordedResponseLatest, -) - - -# input -PrerecordedOptions = PrerecordedOptionsLatest -PreRecordedStreamSource = PreRecordedStreamSourceLatest -UrlSource = UrlSourceLatest -FileSource = FileSourceLatest -PrerecordedSource = PrerecordedSourceLatest - - -# output -AsyncPrerecordedResponse = AsyncPrerecordedResponseLatest -PrerecordedResponse = PrerecordedResponseLatest -SyncPrerecordedResponse = SyncPrerecordedResponseLatest - - -# clients -PreRecordedClient = PreRecordedClientLatest -AsyncPreRecordedClient = AsyncPreRecordedClientLatest diff --git a/venv/Lib/site-packages/deepgram/clients/prerecorded/v1/errors.py b/venv/Lib/site-packages/deepgram/clients/prerecorded/v1/errors.py deleted file mode 100644 index 41a6947c..00000000 --- a/venv/Lib/site-packages/deepgram/clients/prerecorded/v1/errors.py +++ /dev/null @@ -1,37 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - - -class DeepgramError(Exception): - """ - Exception raised for unknown errors related to the Deepgram API. - - Attributes: - message (str): The error message describing the exception. - """ - - def __init__(self, message: str): - super().__init__(message) - self.name = "DeepgramError" - self.message = message - - def __str__(self): - return f"{self.name}: {self.message}" - - -class DeepgramTypeError(Exception): - """ - Exception raised for unknown errors related to unknown Types for Transcription. - - Attributes: - message (str): The error message describing the exception. - """ - - def __init__(self, message: str): - super().__init__(message) - self.name = "DeepgramTypeError" - self.message = message - - def __str__(self): - return f"{self.name}: {self.message}" diff --git a/venv/Lib/site-packages/deepgram/clients/read_router.py b/venv/Lib/site-packages/deepgram/clients/read_router.py deleted file mode 100644 index 1ca09ee3..00000000 --- a/venv/Lib/site-packages/deepgram/clients/read_router.py +++ /dev/null @@ -1,130 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from importlib import import_module -import logging - -from ..utils import verboselogs -from ..options import DeepgramClientOptions -from .errors import DeepgramModuleError - - -class ReadRouter: - """ - Represents a client for interacting with the Deepgram API. - - This class provides a client for making requests to the Deepgram API with various configuration options. - - Attributes: - config_options (DeepgramClientOptions): An optional configuration object specifying client options. - - Raises: - DeepgramApiKeyError: If the API key is missing or invalid. - - Methods: - read: (Preferred) Returns an Threaded AnalyzeClient instance for interacting with Deepgram's read transcription services. - asyncread: Returns an (Async) AnalyzeClient instance for interacting with Deepgram's read transcription services. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - - def __init__(self, config: DeepgramClientOptions): - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - self._config = config - - @property - def analyze(self): - """ - Returns an AnalyzeClient instance for interacting with Deepgram's read services. - """ - return self.Version(self._config, "analyze") - - @property - def asyncanalyze(self): - """ - Returns an AsyncAnalyzeClient instance for interacting with Deepgram's read services. - """ - return self.Version(self._config, "asyncanalyze") - - # INTERNAL CLASSES - class Version: - """ - Represents a version of the Deepgram API. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - _parent: str - - def __init__(self, config, parent: str): - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - self._config = config - self._parent = parent - - # FUTURE VERSIONING: - # When v2 or v1.1beta1 or etc. This allows easy access to the latest version of the API. - # @property - # def latest(self): - # match self._parent: - # case "analyze": - # return AnalyzeClient(self._config) - # case _: - # raise DeepgramModuleError("Invalid parent") - - def v(self, version: str = ""): - """ - Returns a specific version of the Deepgram API. - """ - self._logger.debug("Version.v ENTER") - self._logger.info("version: %s", version) - if len(version) == 0: - self._logger.error("version is empty") - self._logger.debug("Version.v LEAVE") - raise DeepgramModuleError("Invalid module version") - - parent = "" - file_name = "" - class_name = "" - match self._parent: - case "analyze": - parent = "analyze" - file_name = "client" - class_name = "AnalyzeClient" - case "asyncanalyze": - parent = "analyze" - file_name = "async_client" - class_name = "AsyncAnalyzeClient" - case _: - self._logger.error("parent unknown: %s", self._parent) - self._logger.debug("Version.v LEAVE") - raise DeepgramModuleError("Invalid parent type") - - # create class path - path = f"deepgram.clients.{parent}.v{version}.{file_name}" - self._logger.info("path: %s", path) - self._logger.info("class_name: %s", class_name) - - # import class - mod = import_module(path) - if mod is None: - self._logger.error("module path is None") - self._logger.debug("Version.v LEAVE") - raise DeepgramModuleError("Unable to find package") - - my_class = getattr(mod, class_name) - if my_class is None: - self._logger.error("my_class is None") - self._logger.debug("Version.v LEAVE") - raise DeepgramModuleError("Unable to find class") - - # instantiate class - my_class = my_class(self._config) - self._logger.notice("Version.v succeeded") - self._logger.debug("Version.v LEAVE") - return my_class diff --git a/venv/Lib/site-packages/deepgram/clients/selfhosted/__init__.py b/venv/Lib/site-packages/deepgram/clients/selfhosted/__init__.py deleted file mode 100644 index ced8a6f4..00000000 --- a/venv/Lib/site-packages/deepgram/clients/selfhosted/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .client import SelfHostedClient, OnPremClient -from .client import AsyncSelfHostedClient, AsyncOnPremClient diff --git a/venv/Lib/site-packages/deepgram/clients/selfhosted/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/selfhosted/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index a085d984..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/selfhosted/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/selfhosted/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/selfhosted/__pycache__/client.cpython-312.pyc deleted file mode 100644 index 2e5f7ba2..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/selfhosted/__pycache__/client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/selfhosted/client.py b/venv/Lib/site-packages/deepgram/clients/selfhosted/client.py deleted file mode 100644 index 1301c641..00000000 --- a/venv/Lib/site-packages/deepgram/clients/selfhosted/client.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .v1.client import SelfHostedClient as SelfHostedClientLatest -from .v1.async_client import AsyncSelfHostedClient as AsyncSelfHostedClientLatest - - -# The client.py points to the current supported version in the SDK. -# Older versions are supported in the SDK for backwards compatibility. - -SelfHostedClient = SelfHostedClientLatest -AsyncSelfHostedClient = AsyncSelfHostedClientLatest -OnPremClient = SelfHostedClientLatest -AsyncOnPremClient = AsyncSelfHostedClientLatest diff --git a/venv/Lib/site-packages/deepgram/clients/selfhosted/v1/__init__.py b/venv/Lib/site-packages/deepgram/clients/selfhosted/v1/__init__.py deleted file mode 100644 index 8604f754..00000000 --- a/venv/Lib/site-packages/deepgram/clients/selfhosted/v1/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .client import SelfHostedClient -from .async_client import AsyncSelfHostedClient diff --git a/venv/Lib/site-packages/deepgram/clients/selfhosted/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/selfhosted/v1/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index c576a1cb..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/selfhosted/v1/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/selfhosted/v1/__pycache__/async_client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/selfhosted/v1/__pycache__/async_client.cpython-312.pyc deleted file mode 100644 index 0688f17c..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/selfhosted/v1/__pycache__/async_client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/selfhosted/v1/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/selfhosted/v1/__pycache__/client.cpython-312.pyc deleted file mode 100644 index 7686a7c3..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/selfhosted/v1/__pycache__/client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/selfhosted/v1/async_client.py b/venv/Lib/site-packages/deepgram/clients/selfhosted/v1/async_client.py deleted file mode 100644 index cc9bb175..00000000 --- a/venv/Lib/site-packages/deepgram/clients/selfhosted/v1/async_client.py +++ /dev/null @@ -1,170 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -import logging -from typing import Optional - -import httpx - -from ....utils import verboselogs -from ....options import DeepgramClientOptions -from ...common import AbstractAsyncRestClient - - -class AsyncSelfHostedClient(AbstractAsyncRestClient): - """ - Client for interacting with Deepgram's on-premises API. - - This class provides methods to manage and interact with on-premises projects and distribution credentials. - - Args: - config (DeepgramClientOptions): all the options for the client. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - _endpoint: str - - def __init__(self, config: DeepgramClientOptions): - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - self._config = config - self._endpoint = "v1/projects" - super().__init__(config) - - async def list_onprem_credentials( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ): - """ - List all on-premises distribution credentials for a project. - """ - return self.list_selfhosted_credentials(project_id, timeout=timeout, **kwargs) - - async def list_selfhosted_credentials( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ): - """ - List all on-premises distribution credentials for a project. - """ - self._logger.debug("SelfHostedClient.list_selfhosted_credentials ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/selfhosted/distribution/credentials" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - res = await self.get(url, timeout=timeout, **kwargs) - self._logger.verbose("result: %s", res) - self._logger.notice("list_selfhosted_credentials succeeded") - self._logger.debug("SelfHostedClient.list_selfhosted_credentials LEAVE") - return res - - async def get_onprem_credentials( - self, - project_id: str, - distribution_credentials_id: str, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ): - """ - Get a specific on-premises distribution credential for a project. - """ - return self.get_selfhosted_credentials( - project_id, distribution_credentials_id, timeout=timeout, **kwargs - ) - - async def get_selfhosted_credentials( - self, - project_id: str, - distribution_credentials_id: str, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ): - """ - Get a specific on-premises distribution credential for a project. - """ - self._logger.debug("SelfHostedClient.get_selfhosted_credentials ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/selfhosted/distribution/credentials/{distribution_credentials_id}" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info( - "distribution_credentials_id: %s", distribution_credentials_id - ) - res = await self.get(url, timeout=timeout, **kwargs) - self._logger.verbose("result: %s", res) - self._logger.notice("get_selfhosted_credentials succeeded") - self._logger.debug("SelfHostedClient.get_selfhosted_credentials LEAVE") - return res - - async def create_onprem_credentials( - self, - project_id: str, - options, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ): - """ - Create a new on-premises distribution credential for a project. - """ - return self.create_onprem_credentials(project_id, options, timeout, **kwargs) - - async def create_selfhosted_credentials( - self, - project_id: str, - options, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ): - """ - Create a new on-premises distribution credential for a project. - """ - self._logger.debug("SelfHostedClient.create_selfhosted_credentials ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/selfhosted/distribution/credentials/" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("options: %s", options) - res = await self.post(url, json=options, timeout=timeout, **kwargs) - self._logger.verbose("result: %s", res) - self._logger.notice("create_selfhosted_credentials succeeded") - self._logger.debug("SelfHostedClient.create_selfhosted_credentials LEAVE") - return res - - async def delete_onprem_credentials( - self, - project_id: str, - distribution_credentials_id: str, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ): - """ - Delete an on-premises distribution credential for a project. - """ - return self.delete_selfhosted_credentials( - project_id, distribution_credentials_id, timeout=timeout, **kwargs - ) - - async def delete_selfhosted_credentials( - self, - project_id: str, - distribution_credentials_id: str, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ): - """ - Delete an on-premises distribution credential for a project. - """ - self._logger.debug("SelfHostedClient.delete_selfhosted_credentials ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/selfhosted/distribution/credentials/{distribution_credentials_id}" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("distrbution_credentials_id: %s", distribution_credentials_id) - res = await self.delete(url, timeout=timeout, **kwargs) - self._logger.verbose("result: %s", res) - self._logger.notice("delete_selfhosted_credentials succeeded") - self._logger.debug("SelfHostedClient.delete_selfhosted_credentials LEAVE") - return res diff --git a/venv/Lib/site-packages/deepgram/clients/selfhosted/v1/client.py b/venv/Lib/site-packages/deepgram/clients/selfhosted/v1/client.py deleted file mode 100644 index 86d63ff2..00000000 --- a/venv/Lib/site-packages/deepgram/clients/selfhosted/v1/client.py +++ /dev/null @@ -1,172 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -import logging -from typing import Optional - -import httpx - -from ....utils import verboselogs -from ....options import DeepgramClientOptions -from ...common import AbstractSyncRestClient - - -class SelfHostedClient(AbstractSyncRestClient): - """ - Client for interacting with Deepgram's on-premises API. - - This class provides methods to manage and interact with on-premises projects and distribution credentials. - - Args: - config (DeepgramClientOptions): all the options for the client. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - _endpoint: str - - def __init__(self, config: DeepgramClientOptions): - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - self._config = config - self._endpoint = "v1/projects" - super().__init__(config) - - def list_onprem_credentials( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ): - """ - List all on-premises distribution credentials for a project. - """ - return self.list_selfhosted_credentials(project_id, timeout=timeout, **kwargs) - - def list_selfhosted_credentials( - self, - project_id: str, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ): - """ - List all on-premises distribution credentials for a project. - """ - self._logger.debug("SelfHostedClient.list_selfhosted_credentials ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/selfhosted/distribution/credentials" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - res = self.get(url, timeout=timeout, **kwargs) - self._logger.verbose("result: %s", res) - self._logger.notice("list_selfhosted_credentials succeeded") - self._logger.debug("SelfHostedClient.list_selfhosted_credentials LEAVE") - return res - - def get_onprem_credentials( - self, - project_id: str, - distribution_credentials_id: str, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ): - """ - Get a specific on-premises distribution credential for a project. - """ - return self.get_selfhosted_credentials( - project_id, distribution_credentials_id, timeout=timeout, **kwargs - ) - - def get_selfhosted_credentials( - self, - project_id: str, - distribution_credentials_id: str, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ): - """ - Get a specific on-premises distribution credential for a project. - """ - self._logger.debug("SelfHostedClient.get_selfhosted_credentials ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/selfhosted/distribution/credentials/{distribution_credentials_id}" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info( - "distribution_credentials_id: %s", distribution_credentials_id - ) - res = self.get(url, timeout=timeout, **kwargs) - self._logger.verbose("result: %s", res) - self._logger.notice("get_selfhosted_credentials succeeded") - self._logger.debug("SelfHostedClient.get_selfhosted_credentials LEAVE") - return res - - def create_onprem_credentials( - self, - project_id: str, - options, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ): - """ - Create a new on-premises distribution credential for a project. - """ - return self.create_selfhosted_credentials( - project_id, options, timeout=timeout, **kwargs - ) - - def create_selfhosted_credentials( - self, - project_id: str, - options, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ): - """ - Create a new on-premises distribution credential for a project. - """ - self._logger.debug("SelfHostedClient.create_selfhosted_credentials ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/selfhosted/distribution/credentials/" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("options: %s", options) - res = self.post(url, json=options, timeout=timeout, **kwargs) - self._logger.verbose("result: %s", res) - self._logger.notice("create_selfhosted_credentials succeeded") - self._logger.debug("SelfHostedClient.create_selfhosted_credentials LEAVE") - return res - - def delete_onprem_credentials( - self, - project_id: str, - distribution_credentials_id: str, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ): - """ - Delete an on-premises distribution credential for a project. - """ - return self.delete_selfhosted_credentials( - project_id, distribution_credentials_id, timeout=timeout, **kwargs - ) - - def delete_selfhosted_credentials( - self, - project_id: str, - distribution_credentials_id: str, - timeout: Optional[httpx.Timeout] = None, - **kwargs, - ): - """ - Delete an on-premises distribution credential for a project. - """ - self._logger.debug("SelfHostedClient.delete_selfhosted_credentials ENTER") - url = f"{self._config.url}/{self._endpoint}/{project_id}/selfhosted/distribution/credentials/{distribution_credentials_id}" - self._logger.info("url: %s", url) - self._logger.info("project_id: %s", project_id) - self._logger.info("distrbution_credentials_id: %s", distribution_credentials_id) - res = self.delete(url, timeout=timeout, **kwargs) - self._logger.verbose("result: %s", res) - self._logger.notice("delete_selfhosted_credentials succeeded") - self._logger.debug("SelfHostedClient.delete_selfhosted_credentials LEAVE") - return res diff --git a/venv/Lib/site-packages/deepgram/clients/speak/__init__.py b/venv/Lib/site-packages/deepgram/clients/speak/__init__.py deleted file mode 100644 index 874a1739..00000000 --- a/venv/Lib/site-packages/deepgram/clients/speak/__init__.py +++ /dev/null @@ -1,53 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .enums import SpeakWebSocketEvents, SpeakWebSocketMessage - -# rest -from .client import ( - SpeakClient, # backward compat - SpeakRESTClient, - AsyncSpeakRESTClient, -) -from .client import ( - #### top level - SpeakRESTOptions, - SpeakOptions, - # common - TextSource, - BufferSource, - StreamSource, - FileSource, - # unique - SpeakSource, - SpeakRestSource, - SpeakRESTSource, -) -from .client import ( - SpeakResponse, # backward compat - SpeakRESTResponse, -) - -# websocket -from .client import ( - SpeakWSOptions, -) -from .client import ( - SpeakWebSocketClient, - AsyncSpeakWebSocketClient, - SpeakWSClient, - AsyncSpeakWSClient, -) -from .client import ( - #### top level - SpeakWSMetadataResponse, - FlushedResponse, - ClearedResponse, - WarningResponse, - #### shared - OpenResponse, - CloseResponse, - UnhandledResponse, - ErrorResponse, -) diff --git a/venv/Lib/site-packages/deepgram/clients/speak/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/speak/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index 4e6eb981..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/speak/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/speak/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/speak/__pycache__/client.cpython-312.pyc deleted file mode 100644 index d8c5c031..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/speak/__pycache__/client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/speak/__pycache__/enums.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/speak/__pycache__/enums.cpython-312.pyc deleted file mode 100644 index 79d8285b..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/speak/__pycache__/enums.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/speak/client.py b/venv/Lib/site-packages/deepgram/clients/speak/client.py deleted file mode 100644 index 855555c6..00000000 --- a/venv/Lib/site-packages/deepgram/clients/speak/client.py +++ /dev/null @@ -1,95 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -# rest -from .v1 import ( - #### top level - SpeakOptions as SpeakOptionsLatest, - SpeakRESTOptions as SpeakRESTOptionsLatest, - # common - TextSource as TextSourceLatest, - BufferSource as BufferSourceLatest, - StreamSource as StreamSourceLatest, - FileSource as FileSourceLatest, - # unique - SpeakSource as SpeakSourceLatest, - SpeakRestSource as SpeakRestSourceLatest, - SpeakRESTSource as SpeakRESTSourceLatest, -) - -from .v1 import ( - SpeakRESTClient as SpeakRESTClientLatest, - AsyncSpeakRESTClient as AsyncSpeakRESTClientLatest, -) - -from .v1 import ( - SpeakRESTResponse as SpeakRESTResponseLatest, -) - -# websocket -from .v1 import ( - SpeakWebSocketClient as SpeakWebSocketClientLatest, - AsyncSpeakWebSocketClient as AsyncSpeakWebSocketClientLatest, - SpeakWSClient as SpeakWSClientLatest, - AsyncSpeakWSClient as AsyncSpeakWSClientLatest, -) - -from .v1 import ( - SpeakWSOptions as SpeakWSOptionsLatest, -) -from .v1 import ( - OpenResponse as OpenResponseLatest, - SpeakWSMetadataResponse as SpeakWSMetadataResponseLatest, - FlushedResponse as FlushedResponseLatest, - ClearedResponse as ClearedResponseLatest, - CloseResponse as CloseResponseLatest, - UnhandledResponse as UnhandledResponseLatest, - WarningResponse as WarningResponseLatest, - ErrorResponse as ErrorResponseLatest, -) - -# The client.py points to the current supported version in the SDK. -# Older versions are supported in the SDK for backwards compatibility. - -# rest -# input -SpeakOptions = SpeakOptionsLatest -SpeakRESTOptions = SpeakRESTOptionsLatest -TextSource = TextSourceLatest -BufferSource = BufferSourceLatest -StreamSource = StreamSourceLatest -FileSource = FileSourceLatest -SpeakSource = SpeakSourceLatest -SpeakRestSource = SpeakRestSourceLatest -SpeakRESTSource = SpeakRESTSourceLatest # pylint: disable=invalid-name - -# output -SpeakRESTResponse = SpeakRESTResponseLatest - -# websocket -# input -SpeakWSOptions = SpeakWSOptionsLatest - -# output -OpenResponse = OpenResponseLatest -SpeakWSMetadataResponse = SpeakWSMetadataResponseLatest -FlushedResponse = FlushedResponseLatest -ClearedResponse = ClearedResponseLatest -CloseResponse = CloseResponseLatest -UnhandledResponse = UnhandledResponseLatest -WarningResponse = WarningResponseLatest -ErrorResponse = ErrorResponseLatest - - -# backward compatibility -SpeakResponse = SpeakRESTResponseLatest -SpeakClient = SpeakRESTClientLatest - -# clients -SpeakRESTClient = SpeakRESTClientLatest -AsyncSpeakRESTClient = AsyncSpeakRESTClientLatest -SpeakWSClient = SpeakWSClientLatest -AsyncSpeakWSClient = AsyncSpeakWSClientLatest -SpeakWebSocketClient = SpeakWebSocketClientLatest -AsyncSpeakWebSocketClient = AsyncSpeakWebSocketClientLatest diff --git a/venv/Lib/site-packages/deepgram/clients/speak/enums.py b/venv/Lib/site-packages/deepgram/clients/speak/enums.py deleted file mode 100644 index a9d2a5a7..00000000 --- a/venv/Lib/site-packages/deepgram/clients/speak/enums.py +++ /dev/null @@ -1,34 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from aenum import StrEnum - -# Constants mapping to events from the Deepgram API - - -class SpeakWebSocketMessage(StrEnum): - """ - Enumerates the possible message types that can be received from the Deepgram API - """ - - Speak: str = "Speak" - Flush: str = "Flush" - Clear: str = "Clear" - Close: str = "Close" - - -class SpeakWebSocketEvents(StrEnum): - """ - Enumerates the possible events that can be received from the Deepgram API - """ - - Open: str = "Open" - Close: str = "Close" - AudioData: str = "AudioData" - Metadata: str = "Metadata" - Flushed: str = "Flushed" - Cleared: str = "Cleared" - Unhandled: str = "Unhandled" - Error: str = "Error" - Warning: str = "Warning" diff --git a/venv/Lib/site-packages/deepgram/clients/speak/v1/__init__.py b/venv/Lib/site-packages/deepgram/clients/speak/v1/__init__.py deleted file mode 100644 index d878cc5a..00000000 --- a/venv/Lib/site-packages/deepgram/clients/speak/v1/__init__.py +++ /dev/null @@ -1,48 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -# rest -from .rest import ( - #### top level - SpeakRESTOptions, - SpeakOptions, - # common - TextSource, - BufferSource, - StreamSource, - FileSource, - # unique - SpeakSource, - SpeakRestSource, - SpeakRESTSource, -) -from .rest import ( - SpeakRESTOptions, - SpeakOptions, -) -from .rest import SpeakRESTClient, AsyncSpeakRESTClient -from .rest import SpeakRESTResponse - -# websocket -from .websocket import ( - SpeakWSOptions, -) -from .websocket import ( - SpeakWebSocketClient, - AsyncSpeakWebSocketClient, - SpeakWSClient, - AsyncSpeakWSClient, -) -from .websocket import ( - #### top level - MetadataResponse as SpeakWSMetadataResponse, - FlushedResponse, - ClearedResponse, - WarningResponse, - #### shared - OpenResponse, - CloseResponse, - UnhandledResponse, - ErrorResponse, -) diff --git a/venv/Lib/site-packages/deepgram/clients/speak/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/speak/v1/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index 2c903b1b..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/speak/v1/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/__init__.py b/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/__init__.py deleted file mode 100644 index 084cef64..00000000 --- a/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .client import SpeakRESTClient -from .async_client import AsyncSpeakRESTClient -from .response import SpeakRESTResponse -from .options import ( - #### top level - SpeakRESTOptions, - SpeakOptions, - # common - TextSource, - BufferSource, - StreamSource, - FileSource, - # unique - SpeakSource, - SpeakRestSource, - SpeakRESTSource, -) diff --git a/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index 4fe7bcbe..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/__pycache__/async_client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/__pycache__/async_client.cpython-312.pyc deleted file mode 100644 index 1aa4fa35..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/__pycache__/async_client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/__pycache__/client.cpython-312.pyc deleted file mode 100644 index f5d68a9b..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/__pycache__/client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/__pycache__/helpers.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/__pycache__/helpers.cpython-312.pyc deleted file mode 100644 index fc81afc3..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/__pycache__/helpers.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/__pycache__/options.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/__pycache__/options.cpython-312.pyc deleted file mode 100644 index 6c58366f..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/__pycache__/options.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/__pycache__/response.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/__pycache__/response.cpython-312.pyc deleted file mode 100644 index 103cac97..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/__pycache__/response.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/async_client.py b/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/async_client.py deleted file mode 100644 index fc83926b..00000000 --- a/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/async_client.py +++ /dev/null @@ -1,309 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -import logging -from typing import Dict, Union, Optional, cast -import io -import aiofiles - -import httpx - -import deprecation # type: ignore -from ..... import __version__ - -from .....utils import verboselogs -from .....options import DeepgramClientOptions -from ....common import AbstractAsyncRestClient -from ....common import DeepgramError, DeepgramTypeError - -from .helpers import is_text_source -from .options import SpeakRESTOptions, FileSource -from .response import SpeakRESTResponse - - -class AsyncSpeakRESTClient(AbstractAsyncRestClient): - """ - A client class for doing Text-to-Speech. - Provides methods for speaking from text. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - - def __init__(self, config: DeepgramClientOptions): - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - self._config = config - super().__init__(config) - - # pylint: disable=too-many-positional-arguments - - async def stream_raw( - self, - source: FileSource, - options: Optional[Union[Dict, SpeakRESTOptions]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/speak", - **kwargs, - ) -> httpx.Response: - """ - Speak from a text source and store as a Iterator[byte]. - - Args: - source (TextSource): The text source to speak. - options (SpeakRESTOptions): Additional options for the ingest (default is None). - addons (Dict): Additional options for the request (default is None). - headers (Dict): Additional headers for the request (default is None). - timeout (httpx.Timeout): The timeout for the request (default is None). - endpoint (str): The endpoint to use for the request (default is "v1/speak"). - - Returns: - httpx.Response: The direct httpx.Response object from the speak request. - For more information, see https://www.python-httpx.org/api/#response - - IMPORTANT: The response object's `close()` method should be called when done - in order to prevent connection leaks. - - Raises: - DeepgramTypeError: Raised for known API errors. - """ - self._logger.debug("AsyncSpeakClient.stream ENTER") - - url = f"{self._config.url}/{endpoint}" - if is_text_source(source): - body = source - else: - self._logger.error("Unknown speak source type") - self._logger.debug("AsyncSpeakClient.stream LEAVE") - raise DeepgramTypeError("Unknown speak source type") - - if isinstance(options, SpeakRESTOptions) and not options.check(): - self._logger.error("options.check failed") - self._logger.debug("AsyncSpeakClient.stream LEAVE") - raise DeepgramError("Fatal speak options error") - - self._logger.info("url: %s", url) - self._logger.info("source: %s", source) - if isinstance(options, SpeakRESTOptions): - self._logger.info("SpeakRESTOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - - result = await self.post_raw( - url, - options=options, - addons=addons, - headers=headers, - json=body, - timeout=timeout, - **kwargs, - ) - - self._logger.info("result: %s", str(result)) - self._logger.notice("speak succeeded") - self._logger.debug("AsyncSpeakClient.stream LEAVE") - return result - - async def stream_memory( - self, - source: FileSource, - options: Optional[Union[Dict, SpeakRESTOptions]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/speak", - **kwargs, - ) -> SpeakRESTResponse: - """ - Speak from a text source and store in memory. - - Args: - source (TextSource): The text source to speak. - options (SpeakRESTOptions): Additional options for the ingest (default is None). - addons (Dict): Additional options for the request (default is None). - headers (Dict): Additional headers for the request (default is None). - timeout (httpx.Timeout): The timeout for the request (default is None). - endpoint (str): The endpoint to use for the request (default is "v1/speak"). - - Returns: - SpeakRESTResponse: The response from the speak request. - - Raises: - DeepgramTypeError: Raised for known API errors. - """ - self._logger.debug("AsyncSpeakClient.stream ENTER") - - url = f"{self._config.url}/{endpoint}" - if is_text_source(source): - body = source - else: - self._logger.error("Unknown speak source type") - self._logger.debug("AsyncSpeakClient.stream LEAVE") - raise DeepgramTypeError("Unknown speak source type") - - if isinstance(options, SpeakRESTOptions) and not options.check(): - self._logger.error("options.check failed") - self._logger.debug("AsyncSpeakClient.stream LEAVE") - raise DeepgramError("Fatal speak options error") - - self._logger.info("url: %s", url) - self._logger.info("source: %s", source) - if isinstance(options, SpeakRESTOptions): - self._logger.info("SpeakRESTOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - - return_vals = [ - "content-type", - "request-id", - "model-uuid", - "model-name", - "char-count", - "transfer-encoding", - "date", - ] - result = await self.post_memory( - url, - options=options, - addons=addons, - headers=headers, - json=body, - timeout=timeout, - file_result=return_vals, - **kwargs, - ) - self._logger.info("result: %s", result) - resp = SpeakRESTResponse( - content_type=str(result["content-type"]), - request_id=str(result["request-id"]), - model_uuid=str(result["model-uuid"]), - model_name=str(result["model-name"]), - characters=int(str(result["char-count"])), - transfer_encoding=str(result["transfer-encoding"]), - date=str(result["date"]), - stream=cast(io.BytesIO, result["stream"]), - stream_memory=cast(io.BytesIO, result["stream"]), - ) - self._logger.verbose("resp Object: %s", str(resp)) - self._logger.notice("speak succeeded") - self._logger.debug("AsyncSpeakClient.stream LEAVE") - return resp - - @deprecation.deprecated( - deprecated_in="3.4.0", - removed_in="4.0.0", - current_version=__version__, - details="SpeakRESTClient.stream is deprecated. Use SpeakRESTClient.stream_memory instead.", - ) - async def stream( - self, - source: FileSource, - options: Optional[Union[Dict, SpeakRESTOptions]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/speak", - **kwargs, - ) -> SpeakRESTResponse: - """ - DEPRECATED: stream() is deprecated. Use stream_memory() instead. - """ - return await self.stream_memory( - source, - options=options, - addons=addons, - headers=headers, - timeout=timeout, - endpoint=endpoint, - **kwargs, - ) - - async def file( - self, - filename: str, - source: FileSource, - options: Optional[Union[Dict, SpeakRESTOptions]] = None, - addons: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/speak", - **kwargs, - ) -> SpeakRESTResponse: - """ - Speak from a text source and save to a file. - """ - return await self.save( - filename, - source, - options=options, - addons=addons, - timeout=timeout, - endpoint=endpoint, - **kwargs, - ) - - async def save( - self, - filename: str, - source: FileSource, - options: Optional[Union[Dict, SpeakRESTOptions]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/speak", - **kwargs, - ) -> SpeakRESTResponse: - """ - Speak from a text source and save to a file. - - Args: - source (TextSource): The text source to speak. - options (SpeakRESTOptions): Additional options for the ingest (default is None). - addons (Dict): Additional options for the request (default is None). - headers (Dict): Additional headers for the request (default is None). - timeout (httpx.Timeout): The timeout for the request (default is None). - endpoint (str): The endpoint to use for the request (default is "v1/speak"). - - Returns: - SpeakRESTResponse: The response from the speak request. - - Raises: - DeepgramTypeError: Raised for known API errors. - """ - self._logger.debug("AsyncSpeakClient.save ENTER") - - res = await self.stream_memory( - source, - options=options, - addons=addons, - headers=headers, - timeout=timeout, - endpoint=endpoint, - **kwargs, - ) - - if res.stream is None: - self._logger.error("stream is None") - self._logger.debug("AsyncSpeakClient.save LEAVE") - raise DeepgramError("BytesIO stream is None") - - # save to file - async with aiofiles.open(filename, "wb") as out: - await out.write(res.stream.getbuffer()) - await out.flush() - - # add filename to response - res.stream = None - res.filename = filename - - self._logger.debug("AsyncSpeakClient.save LEAVE") - return res - - # pylint: enable=too-many-positional-arguments diff --git a/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/client.py b/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/client.py deleted file mode 100644 index e17877e4..00000000 --- a/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/client.py +++ /dev/null @@ -1,309 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -import logging -from typing import Dict, Union, Optional, cast -import io - -import httpx - -import deprecation # type: ignore -from ..... import __version__ - -from .....utils import verboselogs -from .....options import DeepgramClientOptions -from ....common import AbstractSyncRestClient -from ....common import DeepgramError, DeepgramTypeError -from .helpers import is_text_source - -from .options import SpeakRESTOptions, FileSource -from .response import SpeakRESTResponse - - -class SpeakRESTClient(AbstractSyncRestClient): - """ - A client class for doing Text-to-Speech. - Provides methods for speaking from text. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - - def __init__(self, config: DeepgramClientOptions): - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - self._config = config - super().__init__(config) - - # pylint: disable=too-many-positional-arguments - - def stream_raw( - self, - source: FileSource, - options: Optional[Union[Dict, SpeakRESTOptions]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/speak", - **kwargs, - ) -> httpx.Response: - """ - Speak from a text source and store as a Iterator[byte]. - - Args: - source (TextSource): The text source to speak. - options (SpeakRESTOptions): Additional options for the ingest (default is None). - addons (Dict): Additional options for the request (default is None). - headers (Dict): Additional headers for the request (default is None). - timeout (httpx.Timeout): The timeout for the request (default is None). - endpoint (str): The endpoint to use for the request (default is "v1/speak"). - - Returns: - httpx.Response: The direct httpx.Response object from the speak request. - For more information, see https://www.python-httpx.org/api/#response - - IMPORTANT: The response object's `close()` method should be called when done - in order to prevent connection leaks. - - Raises: - DeepgramTypeError: Raised for known API errors. - """ - self._logger.debug("SpeakClient.stream ENTER") - - url = f"{self._config.url}/{endpoint}" - if is_text_source(source): - body = source - else: - self._logger.error("Unknown speak source type") - self._logger.debug("SpeakClient.stream LEAVE") - raise DeepgramTypeError("Unknown speak source type") - - if isinstance(options, SpeakRESTOptions) and not options.check(): - self._logger.error("options.check failed") - self._logger.debug("SpeakClient.stream LEAVE") - raise DeepgramError("Fatal speak options error") - - self._logger.info("url: %s", url) - self._logger.info("source: %s", source) - if isinstance(options, SpeakRESTOptions): - self._logger.info("SpeakRESTOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - - result = self.post_raw( - url, - options=options, - addons=addons, - headers=headers, - json=body, - timeout=timeout, - **kwargs, - ) - - self._logger.info("result: %s", str(result)) - self._logger.notice("speak succeeded") - self._logger.debug("SpeakClient.stream LEAVE") - return result - - def stream_memory( - self, - source: FileSource, - options: Optional[Union[Dict, SpeakRESTOptions]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/speak", - **kwargs, - ) -> SpeakRESTResponse: - """ - Speak from a text source and store in memory. - - Args: - source (TextSource): The text source to speak. - options (SpeakRESTOptions): Additional options for the ingest (default is None). - addons (Dict): Additional options for the request (default is None). - headers (Dict): Additional headers for the request (default is None). - timeout (httpx.Timeout): The timeout for the request (default is None). - endpoint (str): The endpoint to use for the request (default is "v1/speak"). - - Returns: - SpeakRESTResponse: The response from the speak request. - - Raises: - DeepgramTypeError: Raised for known API errors. - """ - self._logger.debug("SpeakClient.stream ENTER") - - url = f"{self._config.url}/{endpoint}" - if is_text_source(source): - body = source - else: - self._logger.error("Unknown speak source type") - self._logger.debug("SpeakClient.stream LEAVE") - raise DeepgramTypeError("Unknown speak source type") - - if isinstance(options, SpeakRESTOptions) and not options.check(): - self._logger.error("options.check failed") - self._logger.debug("SpeakClient.stream LEAVE") - raise DeepgramError("Fatal speak options error") - - self._logger.info("url: %s", url) - self._logger.info("source: %s", source) - if isinstance(options, SpeakRESTOptions): - self._logger.info("SpeakRESTOptions switching class -> dict") - options = options.to_dict() - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - - return_vals = [ - "content-type", - "request-id", - "model-uuid", - "model-name", - "char-count", - "transfer-encoding", - "date", - ] - result = self.post_memory( - url, - options=options, - addons=addons, - headers=headers, - json=body, - timeout=timeout, - file_result=return_vals, - **kwargs, - ) - - self._logger.info("result: %s", result) - resp = SpeakRESTResponse( - content_type=str(result["content-type"]), - request_id=str(result["request-id"]), - model_uuid=str(result["model-uuid"]), - model_name=str(result["model-name"]), - characters=int(str(result["char-count"])), - transfer_encoding=str(result["transfer-encoding"]), - date=str(result["date"]), - stream=cast(io.BytesIO, result["stream"]), - stream_memory=cast(io.BytesIO, result["stream"]), - ) - self._logger.verbose("resp Object: %s", resp) - self._logger.notice("speak succeeded") - self._logger.debug("SpeakClient.stream LEAVE") - return resp - - @deprecation.deprecated( - deprecated_in="3.4.0", - removed_in="4.0.0", - current_version=__version__, - details="SpeakRESTClient.stream is deprecated. Use SpeakRESTClient.stream_memory instead.", - ) - def stream( - self, - source: FileSource, - options: Optional[Union[Dict, SpeakRESTOptions]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/speak", - **kwargs, - ) -> SpeakRESTResponse: - """ - DEPRECATED: stream() is deprecated. Use stream_memory() instead. - """ - return self.stream_memory( - source, - options=options, - addons=addons, - headers=headers, - timeout=timeout, - endpoint=endpoint, - **kwargs, - ) - - async def file( - self, - filename: str, - source: FileSource, - options: Optional[Union[Dict, SpeakRESTOptions]] = None, - addons: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/speak", - **kwargs, - ) -> SpeakRESTResponse: - """ - Speak from a text source and save to a file. - """ - return self.save( - filename, - source, - options=options, - addons=addons, - timeout=timeout, - endpoint=endpoint, - **kwargs, - ) - - def save( - self, - filename: str, - source: FileSource, - options: Optional[Union[Dict, SpeakRESTOptions]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - timeout: Optional[httpx.Timeout] = None, - endpoint: str = "v1/speak", - **kwargs, - ) -> SpeakRESTResponse: - """ - Speak from a text source and save to a file. - - Args: - source (TextSource): The text source to speak. - options (SpeakRESTOptions): Additional options for the ingest (default is None). - addons (Dict): Additional options for the request (default is None). - headers (Dict): Additional headers for the request (default is None). - timeout (httpx.Timeout): The timeout for the request (default is None). - endpoint (str): The endpoint to use for the request (default is "v1/speak"). - - Returns: - SpeakRESTResponse: The response from the speak request. - - Raises: - DeepgramTypeError: Raised for known API errors. - """ - self._logger.debug("SpeakClient.save ENTER") - - res = self.stream_memory( - source, - options=options, - addons=addons, - headers=headers, - timeout=timeout, - endpoint=endpoint, - **kwargs, - ) - - if res.stream is None: - self._logger.error("stream is None") - self._logger.debug("SpeakClient.save LEAVE") - raise DeepgramError("BytesIO stream is None") - - # save to file - with open(filename, "wb+") as file: - file.write(res.stream.getbuffer()) - file.flush() - - # add filename to response - res.stream = None - res.filename = filename - - self._logger.debug("SpeakClient.save LEAVE") - return res - - # pylint: enable=too-many-positional-arguments diff --git a/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/helpers.py b/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/helpers.py deleted file mode 100644 index 3232c1e7..00000000 --- a/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/helpers.py +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .options import SpeakSource - - -def is_text_source(provided_source: SpeakSource) -> bool: - """ - Check if the provided source is a text source. - """ - return "text" in provided_source - - -def is_readstream_source(provided_source: SpeakSource) -> bool: - """ - Check if the provided source is a readstream source. - """ - return "stream" in provided_source diff --git a/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/options.py b/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/options.py deleted file mode 100644 index 9740abde..00000000 --- a/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/options.py +++ /dev/null @@ -1,64 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from io import BufferedReader -from typing import Union, Optional -import logging - -from dataclasses import dataclass, field -from dataclasses_json import config as dataclass_config - -from .....utils import verboselogs -from ....common import TextSource, BufferSource, StreamSource, FileSource, BaseResponse - - -@dataclass -class SpeakRESTOptions(BaseResponse): - """ - Contains all the options for the SpeakOptions. - - Reference: - https://developers.deepgram.com/reference/text-to-speech-api - """ - - model: Optional[str] = field( - default="aura-2-thalia-en", - metadata=dataclass_config(exclude=lambda f: f is None), - ) - encoding: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - container: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - sample_rate: Optional[int] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - bit_rate: Optional[int] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def check(self): - """ - Check the SpeakOptions for any missing or invalid values. - """ - logger = verboselogs.VerboseLogger(__name__) - logger.addHandler(logging.StreamHandler()) - prev = logger.level - logger.setLevel(verboselogs.ERROR) - - # no op at the moment - - logger.setLevel(prev) - - return True - - -SpeakOptions = SpeakRESTOptions - - -# unqiue -SpeakSource = Union[FileSource, BufferedReader] -SpeakRestSource = SpeakSource -SpeakRESTSource = SpeakSource # pylint: disable=invalid-name diff --git a/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/response.py b/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/response.py deleted file mode 100644 index 30801e30..00000000 --- a/venv/Lib/site-packages/deepgram/clients/speak/v1/rest/response.py +++ /dev/null @@ -1,45 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from typing import Optional, Dict, Any -import io - -from dataclasses import dataclass, field -from dataclasses_json import config as dataclass_config - -from ....common import ( - BaseResponse, -) - - -# Speak Response Types: - - -@dataclass -class SpeakRESTResponse(BaseResponse): # pylint: disable=too-many-instance-attributes - """ - A class for representing a response from the speak endpoint. - """ - - content_type: str = "" - request_id: str = "" - model_uuid: str = "" - model_name: str = "" - characters: int = 0 - transfer_encoding: str = "" - date: str = "" - filename: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - # pylint: disable=W0511 - # TODO: stream will be deprecated in a future release. Please use stream_memory instead. - stream: Optional[io.BytesIO] = field( - default=None, - metadata=dataclass_config(exclude=lambda f: True), - ) - # pylint: enable=W0511 - stream_memory: Optional[io.BytesIO] = field( - default=None, - metadata=dataclass_config(exclude=lambda f: True), - ) diff --git a/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/__init__.py b/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/__init__.py deleted file mode 100644 index 5245b934..00000000 --- a/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from .client import SpeakWebSocketClient, SpeakWSClient -from .async_client import AsyncSpeakWebSocketClient, AsyncSpeakWSClient -from .response import ( - #### top level - MetadataResponse, - FlushedResponse, - ClearedResponse, - WarningResponse, - #### shared - OpenResponse, - CloseResponse, - UnhandledResponse, - ErrorResponse, -) -from .options import SpeakWSOptions diff --git a/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index 4b841c7a..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/__pycache__/async_client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/__pycache__/async_client.cpython-312.pyc deleted file mode 100644 index a1cb7103..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/__pycache__/async_client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/__pycache__/client.cpython-312.pyc deleted file mode 100644 index f57051bf..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/__pycache__/client.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/__pycache__/options.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/__pycache__/options.cpython-312.pyc deleted file mode 100644 index f8dc1043..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/__pycache__/options.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/__pycache__/response.cpython-312.pyc b/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/__pycache__/response.cpython-312.pyc deleted file mode 100644 index 5408315d..00000000 Binary files a/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/__pycache__/response.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/async_client.py b/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/async_client.py deleted file mode 100644 index c69debcf..00000000 --- a/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/async_client.py +++ /dev/null @@ -1,706 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -import asyncio -import json -import logging -from typing import Dict, Union, Optional, cast, Any, Callable -from datetime import datetime -import threading - -from .....utils import verboselogs -from .....options import DeepgramClientOptions -from ...enums import SpeakWebSocketEvents, SpeakWebSocketMessage -from ....common import AbstractAsyncWebSocketClient -from ....common import DeepgramError - -from .response import ( - OpenResponse, - MetadataResponse, - FlushedResponse, - ClearedResponse, - CloseResponse, - WarningResponse, - ErrorResponse, - UnhandledResponse, -) -from .options import SpeakWSOptions - -from .....audio.microphone import Microphone -from .....audio.speaker import Speaker, RATE, CHANNELS, PLAYBACK_DELTA - -ONE_SECOND = 1 -HALF_SECOND = 0.5 -DEEPGRAM_INTERVAL = 5 -PING_INTERVAL = 20 - - -class AsyncSpeakWSClient( - AbstractAsyncWebSocketClient -): # pylint: disable=too-many-instance-attributes - """ - Client for interacting with Deepgram's text-to-speech services over WebSockets. - - This class provides methods to establish a WebSocket connection for TTS synthesis and handle real-time TTS synthesis events. - - Args: - config (DeepgramClientOptions): all the options for the client. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - _endpoint: str - - _event_handlers: Dict[SpeakWebSocketEvents, list] - - _flush_thread: Union[asyncio.Task, None] - _last_datagram: Optional[datetime] = None - _flush_count: int - - _kwargs: Optional[Dict] = None - _addons: Optional[Dict] = None - _options: Optional[Dict] = None - _headers: Optional[Dict] = None - - _speaker_created: bool = False - _speaker: Optional[Speaker] = None - _microphone: Optional[Microphone] = None - - def __init__( - self, config: DeepgramClientOptions, microphone: Optional[Microphone] = None - ): - if config is None: - raise DeepgramError("Config is required") - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - - self._config = config - self._endpoint = "v1/speak" - - self._flush_thread = None - - # auto flush - self._last_datagram = None - self._flush_count = 0 - - # microphone - self._microphone = microphone - - # init handlers - self._event_handlers = { - event: [] for event in SpeakWebSocketEvents.__members__.values() - } - - if self._config.options.get("speaker_playback") == "true": - self._logger.info("speaker_playback is enabled") - rate = self._config.options.get("speaker_playback_rate") - if rate is None: - rate = RATE - channels = self._config.options.get("speaker_playback_channels") - if channels is None: - channels = CHANNELS - playback_delta_in_ms = self._config.options.get( - "speaker_playback_delta_in_ms" - ) - if playback_delta_in_ms is None: - playback_delta_in_ms = PLAYBACK_DELTA - device_index = self._config.options.get("speaker_playback_device_index") - - self._logger.debug("rate: %s", rate) - self._logger.debug("channels: %s", channels) - self._logger.debug("device_index: %s", device_index) - - self._speaker_created = True - - if device_index is not None: - self._speaker = Speaker( - rate=rate, - channels=channels, - last_play_delta_in_ms=playback_delta_in_ms, - verbose=self._config.verbose, - output_device_index=device_index, - microphone=self._microphone, - ) - else: - self._speaker = Speaker( - rate=rate, - channels=channels, - last_play_delta_in_ms=playback_delta_in_ms, - verbose=self._config.verbose, - microphone=self._microphone, - ) - - # call the parent constructor - super().__init__(self._config, self._endpoint) - - # pylint: disable=too-many-branches,too-many-statements - async def start( - self, - options: Optional[Union[SpeakWSOptions, Dict]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - members: Optional[Dict] = None, - **kwargs, - ) -> bool: - """ - Starts the WebSocket connection for text-to-speech synthesis. - """ - self._logger.debug("AsyncSpeakWebSocketClient.start ENTER") - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - self._logger.info("members: %s", members) - self._logger.info("kwargs: %s", kwargs) - - if isinstance(options, SpeakWSOptions) and not options.check(): - self._logger.error("options.check failed") - self._logger.debug("AsyncSpeakWebSocketClient.start LEAVE") - raise DeepgramError("Fatal text-to-speech options error") - - self._addons = addons - self._headers = headers - - # add "members" as members of the class - if members is not None: - self.__dict__.update(members) - - # set kwargs as members of the class - if kwargs is not None: - self._kwargs = kwargs - else: - self._kwargs = {} - - if isinstance(options, SpeakWSOptions): - self._logger.info("SpeakWSOptions switching class -> dict") - self._options = options.to_dict() - elif options is not None: - self._options = options - else: - self._options = {} - - try: - # speaker substitutes the listening thread - if self._speaker is not None: - self._logger.notice("passing speaker to delegate_listening") - super().delegate_listening(self._speaker) - - # call parent start - if ( - await super().start( - self._options, - self._addons, - self._headers, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - is False - ): - self._logger.error("AsyncSpeakWebSocketClient.start failed") - self._logger.debug("AsyncSpeakWebSocketClient.start LEAVE") - return False - - if self._speaker is not None: - self._logger.notice("start delegate_listening thread") - self._speaker.start() - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - # flush thread - if self._config.is_auto_flush_speak_enabled(): - self._logger.notice("autoflush is enabled") - self._flush_thread = asyncio.create_task(self._flush()) - else: - self._logger.notice("autoflush is disabled") - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - self._logger.notice("start succeeded") - self._logger.debug("AsyncSpeakWebSocketClient.start LEAVE") - return True - - except Exception as e: # pylint: disable=broad-except - self._logger.error( - "WebSocketException in AsyncSpeakWebSocketClient.start: %s", e - ) - self._logger.debug("AsyncSpeakWebSocketClient.start LEAVE") - if self._config.options.get("termination_exception_connect") is True: - raise - return False - - # pylint: enable=too-many-branches,too-many-statements - - def on(self, event: SpeakWebSocketEvents, handler: Callable) -> None: - """ - Registers event handlers for specific events. - """ - self._logger.info("event subscribed: %s", event) - if event in SpeakWebSocketEvents.__members__.values() and callable(handler): - self._event_handlers[event].append(handler) - - # triggers the registered event handlers for a specific event - async def _emit(self, event: SpeakWebSocketEvents, *args, **kwargs) -> None: - """ - Emits events to the registered event handlers. - """ - self._logger.debug("AsyncSpeakWebSocketClient._emit ENTER") - self._logger.debug("callback handlers for: %s", event) - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - tasks = [] - for handler in self._event_handlers[event]: - task = asyncio.create_task(handler(self, *args, **kwargs)) - tasks.append(task) - - if tasks: - self._logger.debug("waiting for tasks to finish...") - await asyncio.gather(*filter(None, tasks), return_exceptions=True) - tasks.clear() - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - self._logger.debug("AsyncSpeakWebSocketClient._emit LEAVE") - - async def _process_text(self, message: Union[str, bytes]) -> None: - """ - Processes messages received over the WebSocket connection. - """ - self._logger.debug("AsyncSpeakWebSocketClient._process_text ENTER") - - try: - self._logger.debug("Text data received") - - if len(message) == 0: - self._logger.debug("message is empty") - self._logger.debug("AsyncSpeakWebSocketClient._process_text LEAVE") - return - - data = json.loads(message) - response_type = data.get("type") - self._logger.debug("response_type: %s, data: %s", response_type, data) - - match response_type: - case SpeakWebSocketEvents.Open: - open_result: OpenResponse = OpenResponse.from_json(message) - self._logger.verbose("OpenResponse: %s", open_result) - await self._emit( - SpeakWebSocketEvents(SpeakWebSocketEvents.Open), - open=open_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case SpeakWebSocketEvents.Metadata: - meta_result: MetadataResponse = MetadataResponse.from_json(message) - self._logger.verbose("MetadataResponse: %s", meta_result) - await self._emit( - SpeakWebSocketEvents(SpeakWebSocketEvents.Metadata), - metadata=meta_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case SpeakWebSocketEvents.Flushed: - fl_result: FlushedResponse = FlushedResponse.from_json(message) - self._logger.verbose("FlushedResponse: %s", fl_result) - - # auto flush - if self._config.is_inspecting_speak(): - self._flush_count -= 1 - self._logger.debug( - "Decrement AutoFlush count: %d", - self._flush_count, - ) - - await self._emit( - SpeakWebSocketEvents(SpeakWebSocketEvents.Flushed), - flushed=fl_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case SpeakWebSocketEvents.Cleared: - clear_result: ClearedResponse = ClearedResponse.from_json(message) - self._logger.verbose("ClearedResponse: %s", clear_result) - await self._emit( - SpeakWebSocketEvents(SpeakWebSocketEvents.Cleared), - cleared=clear_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case SpeakWebSocketEvents.Close: - close_result: CloseResponse = CloseResponse.from_json(message) - self._logger.verbose("CloseResponse: %s", close_result) - await self._emit( - SpeakWebSocketEvents(SpeakWebSocketEvents.Close), - close=close_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case SpeakWebSocketEvents.Warning: - war_warning: WarningResponse = WarningResponse.from_json(message) - self._logger.verbose("WarningResponse: %s", war_warning) - await self._emit( - SpeakWebSocketEvents(SpeakWebSocketEvents.Warning), - warning=war_warning, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case SpeakWebSocketEvents.Error: - err_error: ErrorResponse = ErrorResponse.from_json(message) - self._logger.verbose("ErrorResponse: %s", err_error) - await self._emit( - SpeakWebSocketEvents(SpeakWebSocketEvents.Error), - error=err_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case _: - self._logger.warning( - "Unknown Message: response_type: %s, data: %s", - response_type, - data, - ) - unhandled_error: UnhandledResponse = UnhandledResponse( - type=SpeakWebSocketEvents(SpeakWebSocketEvents.Unhandled), - raw=str(message), - ) - await self._emit( - SpeakWebSocketEvents(SpeakWebSocketEvents.Unhandled), - unhandled=unhandled_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - self._logger.notice("_process_text Succeeded") - self._logger.debug("AsyncSpeakWebSocketClient._process_text LEAVE") - - except Exception as e: # pylint: disable=broad-except - self._logger.error( - "Exception in AsyncSpeakWebSocketClient._process_text: %s", e - ) - e_error: ErrorResponse = ErrorResponse( - "Exception in AsyncSpeakWebSocketClient._process_text", - f"{e}", - "Exception", - ) - await self._emit( - SpeakWebSocketEvents(SpeakWebSocketEvents.Error), - error=e_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - # signal exit and close - await super()._signal_exit() - - self._logger.debug("AsyncSpeakWebSocketClient._process_text LEAVE") - - if self._config.options.get("termination_exception") is True: - raise - return - - # pylint: enable=too-many-return-statements,too-many-statements - - async def _process_binary(self, message: bytes) -> None: - self._logger.debug("SpeakWebSocketClient._process_binary ENTER") - self._logger.debug("Binary data received") - - await self._emit( - SpeakWebSocketEvents(SpeakWebSocketEvents.AudioData), - data=message, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - self._logger.notice("_process_binary Succeeded") - self._logger.debug("SpeakWebSocketClient._process_binary LEAVE") - - ## pylint: disable=too-many-return-statements - async def _flush(self) -> None: - self._logger.debug("AsyncSpeakWebSocketClient._flush ENTER") - - delta_in_ms_str = self._config.options.get("auto_flush_speak_delta") - if delta_in_ms_str is None: - self._logger.error("auto_flush_speak_delta is None") - self._logger.debug("AsyncSpeakWebSocketClient._flush LEAVE") - return - delta_in_ms = float(delta_in_ms_str) - - while True: - try: - await asyncio.sleep(HALF_SECOND) - - if self._exit_event.is_set(): - self._logger.notice("_flush exiting gracefully") - self._logger.debug("AsyncSpeakWebSocketClient._flush LEAVE") - return - - if self._last_datagram is None: - self._logger.debug("AutoFlush last_datagram is None") - continue - - delta = datetime.now() - self._last_datagram - diff_in_ms = delta.total_seconds() * 1000 - self._logger.debug("AutoFlush delta: %f", diff_in_ms) - if diff_in_ms < delta_in_ms: - self._logger.debug("AutoFlush delta is less than threshold") - continue - - await self.flush() - - except Exception as e: # pylint: disable=broad-except - self._logger.error( - "Exception in AsyncSpeakWebSocketClient._flush: %s", e - ) - e_error: ErrorResponse = ErrorResponse( - "Exception in AsyncSpeakWebSocketClient._flush", - f"{e}", - "Exception", - ) - self._logger.error( - "Exception in AsyncSpeakWebSocketClient._flush: %s", str(e) - ) - await self._emit( - SpeakWebSocketEvents(SpeakWebSocketEvents.Error), - error=e_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - # signal exit and close - await super()._signal_exit() - - self._logger.debug("AsyncSpeakWebSocketClient._flush LEAVE") - - if self._config.options.get("termination_exception") is True: - raise - return - - # pylint: enable=too-many-return-statements - - async def send_text(self, text_input: str) -> bool: - """ - Sends text to the WebSocket connection to generate audio. - - Args: - text_input (str): The raw text to be synthesized. This function will automatically wrap - the text in a JSON object of type "Speak" with the key "text". - - Returns: - bool: True if the text was successfully sent, False otherwise. - """ - return await self.send_raw(json.dumps({"type": "Speak", "text": text_input})) - - async def send(self, data: Union[bytes, str]) -> bool: - """ - Alias for send_text. Please see send_text for more information. - """ - if isinstance(data, bytes): - self._logger.error("send() failed - data is bytes") - return False - - return await self.send_text(data) - - # pylint: disable=unused-argument - async def send_control( - self, msg_type: Union[SpeakWebSocketMessage, str], data: Optional[str] = "" - ) -> bool: - """ - Sends a control message consisting of type SpeakWebSocketEvents over the WebSocket connection. - - Args: - msg_type (SpeakWebSocketEvents): The type of control message to send. - (Optional) data (str): The data to send with the control message. - - Returns: - bool: True if the control message was successfully sent, False otherwise. - """ - control_msg = json.dumps({"type": msg_type}) - return await self.send_raw(control_msg) - - # pylint: enable=unused-argument - - # pylint: disable=too-many-return-statements,too-many-branches,too-many-statements - async def send_raw(self, msg: str) -> bool: - """ - Sends a raw/control message over the WebSocket connection. This message must contain a valid JSON object. - - Args: - msg (str): The raw message to send over the WebSocket connection. - - Returns: - bool: True if the message was successfully sent, False otherwise. - """ - self._logger.spam("AsyncSpeakWebSocketClient.send_raw ENTER") - - if self._config.is_inspecting_speak(): - try: - _tmp_json = json.loads(msg) - if "type" in _tmp_json: - self._logger.debug( - "Inspecting Message: Sending %s", _tmp_json["type"] - ) - match _tmp_json["type"]: - case SpeakWebSocketMessage.Speak: - inspect_res = await self._inspect() - if not inspect_res: - self._logger.error("inspect_res failed") - case SpeakWebSocketMessage.Flush: - self._last_datagram = None - self._flush_count += 1 - self._logger.debug( - "Increment Flush count: %d", self._flush_count - ) - except Exception as e: # pylint: disable=broad-except - self._logger.error("send_raw() failed - Exception: %s", str(e)) - - try: - if await super().send(msg) is False: - self._logger.error("send_raw() failed") - self._logger.spam("AsyncSpeakWebSocketClient.send_raw LEAVE") - return False - self._logger.spam("send_raw() succeeded") - self._logger.spam("AsyncSpeakWebSocketClient.send_raw LEAVE") - return True - except Exception as e: # pylint: disable=broad-except - self._logger.error("send_raw() failed - Exception: %s", str(e)) - self._logger.spam("AsyncSpeakWebSocketClient.send_raw LEAVE") - if self._config.options.get("termination_exception_send") is True: - raise - return False - - # pylint: enable=too-many-return-statements,too-many-branches - - async def flush(self) -> bool: - """ - Flushes the current buffer and returns generated audio - """ - self._logger.spam("AsyncSpeakWebSocketClient.flush ENTER") - - self._logger.notice("Sending Flush...") - ret = await self.send_control(SpeakWebSocketMessage.Flush) - - if not ret: - self._logger.error("flush failed") - self._logger.spam("AsyncSpeakWebSocketClient.flush LEAVE") - return False - - self._logger.notice("flush succeeded") - self._logger.spam("AsyncSpeakWebSocketClient.flush LEAVE") - - return True - - async def clear(self) -> bool: - """ - Clears the current buffer on the server - """ - self._logger.spam("AsyncSpeakWebSocketClient.clear ENTER") - - self._logger.notice("Sending Clear...") - ret = await self.send_control(SpeakWebSocketMessage.Clear) - - if not ret: - self._logger.error("clear failed") - self._logger.spam("AsyncSpeakWebSocketClient.clear LEAVE") - return False - - self._logger.notice("clear succeeded") - self._logger.spam("AsyncSpeakWebSocketClient.clear LEAVE") - - return True - - async def wait_for_complete(self): - """ - This method will block until the speak is done playing sound. - """ - self._logger.spam("AsyncSpeakWebSocketClient.wait_for_complete ENTER") - - if self._speaker is None: - self._logger.error("speaker is None. Return immediately") - return - - loop = asyncio.get_event_loop() - await loop.run_in_executor(None, self._speaker.wait_for_complete) - self._logger.notice("wait_for_complete succeeded") - self._logger.spam("AsyncSpeakWebSocketClient.wait_for_complete LEAVE") - - async def _close_message(self) -> bool: - return await self.send_control(SpeakWebSocketMessage.Close) - - async def finish(self) -> bool: - """ - Closes the WebSocket connection gracefully. - """ - self._logger.debug("AsyncSpeakWebSocketClient.finish ENTER") - - # stop the threads - self._logger.verbose("cancelling tasks...") - try: - # call parent finish - if await super().finish() is False: - self._logger.error("AsyncListenWebSocketClient.finish failed") - - if self._speaker is not None and self._speaker_created: - self._speaker.finish() - self._speaker_created = False - - # Before cancelling, check if the tasks were created - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("before running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - tasks = [] - - if self._speaker is not None: - self._logger.notice("stopping speaker...") - self._speaker.finish() - self._speaker = None - self._logger.notice("speaker stopped") - - if self._flush_thread is not None: - self._logger.notice("stopping _flush_thread...") - self._flush_thread.cancel() - tasks.append(self._flush_thread) - self._logger.notice("_flush_thread cancelled") - - # Use asyncio.gather to wait for tasks to be cancelled - # Prevent indefinite waiting by setting a timeout - await asyncio.wait_for(asyncio.gather(*tasks), timeout=10) - self._logger.notice("threads joined") - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - self._logger.notice("finish succeeded") - self._logger.spam("AsyncSpeakWebSocketClient.finish LEAVE") - return True - - except asyncio.CancelledError: - self._logger.debug("tasks cancelled") - self._logger.debug("AsyncSpeakWebSocketClient.finish LEAVE") - return False - - except asyncio.TimeoutError as e: - self._logger.error("tasks cancellation timed out: %s", e) - self._logger.debug("AsyncSpeakWebSocketClient.finish LEAVE") - return False - - async def _inspect(self) -> bool: - # auto flush_inspect is generically used to track any messages you might want to snoop on - # place additional logic here to inspect messages of interest - - # for auto flush functionality - # set the last datagram - self._last_datagram = datetime.now() - self._logger.debug( - "AutoFlush last received: %s", - str(self._last_datagram), - ) - - return True - - -AsyncSpeakWebSocketClient = AsyncSpeakWSClient diff --git a/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/client.py b/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/client.py deleted file mode 100644 index d14c3603..00000000 --- a/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/client.py +++ /dev/null @@ -1,686 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -import json -import time -import logging -from typing import Dict, Union, Optional, cast, Any, Callable -from datetime import datetime -import threading - -from .....utils import verboselogs -from .....options import DeepgramClientOptions -from ...enums import SpeakWebSocketEvents, SpeakWebSocketMessage -from ....common import AbstractSyncWebSocketClient -from ....common import DeepgramError - -from .response import ( - OpenResponse, - MetadataResponse, - FlushedResponse, - ClearedResponse, - CloseResponse, - WarningResponse, - ErrorResponse, - UnhandledResponse, -) -from .options import SpeakWSOptions - -from .....audio.microphone import Microphone -from .....audio.speaker import Speaker, RATE, CHANNELS, PLAYBACK_DELTA - -ONE_SECOND = 1 -HALF_SECOND = 0.5 -DEEPGRAM_INTERVAL = 5 -PING_INTERVAL = 20 - - -class SpeakWSClient( - AbstractSyncWebSocketClient -): # pylint: disable=too-many-instance-attributes - """ - Client for interacting with Deepgram's text-to-speech services over WebSockets. - - This class provides methods to establish a WebSocket connection for TTS synthesis and handle real-time TTS synthesis events. - - Args: - config (DeepgramClientOptions): all the options for the client. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - _endpoint: str - - _event_handlers: Dict[SpeakWebSocketEvents, list] - - _flush_thread: Union[threading.Thread, None] - _lock_flush: threading.Lock - _last_datagram: Optional[datetime] = None - _flush_count: int - - _kwargs: Optional[Dict] = None - _addons: Optional[Dict] = None - _options: Optional[Dict] = None - _headers: Optional[Dict] = None - - _speaker_created: bool = False - _speaker: Optional[Speaker] = None - _microphone: Optional[Microphone] = None - - def __init__( - self, config: DeepgramClientOptions, microphone: Optional[Microphone] = None - ): - if config is None: - raise DeepgramError("Config is required") - - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - - self._config = config - self._endpoint = "v1/speak" - self._lock_flush = threading.Lock() - - self._flush_thread = None - - # auto flush - self._last_datagram = None - self._flush_count = 0 - - # microphone - self._microphone = microphone - - # init handlers - self._event_handlers = { - event: [] for event in SpeakWebSocketEvents.__members__.values() - } - - if self._config.options.get("speaker_playback") == "true": - self._logger.info("speaker_playback is enabled") - rate = self._config.options.get("speaker_playback_rate") - if rate is None: - rate = RATE - channels = self._config.options.get("speaker_playback_channels") - if channels is None: - channels = CHANNELS - playback_delta_in_ms = self._config.options.get( - "speaker_playback_delta_in_ms" - ) - if playback_delta_in_ms is None: - playback_delta_in_ms = PLAYBACK_DELTA - device_index = self._config.options.get("speaker_playback_device_index") - - self._logger.debug("rate: %s", rate) - self._logger.debug("channels: %s", channels) - self._logger.debug("device_index: %s", device_index) - - self._speaker_created = True - - if device_index is not None: - self._speaker = Speaker( - rate=rate, - channels=channels, - last_play_delta_in_ms=playback_delta_in_ms, - verbose=self._config.verbose, - output_device_index=device_index, - microphone=self._microphone, - ) - else: - self._speaker = Speaker( - rate=rate, - channels=channels, - last_play_delta_in_ms=playback_delta_in_ms, - verbose=self._config.verbose, - microphone=self._microphone, - ) - - # call the parent constructor - super().__init__(self._config, self._endpoint) - - # pylint: disable=too-many-statements,too-many-branches - def start( - self, - options: Optional[Union[SpeakWSOptions, Dict]] = None, - addons: Optional[Dict] = None, - headers: Optional[Dict] = None, - members: Optional[Dict] = None, - **kwargs, - ) -> bool: - """ - Starts the WebSocket connection for text-to-speech synthesis. - """ - self._logger.debug("SpeakWebSocketClient.start ENTER") - self._logger.info("options: %s", options) - self._logger.info("addons: %s", addons) - self._logger.info("headers: %s", headers) - self._logger.info("members: %s", members) - self._logger.info("kwargs: %s", kwargs) - - if isinstance(options, SpeakWSOptions) and not options.check(): - self._logger.error("options.check failed") - self._logger.debug("SpeakWebSocketClient.start LEAVE") - raise DeepgramError("Fatal text-to-speech options error") - - self._addons = addons - self._headers = headers - - # add "members" as members of the class - if members is not None: - self.__dict__.update(members) - - # set kwargs as members of the class - if kwargs is not None: - self._kwargs = kwargs - else: - self._kwargs = {} - - if isinstance(options, SpeakWSOptions): - self._logger.info("SpeakWSOptions switching class -> dict") - self._options = options.to_dict() - elif options is not None: - self._options = options - else: - self._options = {} - - try: - # speaker substitutes the listening thread - if self._speaker is not None: - self._logger.notice("passing speaker to delegate_listening") - super().delegate_listening(self._speaker) - - # call parent start - if ( - super().start( - self._options, - self._addons, - self._headers, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - is False - ): - self._logger.error("SpeakWebSocketClient.start failed") - self._logger.debug("SpeakWebSocketClient.start LEAVE") - return False - - if self._speaker is not None: - self._logger.notice("start delegate_listening thread") - self._speaker.start() - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - # flush thread - if self._config.is_auto_flush_speak_enabled(): - self._logger.notice("autoflush is enabled") - self._flush_thread = threading.Thread(target=self._flush) - self._flush_thread.start() - else: - self._logger.notice("autoflush is disabled") - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - self._logger.notice("start succeeded") - self._logger.debug("SpeakWebSocketClient.start LEAVE") - return True - - except Exception as e: # pylint: disable=broad-except - self._logger.error( - "WebSocketException in SpeakWebSocketClient.start: %s", e - ) - self._logger.debug("SpeakWebSocketClient.start LEAVE") - if self._config.options.get("termination_exception_connect") is True: - raise - return False - - # pylint: enable=too-many-statements,too-many-branches - - def on(self, event: SpeakWebSocketEvents, handler: Callable) -> None: - """ - Registers event handlers for specific events. - """ - self._logger.info("event subscribed: %s", event) - if event in SpeakWebSocketEvents.__members__.values() and callable(handler): - self._event_handlers[event].append(handler) - - def _emit(self, event: SpeakWebSocketEvents, *args, **kwargs) -> None: - """ - Emits events to the registered event handlers. - """ - self._logger.debug("SpeakWebSocketClient._emit ENTER") - self._logger.debug("callback handlers for: %s", event) - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - self._logger.debug("callback handlers for: %s", event) - for handler in self._event_handlers[event]: - handler(self, *args, **kwargs) - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("after running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - self._logger.debug("ListenWebSocketClient._emit LEAVE") - - def _process_text(self, message: str) -> None: - """ - Processes messages received over the WebSocket connection. - """ - self._logger.debug("SpeakWebSocketClient._process_text ENTER") - - try: - self._logger.debug("Text data received") - - if len(message) == 0: - self._logger.debug("message is empty") - self._logger.debug("SpeakWebSocketClient._process_text LEAVE") - return - - data = json.loads(message) - response_type = data.get("type") - self._logger.debug("response_type: %s, data: %s", response_type, data) - - match response_type: - case SpeakWebSocketEvents.Open: - open_result: OpenResponse = OpenResponse.from_json(message) - self._logger.verbose("OpenResponse: %s", open_result) - self._emit( - SpeakWebSocketEvents(SpeakWebSocketEvents.Open), - open=open_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case SpeakWebSocketEvents.Metadata: - meta_result: MetadataResponse = MetadataResponse.from_json(message) - self._logger.verbose("MetadataResponse: %s", meta_result) - self._emit( - SpeakWebSocketEvents(SpeakWebSocketEvents.Metadata), - metadata=meta_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case SpeakWebSocketEvents.Flushed: - fl_result: FlushedResponse = FlushedResponse.from_json(message) - self._logger.verbose("FlushedResponse: %s", fl_result) - - # auto flush - if self._config.is_inspecting_speak(): - with self._lock_flush: - self._flush_count -= 1 - self._logger.debug( - "Decrement Flush count: %d", - self._flush_count, - ) - - self._emit( - SpeakWebSocketEvents(SpeakWebSocketEvents.Flushed), - flushed=fl_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case SpeakWebSocketEvents.Cleared: - clear_result: ClearedResponse = ClearedResponse.from_json(message) - self._logger.verbose("ClearedResponse: %s", clear_result) - self._emit( - SpeakWebSocketEvents(SpeakWebSocketEvents.Cleared), - cleared=clear_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case SpeakWebSocketEvents.Close: - close_result: CloseResponse = CloseResponse.from_json(message) - self._logger.verbose("CloseResponse: %s", close_result) - self._emit( - SpeakWebSocketEvents(SpeakWebSocketEvents.Close), - close=close_result, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case SpeakWebSocketEvents.Warning: - war_warning: WarningResponse = WarningResponse.from_json(message) - self._logger.verbose("WarningResponse: %s", war_warning) - self._emit( - SpeakWebSocketEvents(SpeakWebSocketEvents.Warning), - warning=war_warning, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case SpeakWebSocketEvents.Error: - err_error: ErrorResponse = ErrorResponse.from_json(message) - self._logger.verbose("ErrorResponse: %s", err_error) - self._emit( - SpeakWebSocketEvents(SpeakWebSocketEvents.Error), - error=err_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - case _: - self._logger.warning( - "Unknown Message: response_type: %s, data: %s", - response_type, - data, - ) - unhandled_error: UnhandledResponse = UnhandledResponse( - type=SpeakWebSocketEvents(SpeakWebSocketEvents.Unhandled), - raw=message, - ) - self._emit( - SpeakWebSocketEvents(SpeakWebSocketEvents.Unhandled), - unhandled=unhandled_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - self._logger.notice("_process_text Succeeded") - self._logger.debug("SpeakWebSocketClient._process_text LEAVE") - - except Exception as e: # pylint: disable=broad-except - self._logger.error("Exception in SpeakWebSocketClient._process_text: %s", e) - e_error: ErrorResponse = ErrorResponse( - "Exception in SpeakWebSocketClient._process_text", - f"{e}", - "Exception", - ) - self._logger.error( - "Exception in SpeakWebSocketClient._process_text: %s", str(e) - ) - self._emit( - SpeakWebSocketEvents(SpeakWebSocketEvents.Error), - e_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - # signal exit and close - super()._signal_exit() - - self._logger.debug("SpeakWebSocketClient._process_text LEAVE") - - if self._config.options.get("termination_exception") is True: - raise - return - - # pylint: enable=too-many-return-statements,too-many-statements - - def _process_binary(self, message: bytes) -> None: - self._logger.debug("SpeakWebSocketClient._process_binary ENTER") - self._logger.debug("Binary data received") - - self._emit( - SpeakWebSocketEvents(SpeakWebSocketEvents.AudioData), - data=message, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - self._logger.notice("_process_binary Succeeded") - self._logger.debug("SpeakWebSocketClient._process_binary LEAVE") - - # pylint: disable=too-many-return-statements - def _flush(self) -> None: - self._logger.debug("SpeakWebSocketClient._flush ENTER") - - delta_in_ms_str = self._config.options.get("auto_flush_speak_delta") - if delta_in_ms_str is None: - self._logger.error("auto_flush_speak_delta is None") - self._logger.debug("SpeakWebSocketClient._flush LEAVE") - return - delta_in_ms = float(delta_in_ms_str) - - while True: - try: - self._exit_event.wait(timeout=HALF_SECOND) - - if self._exit_event.is_set(): - self._logger.notice("_flush exiting gracefully") - self._logger.debug("ListenWebSocketClient._flush LEAVE") - return - - if self._last_datagram is None: - self._logger.debug("AutoFlush last_datagram is None") - continue - - with self._lock_flush: - delta = datetime.now() - self._last_datagram - diff_in_ms = delta.total_seconds() * 1000 - self._logger.debug("AutoFlush delta: %f", diff_in_ms) - if diff_in_ms < delta_in_ms: - self._logger.debug("AutoFlush delta is less than threshold") - continue - - self.flush() - - except Exception as e: # pylint: disable=broad-except - self._logger.error("Exception in SpeakWebSocketClient._flush: %s", e) - e_error: ErrorResponse = ErrorResponse( - "Exception in SpeakWebSocketClient._flush", - f"{e}", - "Exception", - ) - self._logger.error( - "Exception in SpeakWebSocketClient._flush: %s", str(e) - ) - self._emit( - SpeakWebSocketEvents(SpeakWebSocketEvents.Error), - error=e_error, - **dict(cast(Dict[Any, Any], self._kwargs)), - ) - - # signal exit and close - super()._signal_exit() - - self._logger.debug("SpeakWebSocketClient._flush LEAVE") - - if self._config.options.get("termination_exception") is True: - raise - return - - # pylint: enable=too-many-return-statements - - def send_text(self, text_input: str) -> bool: - """ - Sends text to the WebSocket connection to generate audio. - - Args: - text_input (str): The raw text to be synthesized. This function will automatically wrap - the text in a JSON object of type "Speak" with the key "text". - - Returns: - bool: True if the text was successfully sent, False otherwise. - """ - return self.send_raw(json.dumps({"type": "Speak", "text": text_input})) - - def send(self, data: Union[str, bytes]) -> bool: - """ - Alias for send_text. Please see send_text for more information. - """ - if isinstance(data, bytes): - self._logger.error("send() failed - data is bytes") - return False - - return self.send_text(data) - - # pylint: disable=unused-argument - def send_control( - self, msg_type: Union[SpeakWebSocketMessage, str], data: Optional[str] = "" - ) -> bool: - """ - Sends a control message consisting of type SpeakWebSocketEvents over the WebSocket connection. - - Args: - msg_type (SpeakWebSocketEvents): The type of control message to send. - (Optional) data (str): The data to send with the control message. - - Returns: - bool: True if the control message was successfully sent, False otherwise. - """ - control_msg = json.dumps({"type": msg_type}) - return self.send_raw(control_msg) - - # pylint: enable=unused-argument - - # pylint: disable=too-many-return-statements,too-many-branches,too-many-statements - def send_raw(self, msg: str) -> bool: - """ - Sends a raw/control message over the WebSocket connection. This message must contain a valid JSON object. - - Args: - msg (str): The raw message to send over the WebSocket connection. - - Returns: - bool: True if the message was successfully sent, False otherwise. - """ - self._logger.spam("SpeakWebSocketClient.send_raw ENTER") - - if self._config.is_inspecting_speak(): - try: - _tmp_json = json.loads(msg) - if "type" in _tmp_json: - self._logger.debug( - "Inspecting Message: Sending %s", _tmp_json["type"] - ) - match _tmp_json["type"]: - case SpeakWebSocketMessage.Speak: - inspect_res = self._inspect() - if not inspect_res: - self._logger.error("inspect_res failed") - case SpeakWebSocketMessage.Flush: - with self._lock_flush: - self._last_datagram = None - self._flush_count += 1 - self._logger.debug( - "Increment Flush count: %d", self._flush_count - ) - except Exception as e: # pylint: disable=broad-except - self._logger.error("send_raw() failed - Exception: %s", str(e)) - - try: - if super().send(msg) is False: - self._logger.error("send_raw() failed") - self._logger.spam("SpeakWebSocketClient.send_raw LEAVE") - return False - self._logger.spam("send_raw() succeeded") - self._logger.spam("SpeakWebSocketClient.send_raw LEAVE") - return True - except Exception as e: # pylint: disable=broad-except - self._logger.error("send_raw() failed - Exception: %s", str(e)) - self._logger.spam("SpeakWebSocketClient.send_raw LEAVE") - if self._config.options.get("termination_exception_send") is True: - raise - return False - - # pylint: enable=too-many-return-statements,too-many-branches - - def flush(self) -> bool: - """ - Flushes the current buffer and returns generated audio - """ - self._logger.spam("SpeakWebSocketClient.flush ENTER") - - self._logger.notice("Sending Flush...") - ret = self.send_control(SpeakWebSocketMessage.Flush) - - if not ret: - self._logger.error("flush failed") - self._logger.spam("SpeakWebSocketClient.flush LEAVE") - return False - - self._logger.notice("flush succeeded") - self._logger.spam("SpeakWebSocketClient.flush LEAVE") - - return True - - def clear(self) -> bool: - """ - Clears the current buffer on the server - """ - self._logger.spam("SpeakWebSocketClient.clear ENTER") - - self._logger.notice("Sending Clear...") - ret = self.send_control(SpeakWebSocketMessage.Clear) - - if not ret: - self._logger.error("clear failed") - self._logger.spam("SpeakWebSocketClient.clear LEAVE") - return False - - self._logger.notice("clear succeeded") - self._logger.spam("SpeakWebSocketClient.clear LEAVE") - - return True - - def wait_for_complete(self): - """ - This method will block until the speak is done playing sound. - """ - self._logger.spam("SpeakWebSocketClient.wait_for_complete ENTER") - - if self._speaker is None: - self._logger.error("speaker is None. Return immediately") - raise DeepgramError("Speaker is not initialized") - - self._speaker.wait_for_complete() - self._logger.notice("wait_for_complete succeeded") - self._logger.spam("SpeakWebSocketClient.wait_for_complete LEAVE") - - def _close_message(self) -> bool: - return self.send_control(SpeakWebSocketMessage.Close) - - # closes the WebSocket connection gracefully - def finish(self) -> bool: - """ - Closes the WebSocket connection gracefully. - """ - self._logger.spam("SpeakWebSocketClient.finish ENTER") - - # call parent finish which calls signal_exit - if super().finish() is False: - self._logger.error("ListenWebSocketClient.finish failed") - - if self._speaker is not None and self._speaker_created: - self._speaker.finish() - self._speaker_created = False - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("before running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - # stop the threads - if self._speaker is not None: - self._logger.verbose("stopping speaker...") - self._speaker.finish() - self._speaker = None - self._logger.notice("speaker stopped") - - if self._flush_thread is not None: - self._logger.verbose("sdtopping _flush_thread...") - self._flush_thread.join() - self._flush_thread = None - self._logger.notice("_flush_thread joined") - - # debug the threads - for thread in threading.enumerate(): - self._logger.debug("before running thread: %s", thread.name) - self._logger.debug("number of active threads: %s", threading.active_count()) - - self._logger.notice("finish succeeded") - self._logger.spam("SpeakWebSocketClient.finish LEAVE") - return True - - def _inspect(self) -> bool: - # auto flush_inspect is generically used to track any messages you might want to snoop on - # place additional logic here to inspect messages of interest - - # for auto flush functionality - # set the last datagram - with self._lock_flush: - self._last_datagram = datetime.now() - self._logger.debug( - "AutoFlush last received: %s", - str(self._last_datagram), - ) - - return True - - -SpeakWebSocketClient = SpeakWSClient diff --git a/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/options.py b/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/options.py deleted file mode 100644 index 20e5f56c..00000000 --- a/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/options.py +++ /dev/null @@ -1,65 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from io import BufferedReader -from typing import Union, Optional -import logging - -from dataclasses import dataclass, field -from dataclasses_json import config as dataclass_config - -from .....utils import verboselogs -from ....common import BaseResponse - - -@dataclass -class SpeakWSOptions(BaseResponse): - """ - Contains all the options for the SpeakOptions. - - Reference: - https://developers.deepgram.com/reference/transform-text-to-speech-websocket - """ - - model: Optional[str] = field( - default="aura-2-thalia-en", - metadata=dataclass_config(exclude=lambda f: f is None), - ) - encoding: Optional[str] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - # container: Optional[str] = field( - # default=None, metadata=dataclass_config(exclude=lambda f: f is None) - # ) - sample_rate: Optional[int] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - bit_rate: Optional[int] = field( - default=None, metadata=dataclass_config(exclude=lambda f: f is None) - ) - - def __getitem__(self, key): - _dict = self.to_dict() - return _dict[key] - - def __setitem__(self, key, val): - self.__dict__[key] = val - - def __str__(self) -> str: - return self.to_json(indent=4) - - def check(self): - """ - Check the SpeakOptions for any missing or invalid values. - """ - logger = verboselogs.VerboseLogger(__name__) - logger.addHandler(logging.StreamHandler()) - prev = logger.level - logger.setLevel(verboselogs.ERROR) - - # no op at the moment - - logger.setLevel(prev) - - return True diff --git a/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/response.py b/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/response.py deleted file mode 100644 index a5efc4e3..00000000 --- a/venv/Lib/site-packages/deepgram/clients/speak/v1/websocket/response.py +++ /dev/null @@ -1,58 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - - -from dataclasses import dataclass - -from ....common import ( - BaseResponse, - OpenResponse, - CloseResponse, - ErrorResponse, - UnhandledResponse, -) - - -# Speak Response Types: - - -@dataclass -class MetadataResponse(BaseResponse): - """ - Metadata object - """ - - type: str = "" - request_id: str = "" - - -@dataclass -class FlushedResponse(BaseResponse): - """ - Flushed Message from the Deepgram Platform - """ - - type: str = "" - sequence_id: int = 0 - - -@dataclass -class ClearedResponse(BaseResponse): - """ - Cleared object - """ - - type: str = "" - sequence_id: int = 0 - - -@dataclass -class WarningResponse(BaseResponse): - """ - Warning Message from the Deepgram Platform - """ - - warn_code: str = "" - warn_msg: str = "" - type: str = "" diff --git a/venv/Lib/site-packages/deepgram/clients/speak_router.py b/venv/Lib/site-packages/deepgram/clients/speak_router.py deleted file mode 100644 index 7290ed48..00000000 --- a/venv/Lib/site-packages/deepgram/clients/speak_router.py +++ /dev/null @@ -1,171 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -from importlib import import_module -import logging -import deprecation # type: ignore - -from .. import __version__ -from .speak.v1.rest.client import SpeakRESTClient -from ..utils import verboselogs -from ..options import DeepgramClientOptions -from .errors import DeepgramModuleError - - -class SpeakRouter: - """ - This class provides a Speak Clients for making requests to the Deepgram API with various configuration options. - - Attributes: - config_options (DeepgramClientOptions): An optional configuration object specifying client options. - - Methods: - rest: (Preferred) Returns a Threaded REST Client instance for interacting with Deepgram's transcription services. - websocket: (Preferred) Returns an Threaded WebSocket Client instance for interacting with Deepgram's prerecorded transcription services. - - asyncrest: Returns an Async REST Client instance for interacting with Deepgram's transcription services. - asyncwebsocket: Returns an Async WebSocket Client instance for interacting with Deepgram's prerecorded transcription services. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - - def __init__(self, config: DeepgramClientOptions): - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - self._config = config - - # when this is removed, remove --disable=W0622 from Makefile - # pylint: disable=unused-argument - @deprecation.deprecated( - deprecated_in="3.4.0", - removed_in="4.0.0", - current_version=__version__, - details="deepgram.speak.v1 is deprecated. Use deepgram.speak.rest or deepgram.speak.websocket instead.", - ) - def v(self, version: str = ""): - """ - DEPRECATED: deepgram.speak.v1 is deprecated. Use deepgram.speak.rest or deepgram.speak.websocket instead. - """ - return SpeakRESTClient(self._config) - - # pylint: enable=unused-argument - - @property - def rest(self): - """ - Returns a Threaded REST Client instance for interacting with Deepgram's prerecorded Text-to-Speech services. - """ - return self.Version(self._config, "rest") - - @property - def asyncrest(self): - """ - Returns an Async REST Client instance for interacting with Deepgram's prerecorded Text-to-Speech services. - """ - return self.Version(self._config, "asyncrest") - - @property - def websocket(self): - """ - Returns a Threaded WebSocket Client instance for interacting with Deepgram's Text-to-Speech services. - """ - return self.Version(self._config, "websocket") - - @property - def asyncwebsocket(self): - """ - Returns an Async WebSocket Client instance for interacting with Deepgram's Text-to-Speech services. - """ - return self.Version(self._config, "asyncwebsocket") - - # INTERNAL CLASSES - class Version: - """ - Represents a version of the Deepgram API. - """ - - _logger: verboselogs.VerboseLogger - _config: DeepgramClientOptions - _parent: str - - def __init__(self, config, parent: str): - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(config.verbose) - self._config = config - self._parent = parent - - # FUTURE VERSIONING: - # When v2 or v1.1beta1 or etc. This allows easy access to the latest version of the API. - # @property - # def latest(self): - # match self._parent: - # case "live": - # return LiveClient(self._config) - # case "prerecorded": - # return PreRecordedClient(self._config) - # case _: - # raise DeepgramModuleError("Invalid parent") - - def v(self, version: str = ""): - """ - Returns a specific version of the Deepgram API. - """ - self._logger.debug("Version.v ENTER") - self._logger.info("version: %s", version) - if len(version) == 0: - self._logger.error("version is empty") - self._logger.debug("Version.v LEAVE") - raise DeepgramModuleError("Invalid module version") - - type = "" - file_name = "" - class_name = "" - match self._parent: - case "websocket": - type = "websocket" - file_name = "client" - class_name = "SpeakWebSocketClient" - case "asyncwebsocket": - type = "websocket" - file_name = "async_client" - class_name = "AsyncSpeakWebSocketClient" - case "rest": - type = "rest" - file_name = "client" - class_name = "SpeakRESTClient" - case "asyncrest": - type = "rest" - file_name = "async_client" - class_name = "AsyncSpeakRESTClient" - case _: - self._logger.error("parent unknown: %s", self._parent) - self._logger.debug("Version.v LEAVE") - raise DeepgramModuleError("Invalid parent type") - - # create class path - path = f"deepgram.clients.speak.v{version}.{type}.{file_name}" - self._logger.info("path: %s", path) - self._logger.info("class_name: %s", class_name) - - # import class - mod = import_module(path) - if mod is None: - self._logger.error("module path is None") - self._logger.debug("Version.v LEAVE") - raise DeepgramModuleError("Unable to find package") - - my_class = getattr(mod, class_name) - if my_class is None: - self._logger.error("my_class is None") - self._logger.debug("Version.v LEAVE") - raise DeepgramModuleError("Unable to find class") - - # instantiate class - my_class = my_class(self._config) - self._logger.notice("Version.v succeeded") - self._logger.debug("Version.v LEAVE") - return my_class diff --git a/venv/Lib/site-packages/deepgram/errors.py b/venv/Lib/site-packages/deepgram/errors.py index 85f2128f..001d696d 100644 --- a/venv/Lib/site-packages/deepgram/errors.py +++ b/venv/Lib/site-packages/deepgram/errors.py @@ -1,16 +1,88 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT +from typing import Union, Optional +import websockets.exceptions +import urllib.error +import aiohttp +import uuid -class DeepgramApiKeyError(Exception): - """ - Base class for exceptions raised for a missing Deepgram API Key. +class DeepgramError(Exception): + pass + + +class DeepgramSetupError(DeepgramError, ValueError): + pass + + +class DeepgramApiError(DeepgramError): + """An error returned by the Deepgram API. - Attributes: - message (str): The error message describing the exception. + If the error was raised by an http client, the client's error message + is accessible via the `http_library_error` field. This may be useful + for handling different error codes, such as 429s or 503s. + + The `error` field is set to the API's error message (dict), if avilable. + Otherwise the `error` field is set to the parent exception's message (str). + + The `warning` field is set to the API's warning messages (list[str]), if available. + + The `request_id` field is set to the API's request ID, if available. """ + def __init__( + self, + *args: object, + http_library_error: Optional[ + Union[ + urllib.error.HTTPError, + urllib.error.URLError, + websockets.exceptions.InvalidHandshake, + aiohttp.ClientResponseError, + aiohttp.ClientError, + ] + ] = None, + ): + super().__init__(*args) + self.http_library_error = http_library_error + self.error: Union[str, dict] # If you change the type, change it in the docstring as well! + self.warnings: Optional[list[str]] = None # If you change the type, change it in the docstring as well! + self.request_id: Optional[uuid.UUID] = None + self.http_error_status: Optional[int] = None + + # Set the `error`, `warning`, and `request_id` fields from the incoming data object + if isinstance(args[0], dict) and "err_msg" in args[0]: + error_or_warning_data = args[0] + self.error = error_or_warning_data["err_msg"] + if "metadata" in error_or_warning_data and "warnings" in error_or_warning_data["metadata"]: + self.warnings = error_or_warning_data["metadata"]["warnings"] + elif "warnings" in error_or_warning_data: # Occurs when `raise_warnings_as_errors` is enabled + self.warnings = error_or_warning_data["warnings"] + if "metadata" in error_or_warning_data and "request_id" in error_or_warning_data["metadata"]: # Occurs when Deepgram returns a success response (for warnings) + self.request_id = uuid.UUID(error_or_warning_data["request_id"]) + elif "request_id" in error_or_warning_data: # Occurs when Deepgram returns a failed response + self.request_id = uuid.UUID(error_or_warning_data["request_id"]) + elif isinstance(args[0], str): + self.error = args[0] + else: + self.error = str(args[0]) + + # Set the error code from the underlying exception, if possible + if http_library_error is not None: + # Note: The following Exceptions do not have HTTP error codes: + # - urllib.error.URLError + # - websockets.exceptions.InvalidHandshake + # - aiohttp.ClientError + if isinstance(http_library_error, urllib.error.HTTPError): + self.http_error_status = http_library_error.code + elif isinstance(http_library_error, aiohttp.ClientResponseError): + self.http_error_status = http_library_error.status - def __init__(self, message: str): - super().__init__(message) - self.name = "DeepgramApiKeyError" + def __str__(self) -> str: + if self.request_id: + if self.warnings: + warning_string = f"\n\n{self.warnings}" + else: + warning_string = "" + if self.http_error_status: + return f"Request `{self.request_id}` returned {self.http_error_status}: {self.error}" + warning_string + else: + return f"Request `{self.request_id}` returned {self.error}" + warning_string + return super().__str__() diff --git a/venv/Lib/site-packages/deepgram/extra.py b/venv/Lib/site-packages/deepgram/extra.py new file mode 100644 index 00000000..0c8d1020 --- /dev/null +++ b/venv/Lib/site-packages/deepgram/extra.py @@ -0,0 +1,113 @@ +import warnings + +from ._types import PrerecordedTranscriptionResponse, Options +from ._enums import Caption + +class Extra: + """ + Extra post-processing to transform raw Deepgram responses to conveniently-formatted outputs. + """ + + def __init__(self, options: Options) -> None: + self.options = options + + """ + Helper function to transform a seconds mark into a formatted timestamp. + I.e. 6.564 -> 00:00:06,564 + + :param seconds:float + :param separator:str + :return Formatted timestamp string. + """ + def _format_timestamp(self, seconds: float, separator: str): + hours = int(seconds // 3600) + minutes = int((seconds % 3600) // 60) + secs = int(seconds % 60) + millis = int((seconds - int(seconds)) * 1000) + return f"{hours:02}:{minutes:02}:{secs:02}{separator}{millis:03}" + + """ + Transform a Deepgram PrerecordedTranscriptionResponse into a set of captions. + + :param response:PrerecordedTranscriptionResponse: Deepgram response. + :param format:Caption: The caption format enum (SRT or WebVTT). + :param line_length:int: Number of words in each caption line. + :return A string containing the response's captions. + """ + def _to_caption( + self, + response: PrerecordedTranscriptionResponse, + format: Caption, + line_length: int, + ): + if "utterances" in response["results"]: + utterances = response["results"]["utterances"] + else: + warnings.warn( + "Enabling the Utterances feature is strongly recommended for captioning. Utterances allow " + "captions to be delimited by pauses. Add request parameter `'utterances': True`." + ) + utterances = response["results"]["channels"][0]["alternatives"] + captions = [] + line_counter = 1 + if format is Caption.WEBVTT: + captions.append("WEBVTT") + for utt_index, utt in enumerate(utterances): + words = utterances[utt_index]["words"] + word_text = "punctuated_word" if "punctuated_word" in words[0] else "word" + for i in range(0, len(words), line_length): + start_time = words[i]["start"] + end_index = min(len(words) - 1, i + line_length - 1) + end_time = words[end_index]["end"] + text = " ".join([w[word_text] for w in words[i:end_index + 1]]) + separator = "," if format is Caption.SRT else '.' + prefix = "" if format is Caption.SRT else "- " + caption = ( + f"{line_counter}\n" + f"{self._format_timestamp(start_time, separator)} --> " + f"{self._format_timestamp(end_time, separator)}\n" + f"{prefix}{text}" + ) + captions.append(caption) + line_counter += 1 + return "\n\n".join(captions) + + """ + Transform a Deepgram PrerecordedTranscriptionResponse into SRT captions. + + :param response:PrerecordedTranscriptionResponse: Deepgram response. + :param line_length:int: Number of words in each caption line. Defaults to 8. + :param readable:bool: If the captions should be printed in a human-readable format, + instead of with newline characters. Defaults to True. + :return Nothing if readable=True, string of captions if readable=False. + """ + def to_SRT( + self, + response: PrerecordedTranscriptionResponse, + line_length: int=8, + readable: bool=True + ): + captions = self._to_caption(response, Caption.SRT, line_length) + if not readable: + return captions + print(captions) + + """ + Transform a Deepgram PrerecordedTranscriptionResponse into WebVTT captions. + + :param response:PrerecordedTranscriptionResponse: Deepgram response. + :param line_length:int: Number of words in each caption line. Defaults to 8. + :param readable:bool: If the captions should be printed in a human-readable format, + instead of with newline characters. Defaults to True. + :return Nothing if readable=True, string of captions if readable=False. + """ + def to_WebVTT( + self, + response: PrerecordedTranscriptionResponse, + line_length: int=8, + readable: bool=True + ): + captions = self._to_caption(response, Caption.WEBVTT, line_length) + if not readable: + return captions + print(captions) diff --git a/venv/Lib/site-packages/deepgram/invitations.py b/venv/Lib/site-packages/deepgram/invitations.py new file mode 100644 index 00000000..c98dbca4 --- /dev/null +++ b/venv/Lib/site-packages/deepgram/invitations.py @@ -0,0 +1,47 @@ +from ._types import Options, Invitation, InvitationResponse +from ._utils import _request + + +class Invitations: + _root = "/projects" + + def __init__(self, options: Options) -> None: + self.options = options + + async def list_invitations(self, project_id: str) -> Invitation: + """Returns all active invitations on a given project.""" + + return await _request(f'{self._root}/{project_id}/invites', self.options) + + + async def send_invitation(self, project_id: str, option: Invitation) -> InvitationResponse: + """Sends an invitation to a given email address to join a given project""" + + return await _request(f'{self._root}/{project_id}/invites', + self.options, + method='POST', + payload=option, + headers={'Content-Type': 'application/json'}) + + + async def remove_invitation(self, project_id: str, email: str) -> None: + """Removes the invitation of the specified email from the + specified project.""" + + await _request( + f'{self._root}/{project_id}/invites/{email}', + self.options, + method='DELETE' + ) + + async def leave_project(self, project_id: str) -> None: + """Removes the authenticated account from the specified project.""" + + await _request( + f'{self._root}/{project_id}/leave', + self.options, + method='DELETE' + ) + + + diff --git a/venv/Lib/site-packages/deepgram/keys.py b/venv/Lib/site-packages/deepgram/keys.py new file mode 100644 index 00000000..65b479e0 --- /dev/null +++ b/venv/Lib/site-packages/deepgram/keys.py @@ -0,0 +1,39 @@ +from typing import List +from ._types import Options, Key, KeyResponse +from ._utils import _request +import datetime + +class Keys: + _root = "/projects" + + def __init__(self, options: Options) -> None: + self.options = options + + async def list(self, project_id: str) -> KeyResponse: + """Retrieves all keys associated with the provided projectId.""" + return await _request( + f'{self._root}/{project_id}/keys', self.options + ) + + async def get(self, project_id: str, key: str) -> Key: + """Retrieves a specific key associated with the provided projectId.""" + return await _request( + f'{self._root}/{project_id}/keys/{key}', self.options + ) + + async def create( + self, project_id: str, comment: str, scopes: List[str], tags: List[str], expiration_date: datetime, time_to_live_in_seconds: int + ) -> Key: + """Creates an API key with the provided scopes.""" + return await _request( + f'{self._root}/{project_id}/keys', self.options, + method='POST', payload={'comment': comment, 'scopes': scopes, 'tags': tags, 'expiration_date': expiration_date, 'time_to_live_in_seconds': time_to_live_in_seconds}, + headers={'Content-Type': 'application/json'} + ) + + async def delete(self, project_id: str, key: str) -> None: + """Deletes an API key.""" + await _request( + f'{self._root}/{project_id}/keys/{key}', self.options, + method='DELETE' + ) diff --git a/venv/Lib/site-packages/deepgram/members.py b/venv/Lib/site-packages/deepgram/members.py new file mode 100644 index 00000000..a988a24a --- /dev/null +++ b/venv/Lib/site-packages/deepgram/members.py @@ -0,0 +1,24 @@ +from ._types import Options, Member +from ._utils import _request + + +class Members: + _root = "/projects" + + def __init__(self, options: Options) -> None: + self.options = options + + async def list_members(self, project_id: str) -> Member: + """Returns all member account objects for all of the accounts in + the specified project.""" + + return await _request(f'{self._root}/{project_id}/members', self.options) + + + async def remove_member(self, project_id: str, member_id: str) -> None: + """Removes the specified member account from the specified project.""" + + await _request( + f'{self._root}/{project_id}/members/{member_id}', self.options, + method='DELETE' + ) diff --git a/venv/Lib/site-packages/deepgram/options.py b/venv/Lib/site-packages/deepgram/options.py deleted file mode 100644 index ce43480a..00000000 --- a/venv/Lib/site-packages/deepgram/options.py +++ /dev/null @@ -1,245 +0,0 @@ -# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -import sys -import re -import os -from typing import Dict, Optional -import logging -import numbers - -from deepgram import __version__ -from .utils import verboselogs -from .errors import DeepgramApiKeyError - - -class DeepgramClientOptions: # pylint: disable=too-many-instance-attributes - """ - Represents options for configuring a Deepgram client. - - This class allows you to customize various options for interacting with the Deepgram API. - - Attributes: - api_key: (Optional) A Deepgram API key used for authentication. Default uses the `DEEPGRAM_API_KEY` environment variable. - url: (Optional) The URL used to interact with production, On-prem, and other Deepgram environments. Defaults to `api.deepgram.com`. - verbose: (Optional) The logging level for the client. Defaults to `verboselogs.WARNING`. - headers: (Optional) Headers for initializing the client. - options: (Optional) Additional options for initializing the client. - """ - - _logger: verboselogs.VerboseLogger - _inspect_listen: bool = False - _inspect_speak: bool = False - - def __init__( - self, - api_key: str = "", - url: str = "", - verbose: int = verboselogs.WARNING, - headers: Optional[Dict] = None, - options: Optional[Dict] = None, - ): # pylint: disable=too-many-positional-arguments - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - - if api_key is None: - api_key = "" - - self.verbose = verbose - self.api_key = api_key - - if headers is None: - headers = {} - self._update_headers(headers=headers) - - if len(url) == 0: - url = "api.deepgram.com" - self.url = self._get_url(url) - - if options is None: - options = {} - self.options = options - - if self.is_auto_flush_reply_enabled(): - self._inspect_listen = True - if self.is_auto_flush_speak_enabled(): - self._inspect_speak = True - - def set_apikey(self, api_key: str): - """ - set_apikey: Sets the API key for the client. - - Args: - api_key: The Deepgram API key used for authentication. - """ - self.api_key = api_key - self._update_headers() - - def _get_url(self, url) -> str: - if not re.match(r"^https?://", url, re.IGNORECASE): - url = "https://" + url - return url.strip("/") - - def _update_headers(self, headers: Optional[Dict] = None): - self.headers = {} - self.headers["Accept"] = "application/json" - if self.api_key: - self.headers["Authorization"] = f"Token {self.api_key}" - elif "Authorization" in self.headers: - del self.headers["Authorization"] - self.headers[ - "User-Agent" - ] = f"@deepgram/sdk/{__version__} python/{sys.version_info[1]}.{sys.version_info[2]}" - # Overwrite / add any headers that were passed in - if headers: - self.headers.update(headers) - - def is_keep_alive_enabled(self) -> bool: - """ - is_keep_alive_enabled: Returns True if the client is configured to keep the connection alive. - """ - return self.options.get("keepalive", False) or self.options.get( - "keep_alive", False - ) - - def is_auto_flush_reply_enabled(self) -> bool: - """ - is_auto_flush_reply_enabled: Returns True if the client is configured to auto-flush for listen. - """ - auto_flush_reply_delta = float(self.options.get("auto_flush_reply_delta", 0)) - return ( - isinstance(auto_flush_reply_delta, numbers.Number) - and auto_flush_reply_delta > 0 - ) - - def is_auto_flush_speak_enabled(self) -> bool: - """ - is_auto_flush_speak_enabled: Returns True if the client is configured to auto-flush for speak. - """ - auto_flush_speak_delta = float(self.options.get("auto_flush_speak_delta", 0)) - return ( - isinstance(auto_flush_speak_delta, numbers.Number) - and auto_flush_speak_delta > 0 - ) - - def is_inspecting_listen(self) -> bool: - """ - is_inspecting_listen: Returns True if the client is inspecting listen messages. - """ - return self._inspect_listen - - def is_inspecting_speak(self) -> bool: - """ - is_inspecting_speak: Returns True if the client is inspecting speak messages. - """ - return self._inspect_speak - - -class ClientOptionsFromEnv( - DeepgramClientOptions -): # pylint: disable=too-many-branches, too-many-statements - """ - This class extends DeepgramClientOptions and will attempt to use environment variables first before defaults. - """ - - _logger: verboselogs.VerboseLogger - - def __init__( - self, - api_key: str = "", - url: str = "", - verbose: int = verboselogs.WARNING, - headers: Optional[Dict] = None, - options: Optional[Dict] = None, - ): # pylint: disable=too-many-positional-arguments - self._logger = verboselogs.VerboseLogger(__name__) - self._logger.addHandler(logging.StreamHandler()) - self._logger.setLevel(verboselogs.WARNING) # temporary set for setup - - if api_key is None: - api_key = "" - - if api_key == "": - api_key = os.getenv("DEEPGRAM_API_KEY", "") - if api_key == "": - self._logger.critical("Deepgram API KEY is not set") - raise DeepgramApiKeyError("Deepgram API KEY is not set") - - if url == "": - url = os.getenv("DEEPGRAM_HOST", "api.deepgram.com") - self._logger.notice(f"Deepgram host is set to {url}") - - if verbose == verboselogs.WARNING: - _loglevel = os.getenv("DEEPGRAM_LOGGING", "") - if _loglevel != "": - verbose = int(_loglevel) - if isinstance(verbose, str): - match verbose: - case "NOTSET": - self._logger.notice("Logging level is set to NOTSET") - verbose = verboselogs.NOTSET - case "SPAM": - self._logger.notice("Logging level is set to SPAM") - verbose = verboselogs.SPAM - case "DEBUG": - self._logger.notice("Logging level is set to DEBUG") - verbose = verboselogs.DEBUG - case "VERBOSE": - self._logger.notice("Logging level is set to VERBOSE") - verbose = verboselogs.VERBOSE - case "NOTICE": - self._logger.notice("Logging level is set to NOTICE") - verbose = verboselogs.NOTICE - case "WARNING": - self._logger.notice("Logging level is set to WARNING") - verbose = verboselogs.WARNING - case "SUCCESS": - self._logger.notice("Logging level is set to SUCCESS") - verbose = verboselogs.SUCCESS - case "ERROR": - self._logger.notice("Logging level is set to ERROR") - verbose = verboselogs.ERROR - case "CRITICAL": - self._logger.notice("Logging level is set to CRITICAL") - verbose = verboselogs.CRITICAL - case _: - self._logger.notice("Logging level is set to WARNING") - verbose = verboselogs.WARNING - self._logger.notice(f"Logging level is set to {verbose}") - - if headers is None: - headers = {} - for x in range(0, 20): - header = os.getenv(f"DEEPGRAM_HEADER_{x}", None) - if header is not None: - headers[header] = os.getenv(f"DEEPGRAM_HEADER_VALUE_{x}", None) - self._logger.debug( - "Deepgram header %s is set with value %s", - header, - headers[header], - ) - else: - break - if len(headers) == 0: - self._logger.notice("Deepgram headers are not set") - headers = None - - if options is None: - options = {} - for x in range(0, 20): - param = os.getenv(f"DEEPGRAM_PARAM_{x}", None) - if param is not None: - options[param] = os.getenv(f"DEEPGRAM_PARAM_VALUE_{x}", None) - self._logger.debug( - "Deepgram option %s is set with value %s", param, options[param] - ) - else: - break - if len(options) == 0: - self._logger.notice("Deepgram options are not set") - options = None - - super().__init__( - api_key=api_key, url=url, verbose=verbose, headers=headers, options=options - ) diff --git a/venv/Lib/site-packages/deepgram/projects.py b/venv/Lib/site-packages/deepgram/projects.py new file mode 100644 index 00000000..2d8de834 --- /dev/null +++ b/venv/Lib/site-packages/deepgram/projects.py @@ -0,0 +1,43 @@ +from ._types import Options, Project, ProjectResponse, UpdateResponse +from ._utils import _request + + +class Projects: + _root = "/projects" + + def __init__(self, options: Options) -> None: + self.options = options + + async def list(self) -> ProjectResponse: + """Returns all projects accessible by the API key.""" + return await _request(self._root, self.options) + + async def get(self, project_id: str) -> Project: + """Retrieves a specific project based on the provided projectId.""" + return await _request(f'{self._root}/{project_id}', self.options) + + async def create(self, name: str) -> Project: + """Creates a project.""" + return await _request( + self._root, self.options, + method='POST', payload={'name': name}, + headers={'Content-Type': 'application/json'} + ) + + + async def update(self, project_id: str, **payload) -> UpdateResponse: + """Updates a project's information.""" + + return await _request( + f'{self._root}/{project_id}', self.options, + method='PATCH', payload=payload, + headers={'Content-Type': 'application/json'} + ) + + + async def delete(self, project_id: str) -> None: + """Deletes a specific project based on the provided projectId.""" + await _request( + f'{self._root}/{project_id}', self.options, + method='DELETE' + ) diff --git a/venv/Lib/site-packages/deepgram/scopes.py b/venv/Lib/site-packages/deepgram/scopes.py new file mode 100644 index 00000000..75d107da --- /dev/null +++ b/venv/Lib/site-packages/deepgram/scopes.py @@ -0,0 +1,34 @@ +from ._types import Options, Scope, UpdateResponse +from ._utils import _request + + +class Scopes: + _root = "/projects" + + def __init__(self, options: Options) -> None: + self.options = options + + + async def get_scope(self, project_id: str, member_id: str) -> Scope: + """Returns the specified project scopes assigned + to the specified member.""" + + return await _request(f'{self._root}/{project_id}/members/{member_id}/scopes', self.options) + + + async def update_scope(self, project_id: str, member_id: str, scope: str) -> UpdateResponse: + """Updates the specified project scopes assigned to the + specified member.""" + + payload = {} + + if scope: + payload['scope'] = scope + + return await _request( + f'{self._root}/{project_id}/members/{member_id}/scopes', self.options, + method='PUT', payload=payload, + headers={'Content-Type': 'application/json'} + ) + + diff --git a/venv/Lib/site-packages/deepgram/transcription.py b/venv/Lib/site-packages/deepgram/transcription.py new file mode 100644 index 00000000..faff28a4 --- /dev/null +++ b/venv/Lib/site-packages/deepgram/transcription.py @@ -0,0 +1,391 @@ +from typing import Any, Union, Tuple, List, Dict, Awaitable, cast +import json +import asyncio +import inspect +from enum import Enum +from warnings import warn +import websockets.client +import websockets.exceptions +from ._types import (Options, PrerecordedOptions, LiveOptions, ToggleConfigOptions, + TranscriptionSource, PrerecordedTranscriptionResponse, + LiveTranscriptionResponse, Metadata, EventHandler) +from ._enums import LiveTranscriptionEvent +from ._utils import _request, _sync_request, _make_query_string, _socket_connect +from .errors import DeepgramApiError + + +class PrerecordedTranscription: + """This class provides an interface for doing transcription asynchronously on prerecorded audio files.""" + + _root = "/listen" + + def __init__(self, options: Options, + transcription_options: PrerecordedOptions, endpoint) -> None: + """ + This function initializes the options and transcription_options for the PrerecordedTranscription class. + + :param options:Options: Used to Pass in the options for the transcription. + :param transcription_options:PrerecordedOptions: Used to Specify the transcription options for a prerecorded audio file. + :return: Nothing. + + """ + self.options = options + if endpoint is not None: + self._root = endpoint + self.transcription_options = transcription_options + + async def __call__( + self, source: TranscriptionSource, timeout: float = None + ) -> PrerecordedTranscriptionResponse: + """ + The __call__ function is a special method that allows the class to be called + as a function. This is useful for creating instances of the class, where we can + call `PrerecordedTranscription()` and pass in arguments to set up an instance of + the class. For example: + + prerecorded_transcription = PrerecordedTranscription(...) + + :param source:TranscriptionSource: Used to Pass in the audio file. + :param timeout:float: (optional) The request timeout (if not set, defaults to `aiohttp`'s default timeout) + :return: A `PrerecordedTranscriptionResponse` object, which contains the transcription results. + + """ + + if 'buffer' in source and 'mimetype' not in source: + raise DeepgramApiError( + 'Mimetype must be provided if the source is bytes', + http_library_error=None, + ) + payload = cast( + Union[bytes, Dict], + source.get('buffer', {'url': source.get('url')}) + ) + content_type = cast(str, source.get('mimetype', 'application/json')) + return await _request( + f'{self._root}{_make_query_string(self.transcription_options)}', + self.options, method='POST', payload=payload, + headers={'Content-Type': content_type}, + timeout=timeout + ) + + +class SyncPrerecordedTranscription: + """This class provides an interface for doing transcription synchronously on prerecorded audio files.""" + + _root = "/listen" + + def __init__(self, options: Options, + transcription_options: PrerecordedOptions, endpoint) -> None: + """ + This function initializes the options and transcription_options for the PrerecordedTranscription class. + + :param options:Options: Used to Pass in the options for the transcription. + :param transcription_options:PrerecordedOptions: Used to Specify the transcription options for a prerecorded audio file. + :return: Nothing. + + """ + + self.options = options + if endpoint is not None: + self._root = endpoint + self.transcription_options = transcription_options + + def __call__( + self, source: TranscriptionSource, timeout: float = None + ) -> PrerecordedTranscriptionResponse: + + """ + The __call__ function is a special method that allows the class to be called + as a function. This is useful for creating instances of the class, where we can + call `SyncPrerecordedTranscription()` and pass in arguments to set up an instance of + the class. For example: + + sync_prerecorded_transcription = SyncPrerecordedTranscription(...) + + :param source:TranscriptionSource: Used to Pass in the audio file. + :param timeout:float: (optional) The request timeout, excluding the upload time of the audio file. + :return: A `prerecordedtranscriptionresponse` object, which contains the transcription results. + + """ + + if 'buffer' in source and 'mimetype' not in source: + raise DeepgramApiError( + 'Mimetype must be provided if the source is bytes', + http_library_error=None, + ) + payload = cast( + Union[bytes, Dict], + source.get('buffer', {'url': source.get('url')}) + ) + content_type = cast(str, source.get('mimetype', 'application/json')) + return _sync_request( + f'{self._root}{_make_query_string(self.transcription_options)}', + self.options, method='POST', payload=payload, + headers={'Content-Type': content_type}, + timeout=timeout + ) + + +class LiveTranscription: + """ + This class allows you to perform live transcription by connecting to Deepgram's Transcribe Streaming API. + It takes in options for the transcription job, and a callback function to handle events. + + """ + + _root = "/listen" + MESSAGE_TIMEOUT = 1.0 + + def __init__(self, options: Options, + transcription_options: LiveOptions, endpoint) -> None: + """ + The __init__ function is called when an instance of the class is created. + It initializes all of the attributes that are part of the object, and can be + accessed using "self." notation. In this case, it sets up a list to store any + messages received from Transcribe Streaming. + + :param options:Options: Used to Pass the options for the transcription job. + :param transcription_options:LiveOptions: Used to Pass in the configuration for the transcription job. + :return: None. + + """ + + self.options = options + if endpoint is not None: + self._root = endpoint + self.transcription_options = transcription_options + self.handlers: List[Tuple[LiveTranscriptionEvent, EventHandler]] = [] + # all received messages + self.received: List[Union[LiveTranscriptionResponse, Metadata]] = [] + # is the transcription job done? + self.done = False + self._socket = cast(websockets.client.WebSocketClientProtocol, None) + self._queue: asyncio.Queue[Tuple[bool, Any]] = asyncio.Queue() + + async def __call__(self) -> 'LiveTranscription': + """ + The __call__ function is a special method that allows the object to be called + as a function. In this case, it is used to connect the client and start the + transcription process. It returns itself after starting so that operations can + be chained. + + :return: The object itself. + + """ + self._socket = await _socket_connect( + f'{self._root}{_make_query_string(self.transcription_options)}', + self.options + ) + asyncio.create_task(self._start()) + return self + + async def _start(self) -> None: + """ + The _start function is the main function of the LiveTranscription class. + It is responsible for creating a websocket connection to Deepgram Transcribe, + and then listening for incoming messages from that socket. It also sends any + messages that are in its queue (which is populated by other functions). The + _start function will run until it receives a message with an empty transcription, + at which point it will close the socket and return. + + :return: None. + + """ + + asyncio.create_task(self._receiver()) + self._ping_handlers(LiveTranscriptionEvent.OPEN, self) + + while not self.done: + try: + incoming, body = await asyncio.wait_for(self._queue.get(), self.MESSAGE_TIMEOUT) + except asyncio.TimeoutError: + if self._socket.closed: + self.done = True + break + continue + + if incoming: + try: + parsed: Union[ + LiveTranscriptionResponse, Metadata + ] = json.loads(body) + # Stream-ending response is only a metadata object + self._ping_handlers( + LiveTranscriptionEvent.TRANSCRIPT_RECEIVED, + parsed + ) + self.received.append(parsed) + if 'sha256' in parsed: + self.done = True + except json.decoder.JSONDecodeError: + self._ping_handlers( + LiveTranscriptionEvent.ERROR, + f'Couldn\'t parse response JSON: {body}' + ) + else: + await self._socket.send(body) + self._ping_handlers( + LiveTranscriptionEvent.CLOSE, + self._socket.close_code + ) + + async def _receiver(self) -> None: + """ + The _receiver function is a coroutine that receives messages from the socket and puts them in a queue. + It is started by calling start_receiver() on an instance of AsyncSocket. It runs until the socket is closed, + or until an exception occurs. + + :return: None. + + """ + + while not self.done: + try: + body = await self._socket.recv() + self._queue.put_nowait((True, body)) + except websockets.exceptions.ConnectionClosedOK: + await self._queue.join() + self.done = True # socket closed, will terminate on next loop + + def _ping_handlers(self, event_type: LiveTranscriptionEvent, + body: Any) -> None: + """ + The _ping_handlers function is a callback that is called when the + transcription service sends a ping event. It calls all of the functions + in self.handlers, which are registered by calling add_ping_handler(). + + :param event_type:LiveTranscriptionEvent: Used to Determine if the function should be called. + :param body:Any: Used to Pass the event data to the handler function. + :return: The list of handlers for the event type. + + """ + + for handled_type, func in self.handlers: + if handled_type is event_type: + if inspect.iscoroutinefunction(func): + asyncio.create_task(cast(Awaitable[None], func(body))) + else: + func(body) + + # Public + + def register_handler(self, event_type: LiveTranscriptionEvent, + handler: EventHandler) -> None: + """Adds an event handler to the transcription client.""" + + self.handlers.append((event_type, handler)) + + # alias for incorrect method name in v0.1.x + def registerHandler(self, *args, **kwargs): + warn( + ( + "This method name is deprecated, " + "and will be removed in the future - " + "use `register_handler`." + ), + DeprecationWarning + ) + return self.register_handler(*args, **kwargs) + + def deregister_handler(self, event_type: LiveTranscriptionEvent, + handler: EventHandler) -> None: + """Removes an event handler from the transcription client.""" + + self.handlers.remove((event_type, handler)) + + # alias for incorrect method name in v0.1.x + def deregisterHandler(self, *args, **kwargs): + warn( + ( + "This method name is deprecated, " + "and will be removed in the future - " + "use `deregister_handler`." + ), + DeprecationWarning + ) + return self.deregister_handler(*args, **kwargs) + + def send(self, data: Union[bytes, str]) -> None: + """Sends data to the Deepgram endpoint.""" + + self._queue.put_nowait((False, data)) + + def configure(self, config: ToggleConfigOptions) -> None: + """Sends messages to configure transcription parameters mid-stream.""" + self._queue.put_nowait((False, json.dumps({ + "type": "Configure", + "processors": config + }))) + + def keep_alive(self) -> None: + """Keeps the connection open when no audio data is being sent.""" + self._queue.put_nowait((False, json.dumps({"type": "KeepAlive"}))) + + async def finish(self) -> None: + """Closes the connection to the Deepgram endpoint, + waiting until ASR is complete on all submitted data.""" + + self.send(json.dumps({"type": "CloseStream"})) # Set message for "data is finished sending" + while not self.done: + await asyncio.sleep(0.1) + + @property + def event(self) -> Enum: + """An enum representing different possible transcription events + that handlers can be registered against.""" + + return cast(Enum, LiveTranscriptionEvent) + + +class Transcription: + """ + This is the Transcription class. It provides two async methods, prerecorded and live, that + return transcription responses for audio files and live audio streams, respectively. + + """ + + def __init__(self, options: Options) -> None: + self.options = options + + async def prerecorded( + self, source: TranscriptionSource, + options: PrerecordedOptions = None, + endpoint = "/listen", + timeout: float = None, + **kwargs + ) -> PrerecordedTranscriptionResponse: + """Retrieves a transcription for an already-existing audio file, + local or web-hosted.""" + if options is None: + options = {} + full_options = cast(PrerecordedOptions, {**options, **kwargs}) + return await PrerecordedTranscription( + self.options, full_options, endpoint + )(source, timeout=timeout) + + def sync_prerecorded( + self, source: TranscriptionSource, + options: PrerecordedOptions = None, + endpoint = "/listen", + timeout: float = None, + **kwargs + ) -> PrerecordedTranscriptionResponse: + """Retrieves a transcription for an already-existing audio file, + local or web-hosted.""" + if options is None: + options = {} + full_options = cast(PrerecordedOptions, {**options, **kwargs}) + return SyncPrerecordedTranscription( + self.options, full_options, endpoint + )(source, timeout=timeout) + + async def live( + self, options: LiveOptions = None, endpoint = "/listen", **kwargs + ) -> LiveTranscription: + """Provides a client to send raw audio data to be transcribed.""" + if options is None: + options = {} + full_options = cast(LiveOptions, {**options, **kwargs}) + return await LiveTranscription( + self.options, full_options, endpoint + )() diff --git a/venv/Lib/site-packages/deepgram/usage.py b/venv/Lib/site-packages/deepgram/usage.py new file mode 100644 index 00000000..0c5736a6 --- /dev/null +++ b/venv/Lib/site-packages/deepgram/usage.py @@ -0,0 +1,54 @@ +from typing import cast +from ._types import (Options, UsageField, UsageFieldOptions, + UsageOptions, UsageRequest, UsageRequestList, + UsageRequestListOptions, UsageResponse) +from ._utils import _request, _make_query_string + + +class Usage: + _root = "/projects" + + def __init__(self, options: Options) -> None: + self.options = options + + async def list_requests( + self, project_id: str, options: UsageRequestListOptions = None + ) -> UsageRequestList: + """Retrieves a range of requests sent to a given project.""" + if options is None: + options = cast(UsageRequestListOptions, {}) + return await _request( + f'{self._root}/{project_id}/requests{_make_query_string(options)}', + self.options + ) + + async def get_request( + self, project_id: str, request_id: str + ) -> UsageRequest: + """Retrieves a single request sent to a given project.""" + return await _request( + f'{self._root}/{project_id}/requests/{request_id}', + self.options + ) + + async def get_usage( + self, project_id: str, options: UsageOptions = None + ) -> UsageResponse: + """Summarizes the usage for a given project.""" + if options is None: + options = cast(UsageOptions, {}) + return await _request( + f'{self._root}/{project_id}/usage{_make_query_string(options)}', + self.options + ) + + async def get_fields( + self, project_id: str, options: UsageFieldOptions = None + ) -> UsageField: + """Summarizes the options used in transcription for a given project.""" + if options is None: + options = cast(UsageFieldOptions, {}) + return await _request( + f'{self._root}/{project_id}/fields{_make_query_string(options)}', + self.options + ) diff --git a/venv/Lib/site-packages/deepgram/utils/__init__.py b/venv/Lib/site-packages/deepgram/utils/__init__.py deleted file mode 100644 index 21343d9d..00000000 --- a/venv/Lib/site-packages/deepgram/utils/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -import logging -from .verboselogs import VerboseLogger -from .verboselogs import ( - NOTICE, - SPAM, - SUCCESS, - VERBOSE, - WARNING, - ERROR, - FATAL, - CRITICAL, - INFO, - DEBUG, - NOTSET, -) diff --git a/venv/Lib/site-packages/deepgram/utils/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/utils/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index 9b6f058f..00000000 Binary files a/venv/Lib/site-packages/deepgram/utils/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram/utils/verboselogs/__init__.py b/venv/Lib/site-packages/deepgram/utils/verboselogs/__init__.py deleted file mode 100644 index c7d39326..00000000 --- a/venv/Lib/site-packages/deepgram/utils/verboselogs/__init__.py +++ /dev/null @@ -1,168 +0,0 @@ -# Copyright 2024 Deepgram SDK contributors. All Rights Reserved. -# Use of this source code is governed by a MIT license that can be found in the LICENSE file. -# SPDX-License-Identifier: MIT - -""" -Custom log levels for Python's :mod:`logging` module. - -The :mod:`verboselogs` module defines the :data:`NOTICE`, :data:`SPAM`, -:data:`SUCCESS` and :data:`VERBOSE` constants, the :class:`VerboseLogger` class -and the :func:`add_log_level()` and :func:`install()` functions. - -At import time :func:`add_log_level()` is used to register the custom log -levels :data:`NOTICE`, :data:`SPAM`, :data:`SUCCESS` and :data:`VERBOSE` with -Python's :mod:`logging` module. -""" - -import logging - -__version__ = "1.8" -"""Semi-standard module versioning.""" - -NOTICE = 25 -""" -The numeric value of the 'notice' log level (a number). - -The value of :data:`NOTICE` positions the notice log level between the -:data:`~verboselogs.WARNING` and :data:`~verboselogs.INFO` levels. - -:see also: The :func:`~VerboseLogger.notice()` method of the - :class:`VerboseLogger` class. -""" - -SPAM = 5 -""" -The numeric value of the 'spam' log level (a number). - -The value of :data:`SPAM` positions the spam log level between the -:data:`~verboselogs.DEBUG` and :data:`~verboselogs.NOTSET` levels. - -:see also: The :func:`~VerboseLogger.spam()` method of the - :class:`VerboseLogger` class. -""" - -SUCCESS = 35 -""" -The numeric value of the 'success' log level (a number). - -The value of :data:`SUCCESS` positions the success log level between the -:data:`~verboselogs.WARNING` and :data:`~verboselogs.ERROR` levels. - -:see also: The :func:`~VerboseLogger.success()` method of the - :class:`VerboseLogger` class. -""" - -VERBOSE = 15 -""" -The numeric value of the 'verbose' log level (a number). - -The value of :data:`VERBOSE` positions the verbose log level between the -:data:`~verboselogs.INFO` and :data:`~verboselogs.DEBUG` levels. - -:see also: The :func:`~VerboseLogger.verbose()` method of the - :class:`VerboseLogger` class. -""" - - -def install(): - """ - Make :class:`VerboseLogger` the default logger class. - - The :func:`install()` function uses :func:`~logging.setLoggerClass()` to - configure :class:`VerboseLogger` as the default class for all loggers - created by :func:`logging.getLogger()` after :func:`install()` has been - called. Here's how it works: - - .. code-block:: python - - import logging - import verboselogs - - verboselogs.install() - logger = logging.getLogger(__name__) # will be a VerboseLogger instance - """ - logging.setLoggerClass(VerboseLogger) - - -def add_log_level(value, name): - """ - Add a new log level to the :mod:`logging` module. - - :param value: The log level's number (an integer). - :param name: The name for the log level (a string). - """ - logging.addLevelName(value, name) - setattr(logging, name, value) - - -WARNING = logging.WARNING -ERROR = logging.ERROR -FATAL = logging.FATAL -CRITICAL = logging.CRITICAL -INFO = logging.INFO -DEBUG = logging.DEBUG -NOTSET = logging.NOTSET - -# Define the NOTICE log level. -add_log_level(NOTICE, "NOTICE") - -# Define the SPAM log level. -add_log_level(SPAM, "SPAM") - -# Define the SUCCESS log level. -add_log_level(SUCCESS, "SUCCESS") - -# Define the VERBOSE log level. -add_log_level(VERBOSE, "VERBOSE") - - -class VerboseLogger(logging.Logger): - """ - Custom logger class to support the additional logging levels. - - This subclass of :class:`verboselogs.Logger` adds support for the additional - logging methods :func:`notice()`, :func:`spam()`, :func:`success()` and - :func:`verbose()`. - - You can use :func:`verboselogs.install()` to make :class:`VerboseLogger` - the default logger class. - """ - - def __init__(self, *args, **kw): - """ - Initialize a :class:`VerboseLogger` object. - - :param args: Refer to the superclass (:class:`verboselogs.Logger`). - :param kw: Refer to the superclass (:class:`verboselogs.Logger`). - - This method first initializes the superclass and then it sets the root - logger as the parent of this logger. - - The function :func:`logging.getLogger()` is normally responsible for - defining the hierarchy of logger objects however because verbose - loggers can be created by calling the :class:`VerboseLogger` - constructor, we're responsible for defining the parent relationship - ourselves. - """ - logging.Logger.__init__(self, *args, **kw) - self.parent = logging.getLogger() - - def notice(self, msg, *args, **kw): - """Log a message with level :data:`NOTICE`. The arguments are interpreted as for :func:`logging.debug()`.""" - if self.isEnabledFor(NOTICE): - self._log(NOTICE, msg, args, **kw) - - def spam(self, msg, *args, **kw): - """Log a message with level :data:`SPAM`. The arguments are interpreted as for :func:`logging.debug()`.""" - if self.isEnabledFor(SPAM): - self._log(SPAM, msg, args, **kw) - - def success(self, msg, *args, **kw): - """Log a message with level :data:`SUCCESS`. The arguments are interpreted as for :func:`logging.debug()`.""" - if self.isEnabledFor(SUCCESS): - self._log(SUCCESS, msg, args, **kw) - - def verbose(self, msg, *args, **kw): - """Log a message with level :data:`VERBOSE`. The arguments are interpreted as for :func:`logging.debug()`.""" - if self.isEnabledFor(VERBOSE): - self._log(VERBOSE, msg, args, **kw) diff --git a/venv/Lib/site-packages/deepgram/utils/verboselogs/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/deepgram/utils/verboselogs/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index 4c44a917..00000000 Binary files a/venv/Lib/site-packages/deepgram/utils/verboselogs/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/venv/Lib/site-packages/deepgram_sdk-2.12.0.dist-info/INSTALLER b/venv/Lib/site-packages/deepgram_sdk-2.12.0.dist-info/INSTALLER new file mode 100644 index 00000000..a1b589e3 --- /dev/null +++ b/venv/Lib/site-packages/deepgram_sdk-2.12.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/Lib/site-packages/deepgram_sdk-4.2.0.dist-info/licenses/LICENSE b/venv/Lib/site-packages/deepgram_sdk-2.12.0.dist-info/LICENSE similarity index 100% rename from venv/Lib/site-packages/deepgram_sdk-4.2.0.dist-info/licenses/LICENSE rename to venv/Lib/site-packages/deepgram_sdk-2.12.0.dist-info/LICENSE diff --git a/venv/Lib/site-packages/deepgram_sdk-2.12.0.dist-info/METADATA b/venv/Lib/site-packages/deepgram_sdk-2.12.0.dist-info/METADATA new file mode 100644 index 00000000..795db609 --- /dev/null +++ b/venv/Lib/site-packages/deepgram_sdk-2.12.0.dist-info/METADATA @@ -0,0 +1,1021 @@ +Metadata-Version: 2.1 +Name: deepgram-sdk +Version: 2.12.0 +Summary: The official Python SDK for the Deepgram automated speech recognition platform. +Home-page: https://github.com/deepgram/deepgram-python-sdk +Author: Luca Todd +Author-email: luca.todd@deepgram.com +License: MIT +Keywords: deepgram speech-to-text +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python :: 3 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: aiohttp +Requires-Dist: websockets +Requires-Dist: typing-extensions ; python_version < "3.8.0" + +# Deepgram Python SDK + + [![Discord](https://dcbadge.vercel.app/api/server/xWRaCDBtW4?style=flat)](https://discord.gg/xWRaCDBtW4) [![GitHub Workflow Status](https://img.shields.io/github/workflow/status/deepgram/deepgram-python-sdk/CI)](https://github.com/deepgram/deepgram-python-sdk/actions/workflows/CI.yml) [![PyPI](https://img.shields.io/pypi/v/deepgram-sdk)](https://pypi.org/project/deepgram-sdk/) +[![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg?style=flat-rounded)](./.github/CODE_OF_CONDUCT.md) + +Official Python SDK for [Deepgram](https://www.deepgram.com/). Power your apps with world-class speech and Language AI models. + +> This SDK only supports hosted usage of api.deepgram.com. + +* [Deepgram Python SDK](#deepgram-python-sdk) +* [Documentation](#documentation) +* [Getting an API Key](#getting-an-api-key) +* [Installation](#installation) +* [Examples](#examples) +* [Testing](#testing) +* [Configuration](#configuration) + * [Custom API Endpoint] [#custom-api-endpoint] +* [Transcription](#transcription) + * [Remote Files](#remote-files) + * [Local Files](#local-files) + * [Live Audio](#live-audio) + * [Parameters](#parameters) +* [Projects](#projects) + * [Get Projects](#get-projects) + * [Get Project](#get-project) + * [Update Project](#update-project) +* [Keys](#keys) + * [List Keys](#list-keys) + * [Get Key](#get-key) + * [Create Key](#create-key) + * [Delete Key](#delete-key) +* [Members](#members) + * [Get Members](#get-members) + * [Remove Member](#remove-member) +* [Scopes](#scopes) + * [Get Member Scopes](#get-member-scopes) + * [Update Scope](#update-scope) +* [Invitations](#invitations) + * [List Invites](#list-invites) + * [Send Invite](#send-invite) + * [Delete Invite](#delete-invite) + * [Leave Project](#leave-project) +* [Usage](#usage) + * [Get All Requests](#get-all-requests) + * [Get Request](#get-request) + * [Get Fields](#get-fields) +* [Billing](#billing) + * [Get All Balances](#get-all-balances) + * [Get Balance](#get-balance) +* [Development and Contributing](#development-and-contributing) +* [Getting Help](#getting-help) + +# Documentation + +You can learn more about the Deepgram API at [developers.deepgram.com](https://developers.deepgram.com/docs). + +# Getting an API Key + +🔑 To access the Deepgram API you will need a [free Deepgram API Key](https://console.deepgram.com/signup?jump=keys). + +# Installation + +```sh +pip install deepgram-sdk +``` +# Examples + +To quickly get started with examples for prerecorded and streaming, run the files in the example folder. See the README in that folder for more information on getting started. + +# Testing + +## Setup + +Run the following command to install `pytest` and `pytest-cov` as dev dependencies. + +``` +pip install -r requirements-dev.txt +``` + +## Run All Tests + +## Setup + +``` +pip install pytest +pip install pytest-cov +``` + +## Run All Tests + +``` +pytest --api-key tests/ +``` + +## Test Coverage Report + +``` +pytest --cov=deepgram --api-key tests/ +``` + +# Configuration + +To setup the configuration of the Deepgram Client, do the following: + +- Import the Deepgram client +- Create a Deepgram Client instance and pass in credentials to the constructor. + +```python +from deepgram import Deepgram + +DEEPGRAM_API_KEY = 'YOUR_API_KEY' +deepgram = Deepgram(DEEPGRAM_API_KEY) +``` + +## Custom API Endpoint + +In order to point the SDK at a different API environment (e.g., for on-prem deployments), you can pass in an object setting the `api_url` when initializing the Deepgram client. + +```py +dg_client = Deepgram({ + "api_key": DEEPGRAM_API_KEY, + "api_url": "http://localhost:8080/v1/listen" +}) +``` + +# Transcription + +## Remote Files + +```python +from deepgram import Deepgram +import asyncio, json + +DEEPGRAM_API_KEY = 'YOUR_API_KEY' +FILE_URL = 'https://static.deepgram.com/examples/interview_speech-analytics.wav' + +async def main(): + # Initializes the Deepgram SDK + deepgram = Deepgram(DEEPGRAM_API_KEY) + source = {'url': FILE_URL} + response = await asyncio.create_task( + deepgram.transcription.prerecorded(source, { + 'smart_format': True, + 'model': 'nova', + })) + print(json.dumps(response, indent=4)) + +asyncio.run(main()) +``` + +## Local Files + +```python +from deepgram import Deepgram +import json + +DEEPGRAM_API_KEY = 'YOUR_API_KEY' +PATH_TO_FILE = 'some/file.wav' + +def main(): + # Initializes the Deepgram SDK + deepgram = Deepgram(DEEPGRAM_API_KEY) + # Open the audio file + with open(PATH_TO_FILE, 'rb') as audio: + # ...or replace mimetype as appropriate + source = {'buffer': audio, 'mimetype': 'audio/wav'} + response = deepgram.transcription.sync_prerecorded(source, {'punctuate': True}) + print(json.dumps(response, indent=4)) + +main() +``` + +## Live Audio + +```python +from deepgram import Deepgram +import asyncio +import aiohttp + +# Your Deepgram API Key +DEEPGRAM_API_KEY = 'YOUR_API_KEY' + +# URL for the audio you would like to stream +URL = 'http://stream.live.vc.bbcmedia.co.uk/bbc_world_service' + +async def main(): + # Initialize the Deepgram SDK + deepgram = Deepgram(DEEPGRAM_API_KEY) + + # Create a websocket connection to Deepgram + # In this example, punctuation is turned on, interim results are turned off, and language is set to US English. + try: + deepgramLive = await deepgram.transcription.live({ 'punctuate': True, 'interim_results': False, 'language': 'en-US' }) + except Exception as e: + print(f'Could not open socket: {e}') + return + +# Listen for the connection to close + deepgramLive.registerHandler(deepgramLive.event.CLOSE, lambda c: print(f'Connection closed with code {c}.')) + + # Listen for any transcripts received from Deepgram and write them to the console + deepgramLive.registerHandler(deepgramLive.event.TRANSCRIPT_RECEIVED, print) + + # Listen for the connection to open and send streaming audio from the URL to Deepgram + async with aiohttp.ClientSession() as session: + async with session.get(URL) as audio: + while True: + data = await audio.content.readany() + deepgramLive.send(data) + + # If there's no data coming from the livestream then break out of the loop + if not data: + break + + # Indicate that we've finished sending data by sending the customary zero-byte message to the Deepgram streaming endpoint, and wait until we get back the final summary metadata object + await deepgramLive.finish() + +asyncio.run(main()) +``` + +## Parameters + +Query parameters like `punctuate` are added as part of the `TranscriptionOptions` `dict` in the `.prerecorded`/`.live` transcription call. +Multiple query parameters can be added similarly, and any dict will do - the types are provided for reference/convenience. + +```python +response = await dg_client.transcription.prerecorded(source, {'punctuate': True, 'keywords': ['first:5', 'second']}) +``` + +Depending on your preference, you can also add parameters as named arguments, instead. + +```python +response = await dg_client.transcription.prerecorded(source, punctuate=True, keywords=['first:5', 'second']) +``` + +# Projects + +The `Deepgram.projects` object provides access to manage projects associated with the API key you provided when instantiating the Deepgram client. + +## Get Projects + +### Get Projects Example Request + +```python +projects = await deepgram.projects.list() +``` + +### Get Projects Response + +```ts +{ + projects: [ + { + project_id: String, + name: String, + }, + ], +} +``` + +## Get Project + +Retrieves a project based on the provided project id. + +### Get a Project Parameters + +| Parameter | Type | Description | +| ---------- | ------ | ----------------------------------------------- | +| project_id | String | A unique identifier for the project to retrieve | + +### Get a Project Example Request + +```python +project = await deepgram.projects.get(PROJECT_ID) +``` + +### Get a Project Response + +``` +{ + project_id: String, + name: String, +} +``` + +## Update Project + +Updates a project based on a provided project object. + +### Update Project Parameters + +| Parameter | Type | Description | +| --------- | ------ | ------------------------------------------------------------------------------- | +| project | Object | Object representing a project. Must contain `project_id` and `name` properties. | + + +### Update a Project Example Request + +```python +updateResponse = await deepgram.projects.update(project) +``` + +### Update a Project Response + +``` +{ + message: String; +} +``` + +# Keys + +The `Deepgram.keys` object provides access to manage keys associated with your projects. Every function provided will required a `PROJECT_ID` that your current has access to manage. + +## List Keys + +You can retrieve all keys for a given project using the `keys.list` function. + +### List Project API Keys Parameters + +| Parameter | Type | Description | +| ---------- | ------ | ------------------------------------------------------------------- | +| project_id | String | A unique identifier for the project the API key will be created for | + +### List Project Keys Example Request + +```python +response = await deepgram.keys.list(PROJECT_ID) +``` + +### List Keys Response + +``` +{ + api_keys: [ + { + api_key_id: string, + comment: string, + created: string, + scopes: Array, + }, + ]; +} +``` + +## Create Key + +Create a new API key for a project using the `keys.create` function with a name for the key. + +### Create API Key Parameters + +| Parameter | Type | Description | +| --------------- | ------ | ------------------------------------------------------------------- | +| project_id | String | A unique identifier for the project the API key will be created for | +| comment_for_key | String | A comment to denote what the API key is for | +| scopes | Array | A permissions scopes of the key to create | + +### Create API Key Example Request + +```python +response = await deepgram.keys.create(PROJECT_ID, COMMENT_FOR_KEY, SCOPES) +``` + +### Create API Key Response + +``` +{ + api_key_id: string, + key: string, + comment: string, + created: string, + scopes: string[] +} +``` + +## Delete Key + +Delete an existing API key using the `keys.delete` method with project id and key id to delete. + +### Delete Key Parameters + +| Parameter | Type | Description | +| ---------- | ------ | ------------------------------------------------------------------- | +| project_id | String | A unique identifier for the project the API key will be delete from | +| key_id | String | A unique identifier for the API key to delete | + +### Delete Key Example Request + +```python +await deepgram.keys.delete(PROJECT_ID, KEY_ID) +``` + +### Delete Key Response + +The `keys.delete` function returns a void. + +# Members + +The `deepgram.members` object provides access to the members endpoints of the Deepgram API. Each request is project based and will require a `project_id`. + +## Get Members + +You can retrieve all members on a given project using the `members.list_members` function. + +### Get Members Parameters + +| Parameter | Type | Description | +| ---------- | ------ | ------------------------------------------------------------------ | +| project_id | String | A unique identifier for the project you wish to see the members of | + +### Get Members Example Request + +```python +response = await deepgram.members.list_members(PROJECT_ID) +``` + +### Get Members Response + +``` +{ + members: [ + { + member_id: string, + scopes: Array + email: string, + first_name: string, + last_name: string, + }, + ]; +} +``` + +## Remove Member + +You can remove a member from a given project using the `members.remove_member` function. + +### Remove Member Parameters + +| Parameter | Type | Description | +| ---------- | ------ | ------------------------------------------------------------------ | +| project_id | String | A unique identifier for the project you wish to see the members of | +| member_id | String | A unique identifier for the member you wish to remove | + +### Remove Member Example Request + +```python +response = await deepgram.members.remove_member(PROJECT_ID, MEMBER_ID) +``` + +### Remove Member Response + +``` +{ + message: string; +} +``` +# Scopes + +The `deepgram.scopes` object provides access to the scopes endpoints of the Deepgram API. Each request is project based and will require a `project_id`. + +## Get Member Scopes + +You can retrieve all scopes of a member on a given project using the `scopes.get_scope` function. + +### Get Member Scopes Parameters + +| Parameter | Type | Description | +| ---------- | ------ | ------------------------------------------------------------------------ | +| project_id | String | A unique identifier for the project you wish to see the member scopes of | +| member_id | String | A unique identifier for the member you wish to see member scopes of | + +### Get Member Scopes Example Request + +```python +response = await deepgram.scopes.get_scope(PROJECT_ID, MEMBER_ID) +``` + +### Get Member Scopes Response + +``` +{ + scopes: string[] +} +``` + +## Update Scope + +You can update the scope of a member on a given project using the `scopes.update_scope` function. + +### Update Scope Parameters + +| Parameter | Type | Description | +| ---------- | ------ | --------------------------------------------------------------------------- | +| project_id | String | A unique identifier for the project you wish to update the member scopes of | +| member_id | String | A unique identifier for the member you wish to update member scopes of | +| scopes | String | The scope you wish to update the member to | + +### Update Scope Example Request + +```python +response = await deepgram.scopes.update_scope(PROJECT_ID, MEMBER_ID, 'member') +``` + +### Update Scope Response + +``` +{ + message: string; +} +``` + +# Invitations + +The `deepgram.invitations` object provides access to the invites endpoints of the Deepgram API. Each request is project based and will require a `project_id`. + +## List Invites + +You can retrieve all active invitations on a given project using the `invitations.list_invitations` function. + +### List Invites Parameters + +| Parameter | Type | Description | +| ---------- | ------ | ---------------------------------------------------------------------- | +| project_id | String | A unique identifier for the project you wish to see the invitations of | + +### List Invites Example Request + +```python +response = await deepgram.invitations.list_invitations(PROJECT_ID) +``` + +### List Invites Response + +``` +{ + members: [ + { + email: string, + scope: string, + }, + ]; +} +``` + +## Send Invite + +You can send an invitation to a given email address to join a given project using the `invitations.send_invitation` function. + +### Send Invite Parameters + +| Parameter | Type | Description | +| ---------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------- | +| project_id | String | A unique identifier for the project you wish to send an invitation from | +| option | Object | An object containing the email address of the person you wish to send an invite to, and the scope you want them to have in the project | + +### Send Invite Example Request + +```python +response = await deepgram.invitations.send_invitation(PROJECT_ID, { + email: 'example@email.com', + scope: 'member', +}) +``` + +### Send Invite Response + +``` +{ + message: string; +} +``` + +## Delete Invite + +Removes the invitation of the specified email from the specified project. + +### Delete Invite Parameters + +| Parameter | Type | Description | +| ---------- | ------ | ---------------------------------------------------------------------- | +| project_id | String | A unique identifier for the project you wish to remove the invite from | +| email | String | The email address of the invitee | + +### Delete Invite Example Request + +```python +response = await deepgram.invitations.remove_invitation( + PROJECT_ID, + 'example@email.com' +) +``` + +### Delete Invite Response + +``` +{ + message: string; +} +``` + +## Leave Project + +Removes the authenticated account from the specified project. + +### Leave Project Parameters + +| Parameter | Type | Description | +| ---------- | ------ | ----------------------------------------------------- | +| project_id | String | A unique identifier for the project you wish to leave | + +### Leave Project Example Request + +```python +response = await deepgram.invitations.leave_project(PROJECT_ID) +``` + +### Leave Project Response + +``` +{ + message: string; +} +``` + +# Usage + +The `deepgram.usage` object provides access to the usage endpoints of the Deepgram API. Each request is project based and will require a `project_id`. + +## Get All Requests + +Retrieves transcription requests for a project based on the provided options. + +### Get All Requests Parameters + +| Parameter | Type | Description | +| ---------- | ------ | --------------------------------------------------------- | +| project_id | String | A unique identifier for the project to retrieve usage for | +| options | Object | Parameters to filter requests. See below. | + +#### Get All Requests Options + +```python +{ + // The time to retrieve requests made since + // Example: "2020-01-01T00:00:00+00:00" + start?: String, + // The time to retrieve requests made until + // Example: "2021-01-01T00:00:00+00:00" + end?: String, + // Page of requests to return + // Defaults to 0 + page?: Number, + // Number of requests to return per page + // Defaults to 10. Maximum of 100 + limit?: Number, + // Filter by succeeded or failed requests + // By default, all requests are returned + status?: 'succeeded' | 'failed' +} +``` + +### Get All Requests Example Request + +```python +response = await deepgram.usage.list_requests(PROJECT_ID, { + 'limit': 10, + # other options are available +}) +``` + +### Get All Requests Response + +``` +{ + page: Number, + limit: Number, + requests?: [ + { + request_id: String; + created: String; + path: String; + accessor: String; + response?: { + details: { + usd: Number; + duration: Number; + total_audio: Number; + channels: Number; + streams: Number; + model: String; + method: String; + tags: String[]; + features: String[]; + config: { + multichannel?: Boolean; + interim_results?: Boolean; + punctuate?: Boolean; + ner?: Boolean; + utterances?: Boolean; + replace?: Boolean; + profanity_filter?: Boolean; + keywords?: Boolean; + diarize?: Boolean; + search?: Boolean; + redact?: Boolean; + alternatives?: Boolean; + numerals?: Boolean; + }; + } + }, || + { + message?: String; + }, + callback?: { + code: Number; + completed: String; + }, + }, + ]; +} +``` + +## Get Request + +Retrieves a specific transcription request for a project based on the provided `projectId` and `requestId`. + +### Get Request Parameters + +| Parameter | Type | Description | +| ---------- | ------ | --------------------------------------------------------- | +| project_id | String | A unique identifier for the project to retrieve usage for | +| request_id | String | Unique identifier of the request to retrieve | + +### Get Request Example Request + +```python +response = await deepgram.usage.get_request(PROJECT_ID, REQUEST_ID) +``` + +### Get Request Response + +``` +{ + request_id: String; + created: String; + path: String; + accessor: String; + response?: { + details: { + usd: Number; + duration: Number; + total_audio: Number; + channels: Number; + streams: Number; + model: String; + method: String; + tags: String[]; + features: String[]; + config: { + multichannel?: Boolean; + interim_results?: Boolean; + punctuate?: Boolean; + ner?: Boolean; + utterances?: Boolean; + replace?: Boolean; + profanity_filter?: Boolean; + keywords?: Boolean; + diarize?: Boolean; + search?: Boolean; + redact?: Boolean; + alternatives?: Boolean; + numerals?: Boolean; + }; + } + }, || + { + message?: String; + }, + callback?: { + code: Number; + completed: String; + } +} +``` + +## Get Usage + +Retrieves aggregated usage data for a project based on the provided options. + +### Get Usage Parameters + +| Parameter | Type | Description | +| ---------- | ------ | --------------------------------------------------------- | +| project_id | String | A unique identifier for the project to retrieve usage for | +| options | Object | Parameters to filter requests. See below. | + +#### Get Usage Options + +```python +{ + // The time to retrieve requests made since + // Example: "2020-01-01T00:00:00+00:00" + start?: String, + // The time to retrieve requests made until + // Example: "2021-01-01T00:00:00+00:00" + end?: String, + // Specific identifer for a request + accessor?: String, + // Array of tags used in requests + tag?: String[], + // Filter requests by method + method?: "sync" | "async" | "streaming", + // Filter requests by model used + model?: String, + // Filter only requests using multichannel feature + multichannel?: Boolean, + // Filter only requests using interim results feature + interim_results?: Boolean, + // Filter only requests using the punctuation feature + punctuate?: Boolean, + // Filter only requests using ner feature + ner?: Boolean, + // Filter only requests using utterances feature + utterances?: Boolean, + // Filter only requests using replace feature + replace?: Boolean, + // Filter only requests using profanity_filter feature + profanity_filter?: Boolean, + // Filter only requests using keywords feature + keywords?: Boolean, + // Filter only requests using diarization feature + diarize?: Boolean, + // Filter only requests using search feature + search?: Boolean, + // Filter only requests using redact feature + redact?: Boolean, + // Filter only requests using alternatives feature + alternatives?: Boolean, + // Filter only requests using numerals feature + numerals?: Boolean +} +``` + +### Get Usage Example Request + +```python +response = await deepgram.usage.get_usage(PROJECT_ID, { + 'start': '2020-01-01T00:00:00+00:00', + # other options are available +}) +``` + +### Get Usage Response + +``` +{ + start: String, + end: String, + resolution: { + units: String, + amount: Number + }; + results: [ + { + start: String, + end: String, + hours: Number, + requests: Number + } + ]; +} +``` + +## Get Fields + +Retrieves features used by the provided project_id based on the provided options. + +### Get Fields Parameters + +| Parameter | Type | Description | +| ---------- | ------ | --------------------------------------------------------------- | +| project_id | String | A unique identifier for the project to retrieve fields used for | +| options | Object | Parameters to filter requests. See below. | + +#### Get Fields Options + +```typescript +{ + // The time to retrieve requests made since + // Example: "2020-01-01T00:00:00+00:00" + start?: String, + // The time to retrieve requests made until + // Example: "2021-01-01T00:00:00+00:00" + end?: String +} +``` + +### Get Fields Example Request + +```python +response = await deepgram.usage.get_fields(PROJECT_ID, { + 'start': '2020-01-01T00:00:00+00:00', + # other options are available +}) +``` + +#### Get Fields Response + +``` +{ + tags: String[], + models: String[], + processing_methods: String[], + languages: String[], + features: String[] +} +``` + +# Billing + +The `deepgram.billing` object provides access to the balances endpoints of the Deepgram API. Each request is project based and will require a `project_id`. + + +## Get All Balances + +You can retrieve all balances on a given project using the `billing.list_balance` function. + +### Get All Balances Parameters + +| Parameter | Type | Description | +| ---------- | ------ | ----------------------------------------------------------------------- | +| project_id | String | A unique identifier for the project you wish to see the balance info of | + +### Get All Balances Example Request + +```python +response = await deepgram.billing.list_balance(PROJECT_ID) +``` + +### Get All Balances Response + +``` +{ + balances: [ + { + balance_id: string + amount: number + units: string + purchase: string + } + ] +} +``` + +## Get Balance + +You can retrieve all balances on a given project using the `billing.get_balance` function. + +### Get Balance Parameters + +| Parameter | Type | Description | +| ---------- | ------ | ----------------------------------------------------------------------- | +| project_id | String | A unique identifier for the project you wish to see the balance info of | +| balance_id | String | A unique identifier for the balance you wish to see the balance info of | + +### Get Balance Example Request + +```python +const response = deepgram.billing.get_balance(PROJECT_ID, BALANCE_ID) +``` + +### Get Balance Response + +``` +{ + balance: { + balance_id: string; + amount: number; + units: string; + purchase: string; + } +} +``` + +# Development and Contributing + +Interested in contributing? We ❤️ pull requests! + +To make sure our community is safe for all, be sure to review and agree to our +[Code of Conduct](./CODE_OF_CONDUCT.md). Then see the +[Contribution](./CONTRIBUTING.md) guidelines for more information. + +# Getting Help + +We love to hear from you so if you have questions, comments or find a bug in the +project, let us know! You can either: + +- [Open an issue in this repository](https://github.com/deepgram/deepgram-python-sdk/issues/new) +- [Join the Deepgram Github Discussions Community](https://github.com/orgs/deepgram/discussions) +- [Join the Deepgram Discord Community](https://discord.gg/xWRaCDBtW4) + +[license]: LICENSE.txt + + diff --git a/venv/Lib/site-packages/deepgram_sdk-2.12.0.dist-info/RECORD b/venv/Lib/site-packages/deepgram_sdk-2.12.0.dist-info/RECORD new file mode 100644 index 00000000..f1221ab1 --- /dev/null +++ b/venv/Lib/site-packages/deepgram_sdk-2.12.0.dist-info/RECORD @@ -0,0 +1,39 @@ +deepgram/__init__.py,sha256=yskGjCYkzt9DIG9BizXuqqQnTg3_IbFItHC8ew3b14c,2127 +deepgram/__pycache__/__init__.cpython-312.pyc,, +deepgram/__pycache__/_constants.cpython-312.pyc,, +deepgram/__pycache__/_enums.cpython-312.pyc,, +deepgram/__pycache__/_types.cpython-312.pyc,, +deepgram/__pycache__/_utils.cpython-312.pyc,, +deepgram/__pycache__/_version.cpython-312.pyc,, +deepgram/__pycache__/billing.cpython-312.pyc,, +deepgram/__pycache__/errors.cpython-312.pyc,, +deepgram/__pycache__/extra.cpython-312.pyc,, +deepgram/__pycache__/invitations.cpython-312.pyc,, +deepgram/__pycache__/keys.cpython-312.pyc,, +deepgram/__pycache__/members.cpython-312.pyc,, +deepgram/__pycache__/projects.cpython-312.pyc,, +deepgram/__pycache__/scopes.cpython-312.pyc,, +deepgram/__pycache__/transcription.cpython-312.pyc,, +deepgram/__pycache__/usage.cpython-312.pyc,, +deepgram/_constants.py,sha256=EEYmkv_-aNTvqIH8fca7P7mzItVM-uvVBqR0pZNpTn8,49 +deepgram/_enums.py,sha256=ZpgDwcV-EZAJ0RpkOLaTYTtg0TaE-CMSLWl3NLKAhrI,226 +deepgram/_types.py,sha256=oOHJsoaJKPcKt63moSg58PRB0zw7VnGZk_Lw1LxhKKY,9156 +deepgram/_utils.py,sha256=lH7qY8bjeSSOqHMeKSA_lova4WB_GfB3YOrsXTRangc,9663 +deepgram/_version.py,sha256=oVNlkZ967jzwDYde_JFnxJlmjNK42f0XhFKROknSgOw,24 +deepgram/billing.py,sha256=f9fbHcMTjhGnwbpdSDK6O_-FnsxqurMRHgo5pqxzYbI,708 +deepgram/errors.py,sha256=bmEkgYen2ZQW7EhpshqZQAu8UqyRFbLxNS2-lGjipn8,3904 +deepgram/extra.py,sha256=stQNvvilKNlQtqtjkFgOeKzlmwIiJB8wboACmKKa6vw,4529 +deepgram/invitations.py,sha256=ALzRwvoGKoZKRjq2dfST543lqfVlLQ-d3C3OCZbRuCg,1517 +deepgram/keys.py,sha256=MA1f6LBmZdD8T7qZOJ30CRcc_JqHVyg_obBhAC5BGU4,1509 +deepgram/members.py,sha256=TVdQYLmypquJ5cPwwNs3bXZF25o2FwjGCPKw2PMw4x8,745 +deepgram/projects.py,sha256=N3_iV9YfDfgqf0WWqHI_OZOzwK44VzvfQgo-4TrHsxQ,1443 +deepgram/scopes.py,sha256=z_LVWI2NgUfgJoAzlPHQeq4O-whbQffiib1gN5-bkgI,1003 +deepgram/transcription.py,sha256=xs-gdJnomVXS__6Cjqpwg7QdJWksobn2EYwRqLDHABY,15370 +deepgram/usage.py,sha256=7sRwuQe-QNYO0BSoDGRawfre3wk56sfb6RjNTO4B6qk,1901 +deepgram_sdk-2.12.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +deepgram_sdk-2.12.0.dist-info/LICENSE,sha256=mj1MHMQqj2_8WE8rl5d7-Q3i5zkcuqrHWuwQm5Ztr2A,1065 +deepgram_sdk-2.12.0.dist-info/METADATA,sha256=OLzyOWSof1gNBLIAecYbAcixd14xUc085Pkgfe4dX0o,27644 +deepgram_sdk-2.12.0.dist-info/RECORD,, +deepgram_sdk-2.12.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +deepgram_sdk-2.12.0.dist-info/WHEEL,sha256=Xo9-1PvkuimrydujYJAjF7pCkriuXBpUPEjma1nZyJ0,92 +deepgram_sdk-2.12.0.dist-info/top_level.txt,sha256=i_v4rcE13LLCmMx7hzaEbCMVU8YYUpWNu6eNCU3_UQs,9 diff --git a/venv/Lib/site-packages/deepgram_sdk-2.12.0.dist-info/REQUESTED b/venv/Lib/site-packages/deepgram_sdk-2.12.0.dist-info/REQUESTED new file mode 100644 index 00000000..e69de29b diff --git a/venv/Lib/site-packages/deepgram_sdk-2.12.0.dist-info/WHEEL b/venv/Lib/site-packages/deepgram_sdk-2.12.0.dist-info/WHEEL new file mode 100644 index 00000000..ba48cbcf --- /dev/null +++ b/venv/Lib/site-packages/deepgram_sdk-2.12.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.41.3) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/venv/Lib/site-packages/deepgram_sdk-4.2.0.dist-info/top_level.txt b/venv/Lib/site-packages/deepgram_sdk-2.12.0.dist-info/top_level.txt similarity index 100% rename from venv/Lib/site-packages/deepgram_sdk-4.2.0.dist-info/top_level.txt rename to venv/Lib/site-packages/deepgram_sdk-2.12.0.dist-info/top_level.txt diff --git a/venv/Lib/site-packages/deepgram_sdk-4.2.0.dist-info/METADATA b/venv/Lib/site-packages/deepgram_sdk-4.2.0.dist-info/METADATA deleted file mode 100644 index 9d1bfbae..00000000 --- a/venv/Lib/site-packages/deepgram_sdk-4.2.0.dist-info/METADATA +++ /dev/null @@ -1,844 +0,0 @@ -Metadata-Version: 2.4 -Name: deepgram-sdk -Version: 4.2.0 -Summary: The official Python SDK for the Deepgram automated speech recognition platform. -Home-page: https://github.com/deepgram/deepgram-python-sdk -Author: Deepgram -Author-email: devrel@deepgram.com -License: MIT -Keywords: deepgram,deepgram speech-to-text -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: MIT License -Classifier: Programming Language :: Python :: 3 -Description-Content-Type: text/markdown -License-File: LICENSE -Requires-Dist: httpx>=0.25.2 -Requires-Dist: websockets>=12.0 -Requires-Dist: dataclasses-json>=0.6.3 -Requires-Dist: typing_extensions>=4.9.0 -Requires-Dist: aiohttp>=3.9.1 -Requires-Dist: aiofiles>=23.2.1 -Requires-Dist: aenum>=3.1.0 -Requires-Dist: deprecation>=2.1.0 -Dynamic: author -Dynamic: author-email -Dynamic: classifier -Dynamic: description -Dynamic: description-content-type -Dynamic: home-page -Dynamic: keywords -Dynamic: license -Dynamic: license-file -Dynamic: requires-dist -Dynamic: summary - -# Deepgram Python SDK - -[![Discord](https://dcbadge.vercel.app/api/server/xWRaCDBtW4?style=flat)](https://discord.gg/xWRaCDBtW4) [![GitHub Workflow Status](https://img.shields.io/github/workflow/status/deepgram/deepgram-python-sdk/CI)](https://github.com/deepgram/deepgram-python-sdk/actions/workflows/CI.yml) [![PyPI](https://img.shields.io/pypi/v/deepgram-sdk)](https://pypi.org/project/deepgram-sdk/) -[![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg?style=flat-rounded)](./.github/CODE_OF_CONDUCT.md) - -Official Python SDK for [Deepgram](https://www.deepgram.com/). Power your apps with world-class speech and Language AI models. - -- [Documentation](#documentation) -- [Migrating from earlier versions](#migrating-from-earlier-versions) - - [V2 to V3](#v2-to-v3) - - [V3.*\ to V4](#v3-to-v4) -- [Requirements](#requirements) -- [Installation](#installation) -- [Initialization](#initialization) - - [Getting an API Key](#getting-an-api-key) -- [Pre-Recorded (Synchronous)](#pre-recorded-synchronous) - - [Remote Files (Synchronous)](#remote-files-synchronous) - - [Local Files (Synchronous)](#local-files-synchronous) -- [Pre-Recorded (Asynchronous / Callbacks)](#pre-recorded-asynchronous--callbacks) - - [Remote Files (Asynchronous)](#remote-files-asynchronous) - - [Local Files (Asynchronous)](#local-files-asynchronous) -- [Streaming Audio](#streaming-audio) -- [Transcribing to Captions](#transcribing-to-captions) -- [Voice Agent](#voice-agent) -- [Text to Speech REST](#text-to-speech-rest) -- [Text to Speech Streaming](#text-to-speech-streaming) -- [Text Intelligence](#text-intelligence) -- [Authentication](#authentication) - - [Get Token Details](#get-token-details) - - [Grant Token](#grant-token) -- [Projects](#projects) - - [Get Projects](#get-projects) - - [Get Project](#get-project) - - [Update Project](#update-project) - - [Delete Project](#delete-project) -- [Keys](#keys) - - [List Keys](#list-keys) - - [Get Key](#get-key) - - [Create Key](#create-key) - - [Delete Key](#delete-key) -- [Members](#members) - - [Get Members](#get-members) - - [Remove Member](#remove-member) -- [Scopes](#scopes) - - [Get Member Scopes](#get-member-scopes) - - [Update Scope](#update-scope) -- [Invitations](#invitations) - - [List Invites](#list-invites) - - [Send Invite](#send-invite) - - [Delete Invite](#delete-invite) - - [Leave Project](#leave-project) -- [Usage](#usage) - - [Get All Requests](#get-all-requests) - - [Get Request](#get-request) - - [Summarize Usage](#summarize-usage) - - [Get Fields](#get-fields) -- [Billing](#billing) - - [Get All Balances](#get-all-balances) - - [Get Balance](#get-balance) -- [Models](#models) - - [Get All Project Models](#get-all-project-models) - - [Get Model](#get-model) -- [On-Prem APIs](#on-prem-apis) - - [List On-Prem credentials](#list-on-prem-credentials) - - [Get On-Prem credentials](#get-on-prem-credentials) - - [Create On-Prem credentials](#create-on-prem-credentials) - - [Delete On-Prem credentials](#delete-on-prem-credentials) -- [Logging](#logging) -- [Backwards Compatibility](#backwards-compatibility) -- [Development and Contributing](#development-and-contributing) -- [Getting Help](#getting-help) - -## Documentation - -You can learn more about the Deepgram API at [developers.deepgram.com](https://developers.deepgram.com/docs). - -## Migrating from earlier versions - -### V2 to V3 - -We have published [a migration guide on our docs](https://developers.deepgram.com/sdks/python-sdk/v2-to-v3-migration), showing how to move from v2 to v3. - -### V3.\* to V4 - -The Voice Agent interfaces have been updated to use the new Voice Agent V1 API. Please refer to our [Documentation](https://developers.deepgram.com/docs/voice-agent-v1-migration) on Migration to new V1 Agent API. - -## Requirements - -[Python](https://www.python.org/downloads/) (version ^3.10) - -## Installation - -To install the latest version available: - -```sh -pip install deepgram-sdk -``` - -## Initialization - -All of the examples below will require `DeepgramClient`. - -```python -from deepgram import DeepgramClient - -# Initialize the client -deepgram = DeepgramClient("YOUR_API_KEY") # Replace with your API key -``` - -### Getting an API Key - -🔑 To access the Deepgram API you will need a [free Deepgram API Key](https://console.deepgram.com/signup?jump=keys). - -## Pre-Recorded (Synchronous) - -### Remote Files (Synchronous) - -Transcribe audio from a URL. - -```python - -from deepgram import PrerecordedOptions - -response = deepgram.listen.rest.v("1").transcribe_url( - source={"url": "https://dpgr.am/spacewalk.wav"}, - options=PrerecordedOptions(model="nova-3") # Apply other options -) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/speech-to-text-api/listen). - -[See the Example for more info](./examples/speech-to-text/rest/sync/url/main.py). - -### Local Files (Synchronous) - -Transcribe audio from a file. - -```python -from deepgram import PrerecordedOptions - -response = deepgram.listen.rest.v("1").transcribe_file( - source=open("path/to/your/audio.wav", "rb"), - options=PrerecordedOptions(model="nova-3") # Apply other options -) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/speech-to-text-api/listen). - -[See the Example for more info](./examples/speech-to-text/rest/sync/file/main.py). - -## Pre-Recorded (Asynchronous / Callbacks) - -### Remote Files (Asynchronous) - -Transcribe audio from a URL. - -```python -from deepgram import PrerecordedOptions - -response = deepgram.listen.rest.v("1").transcribe_url_async( - source={"url": "https://dpgr.am/spacewalk.wav"}, - callback_url="https://your-callback-url.com/webhook", - options=PrerecordedOptions(model="nova-3") # Apply other options -) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/speech-to-text-api/listen). - -[See the Example for more info](./examples/speech-to-text/rest/async/url/main.py). - -### Local Files (Asynchronous) - -Transcribe audio from a file. - -```python -from deepgram import PrerecordedOptions - -response = deepgram.listen.rest.v("1").transcribe_file_async( - source=open("path/to/your/audio.wav", "rb"), - callback_url="https://your-callback-url.com/webhook", - options=PrerecordedOptions(model="nova-3") # Apply other options -) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/speech-to-text-api/listen). - -[See the Example for more info](./examples/speech-to-text/rest/async/file/main.py). - -## Streaming Audio - -Transcribe streaming audio. - -```python -from deepgram import LiveOptions, LiveTranscriptionEvents - -# Create a websocket connection -connection = deepgram.listen.websocket.v("1") - -# Handle transcription events -@connection.on(LiveTranscriptionEvents.Transcript) -def handle_transcript(result): - print(result.channel.alternatives[0].transcript) - -# Start connection with streaming options -connection.start(LiveOptions(model="nova-3", language="en-US")) - -# Send audio data -connection.send(open("path/to/your/audio.wav", "rb").read()) - -# Close when done -connection.finish() -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/streaming-api). - -[See the Examples for more info](./examples/speech-to-text/websocket/). - -## Transcribing to Captions - -Transcribe audio to captions. - -### WebVTT - -```python -from deepgram_captions import DeepgramConverter, webvtt - -transcription = DeepgramConverter(dg_response) -captions = webvtt(transcription) -``` - -### SRT - -```python -from deepgram_captions import DeepgramConverter, srt - -transcription = DeepgramConverter(dg_response) -captions = srt(transcription) -``` - -[See our stand alone captions library for more information.](https://github.com/deepgram/deepgram-python-captions). - -## Voice Agent - -Configure a Voice Agent. - -```python -from deepgram import ( - SettingsOptions -) - -# Create websocket connection -connection = deepgram.agent.websocket.v("1") - -# Configure agent settings -options = SettingsOptions() -options.language = "en" -options.agent.think.provider.type = "open_ai" -options.agent.think.provider.model = "gpt-4o-mini" -options.agent.think.prompt = "You are a helpful AI assistant." -options.agent.listen.provider.type = "deepgram" -options.agent.listen.provider.model = "nova-3" -options.agent.speak.provider.type = "deepgram" -options.agent.speak.provider.model ="aura-2-thalia-en" - -options.greeting = "Hello, I'm your AI assistant." - -# Start the connection -connection.start(options) - -# Close the connection -connection.finish() -``` - -This example demonstrates: - -- Setting up a WebSocket connection -- Configuring the agent with speech, language, and audio settings -- Handling various agent events (speech, transcripts, audio) -- Sending audio data and keeping the connection alive - -For a complete implementation, you would need to: - -1. Add your audio input source (e.g., microphone) -2. Implement audio playback for the agent's responses -3. Handle any function calls if your agent uses them -4. Add proper error handling and connection management - -[See our API reference for more info](https://developers.deepgram.com/reference/voice-agent-api/agent). - -[See the Examples for more info](./examples/agent/). - -## Text to Speech REST - -Convert text into speech using the REST API. - -```python -from deepgram import SpeakOptions - -# Configure speech options -options = SpeakOptions(model="aura-2-thalia-en") - -# Convert text to speech and save to file -response = deepgram.speak.rest.v("1").save( - "output.mp3", - {"text": "Hello world!"}, - options -) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/text-to-speech-api/speak). - -[See the Example for more info](./examples/text-to-speech/rest/). - -## Text to Speech Streaming - -Convert streaming text into speech using a Websocket. - -```python -from deepgram import ( - SpeakWSOptions, - SpeakWebSocketEvents -) - -# Create websocket connection -connection = deepgram.speak.websocket.v("1") - -# Handle audio data -@connection.on(SpeakWebSocketEvents.AudioData) - -# Configure streaming options -options = SpeakWSOptions( - model="aura-2-thalia-en", - encoding="linear16", - sample_rate=16000 -) - -# Start connection and send text -connection.start(options) -connection.send_text("Hello, this is a text to speech example.") -connection.flush() -connection.wait_for_complete() - -# Close when done -connection.finish() -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/text-to-speech-api/speak). - -[See the Examples for more info](./examples/text-to-speech/websocket/). - -## Text Intelligence - -Analyze text. - -```python -from deepgram import ReadOptions - -# Configure read options -options = ReadOptions( - model="nova-3", - language="en" -) - -# Process text for intelligence -response = deepgram.read.rest.v("1").process( - text="The quick brown fox jumps over the lazy dog.", - options=options -) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/text-intelligence-api/text-read). - -## Authentication - -### Get Token Details - -Retrieves the details of the current authentication token. - -```python -response = deepgram.manage.rest.v("1").get_token_details() -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/authentication). - -### Grant Token - -Creates a temporary token with a 30-second TTL. - -```python -response = deepgram.auth.v("1").grant_token() - -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/token-based-auth-api/grant-token). - -[See The Examples for more info](./examples/auth/) - -## Projects - -### Get Projects - -Returns all projects accessible by the API key. - -```python -response = deepgram.manage.v("1").get_projects() -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/management-api/projects/list). - -[See The Example for more info](./examples/manage/projects/main.py). - -### Get Project - -Retrieves a specific project based on the provided project_id. - -```python -response = deepgram.manage.v("1").get_project(myProjectId) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/management-api/projects/get). - -[See The Example for more info](./examples/manage/projects/main.py). - -### Update Project - -Update a project. - -```python -response = deepgram.manage.v("1").update_project(myProjectId, options) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/management-api/projects/update). - -[See The Example for more info](./examples/manage/projects/main.py). - -### Delete Project - -Delete a project. - -```python -response = deepgram.manage.v("1").delete_project(myProjectId) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/management-api/projects/delete). - -[See The Example for more info](./examples/manage/projects/main.py). - -## Keys - -### List Keys - -Retrieves all keys associated with the provided project_id. - -```python -response = deepgram.manage.v("1").get_keys(myProjectId) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/management-api/keys/list) - -[See The Example for more info](./examples/manage/keys/main.py). - -### Get Key - -Retrieves a specific key associated with the provided project_id. - -```python -response = deepgram.manage.v("1").get_key(myProjectId, myKeyId) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/management-api/keys/get) - -[See The Example for more info](./examples/manage/keys/main.py). - -### Create Key - -Creates an API key with the provided scopes. - -```python - response = deepgram.manage.v("1").create_key(myProjectId, options) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/management-api/keys/create) - -[See The Example for more info](./examples/manage/keys/main.py). - -### Delete Key - -Deletes a specific key associated with the provided project_id. - -```python -response = deepgram.manage.v("1").delete_key(myProjectId, myKeyId) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/management-api/keys/delete) - -[See The Example for more info](./examples/manage/keys/main.py). - -## Members - -### Get Members - -Retrieves account objects for all of the accounts in the specified project_id. - -```python -response = deepgram.manage.v("1").get_members(myProjectId) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/management-api/members/list). - -[See The Example for more info](./examples/manage/members/main.py). - -### Remove Member - -Removes member account for specified member_id. - -```python -response = deepgram.manage.v("1").remove_member(myProjectId, MemberId) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/management-api/members/delete). - -[See The Example for more info](./examples/manage/members/main.py). - -## Scopes - -### Get Member Scopes - -Retrieves scopes of the specified member in the specified project. - -```python -response = deepgram.manage.v("1").get_member_scopes(myProjectId, memberId) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/management-api/scopes/list). - -[See The Example for more info](./examples/manage/scopes/main.py). - -### Update Scope - -Updates the scope for the specified member in the specified project. - -```python -response = deepgram.manage.v("1").update_member_scope(myProjectId, memberId, options) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/management-api/scopes/update). - -[See The Example for more info](./examples/manage/scopes/main.py). - -## Invitations - -### List Invites - -Retrieves all invitations associated with the provided project_id. - -```python -response = deepgram.manage.v("1").get_invites(myProjectId) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/management-api/invitations/list). - -### Send Invite - -Sends an invitation to the provided email address. - -```python -response = deepgram.manage.v("1").send_invite(myProjectId, options) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/management-api/invitations/create). - -### Delete Invite - -Removes the specified invitation from the project. - -```python -response = deepgram.manage.v("1").delete_invite(myProjectId, email) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/management-api/invitations/delete). - -### Leave Project - -```python -response = deepgram.manage.v("1").leave_project(myProjectId) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/management-api/invitations/leave). - -## Usage - -### Get All Requests - -Retrieves all requests associated with the provided project_id based on the provided options. - -```python -response = deepgram.manage.v("1").get_usage_requests(myProjectId) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/management-api/usage/list-requests). - -### Get Request - -Retrieves a specific request associated with the provided project_id - -```python -response = deepgram.manage.v("1").get_usage_request(myProjectId, RequestId) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/management-api/usage/get-request). - -### Get Fields - -Lists the features, models, tags, languages, and processing method used for requests in the specified project. - -```python -response = deepgram.manage.v("1").get_usage_fields(myProjectId) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/management-api/usage/list-fields). - -### Summarize Usage - -`Deprecated` Retrieves the usage for a specific project. Use Get Project Usage Breakdown for a more comprehensive usage summary. - -```python -response = deepgram.manage.v("1").get_usage_summary(myProjectId) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/management-api/usage/get). - -## Billing - -### Get All Balances - -Retrieves the list of balance info for the specified project. - -```python -response = deepgram.manage.v("1").get_balances(myProjectId) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/management-api/balances/list). - -### Get Balance - -Retrieves the balance info for the specified project and balance_id. - -```python -response = deepgram.manage.v("1").get_balance(myProjectId) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/management-api/balances/get). - -## Models - -### Get All Project Models - -Retrieves all models available for a given project. - -```python -response = deepgram.manage.v("1").get_project_models(myProjectId) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/management-api/projects/list-models). - -### Get Model - -Retrieves details of a specific model. - -```python -response = deepgram.manage.v("1").get_project_model(myProjectId, ModelId) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/management-api/projects/get-model). - -## On-Prem APIs - -### List On-Prem credentials - -Lists sets of distribution credentials for the specified project. - -```python -response = deepgram.selfhosted.v("1").list_selfhosted_credentials(projectId) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/self-hosted-api/list-credentials). - -### Get On-Prem credentials - -Returns a set of distribution credentials for the specified project. - -```python -response = deepgram.selfhosted.v("1").get_selfhosted_credentials(projectId, distributionCredentialsId) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/self-hosted-api/get-credentials). - -### Create On-Prem credentials - -Creates a set of distribution credentials for the specified project. - -```python -response = deepgram.selfhosted.v("1").create_selfhosted_credentials(project_id, options) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/self-hosted-api/create-credentials). - -### Delete On-Prem credentials - -Deletes a set of distribution credentials for the specified project. - -```python -response = deepgram.selfhosted.v("1").delete_selfhosted_credentials(projectId, distributionCredentialId) -``` - -[See our API reference for more info](https://developers.deepgram.com/reference/self-hosted-api/delete-credentials). - -## Pinning Versions - -To ensure your application remains stable and reliable, we recommend using version pinning in your project. This is a best practice in Python development that helps prevent unexpected changes. You can pin to a major version (like `==4.*`) for a good balance of stability and updates, or to a specific version (like `==4.1.0`) for maximum stability. We've included some helpful resources about [version pinning](https://discuss.python.org/t/how-to-pin-a-package-to-a-specific-major-version-or-lower/17077) and [dependency management](https://www.easypost.com/dependency-pinning-guide) if you'd like to learn more. For a deeper understanding of how version numbers work, check out[semantic versioning](https://semver.org/). - -In a `requirements.txt` file, you can pin to a specific version like this: - -```sh -deepgram-sdk==4.1.0 -``` - -Or using pip: - -```sh -pip install deepgram-sdk==4.1.0 -``` - -## Logging - -This SDK provides logging as a means to troubleshoot and debug issues encountered. By default, this SDK will enable `Information` level messages and higher (ie `Warning`, `Error`, etc) when you initialize the library as follows: - -```python -deepgram: DeepgramClient = DeepgramClient() -``` - -To increase the logging output/verbosity for debug or troubleshooting purposes, you can set the `DEBUG` level but using this code: - -```python -config: DeepgramClientOptions = DeepgramClientOptions( - verbose=logging.DEBUG, -) -deepgram: DeepgramClient = DeepgramClient("", config) -``` - -## Testing - -### Daily and Unit Tests - -If you are looking to use, run, contribute or modify to the daily/unit tests, then you need to install the following dependencies: - -```bash -pip install -r requirements-dev.txt -``` - -### Daily Tests - -The daily tests invoke a series of checks against the actual/real API endpoint and save the results in the `tests/response_data` folder. This response data is updated nightly to reflect the latest response from the server. Running the daily tests does require a `DEEPGRAM_API_KEY` set in your environment variables. - -To run the Daily Tests: - -```bash -make daily-test -``` - -#### Unit Tests - -The unit tests invoke a series of checks against mock endpoints using the responses saved in `tests/response_data` from the daily tests. These tests are meant to simulate running against the endpoint without actually reaching out to the endpoint; running the unit tests does require a `DEEPGRAM_API_KEY` set in your environment variables, but you will not actually reach out to the server. - -```bash -make unit-test -``` - -## Backwards Compatibility - -We follow semantic versioning (semver) to ensure a smooth upgrade experience. Within a major version (like `4.*`), we will maintain backward compatibility so your code will continue to work without breaking changes. When we release a new major version (like moving from `3.*` to `4.*`), we may introduce breaking changes to improve the SDK. We'll always document these changes clearly in our release notes to help you upgrade smoothly. - -Older SDK versions will receive Priority 1 (P1) bug support only. Security issues, both in our code and dependencies, are promptly addressed. Significant bugs without clear workarounds are also given priority attention. - -## Development and Contributing - -Interested in contributing? We ❤️ pull requests! - -To make sure our community is safe for all, be sure to review and agree to our -[Code of Conduct](CODE_OF_CONDUCT.md). Then see the -[Contribution](CONTRIBUTING.md) guidelines for more information. - -In order to develop new features for the SDK itself, you first need to uninstall any previous installation of the `deepgram-sdk` and then install/pip the dependencies contained in the `requirements.txt` then instruct python (via pip) to use the SDK by installing it locally. - -From the root of the repo, that would entail: - -```bash -pip uninstall deepgram-sdk -pip install -r requirements.txt -pip install -e . -``` - -## Getting Help - -We love to hear from you so if you have questions, comments or find a bug in the -project, let us know! You can either: - -- [Open an issue in this repository](https://github.com/deepgram/deepgram-python-sdk/issues/new) -- [Join the Deepgram Github Discussions Community](https://github.com/orgs/deepgram/discussions) -- [Join the Deepgram Discord Community](https://discord.gg/xWRaCDBtW4) diff --git a/venv/Lib/site-packages/deepgram_sdk-4.2.0.dist-info/RECORD b/venv/Lib/site-packages/deepgram_sdk-4.2.0.dist-info/RECORD deleted file mode 100644 index 9dba23f3..00000000 --- a/venv/Lib/site-packages/deepgram_sdk-4.2.0.dist-info/RECORD +++ /dev/null @@ -1,223 +0,0 @@ -deepgram/__init__.py,sha256=kln0NVvKBJ0ablYtWdSUqolZsln5YW5OaDoVy5sEOoo,7207 -deepgram/__pycache__/__init__.cpython-312.pyc,, -deepgram/__pycache__/client.cpython-312.pyc,, -deepgram/__pycache__/errors.cpython-312.pyc,, -deepgram/__pycache__/options.cpython-312.pyc,, -deepgram/audio/__init__.py,sha256=yluAOVzIdSqqsBtVQzxHSPURKfGAxtBLhGN2xmWq_uk,677 -deepgram/audio/__pycache__/__init__.cpython-312.pyc,, -deepgram/audio/microphone/__init__.py,sha256=4mlErQgfu8sj6AnDNiQGcauMoyPYLxz-UJXFkDkXkAU,329 -deepgram/audio/microphone/__pycache__/__init__.cpython-312.pyc,, -deepgram/audio/microphone/__pycache__/constants.cpython-312.pyc,, -deepgram/audio/microphone/__pycache__/errors.cpython-312.pyc,, -deepgram/audio/microphone/__pycache__/microphone.cpython-312.pyc,, -deepgram/audio/microphone/constants.py,sha256=3Nv655J7a48Q-HU35Ml2vak14vO5_Sd-6AxZ78lsxCc,326 -deepgram/audio/microphone/errors.py,sha256=cPcyWoHUdFCCDBORg6JCmCx5CjOj0pwy94fpjAg-4VY,656 -deepgram/audio/microphone/microphone.py,sha256=NII5KlUOuIcpP8S-M3Ijh2erfztuB-XxwdAgRQeIlDM,9545 -deepgram/audio/speaker/__init__.py,sha256=qpaZbGafC5Bv50yHbY_90T_KxIbBxCh-L9_7EMFEYbI,336 -deepgram/audio/speaker/__pycache__/__init__.cpython-312.pyc,, -deepgram/audio/speaker/__pycache__/constants.cpython-312.pyc,, -deepgram/audio/speaker/__pycache__/errors.cpython-312.pyc,, -deepgram/audio/speaker/__pycache__/speaker.cpython-312.pyc,, -deepgram/audio/speaker/constants.py,sha256=0I02aFd8mjPERmjIfywlok_-BkM_gohfyIy92OjwmZo,381 -deepgram/audio/speaker/errors.py,sha256=pBzH90zf9rMhK6xpjvyavYZH6-PdbjCY87fvsHynI2o,639 -deepgram/audio/speaker/speaker.py,sha256=1ZJwwLAQko-rBDqDPOUTBM60-T3RlzWtL7HepTntWwk,13707 -deepgram/client.py,sha256=X0tFjZGKF6t2oSgqOVy8BHQzyWnL86e87HZ5Gx6r07E,17515 -deepgram/clients/__init__.py,sha256=OGXeEMZDvLcyp1YSvILycwBux4c9d3-YlKJwmt4PGFg,6980 -deepgram/clients/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/__pycache__/agent_router.cpython-312.pyc,, -deepgram/clients/__pycache__/errors.cpython-312.pyc,, -deepgram/clients/__pycache__/listen_router.cpython-312.pyc,, -deepgram/clients/__pycache__/read_router.cpython-312.pyc,, -deepgram/clients/__pycache__/speak_router.cpython-312.pyc,, -deepgram/clients/agent/__init__.py,sha256=sQ2oa1XjOZJ2kP8Cj5mG56oGQHvFw8tOWR-vHNnFHo0,1121 -deepgram/clients/agent/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/agent/__pycache__/client.cpython-312.pyc,, -deepgram/clients/agent/__pycache__/enums.cpython-312.pyc,, -deepgram/clients/agent/client.py,sha256=u__QRG7SNmmbkaZKbVxphtkhhxOHDYSRCzXB0ZDe42E,3467 -deepgram/clients/agent/enums.py,sha256=PdoOHRSnuR0YhA7WmkEWR8_4Lxv_yGs79PBMOkZMcCk,1199 -deepgram/clients/agent/v1/__init__.py,sha256=Xdl40wxUU856qh1IgFOkEKv8K1K7kQx8JwLAKfDZoC0,1214 -deepgram/clients/agent/v1/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/agent/v1/websocket/__init__.py,sha256=Gy209uZBNcla0adx32rLUiLYyCIsUim08maXPMBz324,1095 -deepgram/clients/agent/v1/websocket/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/agent/v1/websocket/__pycache__/async_client.cpython-312.pyc,, -deepgram/clients/agent/v1/websocket/__pycache__/client.cpython-312.pyc,, -deepgram/clients/agent/v1/websocket/__pycache__/options.cpython-312.pyc,, -deepgram/clients/agent/v1/websocket/__pycache__/response.cpython-312.pyc,, -deepgram/clients/agent/v1/websocket/async_client.py,sha256=Z_dkLqqCb0Y4Erk5ckx2dEXgEgP1W7-qz0vWLQxU9t4,27925 -deepgram/clients/agent/v1/websocket/client.py,sha256=PowSm3ol2ROm5IsvAPMWIG4RqIK_kaSAP3PKCcXYrWY,26823 -deepgram/clients/agent/v1/websocket/options.py,sha256=Grt9JnraOJqKc-4KRVFqOrqEbP2l9RNmFEDRvHSGfuc,10672 -deepgram/clients/agent/v1/websocket/response.py,sha256=kHul80uAqOgWNkSstWeWij6hW-5KYqXWpSClhatQ6lY,2589 -deepgram/clients/agent_router.py,sha256=ODNOSmwa5LAu4I_4bRGP_1gDjPppiBiNePCOr-9QJEY,4812 -deepgram/clients/analyze/__init__.py,sha256=Y6_b6JT3v92zVD9r3C89YH9sLGewAfYTiLVRWdrLu1Q,867 -deepgram/clients/analyze/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/analyze/__pycache__/client.cpython-312.pyc,, -deepgram/clients/analyze/client.py,sha256=chknRcygzDL-yVM0Q8lJHi-jRFZIyntGZeZSSQe4JQs,2613 -deepgram/clients/analyze/v1/__init__.py,sha256=coTuK8O-5VQX4aRuTji7c3N8ILK0hoYAQsXe2hQPHNI,828 -deepgram/clients/analyze/v1/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/analyze/v1/__pycache__/async_client.cpython-312.pyc,, -deepgram/clients/analyze/v1/__pycache__/client.cpython-312.pyc,, -deepgram/clients/analyze/v1/__pycache__/helpers.cpython-312.pyc,, -deepgram/clients/analyze/v1/__pycache__/options.cpython-312.pyc,, -deepgram/clients/analyze/v1/__pycache__/response.cpython-312.pyc,, -deepgram/clients/analyze/v1/async_client.py,sha256=xWmmN_8WWVPTuaWeTX_RKaskq2ocV1FLgSgjiAmYyUk,13286 -deepgram/clients/analyze/v1/client.py,sha256=W6DlR2QaV4-opHSj6sYAepHbSh0H2Up4zRYHtKax4X4,13171 -deepgram/clients/analyze/v1/helpers.py,sha256=rXCvbu1wXZhXjTDGQx2dtomQdf4UMdzPFbGyFoOlxMQ,746 -deepgram/clients/analyze/v1/options.py,sha256=Yu9BQd1bQK1-X5lto2fBkLKKsnW8nxP3ql5YLV9S-0Q,2598 -deepgram/clients/analyze/v1/response.py,sha256=MIQV4e8u_h7Hfeioz4pObqcnwKLDHm6MnNT64NMXdwc,3816 -deepgram/clients/auth/__init__.py,sha256=f5ul6qUKYQNCHcLJzwEtda9WJMz46OJ0LHs_soP7gvg,318 -deepgram/clients/auth/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/auth/__pycache__/client.cpython-312.pyc,, -deepgram/clients/auth/client.py,sha256=7cE4C8qSBaV536t88YGK63KLuWKv-JR0zfsJzRxbVQs,541 -deepgram/clients/auth/v1/__init__.py,sha256=3wx1uwB2PaPNzp-rn2K7dGQzDsD_MxJYX_JsdUtTFmw,320 -deepgram/clients/auth/v1/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/auth/v1/__pycache__/async_client.cpython-312.pyc,, -deepgram/clients/auth/v1/__pycache__/client.cpython-312.pyc,, -deepgram/clients/auth/v1/__pycache__/response.cpython-312.pyc,, -deepgram/clients/auth/v1/async_client.py,sha256=wNzNHkft4056DzfoLZJQ2l_HiWI38dqrEmX4IK48kFc,1825 -deepgram/clients/auth/v1/client.py,sha256=1c_Luizqoo8VIyF4mQMGCLnEJjka73eZg29ldVMohXA,1806 -deepgram/clients/auth/v1/response.py,sha256=5f_Rar5oH12REj8oQ_hj1glqn91_9dIqjS1SAu8C0aQ,708 -deepgram/clients/common/__init__.py,sha256=i8ymuZHN6aw7cuVeox8C-9s5WaUFrwWjDLPEUsfPN1k,2213 -deepgram/clients/common/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/common/v1/__init__.py,sha256=bqz4wmjzWsxyC6cLBXxvmWNiqGpLfVySDyxdxDFXViM,1106 -deepgram/clients/common/v1/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/common/v1/__pycache__/abstract_async_rest.cpython-312.pyc,, -deepgram/clients/common/v1/__pycache__/abstract_async_websocket.cpython-312.pyc,, -deepgram/clients/common/v1/__pycache__/abstract_sync_rest.cpython-312.pyc,, -deepgram/clients/common/v1/__pycache__/abstract_sync_websocket.cpython-312.pyc,, -deepgram/clients/common/v1/__pycache__/enums.cpython-312.pyc,, -deepgram/clients/common/v1/__pycache__/errors.cpython-312.pyc,, -deepgram/clients/common/v1/__pycache__/helpers.cpython-312.pyc,, -deepgram/clients/common/v1/__pycache__/options.cpython-312.pyc,, -deepgram/clients/common/v1/__pycache__/rest_response.cpython-312.pyc,, -deepgram/clients/common/v1/__pycache__/shared_response.cpython-312.pyc,, -deepgram/clients/common/v1/__pycache__/websocket_events.cpython-312.pyc,, -deepgram/clients/common/v1/__pycache__/websocket_response.cpython-312.pyc,, -deepgram/clients/common/v1/abstract_async_rest.py,sha256=4_jZuB1ETMja4DGg9BabA7Pr22W7SC3gb85xeB7QJRE,12927 -deepgram/clients/common/v1/abstract_async_websocket.py,sha256=568wodHQdtrRMleo5O4QM23ZCvrlJYBnO7LB29tQsyI,20841 -deepgram/clients/common/v1/abstract_sync_rest.py,sha256=IgM9cMLQJx-EMupb7AHNevSyt2MZcRwZx-u19xn3Sq8,12612 -deepgram/clients/common/v1/abstract_sync_websocket.py,sha256=4eQrz_Y5vWCvtUTwGu-p3TptSPPsdRi_1FVJmxK_gvs,20461 -deepgram/clients/common/v1/enums.py,sha256=f66HjY5EHg1y7QgT23in5_V1fnMA1GO2xZpQ9b6q3Ww,450 -deepgram/clients/common/v1/errors.py,sha256=BM9ZtJcE-hmgBApP7P58tI3BSdnP4I1AeKud4M3hLQ4,2344 -deepgram/clients/common/v1/helpers.py,sha256=lod5Nu1gZ1L-K_jGN9yN88YTRj5Y3HfEyMzP9xfbOUs,1939 -deepgram/clients/common/v1/options.py,sha256=_8y3CtSCSU3EOCT_TERZvA-I_YJwK5m6OLS6QX-DbGw,1749 -deepgram/clients/common/v1/rest_response.py,sha256=RTlkNlC01jjm3kJ1X6LnfmWEVZuUIEhyjVfAg2oNuFg,3918 -deepgram/clients/common/v1/shared_response.py,sha256=k0mh2KQMEblNUqlkNC5DVy2_BJkFKLg4pmPrcUah-Bw,2044 -deepgram/clients/common/v1/websocket_events.py,sha256=c-gRRVD5JPdA8xIBmd79xuzbKja-lB2QpqV8FDOg8g8,534 -deepgram/clients/common/v1/websocket_response.py,sha256=ohv01NuxptcAdBthdLIUeA7GHpJ5mnk61DgoiBhF8ho,1161 -deepgram/clients/errors.py,sha256=SeAaY9o_x0G2zfLvkf_99kvnCQM4XL6C55GNR7C3ELw,518 -deepgram/clients/listen/__init__.py,sha256=0qrpHWQOMfNDb4I3Dwzt_VoYFkPin_TDePMGpUFBsFU,1920 -deepgram/clients/listen/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/listen/__pycache__/client.cpython-312.pyc,, -deepgram/clients/listen/__pycache__/enums.cpython-312.pyc,, -deepgram/clients/listen/client.py,sha256=eEun_s4IQDXoqLHkYNpVgDTd6pmTzluvcJtlEHHNKxI,5794 -deepgram/clients/listen/enums.py,sha256=ylHcsr8gtAq69ijiHN47Q63HhpjT5zi7prtklslFk1E,721 -deepgram/clients/listen/v1/__init__.py,sha256=Lvy-nqWOj0wPBiXc14Qw1XBuZ4N3foE5lYaHuwnEVZo,2664 -deepgram/clients/listen/v1/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/listen/v1/rest/__init__.py,sha256=mYEjKwAZEipFFUybqVoHl7t7RBMCbnIrSS3P0FX-P5I,1175 -deepgram/clients/listen/v1/rest/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/listen/v1/rest/__pycache__/async_client.cpython-312.pyc,, -deepgram/clients/listen/v1/rest/__pycache__/client.cpython-312.pyc,, -deepgram/clients/listen/v1/rest/__pycache__/helpers.cpython-312.pyc,, -deepgram/clients/listen/v1/rest/__pycache__/options.cpython-312.pyc,, -deepgram/clients/listen/v1/rest/__pycache__/response.cpython-312.pyc,, -deepgram/clients/listen/v1/rest/async_client.py,sha256=PhLvHN5GLNDvRA9QkI4Vcl8_KeOO92dt8C9bUnb_yxM,13638 -deepgram/clients/listen/v1/rest/client.py,sha256=t4LOLyETj4hbNOL-rsXk0eVyOSGTgPl4WEwpX8VKa9g,13572 -deepgram/clients/listen/v1/rest/helpers.py,sha256=tNMcGIXnPeKOchi9HJ4nac9yLITJ9HG_j1A5gGqgJ-4,762 -deepgram/clients/listen/v1/rest/options.py,sha256=Uaj3fM4bbmoq6zQwrl-dPZ8Og0GId9VMOAfIlS2k8QA,6648 -deepgram/clients/listen/v1/rest/response.py,sha256=HHy7YOHLYGBzc4NIoXfd4bXqQ-ops0e1NZ-Rd9omqrA,14101 -deepgram/clients/listen/v1/websocket/__init__.py,sha256=1L1bcaKvO02RPiUWl9a49LEgQxh6lVccKAzeWzoXmis,819 -deepgram/clients/listen/v1/websocket/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/listen/v1/websocket/__pycache__/async_client.cpython-312.pyc,, -deepgram/clients/listen/v1/websocket/__pycache__/client.cpython-312.pyc,, -deepgram/clients/listen/v1/websocket/__pycache__/options.cpython-312.pyc,, -deepgram/clients/listen/v1/websocket/__pycache__/response.cpython-312.pyc,, -deepgram/clients/listen/v1/websocket/async_client.py,sha256=zedQHRFL0G7Sg9Gsan6hmB9dd85Fiq_bAMT_UjHfKnw,23125 -deepgram/clients/listen/v1/websocket/client.py,sha256=o80o7SzX2Byp7I-7uwfqTOJ7C5AP70xXCVUeWcc0bqY,22804 -deepgram/clients/listen/v1/websocket/options.py,sha256=Fo7prf7nek4Ktc2H8xHMvnoTwvJdJkIpIntrx5uaiAc,6081 -deepgram/clients/listen/v1/websocket/response.py,sha256=CfLejy3Io54rOz7XWll3GXgoS6J0f41lnU94xZLSe7w,5718 -deepgram/clients/listen_router.py,sha256=xJ_09tlG62tba7txruvFvGtmb3qs9Ep5Wfp_hxK1xdo,8376 -deepgram/clients/live/__init__.py,sha256=EvLKoa_ewpN8uojRPdNQ7yTnOMqnsxXHHAzDIw9U-Tg,572 -deepgram/clients/live/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/live/v1/__init__.py,sha256=lSyv1CfXfrV-67tn53Znfhw5AiZ1dRaJV7isw4pjPXk,591 -deepgram/clients/live/v1/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/live/v1/__pycache__/client.cpython-312.pyc,, -deepgram/clients/live/v1/__pycache__/enums.cpython-312.pyc,, -deepgram/clients/live/v1/client.py,sha256=sJB5YvCOtVrCVD_l8usrrZwxlavnXJgYj9pZqtArKnk,1504 -deepgram/clients/live/v1/enums.py,sha256=h3zbI22I9tqPgUVE-6V2X_OR00Cb4dfpiBJ9mRze-Hw,242 -deepgram/clients/manage/__init__.py,sha256=EhzJKuOT9QKk_s0dBKpsjQ4lwCvhhWaxlQdEvvkcsxQ,1104 -deepgram/clients/manage/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/manage/__pycache__/client.cpython-312.pyc,, -deepgram/clients/manage/client.py,sha256=gnosDmhpQKPNcG4kZgQ80e2Tk4FzwjVGm78MMa5LIvo,3759 -deepgram/clients/manage/v1/__init__.py,sha256=Ng6zQQFd0b-5aV3QdzGi_1Hz73SbhRpfKqAUHdRo2wk,1114 -deepgram/clients/manage/v1/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/manage/v1/__pycache__/async_client.cpython-312.pyc,, -deepgram/clients/manage/v1/__pycache__/client.cpython-312.pyc,, -deepgram/clients/manage/v1/__pycache__/options.cpython-312.pyc,, -deepgram/clients/manage/v1/__pycache__/response.cpython-312.pyc,, -deepgram/clients/manage/v1/async_client.py,sha256=OCSsO4akPc2yDjxuz7qJnpzJuorJxbskDLTnbkL2HIk,42360 -deepgram/clients/manage/v1/client.py,sha256=K2-kr9MIqVJMAAQfKXfNrSE07gnf_CFrcu7jbmFr8MA,42054 -deepgram/clients/manage/v1/options.py,sha256=5FNK7wtpvdpJ2cWbgrgWCcLg2X4oQlPvBBBEbHKhq2w,5070 -deepgram/clients/manage/v1/response.py,sha256=WZihXc_TkhGZ2GWC__6qJMd2wfYjXohQhv0reQawI1Y,16668 -deepgram/clients/prerecorded/__init__.py,sha256=98vyFGku8WhtUT-8LM7K55i8MNADteGB4KcdPh2hKm8,511 -deepgram/clients/prerecorded/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/prerecorded/v1/__init__.py,sha256=fbvUd_1tG8VJmf4isodXz60sBheH6R4-WWnEt_INtSo,531 -deepgram/clients/prerecorded/v1/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/prerecorded/v1/__pycache__/client.cpython-312.pyc,, -deepgram/clients/prerecorded/v1/__pycache__/errors.cpython-312.pyc,, -deepgram/clients/prerecorded/v1/client.py,sha256=rVHIZfcO2Q-Wu3hMAzx-3MEmpKMx-Y7EUD7SFMWD3J0,1303 -deepgram/clients/prerecorded/v1/errors.py,sha256=eKZ-swaEh0Zia7ZdbbPa_idKhPKmQSy-cQYhNuwVado,1044 -deepgram/clients/read_router.py,sha256=0fb6vvS1O0vDuKcE_ZNkAYYOQgzZsqgySD-Ba2c-6iM,4769 -deepgram/clients/selfhosted/__init__.py,sha256=RLUDITdO3MfNi93bl9SfUGmRcVUxhXOOJ2MoM9fTBlM,308 -deepgram/clients/selfhosted/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/selfhosted/__pycache__/client.cpython-312.pyc,, -deepgram/clients/selfhosted/client.py,sha256=6pGDktgr8dgGllX9EaVd6F2JF9woFFmDCMPj27F-Cio,666 -deepgram/clients/selfhosted/v1/__init__.py,sha256=rUUckO_Kt5dCLeRKzu908SNMzPdD0XVcyKxuOe6L6qU,281 -deepgram/clients/selfhosted/v1/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/selfhosted/v1/__pycache__/async_client.cpython-312.pyc,, -deepgram/clients/selfhosted/v1/__pycache__/client.cpython-312.pyc,, -deepgram/clients/selfhosted/v1/async_client.py,sha256=zqsYnxqFiY1biZ-4zTjpP6tGc6E5fl7Me7GsoHAZC1s,6354 -deepgram/clients/selfhosted/v1/client.py,sha256=GrjndD0UHOf8_Z3L08NSX6wVqjQlQ9KS6iTlWsoPhFI,6309 -deepgram/clients/speak/__init__.py,sha256=eLF6ntT7zVRJq2yVaEu7d0rUAdxVXb25xUNkry4pKWA,1101 -deepgram/clients/speak/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/speak/__pycache__/client.cpython-312.pyc,, -deepgram/clients/speak/__pycache__/enums.cpython-312.pyc,, -deepgram/clients/speak/client.py,sha256=y6lSNR_Gnl6kORjVU63jit2Wh_AddxunE0mZl42kv2w,2884 -deepgram/clients/speak/enums.py,sha256=P1dQfgpJgx3dbwlE39s-rX88tx3GNGiJyEew9X7cb2k,903 -deepgram/clients/speak/v1/__init__.py,sha256=IIu6A0cQkL39tAph2iktnqQKcr7OKroIQssnvNI_kek,1026 -deepgram/clients/speak/v1/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/speak/v1/rest/__init__.py,sha256=igYW2BarSlyY-EyqZjHYnbIwnoE4yxsbMOkP_G5e5HE,551 -deepgram/clients/speak/v1/rest/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/speak/v1/rest/__pycache__/async_client.cpython-312.pyc,, -deepgram/clients/speak/v1/rest/__pycache__/client.cpython-312.pyc,, -deepgram/clients/speak/v1/rest/__pycache__/helpers.cpython-312.pyc,, -deepgram/clients/speak/v1/rest/__pycache__/options.cpython-312.pyc,, -deepgram/clients/speak/v1/rest/__pycache__/response.cpython-312.pyc,, -deepgram/clients/speak/v1/rest/async_client.py,sha256=LL3ueO-wF6BJ6KgyQnRVmgD_2wCEg8JrLHCBChAus-g,10888 -deepgram/clients/speak/v1/rest/client.py,sha256=XrWG5JxdXFl58KjSDtJpXzfSoaiKYgiGlRMhMI7tshU,10729 -deepgram/clients/speak/v1/rest/helpers.py,sha256=SRAKIt9gysCDKV5eN37ZWXoj4LKawCL0uPRbk6y-aF4,566 -deepgram/clients/speak/v1/rest/options.py,sha256=YZ34ph48RFw7JBt3FePV-U9Q8gULXymC7mN12-96P9k,1872 -deepgram/clients/speak/v1/rest/response.py,sha256=caVeilf2yZHziquyH2GZkcescWsXzbyNwIssiZ8eM2I,1302 -deepgram/clients/speak/v1/websocket/__init__.py,sha256=ZScBs2NXEmXHVL2rRT7CYi-NF-Stx_J1LuvEjRQnCz8,580 -deepgram/clients/speak/v1/websocket/__pycache__/__init__.cpython-312.pyc,, -deepgram/clients/speak/v1/websocket/__pycache__/async_client.cpython-312.pyc,, -deepgram/clients/speak/v1/websocket/__pycache__/client.cpython-312.pyc,, -deepgram/clients/speak/v1/websocket/__pycache__/options.cpython-312.pyc,, -deepgram/clients/speak/v1/websocket/__pycache__/response.cpython-312.pyc,, -deepgram/clients/speak/v1/websocket/async_client.py,sha256=C___hgMRu5p1s0B2klv1YROKe1XXHSuJuA43B4WiMAE,27624 -deepgram/clients/speak/v1/websocket/client.py,sha256=sL3tbIgzkmhSnWmQ7YVSKAX5PMjz6LIr7GGihny5kLY,26454 -deepgram/clients/speak/v1/websocket/options.py,sha256=gkL-Nap2IVED2Pf-uqQfA7pym8oKp3kHYLLjwYAj4OA,1885 -deepgram/clients/speak/v1/websocket/response.py,sha256=bclXcz40jaRe7BhgSGApwA3LMtKVpZ62XZVE2G01IC4,977 -deepgram/clients/speak_router.py,sha256=hLw_sh258iwxw7X7AxgAuvzyJbjRV1K0F-OngKeFgCk,6561 -deepgram/errors.py,sha256=9J2DuCAv3Oc7XFwhxFJM5xGMdMOG5Ygojdy0sViCiSo,519 -deepgram/options.py,sha256=eTwy8j1Zl7YOiscOBjcGZEF_qnK4nTmV_lb-UznTPkI,9277 -deepgram/utils/__init__.py,sha256=LHLuOBMz5e_060rPaiVqoxUltqpJedLOOLRUkPC4XDo,404 -deepgram/utils/__pycache__/__init__.cpython-312.pyc,, -deepgram/utils/verboselogs/__init__.py,sha256=DSrWTO3FXiIVAxiY_gJMyJ8x81iZXe08QXU9OeeB7_0,5480 -deepgram/utils/verboselogs/__pycache__/__init__.cpython-312.pyc,, -deepgram_sdk-4.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -deepgram_sdk-4.2.0.dist-info/METADATA,sha256=ZTyo9WcPi8akUNFMTX14yxEtQYtG3mvF2R1OMfxGO90,25652 -deepgram_sdk-4.2.0.dist-info/RECORD,, -deepgram_sdk-4.2.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -deepgram_sdk-4.2.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 -deepgram_sdk-4.2.0.dist-info/licenses/LICENSE,sha256=mj1MHMQqj2_8WE8rl5d7-Q3i5zkcuqrHWuwQm5Ztr2A,1065 -deepgram_sdk-4.2.0.dist-info/top_level.txt,sha256=i_v4rcE13LLCmMx7hzaEbCMVU8YYUpWNu6eNCU3_UQs,9 diff --git a/venv/Lib/site-packages/distro/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/distro/__pycache__/__init__.cpython-312.pyc index 1ff27ed0..4cc74270 100644 Binary files a/venv/Lib/site-packages/distro/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/distro/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/distro/__pycache__/distro.cpython-312.pyc b/venv/Lib/site-packages/distro/__pycache__/distro.cpython-312.pyc index 1754cb96..bdea3a8d 100644 Binary files a/venv/Lib/site-packages/distro/__pycache__/distro.cpython-312.pyc and b/venv/Lib/site-packages/distro/__pycache__/distro.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dotenv/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/dotenv/__pycache__/__init__.cpython-312.pyc index 84170da8..669d5b85 100644 Binary files a/venv/Lib/site-packages/dotenv/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/dotenv/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dotenv/__pycache__/main.cpython-312.pyc b/venv/Lib/site-packages/dotenv/__pycache__/main.cpython-312.pyc index a697f296..cb11ac52 100644 Binary files a/venv/Lib/site-packages/dotenv/__pycache__/main.cpython-312.pyc and b/venv/Lib/site-packages/dotenv/__pycache__/main.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dotenv/__pycache__/parser.cpython-312.pyc b/venv/Lib/site-packages/dotenv/__pycache__/parser.cpython-312.pyc index 4d9b643d..49466bcc 100644 Binary files a/venv/Lib/site-packages/dotenv/__pycache__/parser.cpython-312.pyc and b/venv/Lib/site-packages/dotenv/__pycache__/parser.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/dotenv/__pycache__/variables.cpython-312.pyc b/venv/Lib/site-packages/dotenv/__pycache__/variables.cpython-312.pyc index bbb96bc9..b96d6cfb 100644 Binary files a/venv/Lib/site-packages/dotenv/__pycache__/variables.cpython-312.pyc and b/venv/Lib/site-packages/dotenv/__pycache__/variables.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi-0.115.14.dist-info/INSTALLER b/venv/Lib/site-packages/fastapi-0.115.14.dist-info/INSTALLER new file mode 100644 index 00000000..a1b589e3 --- /dev/null +++ b/venv/Lib/site-packages/fastapi-0.115.14.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/Lib/site-packages/fastapi-0.115.14.dist-info/METADATA b/venv/Lib/site-packages/fastapi-0.115.14.dist-info/METADATA new file mode 100644 index 00000000..b67c559a --- /dev/null +++ b/venv/Lib/site-packages/fastapi-0.115.14.dist-info/METADATA @@ -0,0 +1,563 @@ +Metadata-Version: 2.1 +Name: fastapi +Version: 0.115.14 +Summary: FastAPI framework, high performance, easy to learn, fast to code, ready for production +Author-Email: =?utf-8?q?Sebasti=C3=A1n_Ram=C3=ADrez?= +Classifier: Intended Audience :: Information Technology +Classifier: Intended Audience :: System Administrators +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python +Classifier: Topic :: Internet +Classifier: Topic :: Software Development :: Libraries :: Application Frameworks +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Software Development +Classifier: Typing :: Typed +Classifier: Development Status :: 4 - Beta +Classifier: Environment :: Web Environment +Classifier: Framework :: AsyncIO +Classifier: Framework :: FastAPI +Classifier: Framework :: Pydantic +Classifier: Framework :: Pydantic :: 1 +Classifier: Framework :: Pydantic :: 2 +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers +Classifier: Topic :: Internet :: WWW/HTTP +Project-URL: Homepage, https://github.com/fastapi/fastapi +Project-URL: Documentation, https://fastapi.tiangolo.com/ +Project-URL: Repository, https://github.com/fastapi/fastapi +Project-URL: Issues, https://github.com/fastapi/fastapi/issues +Project-URL: Changelog, https://fastapi.tiangolo.com/release-notes/ +Requires-Python: >=3.8 +Requires-Dist: starlette<0.47.0,>=0.40.0 +Requires-Dist: pydantic!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,<3.0.0,>=1.7.4 +Requires-Dist: typing-extensions>=4.8.0 +Provides-Extra: standard +Requires-Dist: fastapi-cli[standard]>=0.0.5; extra == "standard" +Requires-Dist: httpx>=0.23.0; extra == "standard" +Requires-Dist: jinja2>=3.1.5; extra == "standard" +Requires-Dist: python-multipart>=0.0.18; extra == "standard" +Requires-Dist: email-validator>=2.0.0; extra == "standard" +Requires-Dist: uvicorn[standard]>=0.12.0; extra == "standard" +Provides-Extra: all +Requires-Dist: fastapi-cli[standard]>=0.0.5; extra == "all" +Requires-Dist: httpx>=0.23.0; extra == "all" +Requires-Dist: jinja2>=3.1.5; extra == "all" +Requires-Dist: python-multipart>=0.0.18; extra == "all" +Requires-Dist: itsdangerous>=1.1.0; extra == "all" +Requires-Dist: pyyaml>=5.3.1; extra == "all" +Requires-Dist: ujson!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0,>=4.0.1; extra == "all" +Requires-Dist: orjson>=3.2.1; extra == "all" +Requires-Dist: email-validator>=2.0.0; extra == "all" +Requires-Dist: uvicorn[standard]>=0.12.0; extra == "all" +Requires-Dist: pydantic-settings>=2.0.0; extra == "all" +Requires-Dist: pydantic-extra-types>=2.0.0; extra == "all" +Description-Content-Type: text/markdown + +

+ FastAPI +

+

+ FastAPI framework, high performance, easy to learn, fast to code, ready for production +

+

+ + Test + + + Coverage + + + Package version + + + Supported Python versions + +

+ +--- + +**Documentation**: https://fastapi.tiangolo.com + +**Source Code**: https://github.com/fastapi/fastapi + +--- + +FastAPI is a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints. + +The key features are: + +* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance). +* **Fast to code**: Increase the speed to develop features by about 200% to 300%. * +* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. * +* **Intuitive**: Great editor support. Completion everywhere. Less time debugging. +* **Easy**: Designed to be easy to use and learn. Less time reading docs. +* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs. +* **Robust**: Get production-ready code. With automatic interactive documentation. +* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema. + +* estimation based on tests on an internal development team, building production applications. + +## Sponsors + + + + + + + + + + + + + + + + + + + + + + +Other sponsors + +## Opinions + +"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" + +
Kabir Khan - Microsoft (ref)
+ +--- + +"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_" + +
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
+ +--- + +"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_" + +
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
+ +--- + +"_I’m over the moon excited about **FastAPI**. It’s so fun!_" + +
Brian Okken - Python Bytes podcast host (ref)
+ +--- + +"_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" + +
Timothy Crosley - Hug creator (ref)
+ +--- + +"_If you're looking to learn one **modern framework** for building REST APIs, check out **FastAPI** [...] It's fast, easy to use and easy to learn [...]_" + +"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_" + +
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
+ +--- + +"_If anyone is looking to build a production Python API, I would highly recommend **FastAPI**. It is **beautifully designed**, **simple to use** and **highly scalable**, it has become a **key component** in our API first development strategy and is driving many automations and services such as our Virtual TAC Engineer._" + +
Deon Pillsbury - Cisco (ref)
+ +--- + +## **Typer**, the FastAPI of CLIs + + + +If you are building a CLI app to be used in the terminal instead of a web API, check out **Typer**. + +**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 🚀 + +## Requirements + +FastAPI stands on the shoulders of giants: + +* Starlette for the web parts. +* Pydantic for the data parts. + +## Installation + +Create and activate a virtual environment and then install FastAPI: + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +**Note**: Make sure you put `"fastapi[standard]"` in quotes to ensure it works in all terminals. + +## Example + +### Create it + +Create a file `main.py` with: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +
+Or use async def... + +If your code uses `async` / `await`, use `async def`: + +```Python hl_lines="9 14" +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +**Note**: + +If you don't know, check the _"In a hurry?"_ section about `async` and `await` in the docs. + +
+ +### Run it + +Run the server with: + +
+ +```console +$ fastapi dev main.py + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + │ fastapi run │ + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2248755] using WatchFiles +INFO: Started server process [2248757] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +
+About the command fastapi dev main.py... + +The command `fastapi dev` reads your `main.py` file, detects the **FastAPI** app in it, and starts a server using Uvicorn. + +By default, `fastapi dev` will start with auto-reload enabled for local development. + +You can read more about it in the FastAPI CLI docs. + +
+ +### Check it + +Open your browser at http://127.0.0.1:8000/items/5?q=somequery. + +You will see the JSON response as: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +You already created an API that: + +* Receives HTTP requests in the _paths_ `/` and `/items/{item_id}`. +* Both _paths_ take `GET` operations (also known as HTTP _methods_). +* The _path_ `/items/{item_id}` has a _path parameter_ `item_id` that should be an `int`. +* The _path_ `/items/{item_id}` has an optional `str` _query parameter_ `q`. + +### Interactive API docs + +Now go to http://127.0.0.1:8000/docs. + +You will see the automatic interactive API documentation (provided by Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Alternative API docs + +And now, go to http://127.0.0.1:8000/redoc. + +You will see the alternative automatic documentation (provided by ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## Example upgrade + +Now modify the file `main.py` to receive a body from a `PUT` request. + +Declare the body using standard Python types, thanks to Pydantic. + +```Python hl_lines="4 9-12 25-27" +from typing import Union + +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + price: float + is_offer: Union[bool, None] = None + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} + + +@app.put("/items/{item_id}") +def update_item(item_id: int, item: Item): + return {"item_name": item.name, "item_id": item_id} +``` + +The `fastapi dev` server should reload automatically. + +### Interactive API docs upgrade + +Now go to http://127.0.0.1:8000/docs. + +* The interactive API documentation will be automatically updated, including the new body: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Click on the button "Try it out", it allows you to fill the parameters and directly interact with the API: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +* Then click on the "Execute" button, the user interface will communicate with your API, send the parameters, get the results and show them on the screen: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### Alternative API docs upgrade + +And now, go to http://127.0.0.1:8000/redoc. + +* The alternative documentation will also reflect the new query parameter and body: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Recap + +In summary, you declare **once** the types of parameters, body, etc. as function parameters. + +You do that with standard modern Python types. + +You don't have to learn a new syntax, the methods or classes of a specific library, etc. + +Just standard **Python**. + +For example, for an `int`: + +```Python +item_id: int +``` + +or for a more complex `Item` model: + +```Python +item: Item +``` + +...and with that single declaration you get: + +* Editor support, including: + * Completion. + * Type checks. +* Validation of data: + * Automatic and clear errors when the data is invalid. + * Validation even for deeply nested JSON objects. +* Conversion of input data: coming from the network to Python data and types. Reading from: + * JSON. + * Path parameters. + * Query parameters. + * Cookies. + * Headers. + * Forms. + * Files. +* Conversion of output data: converting from Python data and types to network data (as JSON): + * Convert Python types (`str`, `int`, `float`, `bool`, `list`, etc). + * `datetime` objects. + * `UUID` objects. + * Database models. + * ...and many more. +* Automatic interactive API documentation, including 2 alternative user interfaces: + * Swagger UI. + * ReDoc. + +--- + +Coming back to the previous code example, **FastAPI** will: + +* Validate that there is an `item_id` in the path for `GET` and `PUT` requests. +* Validate that the `item_id` is of type `int` for `GET` and `PUT` requests. + * If it is not, the client will see a useful, clear error. +* Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`) for `GET` requests. + * As the `q` parameter is declared with `= None`, it is optional. + * Without the `None` it would be required (as is the body in the case with `PUT`). +* For `PUT` requests to `/items/{item_id}`, read the body as JSON: + * Check that it has a required attribute `name` that should be a `str`. + * Check that it has a required attribute `price` that has to be a `float`. + * Check that it has an optional attribute `is_offer`, that should be a `bool`, if present. + * All this would also work for deeply nested JSON objects. +* Convert from and to JSON automatically. +* Document everything with OpenAPI, that can be used by: + * Interactive documentation systems. + * Automatic client code generation systems, for many languages. +* Provide 2 interactive documentation web interfaces directly. + +--- + +We just scratched the surface, but you already get the idea of how it all works. + +Try changing the line with: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...from: + +```Python + ... "item_name": item.name ... +``` + +...to: + +```Python + ... "item_price": item.price ... +``` + +...and see how your editor will auto-complete the attributes and know their types: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +For a more complete example including more features, see the Tutorial - User Guide. + +**Spoiler alert**: the tutorial - user guide includes: + +* Declaration of **parameters** from other different places as: **headers**, **cookies**, **form fields** and **files**. +* How to set **validation constraints** as `maximum_length` or `regex`. +* A very powerful and easy to use **Dependency Injection** system. +* Security and authentication, including support for **OAuth2** with **JWT tokens** and **HTTP Basic** auth. +* More advanced (but equally easy) techniques for declaring **deeply nested JSON models** (thanks to Pydantic). +* **GraphQL** integration with Strawberry and other libraries. +* Many extra features (thanks to Starlette) as: + * **WebSockets** + * extremely easy tests based on HTTPX and `pytest` + * **CORS** + * **Cookie Sessions** + * ...and more. + +## Performance + +Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*) + +To understand more about it, see the section Benchmarks. + +## Dependencies + +FastAPI depends on Pydantic and Starlette. + +### `standard` Dependencies + +When you install FastAPI with `pip install "fastapi[standard]"` it comes with the `standard` group of optional dependencies: + +Used by Pydantic: + +* email-validator - for email validation. + +Used by Starlette: + +* httpx - Required if you want to use the `TestClient`. +* jinja2 - Required if you want to use the default template configuration. +* python-multipart - Required if you want to support form "parsing", with `request.form()`. + +Used by FastAPI / Starlette: + +* uvicorn - for the server that loads and serves your application. This includes `uvicorn[standard]`, which includes some dependencies (e.g. `uvloop`) needed for high performance serving. +* `fastapi-cli` - to provide the `fastapi` command. + +### Without `standard` Dependencies + +If you don't want to include the `standard` optional dependencies, you can install with `pip install fastapi` instead of `pip install "fastapi[standard]"`. + +### Additional Optional Dependencies + +There are some additional dependencies you might want to install. + +Additional optional Pydantic dependencies: + +* pydantic-settings - for settings management. +* pydantic-extra-types - for extra types to be used with Pydantic. + +Additional optional FastAPI dependencies: + +* orjson - Required if you want to use `ORJSONResponse`. +* ujson - Required if you want to use `UJSONResponse`. + +## License + +This project is licensed under the terms of the MIT license. diff --git a/venv/Lib/site-packages/fastapi-0.115.14.dist-info/RECORD b/venv/Lib/site-packages/fastapi-0.115.14.dist-info/RECORD new file mode 100644 index 00000000..b14145eb --- /dev/null +++ b/venv/Lib/site-packages/fastapi-0.115.14.dist-info/RECORD @@ -0,0 +1,97 @@ +../../Scripts/fastapi.exe,sha256=HeMeOECE5j0VKhIfzIDfMnAA4LATyaoAegFr0AGuWKM,108404 +fastapi-0.115.14.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +fastapi-0.115.14.dist-info/METADATA,sha256=BKQS5L_nvCHYJUCYQujjjM8dxMoJDV84thmsHYxZiI0,27180 +fastapi-0.115.14.dist-info/RECORD,, +fastapi-0.115.14.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +fastapi-0.115.14.dist-info/WHEEL,sha256=tSfRZzRHthuv7vxpI4aehrdN9scLjk-dCJkPLzkHxGg,90 +fastapi-0.115.14.dist-info/entry_points.txt,sha256=GCf-WbIZxyGT4MUmrPGj1cOHYZoGsNPHAvNkT6hnGeA,61 +fastapi-0.115.14.dist-info/licenses/LICENSE,sha256=Tsif_IFIW5f-xYSy1KlhAy7v_oNEU4lP2cEnSQbMdE4,1086 +fastapi/__init__.py,sha256=zto_Knb1xNkut8EXy4Q4enLzjY6UIFsGKNCJUQpgcwc,1082 +fastapi/__main__.py,sha256=bKePXLdO4SsVSM6r9SVoLickJDcR2c0cTOxZRKq26YQ,37 +fastapi/__pycache__/__init__.cpython-312.pyc,, +fastapi/__pycache__/__main__.cpython-312.pyc,, +fastapi/__pycache__/_compat.cpython-312.pyc,, +fastapi/__pycache__/applications.cpython-312.pyc,, +fastapi/__pycache__/background.cpython-312.pyc,, +fastapi/__pycache__/cli.cpython-312.pyc,, +fastapi/__pycache__/concurrency.cpython-312.pyc,, +fastapi/__pycache__/datastructures.cpython-312.pyc,, +fastapi/__pycache__/encoders.cpython-312.pyc,, +fastapi/__pycache__/exception_handlers.cpython-312.pyc,, +fastapi/__pycache__/exceptions.cpython-312.pyc,, +fastapi/__pycache__/logger.cpython-312.pyc,, +fastapi/__pycache__/param_functions.cpython-312.pyc,, +fastapi/__pycache__/params.cpython-312.pyc,, +fastapi/__pycache__/requests.cpython-312.pyc,, +fastapi/__pycache__/responses.cpython-312.pyc,, +fastapi/__pycache__/routing.cpython-312.pyc,, +fastapi/__pycache__/staticfiles.cpython-312.pyc,, +fastapi/__pycache__/templating.cpython-312.pyc,, +fastapi/__pycache__/testclient.cpython-312.pyc,, +fastapi/__pycache__/types.cpython-312.pyc,, +fastapi/__pycache__/utils.cpython-312.pyc,, +fastapi/__pycache__/websockets.cpython-312.pyc,, +fastapi/_compat.py,sha256=PwGTZd6d-u2o6YF9M8pQahuBtD_3q3Kpj7vU5-ngChc,24228 +fastapi/applications.py,sha256=rZTr0Ix-vdMwh6MQGCI_NC-Ir9lpfIGHHBY-JnNWZ_E,176550 +fastapi/background.py,sha256=rouLirxUANrcYC824MSMypXL_Qb2HYg2YZqaiEqbEKI,1768 +fastapi/cli.py,sha256=OYhZb0NR_deuT5ofyPF2NoNBzZDNOP8Salef2nk-HqA,418 +fastapi/concurrency.py,sha256=MirfowoSpkMQZ8j_g0ZxaQKpV6eB3G-dB5TgcXCrgEA,1424 +fastapi/datastructures.py,sha256=b2PEz77XGq-u3Ur1Inwk0AGjOsQZO49yF9C7IPJ15cY,5766 +fastapi/dependencies/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +fastapi/dependencies/__pycache__/__init__.cpython-312.pyc,, +fastapi/dependencies/__pycache__/models.cpython-312.pyc,, +fastapi/dependencies/__pycache__/utils.cpython-312.pyc,, +fastapi/dependencies/models.py,sha256=Pjl6vx-4nZ5Tta9kJa3-RfQKkXtCpS09-FhMgs9eWNs,1507 +fastapi/dependencies/utils.py,sha256=wGN-BAb0NpG-89nA_OllS0F4wYwGfhHgb8IuT3MTqck,36619 +fastapi/encoders.py,sha256=LvwYmFeOz4tVwvgBoC5rvZnbr7hZr73KGrU8O7zSptU,11068 +fastapi/exception_handlers.py,sha256=MBrIOA-ugjJDivIi4rSsUJBdTsjuzN76q4yh0q1COKw,1332 +fastapi/exceptions.py,sha256=taNixuFEXb67lI1bnX1ubq8y8TseJ4yoPlWjyP0fTzk,4969 +fastapi/logger.py,sha256=I9NNi3ov8AcqbsbC9wl1X-hdItKgYt2XTrx1f99Zpl4,54 +fastapi/middleware/__init__.py,sha256=oQDxiFVcc1fYJUOIFvphnK7pTT5kktmfL32QXpBFvvo,58 +fastapi/middleware/__pycache__/__init__.cpython-312.pyc,, +fastapi/middleware/__pycache__/cors.cpython-312.pyc,, +fastapi/middleware/__pycache__/gzip.cpython-312.pyc,, +fastapi/middleware/__pycache__/httpsredirect.cpython-312.pyc,, +fastapi/middleware/__pycache__/trustedhost.cpython-312.pyc,, +fastapi/middleware/__pycache__/wsgi.cpython-312.pyc,, +fastapi/middleware/cors.py,sha256=ynwjWQZoc_vbhzZ3_ZXceoaSrslHFHPdoM52rXr0WUU,79 +fastapi/middleware/gzip.py,sha256=xM5PcsH8QlAimZw4VDvcmTnqQamslThsfe3CVN2voa0,79 +fastapi/middleware/httpsredirect.py,sha256=rL8eXMnmLijwVkH7_400zHri1AekfeBd6D6qs8ix950,115 +fastapi/middleware/trustedhost.py,sha256=eE5XGRxGa7c5zPnMJDGp3BxaL25k5iVQlhnv-Pk0Pss,109 +fastapi/middleware/wsgi.py,sha256=Z3Ue-7wni4lUZMvH3G9ek__acgYdJstbnpZX_HQAboY,79 +fastapi/openapi/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +fastapi/openapi/__pycache__/__init__.cpython-312.pyc,, +fastapi/openapi/__pycache__/constants.cpython-312.pyc,, +fastapi/openapi/__pycache__/docs.cpython-312.pyc,, +fastapi/openapi/__pycache__/models.cpython-312.pyc,, +fastapi/openapi/__pycache__/utils.cpython-312.pyc,, +fastapi/openapi/constants.py,sha256=adGzmis1L1HJRTE3kJ5fmHS_Noq6tIY6pWv_SFzoFDU,153 +fastapi/openapi/docs.py,sha256=zSDv4xY6XHcKsaG4zyk1HqSnrZtfZFBB0J7ZBk5YHPE,10345 +fastapi/openapi/models.py,sha256=PqkxQiqcEgjKuhfUIWPZPQcyTcubtUCB3vcObLsB7VE,15397 +fastapi/openapi/utils.py,sha256=e00G_p0IdpiffBUaq31BUyiloXbpld8RryKYnYKisdY,23964 +fastapi/param_functions.py,sha256=JHNPLIYvoAwdnZZavIVsxOat8x23fX_Kl33reh7HKl8,64019 +fastapi/params.py,sha256=g450axUBQgQJODdtM7WBxZbQj9Z64inFvadrgHikBbU,28237 +fastapi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +fastapi/requests.py,sha256=zayepKFcienBllv3snmWI20Gk0oHNVLU4DDhqXBb4LU,142 +fastapi/responses.py,sha256=QNQQlwpKhQoIPZTTWkpc9d_QGeGZ_aVQPaDV3nQ8m7c,1761 +fastapi/routing.py,sha256=gnGRnOzM-CBOYj7hI0bZlC_5c-RQKh6BPmlsDD8IVUo,176315 +fastapi/security/__init__.py,sha256=bO8pNmxqVRXUjfl2mOKiVZLn0FpBQ61VUYVjmppnbJw,881 +fastapi/security/__pycache__/__init__.cpython-312.pyc,, +fastapi/security/__pycache__/api_key.cpython-312.pyc,, +fastapi/security/__pycache__/base.cpython-312.pyc,, +fastapi/security/__pycache__/http.cpython-312.pyc,, +fastapi/security/__pycache__/oauth2.cpython-312.pyc,, +fastapi/security/__pycache__/open_id_connect_url.cpython-312.pyc,, +fastapi/security/__pycache__/utils.cpython-312.pyc,, +fastapi/security/api_key.py,sha256=cBI5Z4zWVjL1uJrsjTeLy7MafHPAO2HQPzTrpyoIYWA,9094 +fastapi/security/base.py,sha256=dl4pvbC-RxjfbWgPtCWd8MVU-7CB2SZ22rJDXVCXO6c,141 +fastapi/security/http.py,sha256=rWR2x-5CUsjWmRucYthwRig6MG1o-boyrr4Xo-PuuxU,13606 +fastapi/security/oauth2.py,sha256=M1AFIDT7G3oQChq83poI3eg8ZDeibcvnGmya2CTS7JY,22036 +fastapi/security/open_id_connect_url.py,sha256=8vizZ2tGqEp1ur8SwtVgyHJhGAJ5AqahgcvSpaIioDI,2722 +fastapi/security/utils.py,sha256=bd8T0YM7UQD5ATKucr1bNtAvz_Y3__dVNAv5UebiPvc,293 +fastapi/staticfiles.py,sha256=iirGIt3sdY2QZXd36ijs3Cj-T0FuGFda3cd90kM9Ikw,69 +fastapi/templating.py,sha256=4zsuTWgcjcEainMJFAlW6-gnslm6AgOS1SiiDWfmQxk,76 +fastapi/testclient.py,sha256=nBvaAmX66YldReJNZXPOk1sfuo2Q6hs8bOvIaCep6LQ,66 +fastapi/types.py,sha256=nFb36sK3DSoqoyo7Miwy3meKK5UdFBgkAgLSzQlUVyI,383 +fastapi/utils.py,sha256=y8Bj5ttMaI9tS4D60OUgXqKnktBr99NdYUnHHV9LgoY,7948 +fastapi/websockets.py,sha256=419uncYObEKZG0YcrXscfQQYLSWoE10jqxVMetGdR98,222 diff --git a/venv/Lib/site-packages/fastapi-0.115.14.dist-info/REQUESTED b/venv/Lib/site-packages/fastapi-0.115.14.dist-info/REQUESTED new file mode 100644 index 00000000..e69de29b diff --git a/venv/Lib/site-packages/fastapi-0.115.14.dist-info/WHEEL b/venv/Lib/site-packages/fastapi-0.115.14.dist-info/WHEEL new file mode 100644 index 00000000..45ec8c4e --- /dev/null +++ b/venv/Lib/site-packages/fastapi-0.115.14.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: pdm-backend (2.4.4) +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/venv/Lib/site-packages/fastapi-0.115.14.dist-info/entry_points.txt b/venv/Lib/site-packages/fastapi-0.115.14.dist-info/entry_points.txt new file mode 100644 index 00000000..b81849e1 --- /dev/null +++ b/venv/Lib/site-packages/fastapi-0.115.14.dist-info/entry_points.txt @@ -0,0 +1,5 @@ +[console_scripts] +fastapi = fastapi.cli:main + +[gui_scripts] + diff --git a/venv/Lib/site-packages/fastapi-0.115.14.dist-info/licenses/LICENSE b/venv/Lib/site-packages/fastapi-0.115.14.dist-info/licenses/LICENSE new file mode 100644 index 00000000..3e92463e --- /dev/null +++ b/venv/Lib/site-packages/fastapi-0.115.14.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2018 Sebastián Ramírez + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/venv/Lib/site-packages/fastapi/__init__.py b/venv/Lib/site-packages/fastapi/__init__.py new file mode 100644 index 00000000..e672ec9e --- /dev/null +++ b/venv/Lib/site-packages/fastapi/__init__.py @@ -0,0 +1,25 @@ +"""FastAPI framework, high performance, easy to learn, fast to code, ready for production""" + +__version__ = "0.115.14" + +from starlette import status as status + +from .applications import FastAPI as FastAPI +from .background import BackgroundTasks as BackgroundTasks +from .datastructures import UploadFile as UploadFile +from .exceptions import HTTPException as HTTPException +from .exceptions import WebSocketException as WebSocketException +from .param_functions import Body as Body +from .param_functions import Cookie as Cookie +from .param_functions import Depends as Depends +from .param_functions import File as File +from .param_functions import Form as Form +from .param_functions import Header as Header +from .param_functions import Path as Path +from .param_functions import Query as Query +from .param_functions import Security as Security +from .requests import Request as Request +from .responses import Response as Response +from .routing import APIRouter as APIRouter +from .websockets import WebSocket as WebSocket +from .websockets import WebSocketDisconnect as WebSocketDisconnect diff --git a/venv/Lib/site-packages/fastapi/__main__.py b/venv/Lib/site-packages/fastapi/__main__.py new file mode 100644 index 00000000..fc36465f --- /dev/null +++ b/venv/Lib/site-packages/fastapi/__main__.py @@ -0,0 +1,3 @@ +from fastapi.cli import main + +main() diff --git a/venv/Lib/site-packages/fastapi/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/fastapi/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..7a55750b Binary files /dev/null and b/venv/Lib/site-packages/fastapi/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/__pycache__/__main__.cpython-312.pyc b/venv/Lib/site-packages/fastapi/__pycache__/__main__.cpython-312.pyc new file mode 100644 index 00000000..ba9fdf10 Binary files /dev/null and b/venv/Lib/site-packages/fastapi/__pycache__/__main__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/__pycache__/_compat.cpython-312.pyc b/venv/Lib/site-packages/fastapi/__pycache__/_compat.cpython-312.pyc new file mode 100644 index 00000000..52d218ae Binary files /dev/null and b/venv/Lib/site-packages/fastapi/__pycache__/_compat.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/__pycache__/applications.cpython-312.pyc b/venv/Lib/site-packages/fastapi/__pycache__/applications.cpython-312.pyc new file mode 100644 index 00000000..f2a87e51 Binary files /dev/null and b/venv/Lib/site-packages/fastapi/__pycache__/applications.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/__pycache__/background.cpython-312.pyc b/venv/Lib/site-packages/fastapi/__pycache__/background.cpython-312.pyc new file mode 100644 index 00000000..6ec09524 Binary files /dev/null and b/venv/Lib/site-packages/fastapi/__pycache__/background.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/__pycache__/cli.cpython-312.pyc b/venv/Lib/site-packages/fastapi/__pycache__/cli.cpython-312.pyc new file mode 100644 index 00000000..2bd803c7 Binary files /dev/null and b/venv/Lib/site-packages/fastapi/__pycache__/cli.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/__pycache__/concurrency.cpython-312.pyc b/venv/Lib/site-packages/fastapi/__pycache__/concurrency.cpython-312.pyc new file mode 100644 index 00000000..e7c0719d Binary files /dev/null and b/venv/Lib/site-packages/fastapi/__pycache__/concurrency.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/__pycache__/datastructures.cpython-312.pyc b/venv/Lib/site-packages/fastapi/__pycache__/datastructures.cpython-312.pyc new file mode 100644 index 00000000..8b2c9669 Binary files /dev/null and b/venv/Lib/site-packages/fastapi/__pycache__/datastructures.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/__pycache__/encoders.cpython-312.pyc b/venv/Lib/site-packages/fastapi/__pycache__/encoders.cpython-312.pyc new file mode 100644 index 00000000..16e18d8f Binary files /dev/null and b/venv/Lib/site-packages/fastapi/__pycache__/encoders.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/__pycache__/exception_handlers.cpython-312.pyc b/venv/Lib/site-packages/fastapi/__pycache__/exception_handlers.cpython-312.pyc new file mode 100644 index 00000000..0f9c4677 Binary files /dev/null and b/venv/Lib/site-packages/fastapi/__pycache__/exception_handlers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/__pycache__/exceptions.cpython-312.pyc b/venv/Lib/site-packages/fastapi/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 00000000..2c83d659 Binary files /dev/null and b/venv/Lib/site-packages/fastapi/__pycache__/exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/__pycache__/logger.cpython-312.pyc b/venv/Lib/site-packages/fastapi/__pycache__/logger.cpython-312.pyc new file mode 100644 index 00000000..5133344a Binary files /dev/null and b/venv/Lib/site-packages/fastapi/__pycache__/logger.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/__pycache__/param_functions.cpython-312.pyc b/venv/Lib/site-packages/fastapi/__pycache__/param_functions.cpython-312.pyc new file mode 100644 index 00000000..ebc1c3ae Binary files /dev/null and b/venv/Lib/site-packages/fastapi/__pycache__/param_functions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/__pycache__/params.cpython-312.pyc b/venv/Lib/site-packages/fastapi/__pycache__/params.cpython-312.pyc new file mode 100644 index 00000000..ae052d98 Binary files /dev/null and b/venv/Lib/site-packages/fastapi/__pycache__/params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/__pycache__/requests.cpython-312.pyc b/venv/Lib/site-packages/fastapi/__pycache__/requests.cpython-312.pyc new file mode 100644 index 00000000..08b8b7e9 Binary files /dev/null and b/venv/Lib/site-packages/fastapi/__pycache__/requests.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/__pycache__/responses.cpython-312.pyc b/venv/Lib/site-packages/fastapi/__pycache__/responses.cpython-312.pyc new file mode 100644 index 00000000..ae278fdf Binary files /dev/null and b/venv/Lib/site-packages/fastapi/__pycache__/responses.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/__pycache__/routing.cpython-312.pyc b/venv/Lib/site-packages/fastapi/__pycache__/routing.cpython-312.pyc new file mode 100644 index 00000000..ac901a7f Binary files /dev/null and b/venv/Lib/site-packages/fastapi/__pycache__/routing.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/__pycache__/staticfiles.cpython-312.pyc b/venv/Lib/site-packages/fastapi/__pycache__/staticfiles.cpython-312.pyc new file mode 100644 index 00000000..71a75c07 Binary files /dev/null and b/venv/Lib/site-packages/fastapi/__pycache__/staticfiles.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/__pycache__/templating.cpython-312.pyc b/venv/Lib/site-packages/fastapi/__pycache__/templating.cpython-312.pyc new file mode 100644 index 00000000..3022a791 Binary files /dev/null and b/venv/Lib/site-packages/fastapi/__pycache__/templating.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/__pycache__/testclient.cpython-312.pyc b/venv/Lib/site-packages/fastapi/__pycache__/testclient.cpython-312.pyc new file mode 100644 index 00000000..665bacaa Binary files /dev/null and b/venv/Lib/site-packages/fastapi/__pycache__/testclient.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/__pycache__/types.cpython-312.pyc b/venv/Lib/site-packages/fastapi/__pycache__/types.cpython-312.pyc new file mode 100644 index 00000000..c468add3 Binary files /dev/null and b/venv/Lib/site-packages/fastapi/__pycache__/types.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/fastapi/__pycache__/utils.cpython-312.pyc new file mode 100644 index 00000000..30070740 Binary files /dev/null and b/venv/Lib/site-packages/fastapi/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/__pycache__/websockets.cpython-312.pyc b/venv/Lib/site-packages/fastapi/__pycache__/websockets.cpython-312.pyc new file mode 100644 index 00000000..408b43e7 Binary files /dev/null and b/venv/Lib/site-packages/fastapi/__pycache__/websockets.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/_compat.py b/venv/Lib/site-packages/fastapi/_compat.py new file mode 100644 index 00000000..227ad837 --- /dev/null +++ b/venv/Lib/site-packages/fastapi/_compat.py @@ -0,0 +1,664 @@ +from collections import deque +from copy import copy +from dataclasses import dataclass, is_dataclass +from enum import Enum +from functools import lru_cache +from typing import ( + Any, + Callable, + Deque, + Dict, + FrozenSet, + List, + Mapping, + Sequence, + Set, + Tuple, + Type, + Union, + cast, +) + +from fastapi.exceptions import RequestErrorModel +from fastapi.types import IncEx, ModelNameMap, UnionType +from pydantic import BaseModel, create_model +from pydantic.version import VERSION as PYDANTIC_VERSION +from starlette.datastructures import UploadFile +from typing_extensions import Annotated, Literal, get_args, get_origin + +PYDANTIC_VERSION_MINOR_TUPLE = tuple(int(x) for x in PYDANTIC_VERSION.split(".")[:2]) +PYDANTIC_V2 = PYDANTIC_VERSION_MINOR_TUPLE[0] == 2 + + +sequence_annotation_to_type = { + Sequence: list, + List: list, + list: list, + Tuple: tuple, + tuple: tuple, + Set: set, + set: set, + FrozenSet: frozenset, + frozenset: frozenset, + Deque: deque, + deque: deque, +} + +sequence_types = tuple(sequence_annotation_to_type.keys()) + +Url: Type[Any] + +if PYDANTIC_V2: + from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError + from pydantic import TypeAdapter + from pydantic import ValidationError as ValidationError + from pydantic._internal._schema_generation_shared import ( # type: ignore[attr-defined] + GetJsonSchemaHandler as GetJsonSchemaHandler, + ) + from pydantic._internal._typing_extra import eval_type_lenient + from pydantic._internal._utils import lenient_issubclass as lenient_issubclass + from pydantic.fields import FieldInfo + from pydantic.json_schema import GenerateJsonSchema as GenerateJsonSchema + from pydantic.json_schema import JsonSchemaValue as JsonSchemaValue + from pydantic_core import CoreSchema as CoreSchema + from pydantic_core import PydanticUndefined, PydanticUndefinedType + from pydantic_core import Url as Url + + try: + from pydantic_core.core_schema import ( + with_info_plain_validator_function as with_info_plain_validator_function, + ) + except ImportError: # pragma: no cover + from pydantic_core.core_schema import ( + general_plain_validator_function as with_info_plain_validator_function, # noqa: F401 + ) + + RequiredParam = PydanticUndefined + Undefined = PydanticUndefined + UndefinedType = PydanticUndefinedType + evaluate_forwardref = eval_type_lenient + Validator = Any + + class BaseConfig: + pass + + class ErrorWrapper(Exception): + pass + + @dataclass + class ModelField: + field_info: FieldInfo + name: str + mode: Literal["validation", "serialization"] = "validation" + + @property + def alias(self) -> str: + a = self.field_info.alias + return a if a is not None else self.name + + @property + def required(self) -> bool: + return self.field_info.is_required() + + @property + def default(self) -> Any: + return self.get_default() + + @property + def type_(self) -> Any: + return self.field_info.annotation + + def __post_init__(self) -> None: + self._type_adapter: TypeAdapter[Any] = TypeAdapter( + Annotated[self.field_info.annotation, self.field_info] + ) + + def get_default(self) -> Any: + if self.field_info.is_required(): + return Undefined + return self.field_info.get_default(call_default_factory=True) + + def validate( + self, + value: Any, + values: Dict[str, Any] = {}, # noqa: B006 + *, + loc: Tuple[Union[int, str], ...] = (), + ) -> Tuple[Any, Union[List[Dict[str, Any]], None]]: + try: + return ( + self._type_adapter.validate_python(value, from_attributes=True), + None, + ) + except ValidationError as exc: + return None, _regenerate_error_with_loc( + errors=exc.errors(include_url=False), loc_prefix=loc + ) + + def serialize( + self, + value: Any, + *, + mode: Literal["json", "python"] = "json", + include: Union[IncEx, None] = None, + exclude: Union[IncEx, None] = None, + by_alias: bool = True, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + ) -> Any: + # What calls this code passes a value that already called + # self._type_adapter.validate_python(value) + return self._type_adapter.dump_python( + value, + mode=mode, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + + def __hash__(self) -> int: + # Each ModelField is unique for our purposes, to allow making a dict from + # ModelField to its JSON Schema. + return id(self) + + def get_annotation_from_field_info( + annotation: Any, field_info: FieldInfo, field_name: str + ) -> Any: + return annotation + + def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: + return errors # type: ignore[return-value] + + def _model_rebuild(model: Type[BaseModel]) -> None: + model.model_rebuild() + + def _model_dump( + model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any + ) -> Any: + return model.model_dump(mode=mode, **kwargs) + + def _get_model_config(model: BaseModel) -> Any: + return model.model_config + + def get_schema_from_model_field( + *, + field: ModelField, + schema_generator: GenerateJsonSchema, + model_name_map: ModelNameMap, + field_mapping: Dict[ + Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue + ], + separate_input_output_schemas: bool = True, + ) -> Dict[str, Any]: + override_mode: Union[Literal["validation"], None] = ( + None if separate_input_output_schemas else "validation" + ) + # This expects that GenerateJsonSchema was already used to generate the definitions + json_schema = field_mapping[(field, override_mode or field.mode)] + if "$ref" not in json_schema: + # TODO remove when deprecating Pydantic v1 + # Ref: https://github.com/pydantic/pydantic/blob/d61792cc42c80b13b23e3ffa74bc37ec7c77f7d1/pydantic/schema.py#L207 + json_schema["title"] = ( + field.field_info.title or field.alias.title().replace("_", " ") + ) + return json_schema + + def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: + return {} + + def get_definitions( + *, + fields: List[ModelField], + schema_generator: GenerateJsonSchema, + model_name_map: ModelNameMap, + separate_input_output_schemas: bool = True, + ) -> Tuple[ + Dict[ + Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue + ], + Dict[str, Dict[str, Any]], + ]: + override_mode: Union[Literal["validation"], None] = ( + None if separate_input_output_schemas else "validation" + ) + inputs = [ + (field, override_mode or field.mode, field._type_adapter.core_schema) + for field in fields + ] + field_mapping, definitions = schema_generator.generate_definitions( + inputs=inputs + ) + for item_def in cast(Dict[str, Dict[str, Any]], definitions).values(): + if "description" in item_def: + item_description = cast(str, item_def["description"]).split("\f")[0] + item_def["description"] = item_description + return field_mapping, definitions # type: ignore[return-value] + + def is_scalar_field(field: ModelField) -> bool: + from fastapi import params + + return field_annotation_is_scalar( + field.field_info.annotation + ) and not isinstance(field.field_info, params.Body) + + def is_sequence_field(field: ModelField) -> bool: + return field_annotation_is_sequence(field.field_info.annotation) + + def is_scalar_sequence_field(field: ModelField) -> bool: + return field_annotation_is_scalar_sequence(field.field_info.annotation) + + def is_bytes_field(field: ModelField) -> bool: + return is_bytes_or_nonable_bytes_annotation(field.type_) + + def is_bytes_sequence_field(field: ModelField) -> bool: + return is_bytes_sequence_annotation(field.type_) + + def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo: + cls = type(field_info) + merged_field_info = cls.from_annotation(annotation) + new_field_info = copy(field_info) + new_field_info.metadata = merged_field_info.metadata + new_field_info.annotation = merged_field_info.annotation + return new_field_info + + def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]: + origin_type = ( + get_origin(field.field_info.annotation) or field.field_info.annotation + ) + assert issubclass(origin_type, sequence_types) # type: ignore[arg-type] + return sequence_annotation_to_type[origin_type](value) # type: ignore[no-any-return] + + def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]: + error = ValidationError.from_exception_data( + "Field required", [{"type": "missing", "loc": loc, "input": {}}] + ).errors(include_url=False)[0] + error["input"] = None + return error # type: ignore[return-value] + + def create_body_model( + *, fields: Sequence[ModelField], model_name: str + ) -> Type[BaseModel]: + field_params = {f.name: (f.field_info.annotation, f.field_info) for f in fields} + BodyModel: Type[BaseModel] = create_model(model_name, **field_params) # type: ignore[call-overload] + return BodyModel + + def get_model_fields(model: Type[BaseModel]) -> List[ModelField]: + return [ + ModelField(field_info=field_info, name=name) + for name, field_info in model.model_fields.items() + ] + +else: + from fastapi.openapi.constants import REF_PREFIX as REF_PREFIX + from pydantic import AnyUrl as Url # noqa: F401 + from pydantic import ( # type: ignore[assignment] + BaseConfig as BaseConfig, # noqa: F401 + ) + from pydantic import ValidationError as ValidationError # noqa: F401 + from pydantic.class_validators import ( # type: ignore[no-redef] + Validator as Validator, # noqa: F401 + ) + from pydantic.error_wrappers import ( # type: ignore[no-redef] + ErrorWrapper as ErrorWrapper, # noqa: F401 + ) + from pydantic.errors import MissingError + from pydantic.fields import ( # type: ignore[attr-defined] + SHAPE_FROZENSET, + SHAPE_LIST, + SHAPE_SEQUENCE, + SHAPE_SET, + SHAPE_SINGLETON, + SHAPE_TUPLE, + SHAPE_TUPLE_ELLIPSIS, + ) + from pydantic.fields import FieldInfo as FieldInfo + from pydantic.fields import ( # type: ignore[no-redef,attr-defined] + ModelField as ModelField, # noqa: F401 + ) + + # Keeping old "Required" functionality from Pydantic V1, without + # shadowing typing.Required. + RequiredParam: Any = Ellipsis # type: ignore[no-redef] + from pydantic.fields import ( # type: ignore[no-redef,attr-defined] + Undefined as Undefined, + ) + from pydantic.fields import ( # type: ignore[no-redef, attr-defined] + UndefinedType as UndefinedType, # noqa: F401 + ) + from pydantic.schema import ( + field_schema, + get_flat_models_from_fields, + get_model_name_map, + model_process_schema, + ) + from pydantic.schema import ( # type: ignore[no-redef] # noqa: F401 + get_annotation_from_field_info as get_annotation_from_field_info, + ) + from pydantic.typing import ( # type: ignore[no-redef] + evaluate_forwardref as evaluate_forwardref, # noqa: F401 + ) + from pydantic.utils import ( # type: ignore[no-redef] + lenient_issubclass as lenient_issubclass, # noqa: F401 + ) + + GetJsonSchemaHandler = Any # type: ignore[assignment,misc] + JsonSchemaValue = Dict[str, Any] # type: ignore[misc] + CoreSchema = Any # type: ignore[assignment,misc] + + sequence_shapes = { + SHAPE_LIST, + SHAPE_SET, + SHAPE_FROZENSET, + SHAPE_TUPLE, + SHAPE_SEQUENCE, + SHAPE_TUPLE_ELLIPSIS, + } + sequence_shape_to_type = { + SHAPE_LIST: list, + SHAPE_SET: set, + SHAPE_TUPLE: tuple, + SHAPE_SEQUENCE: list, + SHAPE_TUPLE_ELLIPSIS: list, + } + + @dataclass + class GenerateJsonSchema: # type: ignore[no-redef] + ref_template: str + + class PydanticSchemaGenerationError(Exception): # type: ignore[no-redef] + pass + + def with_info_plain_validator_function( # type: ignore[misc] + function: Callable[..., Any], + *, + ref: Union[str, None] = None, + metadata: Any = None, + serialization: Any = None, + ) -> Any: + return {} + + def get_model_definitions( + *, + flat_models: Set[Union[Type[BaseModel], Type[Enum]]], + model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], + ) -> Dict[str, Any]: + definitions: Dict[str, Dict[str, Any]] = {} + for model in flat_models: + m_schema, m_definitions, m_nested_models = model_process_schema( + model, model_name_map=model_name_map, ref_prefix=REF_PREFIX + ) + definitions.update(m_definitions) + model_name = model_name_map[model] + if "description" in m_schema: + m_schema["description"] = m_schema["description"].split("\f")[0] + definitions[model_name] = m_schema + return definitions + + def is_pv1_scalar_field(field: ModelField) -> bool: + from fastapi import params + + field_info = field.field_info + if not ( + field.shape == SHAPE_SINGLETON # type: ignore[attr-defined] + and not lenient_issubclass(field.type_, BaseModel) + and not lenient_issubclass(field.type_, dict) + and not field_annotation_is_sequence(field.type_) + and not is_dataclass(field.type_) + and not isinstance(field_info, params.Body) + ): + return False + if field.sub_fields: # type: ignore[attr-defined] + if not all( + is_pv1_scalar_field(f) + for f in field.sub_fields # type: ignore[attr-defined] + ): + return False + return True + + def is_pv1_scalar_sequence_field(field: ModelField) -> bool: + if (field.shape in sequence_shapes) and not lenient_issubclass( # type: ignore[attr-defined] + field.type_, BaseModel + ): + if field.sub_fields is not None: # type: ignore[attr-defined] + for sub_field in field.sub_fields: # type: ignore[attr-defined] + if not is_pv1_scalar_field(sub_field): + return False + return True + if _annotation_is_sequence(field.type_): + return True + return False + + def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: + use_errors: List[Any] = [] + for error in errors: + if isinstance(error, ErrorWrapper): + new_errors = ValidationError( # type: ignore[call-arg] + errors=[error], model=RequestErrorModel + ).errors() + use_errors.extend(new_errors) + elif isinstance(error, list): + use_errors.extend(_normalize_errors(error)) + else: + use_errors.append(error) + return use_errors + + def _model_rebuild(model: Type[BaseModel]) -> None: + model.update_forward_refs() + + def _model_dump( + model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any + ) -> Any: + return model.dict(**kwargs) + + def _get_model_config(model: BaseModel) -> Any: + return model.__config__ # type: ignore[attr-defined] + + def get_schema_from_model_field( + *, + field: ModelField, + schema_generator: GenerateJsonSchema, + model_name_map: ModelNameMap, + field_mapping: Dict[ + Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue + ], + separate_input_output_schemas: bool = True, + ) -> Dict[str, Any]: + # This expects that GenerateJsonSchema was already used to generate the definitions + return field_schema( # type: ignore[no-any-return] + field, model_name_map=model_name_map, ref_prefix=REF_PREFIX + )[0] + + def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: + models = get_flat_models_from_fields(fields, known_models=set()) + return get_model_name_map(models) # type: ignore[no-any-return] + + def get_definitions( + *, + fields: List[ModelField], + schema_generator: GenerateJsonSchema, + model_name_map: ModelNameMap, + separate_input_output_schemas: bool = True, + ) -> Tuple[ + Dict[ + Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue + ], + Dict[str, Dict[str, Any]], + ]: + models = get_flat_models_from_fields(fields, known_models=set()) + return {}, get_model_definitions( + flat_models=models, model_name_map=model_name_map + ) + + def is_scalar_field(field: ModelField) -> bool: + return is_pv1_scalar_field(field) + + def is_sequence_field(field: ModelField) -> bool: + return field.shape in sequence_shapes or _annotation_is_sequence(field.type_) # type: ignore[attr-defined] + + def is_scalar_sequence_field(field: ModelField) -> bool: + return is_pv1_scalar_sequence_field(field) + + def is_bytes_field(field: ModelField) -> bool: + return lenient_issubclass(field.type_, bytes) + + def is_bytes_sequence_field(field: ModelField) -> bool: + return field.shape in sequence_shapes and lenient_issubclass(field.type_, bytes) # type: ignore[attr-defined] + + def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo: + return copy(field_info) + + def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]: + return sequence_shape_to_type[field.shape](value) # type: ignore[no-any-return,attr-defined] + + def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]: + missing_field_error = ErrorWrapper(MissingError(), loc=loc) # type: ignore[call-arg] + new_error = ValidationError([missing_field_error], RequestErrorModel) + return new_error.errors()[0] # type: ignore[return-value] + + def create_body_model( + *, fields: Sequence[ModelField], model_name: str + ) -> Type[BaseModel]: + BodyModel = create_model(model_name) + for f in fields: + BodyModel.__fields__[f.name] = f # type: ignore[index] + return BodyModel + + def get_model_fields(model: Type[BaseModel]) -> List[ModelField]: + return list(model.__fields__.values()) # type: ignore[attr-defined] + + +def _regenerate_error_with_loc( + *, errors: Sequence[Any], loc_prefix: Tuple[Union[str, int], ...] +) -> List[Dict[str, Any]]: + updated_loc_errors: List[Any] = [ + {**err, "loc": loc_prefix + err.get("loc", ())} + for err in _normalize_errors(errors) + ] + + return updated_loc_errors + + +def _annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool: + if lenient_issubclass(annotation, (str, bytes)): + return False + return lenient_issubclass(annotation, sequence_types) + + +def field_annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool: + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + for arg in get_args(annotation): + if field_annotation_is_sequence(arg): + return True + return False + return _annotation_is_sequence(annotation) or _annotation_is_sequence( + get_origin(annotation) + ) + + +def value_is_sequence(value: Any) -> bool: + return isinstance(value, sequence_types) and not isinstance(value, (str, bytes)) # type: ignore[arg-type] + + +def _annotation_is_complex(annotation: Union[Type[Any], None]) -> bool: + return ( + lenient_issubclass(annotation, (BaseModel, Mapping, UploadFile)) + or _annotation_is_sequence(annotation) + or is_dataclass(annotation) + ) + + +def field_annotation_is_complex(annotation: Union[Type[Any], None]) -> bool: + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + return any(field_annotation_is_complex(arg) for arg in get_args(annotation)) + + return ( + _annotation_is_complex(annotation) + or _annotation_is_complex(origin) + or hasattr(origin, "__pydantic_core_schema__") + or hasattr(origin, "__get_pydantic_core_schema__") + ) + + +def field_annotation_is_scalar(annotation: Any) -> bool: + # handle Ellipsis here to make tuple[int, ...] work nicely + return annotation is Ellipsis or not field_annotation_is_complex(annotation) + + +def field_annotation_is_scalar_sequence(annotation: Union[Type[Any], None]) -> bool: + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + at_least_one_scalar_sequence = False + for arg in get_args(annotation): + if field_annotation_is_scalar_sequence(arg): + at_least_one_scalar_sequence = True + continue + elif not field_annotation_is_scalar(arg): + return False + return at_least_one_scalar_sequence + return field_annotation_is_sequence(annotation) and all( + field_annotation_is_scalar(sub_annotation) + for sub_annotation in get_args(annotation) + ) + + +def is_bytes_or_nonable_bytes_annotation(annotation: Any) -> bool: + if lenient_issubclass(annotation, bytes): + return True + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + for arg in get_args(annotation): + if lenient_issubclass(arg, bytes): + return True + return False + + +def is_uploadfile_or_nonable_uploadfile_annotation(annotation: Any) -> bool: + if lenient_issubclass(annotation, UploadFile): + return True + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + for arg in get_args(annotation): + if lenient_issubclass(arg, UploadFile): + return True + return False + + +def is_bytes_sequence_annotation(annotation: Any) -> bool: + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + at_least_one = False + for arg in get_args(annotation): + if is_bytes_sequence_annotation(arg): + at_least_one = True + continue + return at_least_one + return field_annotation_is_sequence(annotation) and all( + is_bytes_or_nonable_bytes_annotation(sub_annotation) + for sub_annotation in get_args(annotation) + ) + + +def is_uploadfile_sequence_annotation(annotation: Any) -> bool: + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + at_least_one = False + for arg in get_args(annotation): + if is_uploadfile_sequence_annotation(arg): + at_least_one = True + continue + return at_least_one + return field_annotation_is_sequence(annotation) and all( + is_uploadfile_or_nonable_uploadfile_annotation(sub_annotation) + for sub_annotation in get_args(annotation) + ) + + +@lru_cache +def get_cached_model_fields(model: Type[BaseModel]) -> List[ModelField]: + return get_model_fields(model) diff --git a/venv/Lib/site-packages/fastapi/applications.py b/venv/Lib/site-packages/fastapi/applications.py new file mode 100644 index 00000000..05c7bd2b --- /dev/null +++ b/venv/Lib/site-packages/fastapi/applications.py @@ -0,0 +1,4588 @@ +from enum import Enum +from typing import ( + Any, + Awaitable, + Callable, + Coroutine, + Dict, + List, + Optional, + Sequence, + Type, + TypeVar, + Union, +) + +from fastapi import routing +from fastapi.datastructures import Default, DefaultPlaceholder +from fastapi.exception_handlers import ( + http_exception_handler, + request_validation_exception_handler, + websocket_request_validation_exception_handler, +) +from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError +from fastapi.logger import logger +from fastapi.openapi.docs import ( + get_redoc_html, + get_swagger_ui_html, + get_swagger_ui_oauth2_redirect_html, +) +from fastapi.openapi.utils import get_openapi +from fastapi.params import Depends +from fastapi.types import DecoratedCallable, IncEx +from fastapi.utils import generate_unique_id +from starlette.applications import Starlette +from starlette.datastructures import State +from starlette.exceptions import HTTPException +from starlette.middleware import Middleware +from starlette.middleware.base import BaseHTTPMiddleware +from starlette.requests import Request +from starlette.responses import HTMLResponse, JSONResponse, Response +from starlette.routing import BaseRoute +from starlette.types import ASGIApp, Lifespan, Receive, Scope, Send +from typing_extensions import Annotated, Doc, deprecated + +AppType = TypeVar("AppType", bound="FastAPI") + + +class FastAPI(Starlette): + """ + `FastAPI` app class, the main entrypoint to use FastAPI. + + Read more in the + [FastAPI docs for First Steps](https://fastapi.tiangolo.com/tutorial/first-steps/). + + ## Example + + ```python + from fastapi import FastAPI + + app = FastAPI() + ``` + """ + + def __init__( + self: AppType, + *, + debug: Annotated[ + bool, + Doc( + """ + Boolean indicating if debug tracebacks should be returned on server + errors. + + Read more in the + [Starlette docs for Applications](https://www.starlette.io/applications/#instantiating-the-application). + """ + ), + ] = False, + routes: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Starlette and supported for compatibility. + + --- + + A list of routes to serve incoming HTTP and WebSocket requests. + """ + ), + deprecated( + """ + You normally wouldn't use this parameter with FastAPI, it is inherited + from Starlette and supported for compatibility. + + In FastAPI, you normally would use the *path operation methods*, + like `app.get()`, `app.post()`, etc. + """ + ), + ] = None, + title: Annotated[ + str, + Doc( + """ + The title of the API. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more in the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(title="ChimichangApp") + ``` + """ + ), + ] = "FastAPI", + summary: Annotated[ + Optional[str], + Doc( + """ + A short summary of the API. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more in the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(summary="Deadpond's favorite app. Nuff said.") + ``` + """ + ), + ] = None, + description: Annotated[ + str, + Doc( + ''' + A description of the API. Supports Markdown (using + [CommonMark syntax](https://commonmark.org/)). + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more in the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI( + description=""" + ChimichangApp API helps you do awesome stuff. 🚀 + + ## Items + + You can **read items**. + + ## Users + + You will be able to: + + * **Create users** (_not implemented_). + * **Read users** (_not implemented_). + + """ + ) + ``` + ''' + ), + ] = "", + version: Annotated[ + str, + Doc( + """ + The version of the API. + + **Note** This is the version of your application, not the version of + the OpenAPI specification nor the version of FastAPI being used. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more in the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(version="0.0.1") + ``` + """ + ), + ] = "0.1.0", + openapi_url: Annotated[ + Optional[str], + Doc( + """ + The URL where the OpenAPI schema will be served from. + + If you set it to `None`, no OpenAPI schema will be served publicly, and + the default automatic endpoints `/docs` and `/redoc` will also be + disabled. + + Read more in the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#openapi-url). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(openapi_url="/api/v1/openapi.json") + ``` + """ + ), + ] = "/openapi.json", + openapi_tags: Annotated[ + Optional[List[Dict[str, Any]]], + Doc( + """ + A list of tags used by OpenAPI, these are the same `tags` you can set + in the *path operations*, like: + + * `@app.get("/users/", tags=["users"])` + * `@app.get("/items/", tags=["items"])` + + The order of the tags can be used to specify the order shown in + tools like Swagger UI, used in the automatic path `/docs`. + + It's not required to specify all the tags used. + + The tags that are not declared MAY be organized randomly or based + on the tools' logic. Each tag name in the list MUST be unique. + + The value of each item is a `dict` containing: + + * `name`: The name of the tag. + * `description`: A short description of the tag. + [CommonMark syntax](https://commonmark.org/) MAY be used for rich + text representation. + * `externalDocs`: Additional external documentation for this tag. If + provided, it would contain a `dict` with: + * `description`: A short description of the target documentation. + [CommonMark syntax](https://commonmark.org/) MAY be used for + rich text representation. + * `url`: The URL for the target documentation. Value MUST be in + the form of a URL. + + Read more in the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-tags). + + **Example** + + ```python + from fastapi import FastAPI + + tags_metadata = [ + { + "name": "users", + "description": "Operations with users. The **login** logic is also here.", + }, + { + "name": "items", + "description": "Manage items. So _fancy_ they have their own docs.", + "externalDocs": { + "description": "Items external docs", + "url": "https://fastapi.tiangolo.com/", + }, + }, + ] + + app = FastAPI(openapi_tags=tags_metadata) + ``` + """ + ), + ] = None, + servers: Annotated[ + Optional[List[Dict[str, Union[str, Any]]]], + Doc( + """ + A `list` of `dict`s with connectivity information to a target server. + + You would use it, for example, if your application is served from + different domains and you want to use the same Swagger UI in the + browser to interact with each of them (instead of having multiple + browser tabs open). Or if you want to leave fixed the possible URLs. + + If the servers `list` is not provided, or is an empty `list`, the + default value would be a `dict` with a `url` value of `/`. + + Each item in the `list` is a `dict` containing: + + * `url`: A URL to the target host. This URL supports Server Variables + and MAY be relative, to indicate that the host location is relative + to the location where the OpenAPI document is being served. Variable + substitutions will be made when a variable is named in `{`brackets`}`. + * `description`: An optional string describing the host designated by + the URL. [CommonMark syntax](https://commonmark.org/) MAY be used for + rich text representation. + * `variables`: A `dict` between a variable name and its value. The value + is used for substitution in the server's URL template. + + Read more in the + [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#additional-servers). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI( + servers=[ + {"url": "https://stag.example.com", "description": "Staging environment"}, + {"url": "https://prod.example.com", "description": "Production environment"}, + ] + ) + ``` + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[Depends]], + Doc( + """ + A list of global dependencies, they will be applied to each + *path operation*, including in sub-routers. + + Read more about it in the + [FastAPI docs for Global Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/global-dependencies/). + + **Example** + + ```python + from fastapi import Depends, FastAPI + + from .dependencies import func_dep_1, func_dep_2 + + app = FastAPI(dependencies=[Depends(func_dep_1), Depends(func_dep_2)]) + ``` + """ + ), + ] = None, + default_response_class: Annotated[ + Type[Response], + Doc( + """ + The default response class to be used. + + Read more in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class). + + **Example** + + ```python + from fastapi import FastAPI + from fastapi.responses import ORJSONResponse + + app = FastAPI(default_response_class=ORJSONResponse) + ``` + """ + ), + ] = Default(JSONResponse), + redirect_slashes: Annotated[ + bool, + Doc( + """ + Whether to detect and redirect slashes in URLs when the client doesn't + use the same format. + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(redirect_slashes=True) # the default + + @app.get("/items/") + async def read_items(): + return [{"item_id": "Foo"}] + ``` + + With this app, if a client goes to `/items` (without a trailing slash), + they will be automatically redirected with an HTTP status code of 307 + to `/items/`. + """ + ), + ] = True, + docs_url: Annotated[ + Optional[str], + Doc( + """ + The path to the automatic interactive API documentation. + It is handled in the browser by Swagger UI. + + The default URL is `/docs`. You can disable it by setting it to `None`. + + If `openapi_url` is set to `None`, this will be automatically disabled. + + Read more in the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(docs_url="/documentation", redoc_url=None) + ``` + """ + ), + ] = "/docs", + redoc_url: Annotated[ + Optional[str], + Doc( + """ + The path to the alternative automatic interactive API documentation + provided by ReDoc. + + The default URL is `/redoc`. You can disable it by setting it to `None`. + + If `openapi_url` is set to `None`, this will be automatically disabled. + + Read more in the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(docs_url="/documentation", redoc_url="redocumentation") + ``` + """ + ), + ] = "/redoc", + swagger_ui_oauth2_redirect_url: Annotated[ + Optional[str], + Doc( + """ + The OAuth2 redirect endpoint for the Swagger UI. + + By default it is `/docs/oauth2-redirect`. + + This is only used if you use OAuth2 (with the "Authorize" button) + with Swagger UI. + """ + ), + ] = "/docs/oauth2-redirect", + swagger_ui_init_oauth: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + OAuth2 configuration for the Swagger UI, by default shown at `/docs`. + + Read more about the available configuration options in the + [Swagger UI docs](https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/). + """ + ), + ] = None, + middleware: Annotated[ + Optional[Sequence[Middleware]], + Doc( + """ + List of middleware to be added when creating the application. + + In FastAPI you would normally do this with `app.add_middleware()` + instead. + + Read more in the + [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/). + """ + ), + ] = None, + exception_handlers: Annotated[ + Optional[ + Dict[ + Union[int, Type[Exception]], + Callable[[Request, Any], Coroutine[Any, Any, Response]], + ] + ], + Doc( + """ + A dictionary with handlers for exceptions. + + In FastAPI, you would normally use the decorator + `@app.exception_handler()`. + + Read more in the + [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/). + """ + ), + ] = None, + on_startup: Annotated[ + Optional[Sequence[Callable[[], Any]]], + Doc( + """ + A list of startup event handler functions. + + You should instead use the `lifespan` handlers. + + Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). + """ + ), + ] = None, + on_shutdown: Annotated[ + Optional[Sequence[Callable[[], Any]]], + Doc( + """ + A list of shutdown event handler functions. + + You should instead use the `lifespan` handlers. + + Read more in the + [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). + """ + ), + ] = None, + lifespan: Annotated[ + Optional[Lifespan[AppType]], + Doc( + """ + A `Lifespan` context manager handler. This replaces `startup` and + `shutdown` functions with a single context manager. + + Read more in the + [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). + """ + ), + ] = None, + terms_of_service: Annotated[ + Optional[str], + Doc( + """ + A URL to the Terms of Service for your API. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more at the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). + + **Example** + + ```python + app = FastAPI(terms_of_service="http://example.com/terms/") + ``` + """ + ), + ] = None, + contact: Annotated[ + Optional[Dict[str, Union[str, Any]]], + Doc( + """ + A dictionary with the contact information for the exposed API. + + It can contain several fields. + + * `name`: (`str`) The name of the contact person/organization. + * `url`: (`str`) A URL pointing to the contact information. MUST be in + the format of a URL. + * `email`: (`str`) The email address of the contact person/organization. + MUST be in the format of an email address. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more at the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). + + **Example** + + ```python + app = FastAPI( + contact={ + "name": "Deadpoolio the Amazing", + "url": "http://x-force.example.com/contact/", + "email": "dp@x-force.example.com", + } + ) + ``` + """ + ), + ] = None, + license_info: Annotated[ + Optional[Dict[str, Union[str, Any]]], + Doc( + """ + A dictionary with the license information for the exposed API. + + It can contain several fields. + + * `name`: (`str`) **REQUIRED** (if a `license_info` is set). The + license name used for the API. + * `identifier`: (`str`) An [SPDX](https://spdx.dev/) license expression + for the API. The `identifier` field is mutually exclusive of the `url` + field. Available since OpenAPI 3.1.0, FastAPI 0.99.0. + * `url`: (`str`) A URL to the license used for the API. This MUST be + the format of a URL. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more at the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). + + **Example** + + ```python + app = FastAPI( + license_info={ + "name": "Apache 2.0", + "url": "https://www.apache.org/licenses/LICENSE-2.0.html", + } + ) + ``` + """ + ), + ] = None, + openapi_prefix: Annotated[ + str, + Doc( + """ + A URL prefix for the OpenAPI URL. + """ + ), + deprecated( + """ + "openapi_prefix" has been deprecated in favor of "root_path", which + follows more closely the ASGI standard, is simpler, and more + automatic. + """ + ), + ] = "", + root_path: Annotated[ + str, + Doc( + """ + A path prefix handled by a proxy that is not seen by the application + but is seen by external clients, which affects things like Swagger UI. + + Read more about it at the + [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(root_path="/api/v1") + ``` + """ + ), + ] = "", + root_path_in_servers: Annotated[ + bool, + Doc( + """ + To disable automatically generating the URLs in the `servers` field + in the autogenerated OpenAPI using the `root_path`. + + Read more about it in the + [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#disable-automatic-server-from-root_path). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(root_path_in_servers=False) + ``` + """ + ), + ] = True, + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses to be shown in OpenAPI. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/). + + And in the + [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + OpenAPI callbacks that should apply to all *path operations*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + webhooks: Annotated[ + Optional[routing.APIRouter], + Doc( + """ + Add OpenAPI webhooks. This is similar to `callbacks` but it doesn't + depend on specific *path operations*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + **Note**: This is available since OpenAPI 3.1.0, FastAPI 0.99.0. + + Read more about it in the + [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark all *path operations* as deprecated. You probably don't need it, + but it's available. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) all the *path operations* in the generated OpenAPI. + You probably don't need it, but it's available. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + swagger_ui_parameters: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Parameters to configure Swagger UI, the autogenerated interactive API + documentation (by default at `/docs`). + + Read more about it in the + [FastAPI docs about how to Configure Swagger UI](https://fastapi.tiangolo.com/how-to/configure-swagger-ui/). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + separate_input_output_schemas: Annotated[ + bool, + Doc( + """ + Whether to generate separate OpenAPI schemas for request body and + response body when the results would be more precise. + + This is particularly useful when automatically generating clients. + + For example, if you have a model like: + + ```python + from pydantic import BaseModel + + class Item(BaseModel): + name: str + tags: list[str] = [] + ``` + + When `Item` is used for input, a request body, `tags` is not required, + the client doesn't have to provide it. + + But when using `Item` for output, for a response body, `tags` is always + available because it has a default value, even if it's just an empty + list. So, the client should be able to always expect it. + + In this case, there would be two different schemas, one for input and + another one for output. + """ + ), + ] = True, + **extra: Annotated[ + Any, + Doc( + """ + Extra keyword arguments to be stored in the app, not used by FastAPI + anywhere. + """ + ), + ], + ) -> None: + self.debug = debug + self.title = title + self.summary = summary + self.description = description + self.version = version + self.terms_of_service = terms_of_service + self.contact = contact + self.license_info = license_info + self.openapi_url = openapi_url + self.openapi_tags = openapi_tags + self.root_path_in_servers = root_path_in_servers + self.docs_url = docs_url + self.redoc_url = redoc_url + self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url + self.swagger_ui_init_oauth = swagger_ui_init_oauth + self.swagger_ui_parameters = swagger_ui_parameters + self.servers = servers or [] + self.separate_input_output_schemas = separate_input_output_schemas + self.extra = extra + self.openapi_version: Annotated[ + str, + Doc( + """ + The version string of OpenAPI. + + FastAPI will generate OpenAPI version 3.1.0, and will output that as + the OpenAPI version. But some tools, even though they might be + compatible with OpenAPI 3.1.0, might not recognize it as a valid. + + So you could override this value to trick those tools into using + the generated OpenAPI. Have in mind that this is a hack. But if you + avoid using features added in OpenAPI 3.1.0, it might work for your + use case. + + This is not passed as a parameter to the `FastAPI` class to avoid + giving the false idea that FastAPI would generate a different OpenAPI + schema. It is only available as an attribute. + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI() + + app.openapi_version = "3.0.2" + ``` + """ + ), + ] = "3.1.0" + self.openapi_schema: Optional[Dict[str, Any]] = None + if self.openapi_url: + assert self.title, "A title must be provided for OpenAPI, e.g.: 'My API'" + assert self.version, "A version must be provided for OpenAPI, e.g.: '2.1.0'" + # TODO: remove when discarding the openapi_prefix parameter + if openapi_prefix: + logger.warning( + '"openapi_prefix" has been deprecated in favor of "root_path", which ' + "follows more closely the ASGI standard, is simpler, and more " + "automatic. Check the docs at " + "https://fastapi.tiangolo.com/advanced/sub-applications/" + ) + self.webhooks: Annotated[ + routing.APIRouter, + Doc( + """ + The `app.webhooks` attribute is an `APIRouter` with the *path + operations* that will be used just for documentation of webhooks. + + Read more about it in the + [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/). + """ + ), + ] = webhooks or routing.APIRouter() + self.root_path = root_path or openapi_prefix + self.state: Annotated[ + State, + Doc( + """ + A state object for the application. This is the same object for the + entire application, it doesn't change from request to request. + + You normally wouldn't use this in FastAPI, for most of the cases you + would instead use FastAPI dependencies. + + This is simply inherited from Starlette. + + Read more about it in the + [Starlette docs for Applications](https://www.starlette.io/applications/#storing-state-on-the-app-instance). + """ + ), + ] = State() + self.dependency_overrides: Annotated[ + Dict[Callable[..., Any], Callable[..., Any]], + Doc( + """ + A dictionary with overrides for the dependencies. + + Each key is the original dependency callable, and the value is the + actual dependency that should be called. + + This is for testing, to replace expensive dependencies with testing + versions. + + Read more about it in the + [FastAPI docs for Testing Dependencies with Overrides](https://fastapi.tiangolo.com/advanced/testing-dependencies/). + """ + ), + ] = {} + self.router: routing.APIRouter = routing.APIRouter( + routes=routes, + redirect_slashes=redirect_slashes, + dependency_overrides_provider=self, + on_startup=on_startup, + on_shutdown=on_shutdown, + lifespan=lifespan, + default_response_class=default_response_class, + dependencies=dependencies, + callbacks=callbacks, + deprecated=deprecated, + include_in_schema=include_in_schema, + responses=responses, + generate_unique_id_function=generate_unique_id_function, + ) + self.exception_handlers: Dict[ + Any, Callable[[Request, Any], Union[Response, Awaitable[Response]]] + ] = {} if exception_handlers is None else dict(exception_handlers) + self.exception_handlers.setdefault(HTTPException, http_exception_handler) + self.exception_handlers.setdefault( + RequestValidationError, request_validation_exception_handler + ) + self.exception_handlers.setdefault( + WebSocketRequestValidationError, + # Starlette still has incorrect type specification for the handlers + websocket_request_validation_exception_handler, # type: ignore + ) + + self.user_middleware: List[Middleware] = ( + [] if middleware is None else list(middleware) + ) + self.middleware_stack: Union[ASGIApp, None] = None + self.setup() + + def openapi(self) -> Dict[str, Any]: + """ + Generate the OpenAPI schema of the application. This is called by FastAPI + internally. + + The first time it is called it stores the result in the attribute + `app.openapi_schema`, and next times it is called, it just returns that same + result. To avoid the cost of generating the schema every time. + + If you need to modify the generated OpenAPI schema, you could modify it. + + Read more in the + [FastAPI docs for OpenAPI](https://fastapi.tiangolo.com/how-to/extending-openapi/). + """ + if not self.openapi_schema: + self.openapi_schema = get_openapi( + title=self.title, + version=self.version, + openapi_version=self.openapi_version, + summary=self.summary, + description=self.description, + terms_of_service=self.terms_of_service, + contact=self.contact, + license_info=self.license_info, + routes=self.routes, + webhooks=self.webhooks.routes, + tags=self.openapi_tags, + servers=self.servers, + separate_input_output_schemas=self.separate_input_output_schemas, + ) + return self.openapi_schema + + def setup(self) -> None: + if self.openapi_url: + urls = (server_data.get("url") for server_data in self.servers) + server_urls = {url for url in urls if url} + + async def openapi(req: Request) -> JSONResponse: + root_path = req.scope.get("root_path", "").rstrip("/") + if root_path not in server_urls: + if root_path and self.root_path_in_servers: + self.servers.insert(0, {"url": root_path}) + server_urls.add(root_path) + return JSONResponse(self.openapi()) + + self.add_route(self.openapi_url, openapi, include_in_schema=False) + if self.openapi_url and self.docs_url: + + async def swagger_ui_html(req: Request) -> HTMLResponse: + root_path = req.scope.get("root_path", "").rstrip("/") + openapi_url = root_path + self.openapi_url + oauth2_redirect_url = self.swagger_ui_oauth2_redirect_url + if oauth2_redirect_url: + oauth2_redirect_url = root_path + oauth2_redirect_url + return get_swagger_ui_html( + openapi_url=openapi_url, + title=f"{self.title} - Swagger UI", + oauth2_redirect_url=oauth2_redirect_url, + init_oauth=self.swagger_ui_init_oauth, + swagger_ui_parameters=self.swagger_ui_parameters, + ) + + self.add_route(self.docs_url, swagger_ui_html, include_in_schema=False) + + if self.swagger_ui_oauth2_redirect_url: + + async def swagger_ui_redirect(req: Request) -> HTMLResponse: + return get_swagger_ui_oauth2_redirect_html() + + self.add_route( + self.swagger_ui_oauth2_redirect_url, + swagger_ui_redirect, + include_in_schema=False, + ) + if self.openapi_url and self.redoc_url: + + async def redoc_html(req: Request) -> HTMLResponse: + root_path = req.scope.get("root_path", "").rstrip("/") + openapi_url = root_path + self.openapi_url + return get_redoc_html( + openapi_url=openapi_url, title=f"{self.title} - ReDoc" + ) + + self.add_route(self.redoc_url, redoc_html, include_in_schema=False) + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if self.root_path: + scope["root_path"] = self.root_path + await super().__call__(scope, receive, send) + + def add_api_route( + self, + path: str, + endpoint: Callable[..., Any], + *, + response_model: Any = Default(None), + status_code: Optional[int] = None, + tags: Optional[List[Union[str, Enum]]] = None, + dependencies: Optional[Sequence[Depends]] = None, + summary: Optional[str] = None, + description: Optional[str] = None, + response_description: str = "Successful Response", + responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, + deprecated: Optional[bool] = None, + methods: Optional[List[str]] = None, + operation_id: Optional[str] = None, + response_model_include: Optional[IncEx] = None, + response_model_exclude: Optional[IncEx] = None, + response_model_by_alias: bool = True, + response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, + include_in_schema: bool = True, + response_class: Union[Type[Response], DefaultPlaceholder] = Default( + JSONResponse + ), + name: Optional[str] = None, + openapi_extra: Optional[Dict[str, Any]] = None, + generate_unique_id_function: Callable[[routing.APIRoute], str] = Default( + generate_unique_id + ), + ) -> None: + self.router.add_api_route( + path, + endpoint=endpoint, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + methods=methods, + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def api_route( + self, + path: str, + *, + response_model: Any = Default(None), + status_code: Optional[int] = None, + tags: Optional[List[Union[str, Enum]]] = None, + dependencies: Optional[Sequence[Depends]] = None, + summary: Optional[str] = None, + description: Optional[str] = None, + response_description: str = "Successful Response", + responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, + deprecated: Optional[bool] = None, + methods: Optional[List[str]] = None, + operation_id: Optional[str] = None, + response_model_include: Optional[IncEx] = None, + response_model_exclude: Optional[IncEx] = None, + response_model_by_alias: bool = True, + response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, + include_in_schema: bool = True, + response_class: Type[Response] = Default(JSONResponse), + name: Optional[str] = None, + openapi_extra: Optional[Dict[str, Any]] = None, + generate_unique_id_function: Callable[[routing.APIRoute], str] = Default( + generate_unique_id + ), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + def decorator(func: DecoratedCallable) -> DecoratedCallable: + self.router.add_api_route( + path, + func, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + methods=methods, + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + return func + + return decorator + + def add_api_websocket_route( + self, + path: str, + endpoint: Callable[..., Any], + name: Optional[str] = None, + *, + dependencies: Optional[Sequence[Depends]] = None, + ) -> None: + self.router.add_api_websocket_route( + path, + endpoint, + name=name, + dependencies=dependencies, + ) + + def websocket( + self, + path: Annotated[ + str, + Doc( + """ + WebSocket path. + """ + ), + ], + name: Annotated[ + Optional[str], + Doc( + """ + A name for the WebSocket. Only used internally. + """ + ), + ] = None, + *, + dependencies: Annotated[ + Optional[Sequence[Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be used for this + WebSocket. + + Read more about it in the + [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). + """ + ), + ] = None, + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Decorate a WebSocket function. + + Read more about it in the + [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). + + **Example** + + ```python + from fastapi import FastAPI, WebSocket + + app = FastAPI() + + @app.websocket("/ws") + async def websocket_endpoint(websocket: WebSocket): + await websocket.accept() + while True: + data = await websocket.receive_text() + await websocket.send_text(f"Message text was: {data}") + ``` + """ + + def decorator(func: DecoratedCallable) -> DecoratedCallable: + self.add_api_websocket_route( + path, + func, + name=name, + dependencies=dependencies, + ) + return func + + return decorator + + def include_router( + self, + router: Annotated[routing.APIRouter, Doc("The `APIRouter` to include.")], + *, + prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "", + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to all the *path operations* in this + router. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to all the + *path operations* in this router. + + Read more about it in the + [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). + + **Example** + + ```python + from fastapi import Depends, FastAPI + + from .dependencies import get_token_header + from .internal import admin + + app = FastAPI() + + app.include_router( + admin.router, + dependencies=[Depends(get_token_header)], + ) + ``` + """ + ), + ] = None, + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses to be shown in OpenAPI. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/). + + And in the + [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark all the *path operations* in this router as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + **Example** + + ```python + from fastapi import FastAPI + + from .internal import old_api + + app = FastAPI() + + app.include_router( + old_api.router, + deprecated=True, + ) + ``` + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include (or not) all the *path operations* in this router in the + generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + **Example** + + ```python + from fastapi import FastAPI + + from .internal import old_api + + app = FastAPI() + + app.include_router( + old_api.router, + include_in_schema=False, + ) + ``` + """ + ), + ] = True, + default_response_class: Annotated[ + Type[Response], + Doc( + """ + Default response class to be used for the *path operations* in this + router. + + Read more in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class). + + **Example** + + ```python + from fastapi import FastAPI + from fastapi.responses import ORJSONResponse + + from .internal import old_api + + app = FastAPI() + + app.include_router( + old_api.router, + default_response_class=ORJSONResponse, + ) + ``` + """ + ), + ] = Default(JSONResponse), + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> None: + """ + Include an `APIRouter` in the same app. + + Read more about it in the + [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). + + ## Example + + ```python + from fastapi import FastAPI + + from .users import users_router + + app = FastAPI() + + app.include_router(users_router) + ``` + """ + self.router.include_router( + router, + prefix=prefix, + tags=tags, + dependencies=dependencies, + responses=responses, + deprecated=deprecated, + include_in_schema=include_in_schema, + default_response_class=default_response_class, + callbacks=callbacks, + generate_unique_id_function=generate_unique_id_function, + ) + + def get( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP GET operation. + + ## Example + + ```python + from fastapi import FastAPI + + app = FastAPI() + + @app.get("/items/") + def read_items(): + return [{"name": "Empanada"}, {"name": "Arepa"}] + ``` + """ + return self.router.get( + path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def put( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP PUT operation. + + ## Example + + ```python + from fastapi import FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + + @app.put("/items/{item_id}") + def replace_item(item_id: str, item: Item): + return {"message": "Item replaced", "id": item_id} + ``` + """ + return self.router.put( + path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def post( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP POST operation. + + ## Example + + ```python + from fastapi import FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + + @app.post("/items/") + def create_item(item: Item): + return {"message": "Item created"} + ``` + """ + return self.router.post( + path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def delete( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP DELETE operation. + + ## Example + + ```python + from fastapi import FastAPI + + app = FastAPI() + + @app.delete("/items/{item_id}") + def delete_item(item_id: str): + return {"message": "Item deleted"} + ``` + """ + return self.router.delete( + path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def options( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP OPTIONS operation. + + ## Example + + ```python + from fastapi import FastAPI + + app = FastAPI() + + @app.options("/items/") + def get_item_options(): + return {"additions": ["Aji", "Guacamole"]} + ``` + """ + return self.router.options( + path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def head( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP HEAD operation. + + ## Example + + ```python + from fastapi import FastAPI, Response + + app = FastAPI() + + @app.head("/items/", status_code=204) + def get_items_headers(response: Response): + response.headers["X-Cat-Dog"] = "Alone in the world" + ``` + """ + return self.router.head( + path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def patch( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP PATCH operation. + + ## Example + + ```python + from fastapi import FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + + @app.patch("/items/") + def update_item(item: Item): + return {"message": "Item updated in place"} + ``` + """ + return self.router.patch( + path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def trace( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP TRACE operation. + + ## Example + + ```python + from fastapi import FastAPI + + app = FastAPI() + + @app.trace("/items/{item_id}") + def trace_item(item_id: str): + return None + ``` + """ + return self.router.trace( + path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def websocket_route( + self, path: str, name: Union[str, None] = None + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + def decorator(func: DecoratedCallable) -> DecoratedCallable: + self.router.add_websocket_route(path, func, name=name) + return func + + return decorator + + @deprecated( + """ + on_event is deprecated, use lifespan event handlers instead. + + Read more about it in the + [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). + """ + ) + def on_event( + self, + event_type: Annotated[ + str, + Doc( + """ + The type of event. `startup` or `shutdown`. + """ + ), + ], + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add an event handler for the application. + + `on_event` is deprecated, use `lifespan` event handlers instead. + + Read more about it in the + [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). + """ + return self.router.on_event(event_type) + + def middleware( + self, + middleware_type: Annotated[ + str, + Doc( + """ + The type of middleware. Currently only supports `http`. + """ + ), + ], + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a middleware to the application. + + Read more about it in the + [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/). + + ## Example + + ```python + import time + from typing import Awaitable, Callable + + from fastapi import FastAPI, Request, Response + + app = FastAPI() + + + @app.middleware("http") + async def add_process_time_header( + request: Request, call_next: Callable[[Request], Awaitable[Response]] + ) -> Response: + start_time = time.time() + response = await call_next(request) + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + return response + ``` + """ + + def decorator(func: DecoratedCallable) -> DecoratedCallable: + self.add_middleware(BaseHTTPMiddleware, dispatch=func) + return func + + return decorator + + def exception_handler( + self, + exc_class_or_status_code: Annotated[ + Union[int, Type[Exception]], + Doc( + """ + The Exception class this would handle, or a status code. + """ + ), + ], + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add an exception handler to the app. + + Read more about it in the + [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/). + + ## Example + + ```python + from fastapi import FastAPI, Request + from fastapi.responses import JSONResponse + + + class UnicornException(Exception): + def __init__(self, name: str): + self.name = name + + + app = FastAPI() + + + @app.exception_handler(UnicornException) + async def unicorn_exception_handler(request: Request, exc: UnicornException): + return JSONResponse( + status_code=418, + content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."}, + ) + ``` + """ + + def decorator(func: DecoratedCallable) -> DecoratedCallable: + self.add_exception_handler(exc_class_or_status_code, func) + return func + + return decorator diff --git a/venv/Lib/site-packages/fastapi/background.py b/venv/Lib/site-packages/fastapi/background.py new file mode 100644 index 00000000..203578a4 --- /dev/null +++ b/venv/Lib/site-packages/fastapi/background.py @@ -0,0 +1,59 @@ +from typing import Any, Callable + +from starlette.background import BackgroundTasks as StarletteBackgroundTasks +from typing_extensions import Annotated, Doc, ParamSpec + +P = ParamSpec("P") + + +class BackgroundTasks(StarletteBackgroundTasks): + """ + A collection of background tasks that will be called after a response has been + sent to the client. + + Read more about it in the + [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/). + + ## Example + + ```python + from fastapi import BackgroundTasks, FastAPI + + app = FastAPI() + + + def write_notification(email: str, message=""): + with open("log.txt", mode="w") as email_file: + content = f"notification for {email}: {message}" + email_file.write(content) + + + @app.post("/send-notification/{email}") + async def send_notification(email: str, background_tasks: BackgroundTasks): + background_tasks.add_task(write_notification, email, message="some notification") + return {"message": "Notification sent in the background"} + ``` + """ + + def add_task( + self, + func: Annotated[ + Callable[P, Any], + Doc( + """ + The function to call after the response is sent. + + It can be a regular `def` function or an `async def` function. + """ + ), + ], + *args: P.args, + **kwargs: P.kwargs, + ) -> None: + """ + Add a function to be called in the background after the response is sent. + + Read more about it in the + [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/). + """ + return super().add_task(func, *args, **kwargs) diff --git a/venv/Lib/site-packages/fastapi/cli.py b/venv/Lib/site-packages/fastapi/cli.py new file mode 100644 index 00000000..8d3301e9 --- /dev/null +++ b/venv/Lib/site-packages/fastapi/cli.py @@ -0,0 +1,13 @@ +try: + from fastapi_cli.cli import main as cli_main + +except ImportError: # pragma: no cover + cli_main = None # type: ignore + + +def main() -> None: + if not cli_main: # type: ignore[truthy-function] + message = 'To use the fastapi command, please install "fastapi[standard]":\n\n\tpip install "fastapi[standard]"\n' + print(message) + raise RuntimeError(message) # noqa: B904 + cli_main() diff --git a/venv/Lib/site-packages/fastapi/concurrency.py b/venv/Lib/site-packages/fastapi/concurrency.py new file mode 100644 index 00000000..3202c707 --- /dev/null +++ b/venv/Lib/site-packages/fastapi/concurrency.py @@ -0,0 +1,39 @@ +from contextlib import asynccontextmanager as asynccontextmanager +from typing import AsyncGenerator, ContextManager, TypeVar + +import anyio.to_thread +from anyio import CapacityLimiter +from starlette.concurrency import iterate_in_threadpool as iterate_in_threadpool # noqa +from starlette.concurrency import run_in_threadpool as run_in_threadpool # noqa +from starlette.concurrency import ( # noqa + run_until_first_complete as run_until_first_complete, +) + +_T = TypeVar("_T") + + +@asynccontextmanager +async def contextmanager_in_threadpool( + cm: ContextManager[_T], +) -> AsyncGenerator[_T, None]: + # blocking __exit__ from running waiting on a free thread + # can create race conditions/deadlocks if the context manager itself + # has its own internal pool (e.g. a database connection pool) + # to avoid this we let __exit__ run without a capacity limit + # since we're creating a new limiter for each call, any non-zero limit + # works (1 is arbitrary) + exit_limiter = CapacityLimiter(1) + try: + yield await run_in_threadpool(cm.__enter__) + except Exception as e: + ok = bool( + await anyio.to_thread.run_sync( + cm.__exit__, type(e), e, e.__traceback__, limiter=exit_limiter + ) + ) + if not ok: + raise e + else: + await anyio.to_thread.run_sync( + cm.__exit__, None, None, None, limiter=exit_limiter + ) diff --git a/venv/Lib/site-packages/fastapi/datastructures.py b/venv/Lib/site-packages/fastapi/datastructures.py new file mode 100644 index 00000000..cf8406b0 --- /dev/null +++ b/venv/Lib/site-packages/fastapi/datastructures.py @@ -0,0 +1,204 @@ +from typing import ( + Any, + BinaryIO, + Callable, + Dict, + Iterable, + Optional, + Type, + TypeVar, + cast, +) + +from fastapi._compat import ( + PYDANTIC_V2, + CoreSchema, + GetJsonSchemaHandler, + JsonSchemaValue, + with_info_plain_validator_function, +) +from starlette.datastructures import URL as URL # noqa: F401 +from starlette.datastructures import Address as Address # noqa: F401 +from starlette.datastructures import FormData as FormData # noqa: F401 +from starlette.datastructures import Headers as Headers # noqa: F401 +from starlette.datastructures import QueryParams as QueryParams # noqa: F401 +from starlette.datastructures import State as State # noqa: F401 +from starlette.datastructures import UploadFile as StarletteUploadFile +from typing_extensions import Annotated, Doc + + +class UploadFile(StarletteUploadFile): + """ + A file uploaded in a request. + + Define it as a *path operation function* (or dependency) parameter. + + If you are using a regular `def` function, you can use the `upload_file.file` + attribute to access the raw standard Python file (blocking, not async), useful and + needed for non-async code. + + Read more about it in the + [FastAPI docs for Request Files](https://fastapi.tiangolo.com/tutorial/request-files/). + + ## Example + + ```python + from typing import Annotated + + from fastapi import FastAPI, File, UploadFile + + app = FastAPI() + + + @app.post("/files/") + async def create_file(file: Annotated[bytes, File()]): + return {"file_size": len(file)} + + + @app.post("/uploadfile/") + async def create_upload_file(file: UploadFile): + return {"filename": file.filename} + ``` + """ + + file: Annotated[ + BinaryIO, + Doc("The standard Python file object (non-async)."), + ] + filename: Annotated[Optional[str], Doc("The original file name.")] + size: Annotated[Optional[int], Doc("The size of the file in bytes.")] + headers: Annotated[Headers, Doc("The headers of the request.")] + content_type: Annotated[ + Optional[str], Doc("The content type of the request, from the headers.") + ] + + async def write( + self, + data: Annotated[ + bytes, + Doc( + """ + The bytes to write to the file. + """ + ), + ], + ) -> None: + """ + Write some bytes to the file. + + You normally wouldn't use this from a file you read in a request. + + To be awaitable, compatible with async, this is run in threadpool. + """ + return await super().write(data) + + async def read( + self, + size: Annotated[ + int, + Doc( + """ + The number of bytes to read from the file. + """ + ), + ] = -1, + ) -> bytes: + """ + Read some bytes from the file. + + To be awaitable, compatible with async, this is run in threadpool. + """ + return await super().read(size) + + async def seek( + self, + offset: Annotated[ + int, + Doc( + """ + The position in bytes to seek to in the file. + """ + ), + ], + ) -> None: + """ + Move to a position in the file. + + Any next read or write will be done from that position. + + To be awaitable, compatible with async, this is run in threadpool. + """ + return await super().seek(offset) + + async def close(self) -> None: + """ + Close the file. + + To be awaitable, compatible with async, this is run in threadpool. + """ + return await super().close() + + @classmethod + def __get_validators__(cls: Type["UploadFile"]) -> Iterable[Callable[..., Any]]: + yield cls.validate + + @classmethod + def validate(cls: Type["UploadFile"], v: Any) -> Any: + if not isinstance(v, StarletteUploadFile): + raise ValueError(f"Expected UploadFile, received: {type(v)}") + return v + + @classmethod + def _validate(cls, __input_value: Any, _: Any) -> "UploadFile": + if not isinstance(__input_value, StarletteUploadFile): + raise ValueError(f"Expected UploadFile, received: {type(__input_value)}") + return cast(UploadFile, __input_value) + + if not PYDANTIC_V2: + + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + field_schema.update({"type": "string", "format": "binary"}) + + @classmethod + def __get_pydantic_json_schema__( + cls, core_schema: CoreSchema, handler: GetJsonSchemaHandler + ) -> JsonSchemaValue: + return {"type": "string", "format": "binary"} + + @classmethod + def __get_pydantic_core_schema__( + cls, source: Type[Any], handler: Callable[[Any], CoreSchema] + ) -> CoreSchema: + return with_info_plain_validator_function(cls._validate) + + +class DefaultPlaceholder: + """ + You shouldn't use this class directly. + + It's used internally to recognize when a default value has been overwritten, even + if the overridden default value was truthy. + """ + + def __init__(self, value: Any): + self.value = value + + def __bool__(self) -> bool: + return bool(self.value) + + def __eq__(self, o: object) -> bool: + return isinstance(o, DefaultPlaceholder) and o.value == self.value + + +DefaultType = TypeVar("DefaultType") + + +def Default(value: DefaultType) -> DefaultType: + """ + You shouldn't use this function directly. + + It's used internally to recognize when a default value has been overwritten, even + if the overridden default value was truthy. + """ + return DefaultPlaceholder(value) # type: ignore diff --git a/venv/Lib/site-packages/fastapi/dependencies/__init__.py b/venv/Lib/site-packages/fastapi/dependencies/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/venv/Lib/site-packages/fastapi/dependencies/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/fastapi/dependencies/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..1d200cfe Binary files /dev/null and b/venv/Lib/site-packages/fastapi/dependencies/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/dependencies/__pycache__/models.cpython-312.pyc b/venv/Lib/site-packages/fastapi/dependencies/__pycache__/models.cpython-312.pyc new file mode 100644 index 00000000..2c4ec2a9 Binary files /dev/null and b/venv/Lib/site-packages/fastapi/dependencies/__pycache__/models.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/dependencies/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/fastapi/dependencies/__pycache__/utils.cpython-312.pyc new file mode 100644 index 00000000..285fdda6 Binary files /dev/null and b/venv/Lib/site-packages/fastapi/dependencies/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/dependencies/models.py b/venv/Lib/site-packages/fastapi/dependencies/models.py new file mode 100644 index 00000000..418c1172 --- /dev/null +++ b/venv/Lib/site-packages/fastapi/dependencies/models.py @@ -0,0 +1,37 @@ +from dataclasses import dataclass, field +from typing import Any, Callable, List, Optional, Sequence, Tuple + +from fastapi._compat import ModelField +from fastapi.security.base import SecurityBase + + +@dataclass +class SecurityRequirement: + security_scheme: SecurityBase + scopes: Optional[Sequence[str]] = None + + +@dataclass +class Dependant: + path_params: List[ModelField] = field(default_factory=list) + query_params: List[ModelField] = field(default_factory=list) + header_params: List[ModelField] = field(default_factory=list) + cookie_params: List[ModelField] = field(default_factory=list) + body_params: List[ModelField] = field(default_factory=list) + dependencies: List["Dependant"] = field(default_factory=list) + security_requirements: List[SecurityRequirement] = field(default_factory=list) + name: Optional[str] = None + call: Optional[Callable[..., Any]] = None + request_param_name: Optional[str] = None + websocket_param_name: Optional[str] = None + http_connection_param_name: Optional[str] = None + response_param_name: Optional[str] = None + background_tasks_param_name: Optional[str] = None + security_scopes_param_name: Optional[str] = None + security_scopes: Optional[List[str]] = None + use_cache: bool = True + path: Optional[str] = None + cache_key: Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] = field(init=False) + + def __post_init__(self) -> None: + self.cache_key = (self.call, tuple(sorted(set(self.security_scopes or [])))) diff --git a/venv/Lib/site-packages/fastapi/dependencies/utils.py b/venv/Lib/site-packages/fastapi/dependencies/utils.py new file mode 100644 index 00000000..081b63a8 --- /dev/null +++ b/venv/Lib/site-packages/fastapi/dependencies/utils.py @@ -0,0 +1,1001 @@ +import inspect +from contextlib import AsyncExitStack, contextmanager +from copy import copy, deepcopy +from dataclasses import dataclass +from typing import ( + Any, + Callable, + Coroutine, + Dict, + ForwardRef, + List, + Mapping, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import anyio +from fastapi import params +from fastapi._compat import ( + PYDANTIC_V2, + ErrorWrapper, + ModelField, + RequiredParam, + Undefined, + _regenerate_error_with_loc, + copy_field_info, + create_body_model, + evaluate_forwardref, + field_annotation_is_scalar, + get_annotation_from_field_info, + get_cached_model_fields, + get_missing_field_error, + is_bytes_field, + is_bytes_sequence_field, + is_scalar_field, + is_scalar_sequence_field, + is_sequence_field, + is_uploadfile_or_nonable_uploadfile_annotation, + is_uploadfile_sequence_annotation, + lenient_issubclass, + sequence_types, + serialize_sequence_value, + value_is_sequence, +) +from fastapi.background import BackgroundTasks +from fastapi.concurrency import ( + asynccontextmanager, + contextmanager_in_threadpool, +) +from fastapi.dependencies.models import Dependant, SecurityRequirement +from fastapi.logger import logger +from fastapi.security.base import SecurityBase +from fastapi.security.oauth2 import OAuth2, SecurityScopes +from fastapi.security.open_id_connect_url import OpenIdConnect +from fastapi.utils import create_model_field, get_path_param_names +from pydantic import BaseModel +from pydantic.fields import FieldInfo +from starlette.background import BackgroundTasks as StarletteBackgroundTasks +from starlette.concurrency import run_in_threadpool +from starlette.datastructures import ( + FormData, + Headers, + ImmutableMultiDict, + QueryParams, + UploadFile, +) +from starlette.requests import HTTPConnection, Request +from starlette.responses import Response +from starlette.websockets import WebSocket +from typing_extensions import Annotated, get_args, get_origin + +multipart_not_installed_error = ( + 'Form data requires "python-multipart" to be installed. \n' + 'You can install "python-multipart" with: \n\n' + "pip install python-multipart\n" +) +multipart_incorrect_install_error = ( + 'Form data requires "python-multipart" to be installed. ' + 'It seems you installed "multipart" instead. \n' + 'You can remove "multipart" with: \n\n' + "pip uninstall multipart\n\n" + 'And then install "python-multipart" with: \n\n' + "pip install python-multipart\n" +) + + +def ensure_multipart_is_installed() -> None: + try: + from python_multipart import __version__ + + # Import an attribute that can be mocked/deleted in testing + assert __version__ > "0.0.12" + except (ImportError, AssertionError): + try: + # __version__ is available in both multiparts, and can be mocked + from multipart import __version__ # type: ignore[no-redef,import-untyped] + + assert __version__ + try: + # parse_options_header is only available in the right multipart + from multipart.multipart import ( # type: ignore[import-untyped] + parse_options_header, + ) + + assert parse_options_header + except ImportError: + logger.error(multipart_incorrect_install_error) + raise RuntimeError(multipart_incorrect_install_error) from None + except ImportError: + logger.error(multipart_not_installed_error) + raise RuntimeError(multipart_not_installed_error) from None + + +def get_param_sub_dependant( + *, + param_name: str, + depends: params.Depends, + path: str, + security_scopes: Optional[List[str]] = None, +) -> Dependant: + assert depends.dependency + return get_sub_dependant( + depends=depends, + dependency=depends.dependency, + path=path, + name=param_name, + security_scopes=security_scopes, + ) + + +def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: + assert callable(depends.dependency), ( + "A parameter-less dependency must have a callable dependency" + ) + return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) + + +def get_sub_dependant( + *, + depends: params.Depends, + dependency: Callable[..., Any], + path: str, + name: Optional[str] = None, + security_scopes: Optional[List[str]] = None, +) -> Dependant: + security_requirement = None + security_scopes = security_scopes or [] + if isinstance(depends, params.Security): + dependency_scopes = depends.scopes + security_scopes.extend(dependency_scopes) + if isinstance(dependency, SecurityBase): + use_scopes: List[str] = [] + if isinstance(dependency, (OAuth2, OpenIdConnect)): + use_scopes = security_scopes + security_requirement = SecurityRequirement( + security_scheme=dependency, scopes=use_scopes + ) + sub_dependant = get_dependant( + path=path, + call=dependency, + name=name, + security_scopes=security_scopes, + use_cache=depends.use_cache, + ) + if security_requirement: + sub_dependant.security_requirements.append(security_requirement) + return sub_dependant + + +CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] + + +def get_flat_dependant( + dependant: Dependant, + *, + skip_repeats: bool = False, + visited: Optional[List[CacheKey]] = None, +) -> Dependant: + if visited is None: + visited = [] + visited.append(dependant.cache_key) + + flat_dependant = Dependant( + path_params=dependant.path_params.copy(), + query_params=dependant.query_params.copy(), + header_params=dependant.header_params.copy(), + cookie_params=dependant.cookie_params.copy(), + body_params=dependant.body_params.copy(), + security_requirements=dependant.security_requirements.copy(), + use_cache=dependant.use_cache, + path=dependant.path, + ) + for sub_dependant in dependant.dependencies: + if skip_repeats and sub_dependant.cache_key in visited: + continue + flat_sub = get_flat_dependant( + sub_dependant, skip_repeats=skip_repeats, visited=visited + ) + flat_dependant.path_params.extend(flat_sub.path_params) + flat_dependant.query_params.extend(flat_sub.query_params) + flat_dependant.header_params.extend(flat_sub.header_params) + flat_dependant.cookie_params.extend(flat_sub.cookie_params) + flat_dependant.body_params.extend(flat_sub.body_params) + flat_dependant.security_requirements.extend(flat_sub.security_requirements) + return flat_dependant + + +def _get_flat_fields_from_params(fields: List[ModelField]) -> List[ModelField]: + if not fields: + return fields + first_field = fields[0] + if len(fields) == 1 and lenient_issubclass(first_field.type_, BaseModel): + fields_to_extract = get_cached_model_fields(first_field.type_) + return fields_to_extract + return fields + + +def get_flat_params(dependant: Dependant) -> List[ModelField]: + flat_dependant = get_flat_dependant(dependant, skip_repeats=True) + path_params = _get_flat_fields_from_params(flat_dependant.path_params) + query_params = _get_flat_fields_from_params(flat_dependant.query_params) + header_params = _get_flat_fields_from_params(flat_dependant.header_params) + cookie_params = _get_flat_fields_from_params(flat_dependant.cookie_params) + return path_params + query_params + header_params + cookie_params + + +def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: + signature = inspect.signature(call) + globalns = getattr(call, "__globals__", {}) + typed_params = [ + inspect.Parameter( + name=param.name, + kind=param.kind, + default=param.default, + annotation=get_typed_annotation(param.annotation, globalns), + ) + for param in signature.parameters.values() + ] + typed_signature = inspect.Signature(typed_params) + return typed_signature + + +def get_typed_annotation(annotation: Any, globalns: Dict[str, Any]) -> Any: + if isinstance(annotation, str): + annotation = ForwardRef(annotation) + annotation = evaluate_forwardref(annotation, globalns, globalns) + return annotation + + +def get_typed_return_annotation(call: Callable[..., Any]) -> Any: + signature = inspect.signature(call) + annotation = signature.return_annotation + + if annotation is inspect.Signature.empty: + return None + + globalns = getattr(call, "__globals__", {}) + return get_typed_annotation(annotation, globalns) + + +def get_dependant( + *, + path: str, + call: Callable[..., Any], + name: Optional[str] = None, + security_scopes: Optional[List[str]] = None, + use_cache: bool = True, +) -> Dependant: + path_param_names = get_path_param_names(path) + endpoint_signature = get_typed_signature(call) + signature_params = endpoint_signature.parameters + dependant = Dependant( + call=call, + name=name, + path=path, + security_scopes=security_scopes, + use_cache=use_cache, + ) + for param_name, param in signature_params.items(): + is_path_param = param_name in path_param_names + param_details = analyze_param( + param_name=param_name, + annotation=param.annotation, + value=param.default, + is_path_param=is_path_param, + ) + if param_details.depends is not None: + sub_dependant = get_param_sub_dependant( + param_name=param_name, + depends=param_details.depends, + path=path, + security_scopes=security_scopes, + ) + dependant.dependencies.append(sub_dependant) + continue + if add_non_field_param_to_dependency( + param_name=param_name, + type_annotation=param_details.type_annotation, + dependant=dependant, + ): + assert param_details.field is None, ( + f"Cannot specify multiple FastAPI annotations for {param_name!r}" + ) + continue + assert param_details.field is not None + if isinstance(param_details.field.field_info, params.Body): + dependant.body_params.append(param_details.field) + else: + add_param_to_fields(field=param_details.field, dependant=dependant) + return dependant + + +def add_non_field_param_to_dependency( + *, param_name: str, type_annotation: Any, dependant: Dependant +) -> Optional[bool]: + if lenient_issubclass(type_annotation, Request): + dependant.request_param_name = param_name + return True + elif lenient_issubclass(type_annotation, WebSocket): + dependant.websocket_param_name = param_name + return True + elif lenient_issubclass(type_annotation, HTTPConnection): + dependant.http_connection_param_name = param_name + return True + elif lenient_issubclass(type_annotation, Response): + dependant.response_param_name = param_name + return True + elif lenient_issubclass(type_annotation, StarletteBackgroundTasks): + dependant.background_tasks_param_name = param_name + return True + elif lenient_issubclass(type_annotation, SecurityScopes): + dependant.security_scopes_param_name = param_name + return True + return None + + +@dataclass +class ParamDetails: + type_annotation: Any + depends: Optional[params.Depends] + field: Optional[ModelField] + + +def analyze_param( + *, + param_name: str, + annotation: Any, + value: Any, + is_path_param: bool, +) -> ParamDetails: + field_info = None + depends = None + type_annotation: Any = Any + use_annotation: Any = Any + if annotation is not inspect.Signature.empty: + use_annotation = annotation + type_annotation = annotation + # Extract Annotated info + if get_origin(use_annotation) is Annotated: + annotated_args = get_args(annotation) + type_annotation = annotated_args[0] + fastapi_annotations = [ + arg + for arg in annotated_args[1:] + if isinstance(arg, (FieldInfo, params.Depends)) + ] + fastapi_specific_annotations = [ + arg + for arg in fastapi_annotations + if isinstance(arg, (params.Param, params.Body, params.Depends)) + ] + if fastapi_specific_annotations: + fastapi_annotation: Union[FieldInfo, params.Depends, None] = ( + fastapi_specific_annotations[-1] + ) + else: + fastapi_annotation = None + # Set default for Annotated FieldInfo + if isinstance(fastapi_annotation, FieldInfo): + # Copy `field_info` because we mutate `field_info.default` below. + field_info = copy_field_info( + field_info=fastapi_annotation, annotation=use_annotation + ) + assert ( + field_info.default is Undefined or field_info.default is RequiredParam + ), ( + f"`{field_info.__class__.__name__}` default value cannot be set in" + f" `Annotated` for {param_name!r}. Set the default value with `=` instead." + ) + if value is not inspect.Signature.empty: + assert not is_path_param, "Path parameters cannot have default values" + field_info.default = value + else: + field_info.default = RequiredParam + # Get Annotated Depends + elif isinstance(fastapi_annotation, params.Depends): + depends = fastapi_annotation + # Get Depends from default value + if isinstance(value, params.Depends): + assert depends is None, ( + "Cannot specify `Depends` in `Annotated` and default value" + f" together for {param_name!r}" + ) + assert field_info is None, ( + "Cannot specify a FastAPI annotation in `Annotated` and `Depends` as a" + f" default value together for {param_name!r}" + ) + depends = value + # Get FieldInfo from default value + elif isinstance(value, FieldInfo): + assert field_info is None, ( + "Cannot specify FastAPI annotations in `Annotated` and default value" + f" together for {param_name!r}" + ) + field_info = value + if PYDANTIC_V2: + field_info.annotation = type_annotation + + # Get Depends from type annotation + if depends is not None and depends.dependency is None: + # Copy `depends` before mutating it + depends = copy(depends) + depends.dependency = type_annotation + + # Handle non-param type annotations like Request + if lenient_issubclass( + type_annotation, + ( + Request, + WebSocket, + HTTPConnection, + Response, + StarletteBackgroundTasks, + SecurityScopes, + ), + ): + assert depends is None, f"Cannot specify `Depends` for type {type_annotation!r}" + assert field_info is None, ( + f"Cannot specify FastAPI annotation for type {type_annotation!r}" + ) + # Handle default assignations, neither field_info nor depends was not found in Annotated nor default value + elif field_info is None and depends is None: + default_value = value if value is not inspect.Signature.empty else RequiredParam + if is_path_param: + # We might check here that `default_value is RequiredParam`, but the fact is that the same + # parameter might sometimes be a path parameter and sometimes not. See + # `tests/test_infer_param_optionality.py` for an example. + field_info = params.Path(annotation=use_annotation) + elif is_uploadfile_or_nonable_uploadfile_annotation( + type_annotation + ) or is_uploadfile_sequence_annotation(type_annotation): + field_info = params.File(annotation=use_annotation, default=default_value) + elif not field_annotation_is_scalar(annotation=type_annotation): + field_info = params.Body(annotation=use_annotation, default=default_value) + else: + field_info = params.Query(annotation=use_annotation, default=default_value) + + field = None + # It's a field_info, not a dependency + if field_info is not None: + # Handle field_info.in_ + if is_path_param: + assert isinstance(field_info, params.Path), ( + f"Cannot use `{field_info.__class__.__name__}` for path param" + f" {param_name!r}" + ) + elif ( + isinstance(field_info, params.Param) + and getattr(field_info, "in_", None) is None + ): + field_info.in_ = params.ParamTypes.query + use_annotation_from_field_info = get_annotation_from_field_info( + use_annotation, + field_info, + param_name, + ) + if isinstance(field_info, params.Form): + ensure_multipart_is_installed() + if not field_info.alias and getattr(field_info, "convert_underscores", None): + alias = param_name.replace("_", "-") + else: + alias = field_info.alias or param_name + field_info.alias = alias + field = create_model_field( + name=param_name, + type_=use_annotation_from_field_info, + default=field_info.default, + alias=alias, + required=field_info.default in (RequiredParam, Undefined), + field_info=field_info, + ) + if is_path_param: + assert is_scalar_field(field=field), ( + "Path params must be of one of the supported types" + ) + elif isinstance(field_info, params.Query): + assert ( + is_scalar_field(field) + or is_scalar_sequence_field(field) + or ( + lenient_issubclass(field.type_, BaseModel) + # For Pydantic v1 + and getattr(field, "shape", 1) == 1 + ) + ) + + return ParamDetails(type_annotation=type_annotation, depends=depends, field=field) + + +def add_param_to_fields(*, field: ModelField, dependant: Dependant) -> None: + field_info = field.field_info + field_info_in = getattr(field_info, "in_", None) + if field_info_in == params.ParamTypes.path: + dependant.path_params.append(field) + elif field_info_in == params.ParamTypes.query: + dependant.query_params.append(field) + elif field_info_in == params.ParamTypes.header: + dependant.header_params.append(field) + else: + assert field_info_in == params.ParamTypes.cookie, ( + f"non-body parameters must be in path, query, header or cookie: {field.name}" + ) + dependant.cookie_params.append(field) + + +def is_coroutine_callable(call: Callable[..., Any]) -> bool: + if inspect.isroutine(call): + return inspect.iscoroutinefunction(call) + if inspect.isclass(call): + return False + dunder_call = getattr(call, "__call__", None) # noqa: B004 + return inspect.iscoroutinefunction(dunder_call) + + +def is_async_gen_callable(call: Callable[..., Any]) -> bool: + if inspect.isasyncgenfunction(call): + return True + dunder_call = getattr(call, "__call__", None) # noqa: B004 + return inspect.isasyncgenfunction(dunder_call) + + +def is_gen_callable(call: Callable[..., Any]) -> bool: + if inspect.isgeneratorfunction(call): + return True + dunder_call = getattr(call, "__call__", None) # noqa: B004 + return inspect.isgeneratorfunction(dunder_call) + + +async def solve_generator( + *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] +) -> Any: + if is_gen_callable(call): + cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) + elif is_async_gen_callable(call): + cm = asynccontextmanager(call)(**sub_values) + return await stack.enter_async_context(cm) + + +@dataclass +class SolvedDependency: + values: Dict[str, Any] + errors: List[Any] + background_tasks: Optional[StarletteBackgroundTasks] + response: Response + dependency_cache: Dict[Tuple[Callable[..., Any], Tuple[str]], Any] + + +async def solve_dependencies( + *, + request: Union[Request, WebSocket], + dependant: Dependant, + body: Optional[Union[Dict[str, Any], FormData]] = None, + background_tasks: Optional[StarletteBackgroundTasks] = None, + response: Optional[Response] = None, + dependency_overrides_provider: Optional[Any] = None, + dependency_cache: Optional[Dict[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, + async_exit_stack: AsyncExitStack, + embed_body_fields: bool, +) -> SolvedDependency: + values: Dict[str, Any] = {} + errors: List[Any] = [] + if response is None: + response = Response() + del response.headers["content-length"] + response.status_code = None # type: ignore + dependency_cache = dependency_cache or {} + sub_dependant: Dependant + for sub_dependant in dependant.dependencies: + sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) + sub_dependant.cache_key = cast( + Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key + ) + call = sub_dependant.call + use_sub_dependant = sub_dependant + if ( + dependency_overrides_provider + and dependency_overrides_provider.dependency_overrides + ): + original_call = sub_dependant.call + call = getattr( + dependency_overrides_provider, "dependency_overrides", {} + ).get(original_call, original_call) + use_path: str = sub_dependant.path # type: ignore + use_sub_dependant = get_dependant( + path=use_path, + call=call, + name=sub_dependant.name, + security_scopes=sub_dependant.security_scopes, + ) + + solved_result = await solve_dependencies( + request=request, + dependant=use_sub_dependant, + body=body, + background_tasks=background_tasks, + response=response, + dependency_overrides_provider=dependency_overrides_provider, + dependency_cache=dependency_cache, + async_exit_stack=async_exit_stack, + embed_body_fields=embed_body_fields, + ) + background_tasks = solved_result.background_tasks + dependency_cache.update(solved_result.dependency_cache) + if solved_result.errors: + errors.extend(solved_result.errors) + continue + if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache: + solved = dependency_cache[sub_dependant.cache_key] + elif is_gen_callable(call) or is_async_gen_callable(call): + solved = await solve_generator( + call=call, stack=async_exit_stack, sub_values=solved_result.values + ) + elif is_coroutine_callable(call): + solved = await call(**solved_result.values) + else: + solved = await run_in_threadpool(call, **solved_result.values) + if sub_dependant.name is not None: + values[sub_dependant.name] = solved + if sub_dependant.cache_key not in dependency_cache: + dependency_cache[sub_dependant.cache_key] = solved + path_values, path_errors = request_params_to_args( + dependant.path_params, request.path_params + ) + query_values, query_errors = request_params_to_args( + dependant.query_params, request.query_params + ) + header_values, header_errors = request_params_to_args( + dependant.header_params, request.headers + ) + cookie_values, cookie_errors = request_params_to_args( + dependant.cookie_params, request.cookies + ) + values.update(path_values) + values.update(query_values) + values.update(header_values) + values.update(cookie_values) + errors += path_errors + query_errors + header_errors + cookie_errors + if dependant.body_params: + ( + body_values, + body_errors, + ) = await request_body_to_args( # body_params checked above + body_fields=dependant.body_params, + received_body=body, + embed_body_fields=embed_body_fields, + ) + values.update(body_values) + errors.extend(body_errors) + if dependant.http_connection_param_name: + values[dependant.http_connection_param_name] = request + if dependant.request_param_name and isinstance(request, Request): + values[dependant.request_param_name] = request + elif dependant.websocket_param_name and isinstance(request, WebSocket): + values[dependant.websocket_param_name] = request + if dependant.background_tasks_param_name: + if background_tasks is None: + background_tasks = BackgroundTasks() + values[dependant.background_tasks_param_name] = background_tasks + if dependant.response_param_name: + values[dependant.response_param_name] = response + if dependant.security_scopes_param_name: + values[dependant.security_scopes_param_name] = SecurityScopes( + scopes=dependant.security_scopes + ) + return SolvedDependency( + values=values, + errors=errors, + background_tasks=background_tasks, + response=response, + dependency_cache=dependency_cache, + ) + + +def _validate_value_with_model_field( + *, field: ModelField, value: Any, values: Dict[str, Any], loc: Tuple[str, ...] +) -> Tuple[Any, List[Any]]: + if value is None: + if field.required: + return None, [get_missing_field_error(loc=loc)] + else: + return deepcopy(field.default), [] + v_, errors_ = field.validate(value, values, loc=loc) + if isinstance(errors_, ErrorWrapper): + return None, [errors_] + elif isinstance(errors_, list): + new_errors = _regenerate_error_with_loc(errors=errors_, loc_prefix=()) + return None, new_errors + else: + return v_, [] + + +def _get_multidict_value( + field: ModelField, values: Mapping[str, Any], alias: Union[str, None] = None +) -> Any: + alias = alias or field.alias + if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): + value = values.getlist(alias) + else: + value = values.get(alias, None) + if ( + value is None + or ( + isinstance(field.field_info, params.Form) + and isinstance(value, str) # For type checks + and value == "" + ) + or (is_sequence_field(field) and len(value) == 0) + ): + if field.required: + return + else: + return deepcopy(field.default) + return value + + +def request_params_to_args( + fields: Sequence[ModelField], + received_params: Union[Mapping[str, Any], QueryParams, Headers], +) -> Tuple[Dict[str, Any], List[Any]]: + values: Dict[str, Any] = {} + errors: List[Dict[str, Any]] = [] + + if not fields: + return values, errors + + first_field = fields[0] + fields_to_extract = fields + single_not_embedded_field = False + default_convert_underscores = True + if len(fields) == 1 and lenient_issubclass(first_field.type_, BaseModel): + fields_to_extract = get_cached_model_fields(first_field.type_) + single_not_embedded_field = True + # If headers are in a Pydantic model, the way to disable convert_underscores + # would be with Header(convert_underscores=False) at the Pydantic model level + default_convert_underscores = getattr( + first_field.field_info, "convert_underscores", True + ) + + params_to_process: Dict[str, Any] = {} + + processed_keys = set() + + for field in fields_to_extract: + alias = None + if isinstance(received_params, Headers): + # Handle fields extracted from a Pydantic Model for a header, each field + # doesn't have a FieldInfo of type Header with the default convert_underscores=True + convert_underscores = getattr( + field.field_info, "convert_underscores", default_convert_underscores + ) + if convert_underscores: + alias = ( + field.alias + if field.alias != field.name + else field.name.replace("_", "-") + ) + value = _get_multidict_value(field, received_params, alias=alias) + if value is not None: + params_to_process[field.name] = value + processed_keys.add(alias or field.alias) + processed_keys.add(field.name) + + for key, value in received_params.items(): + if key not in processed_keys: + params_to_process[key] = value + + if single_not_embedded_field: + field_info = first_field.field_info + assert isinstance(field_info, params.Param), ( + "Params must be subclasses of Param" + ) + loc: Tuple[str, ...] = (field_info.in_.value,) + v_, errors_ = _validate_value_with_model_field( + field=first_field, value=params_to_process, values=values, loc=loc + ) + return {first_field.name: v_}, errors_ + + for field in fields: + value = _get_multidict_value(field, received_params) + field_info = field.field_info + assert isinstance(field_info, params.Param), ( + "Params must be subclasses of Param" + ) + loc = (field_info.in_.value, field.alias) + v_, errors_ = _validate_value_with_model_field( + field=field, value=value, values=values, loc=loc + ) + if errors_: + errors.extend(errors_) + else: + values[field.name] = v_ + return values, errors + + +def is_union_of_base_models(field_type: Any) -> bool: + """Check if field type is a Union where all members are BaseModel subclasses.""" + from fastapi.types import UnionType + + origin = get_origin(field_type) + + # Check if it's a Union type (covers both typing.Union and types.UnionType in Python 3.10+) + if origin is not Union and origin is not UnionType: + return False + + union_args = get_args(field_type) + + for arg in union_args: + if not lenient_issubclass(arg, BaseModel): + return False + + return True + + +def _should_embed_body_fields(fields: List[ModelField]) -> bool: + if not fields: + return False + # More than one dependency could have the same field, it would show up as multiple + # fields but it's the same one, so count them by name + body_param_names_set = {field.name for field in fields} + # A top level field has to be a single field, not multiple + if len(body_param_names_set) > 1: + return True + first_field = fields[0] + # If it explicitly specifies it is embedded, it has to be embedded + if getattr(first_field.field_info, "embed", None): + return True + # If it's a Form (or File) field, it has to be a BaseModel (or a union of BaseModels) to be top level + # otherwise it has to be embedded, so that the key value pair can be extracted + if ( + isinstance(first_field.field_info, params.Form) + and not lenient_issubclass(first_field.type_, BaseModel) + and not is_union_of_base_models(first_field.type_) + ): + return True + return False + + +async def _extract_form_body( + body_fields: List[ModelField], + received_body: FormData, +) -> Dict[str, Any]: + values = {} + first_field = body_fields[0] + first_field_info = first_field.field_info + + for field in body_fields: + value = _get_multidict_value(field, received_body) + if ( + isinstance(first_field_info, params.File) + and is_bytes_field(field) + and isinstance(value, UploadFile) + ): + value = await value.read() + elif ( + is_bytes_sequence_field(field) + and isinstance(first_field_info, params.File) + and value_is_sequence(value) + ): + # For types + assert isinstance(value, sequence_types) # type: ignore[arg-type] + results: List[Union[bytes, str]] = [] + + async def process_fn( + fn: Callable[[], Coroutine[Any, Any, Any]], + ) -> None: + result = await fn() + results.append(result) # noqa: B023 + + async with anyio.create_task_group() as tg: + for sub_value in value: + tg.start_soon(process_fn, sub_value.read) + value = serialize_sequence_value(field=field, value=results) + if value is not None: + values[field.alias] = value + for key, value in received_body.items(): + if key not in values: + values[key] = value + return values + + +async def request_body_to_args( + body_fields: List[ModelField], + received_body: Optional[Union[Dict[str, Any], FormData]], + embed_body_fields: bool, +) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: + values: Dict[str, Any] = {} + errors: List[Dict[str, Any]] = [] + assert body_fields, "request_body_to_args() should be called with fields" + single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields + first_field = body_fields[0] + body_to_process = received_body + + fields_to_extract: List[ModelField] = body_fields + + if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): + fields_to_extract = get_cached_model_fields(first_field.type_) + + if isinstance(received_body, FormData): + body_to_process = await _extract_form_body(fields_to_extract, received_body) + + if single_not_embedded_field: + loc: Tuple[str, ...] = ("body",) + v_, errors_ = _validate_value_with_model_field( + field=first_field, value=body_to_process, values=values, loc=loc + ) + return {first_field.name: v_}, errors_ + for field in body_fields: + loc = ("body", field.alias) + value: Optional[Any] = None + if body_to_process is not None: + try: + value = body_to_process.get(field.alias) + # If the received body is a list, not a dict + except AttributeError: + errors.append(get_missing_field_error(loc)) + continue + v_, errors_ = _validate_value_with_model_field( + field=field, value=value, values=values, loc=loc + ) + if errors_: + errors.extend(errors_) + else: + values[field.name] = v_ + return values, errors + + +def get_body_field( + *, flat_dependant: Dependant, name: str, embed_body_fields: bool +) -> Optional[ModelField]: + """ + Get a ModelField representing the request body for a path operation, combining + all body parameters into a single field if necessary. + + Used to check if it's form data (with `isinstance(body_field, params.Form)`) + or JSON and to generate the JSON Schema for a request body. + + This is **not** used to validate/parse the request body, that's done with each + individual body parameter. + """ + if not flat_dependant.body_params: + return None + first_param = flat_dependant.body_params[0] + if not embed_body_fields: + return first_param + model_name = "Body_" + name + BodyModel = create_body_model( + fields=flat_dependant.body_params, model_name=model_name + ) + required = any(True for f in flat_dependant.body_params if f.required) + BodyFieldInfo_kwargs: Dict[str, Any] = { + "annotation": BodyModel, + "alias": "body", + } + if not required: + BodyFieldInfo_kwargs["default"] = None + if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): + BodyFieldInfo: Type[params.Body] = params.File + elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): + BodyFieldInfo = params.Form + else: + BodyFieldInfo = params.Body + + body_param_media_types = [ + f.field_info.media_type + for f in flat_dependant.body_params + if isinstance(f.field_info, params.Body) + ] + if len(set(body_param_media_types)) == 1: + BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] + final_field = create_model_field( + name="body", + type_=BodyModel, + required=required, + alias="body", + field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), + ) + return final_field diff --git a/venv/Lib/site-packages/fastapi/encoders.py b/venv/Lib/site-packages/fastapi/encoders.py new file mode 100644 index 00000000..451ea076 --- /dev/null +++ b/venv/Lib/site-packages/fastapi/encoders.py @@ -0,0 +1,343 @@ +import dataclasses +import datetime +from collections import defaultdict, deque +from decimal import Decimal +from enum import Enum +from ipaddress import ( + IPv4Address, + IPv4Interface, + IPv4Network, + IPv6Address, + IPv6Interface, + IPv6Network, +) +from pathlib import Path, PurePath +from re import Pattern +from types import GeneratorType +from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union +from uuid import UUID + +from fastapi.types import IncEx +from pydantic import BaseModel +from pydantic.color import Color +from pydantic.networks import AnyUrl, NameEmail +from pydantic.types import SecretBytes, SecretStr +from typing_extensions import Annotated, Doc + +from ._compat import PYDANTIC_V2, UndefinedType, Url, _model_dump + + +# Taken from Pydantic v1 as is +def isoformat(o: Union[datetime.date, datetime.time]) -> str: + return o.isoformat() + + +# Taken from Pydantic v1 as is +# TODO: pv2 should this return strings instead? +def decimal_encoder(dec_value: Decimal) -> Union[int, float]: + """ + Encodes a Decimal as int of there's no exponent, otherwise float + + This is useful when we use ConstrainedDecimal to represent Numeric(x,0) + where a integer (but not int typed) is used. Encoding this as a float + results in failed round-tripping between encode and parse. + Our Id type is a prime example of this. + + >>> decimal_encoder(Decimal("1.0")) + 1.0 + + >>> decimal_encoder(Decimal("1")) + 1 + """ + if dec_value.as_tuple().exponent >= 0: # type: ignore[operator] + return int(dec_value) + else: + return float(dec_value) + + +ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = { + bytes: lambda o: o.decode(), + Color: str, + datetime.date: isoformat, + datetime.datetime: isoformat, + datetime.time: isoformat, + datetime.timedelta: lambda td: td.total_seconds(), + Decimal: decimal_encoder, + Enum: lambda o: o.value, + frozenset: list, + deque: list, + GeneratorType: list, + IPv4Address: str, + IPv4Interface: str, + IPv4Network: str, + IPv6Address: str, + IPv6Interface: str, + IPv6Network: str, + NameEmail: str, + Path: str, + Pattern: lambda o: o.pattern, + SecretBytes: str, + SecretStr: str, + set: list, + UUID: str, + Url: str, + AnyUrl: str, +} + + +def generate_encoders_by_class_tuples( + type_encoder_map: Dict[Any, Callable[[Any], Any]], +) -> Dict[Callable[[Any], Any], Tuple[Any, ...]]: + encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict( + tuple + ) + for type_, encoder in type_encoder_map.items(): + encoders_by_class_tuples[encoder] += (type_,) + return encoders_by_class_tuples + + +encoders_by_class_tuples = generate_encoders_by_class_tuples(ENCODERS_BY_TYPE) + + +def jsonable_encoder( + obj: Annotated[ + Any, + Doc( + """ + The input object to convert to JSON. + """ + ), + ], + include: Annotated[ + Optional[IncEx], + Doc( + """ + Pydantic's `include` parameter, passed to Pydantic models to set the + fields to include. + """ + ), + ] = None, + exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Pydantic's `exclude` parameter, passed to Pydantic models to set the + fields to exclude. + """ + ), + ] = None, + by_alias: Annotated[ + bool, + Doc( + """ + Pydantic's `by_alias` parameter, passed to Pydantic models to define if + the output should use the alias names (when provided) or the Python + attribute names. In an API, if you set an alias, it's probably because you + want to use it in the result, so you probably want to leave this set to + `True`. + """ + ), + ] = True, + exclude_unset: Annotated[ + bool, + Doc( + """ + Pydantic's `exclude_unset` parameter, passed to Pydantic models to define + if it should exclude from the output the fields that were not explicitly + set (and that only had their default values). + """ + ), + ] = False, + exclude_defaults: Annotated[ + bool, + Doc( + """ + Pydantic's `exclude_defaults` parameter, passed to Pydantic models to define + if it should exclude from the output the fields that had the same default + value, even when they were explicitly set. + """ + ), + ] = False, + exclude_none: Annotated[ + bool, + Doc( + """ + Pydantic's `exclude_none` parameter, passed to Pydantic models to define + if it should exclude from the output any fields that have a `None` value. + """ + ), + ] = False, + custom_encoder: Annotated[ + Optional[Dict[Any, Callable[[Any], Any]]], + Doc( + """ + Pydantic's `custom_encoder` parameter, passed to Pydantic models to define + a custom encoder. + """ + ), + ] = None, + sqlalchemy_safe: Annotated[ + bool, + Doc( + """ + Exclude from the output any fields that start with the name `_sa`. + + This is mainly a hack for compatibility with SQLAlchemy objects, they + store internal SQLAlchemy-specific state in attributes named with `_sa`, + and those objects can't (and shouldn't be) serialized to JSON. + """ + ), + ] = True, +) -> Any: + """ + Convert any object to something that can be encoded in JSON. + + This is used internally by FastAPI to make sure anything you return can be + encoded as JSON before it is sent to the client. + + You can also use it yourself, for example to convert objects before saving them + in a database that supports only JSON. + + Read more about it in the + [FastAPI docs for JSON Compatible Encoder](https://fastapi.tiangolo.com/tutorial/encoder/). + """ + custom_encoder = custom_encoder or {} + if custom_encoder: + if type(obj) in custom_encoder: + return custom_encoder[type(obj)](obj) + else: + for encoder_type, encoder_instance in custom_encoder.items(): + if isinstance(obj, encoder_type): + return encoder_instance(obj) + if include is not None and not isinstance(include, (set, dict)): + include = set(include) + if exclude is not None and not isinstance(exclude, (set, dict)): + exclude = set(exclude) + if isinstance(obj, BaseModel): + # TODO: remove when deprecating Pydantic v1 + encoders: Dict[Any, Any] = {} + if not PYDANTIC_V2: + encoders = getattr(obj.__config__, "json_encoders", {}) # type: ignore[attr-defined] + if custom_encoder: + encoders.update(custom_encoder) + obj_dict = _model_dump( + obj, + mode="json", + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_none=exclude_none, + exclude_defaults=exclude_defaults, + ) + if "__root__" in obj_dict: + obj_dict = obj_dict["__root__"] + return jsonable_encoder( + obj_dict, + exclude_none=exclude_none, + exclude_defaults=exclude_defaults, + # TODO: remove when deprecating Pydantic v1 + custom_encoder=encoders, + sqlalchemy_safe=sqlalchemy_safe, + ) + if dataclasses.is_dataclass(obj): + obj_dict = dataclasses.asdict(obj) + return jsonable_encoder( + obj_dict, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + custom_encoder=custom_encoder, + sqlalchemy_safe=sqlalchemy_safe, + ) + if isinstance(obj, Enum): + return obj.value + if isinstance(obj, PurePath): + return str(obj) + if isinstance(obj, (str, int, float, type(None))): + return obj + if isinstance(obj, UndefinedType): + return None + if isinstance(obj, dict): + encoded_dict = {} + allowed_keys = set(obj.keys()) + if include is not None: + allowed_keys &= set(include) + if exclude is not None: + allowed_keys -= set(exclude) + for key, value in obj.items(): + if ( + ( + not sqlalchemy_safe + or (not isinstance(key, str)) + or (not key.startswith("_sa")) + ) + and (value is not None or not exclude_none) + and key in allowed_keys + ): + encoded_key = jsonable_encoder( + key, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_none=exclude_none, + custom_encoder=custom_encoder, + sqlalchemy_safe=sqlalchemy_safe, + ) + encoded_value = jsonable_encoder( + value, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_none=exclude_none, + custom_encoder=custom_encoder, + sqlalchemy_safe=sqlalchemy_safe, + ) + encoded_dict[encoded_key] = encoded_value + return encoded_dict + if isinstance(obj, (list, set, frozenset, GeneratorType, tuple, deque)): + encoded_list = [] + for item in obj: + encoded_list.append( + jsonable_encoder( + item, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + custom_encoder=custom_encoder, + sqlalchemy_safe=sqlalchemy_safe, + ) + ) + return encoded_list + + if type(obj) in ENCODERS_BY_TYPE: + return ENCODERS_BY_TYPE[type(obj)](obj) + for encoder, classes_tuple in encoders_by_class_tuples.items(): + if isinstance(obj, classes_tuple): + return encoder(obj) + + try: + data = dict(obj) + except Exception as e: + errors: List[Exception] = [] + errors.append(e) + try: + data = vars(obj) + except Exception as e: + errors.append(e) + raise ValueError(errors) from e + return jsonable_encoder( + data, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + custom_encoder=custom_encoder, + sqlalchemy_safe=sqlalchemy_safe, + ) diff --git a/venv/Lib/site-packages/fastapi/exception_handlers.py b/venv/Lib/site-packages/fastapi/exception_handlers.py new file mode 100644 index 00000000..6c2ba7fe --- /dev/null +++ b/venv/Lib/site-packages/fastapi/exception_handlers.py @@ -0,0 +1,34 @@ +from fastapi.encoders import jsonable_encoder +from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError +from fastapi.utils import is_body_allowed_for_status_code +from fastapi.websockets import WebSocket +from starlette.exceptions import HTTPException +from starlette.requests import Request +from starlette.responses import JSONResponse, Response +from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY, WS_1008_POLICY_VIOLATION + + +async def http_exception_handler(request: Request, exc: HTTPException) -> Response: + headers = getattr(exc, "headers", None) + if not is_body_allowed_for_status_code(exc.status_code): + return Response(status_code=exc.status_code, headers=headers) + return JSONResponse( + {"detail": exc.detail}, status_code=exc.status_code, headers=headers + ) + + +async def request_validation_exception_handler( + request: Request, exc: RequestValidationError +) -> JSONResponse: + return JSONResponse( + status_code=HTTP_422_UNPROCESSABLE_ENTITY, + content={"detail": jsonable_encoder(exc.errors())}, + ) + + +async def websocket_request_validation_exception_handler( + websocket: WebSocket, exc: WebSocketRequestValidationError +) -> None: + await websocket.close( + code=WS_1008_POLICY_VIOLATION, reason=jsonable_encoder(exc.errors()) + ) diff --git a/venv/Lib/site-packages/fastapi/exceptions.py b/venv/Lib/site-packages/fastapi/exceptions.py new file mode 100644 index 00000000..44d4ada8 --- /dev/null +++ b/venv/Lib/site-packages/fastapi/exceptions.py @@ -0,0 +1,176 @@ +from typing import Any, Dict, Optional, Sequence, Type, Union + +from pydantic import BaseModel, create_model +from starlette.exceptions import HTTPException as StarletteHTTPException +from starlette.exceptions import WebSocketException as StarletteWebSocketException +from typing_extensions import Annotated, Doc + + +class HTTPException(StarletteHTTPException): + """ + An HTTP exception you can raise in your own code to show errors to the client. + + This is for client errors, invalid authentication, invalid data, etc. Not for server + errors in your code. + + Read more about it in the + [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/). + + ## Example + + ```python + from fastapi import FastAPI, HTTPException + + app = FastAPI() + + items = {"foo": "The Foo Wrestlers"} + + + @app.get("/items/{item_id}") + async def read_item(item_id: str): + if item_id not in items: + raise HTTPException(status_code=404, detail="Item not found") + return {"item": items[item_id]} + ``` + """ + + def __init__( + self, + status_code: Annotated[ + int, + Doc( + """ + HTTP status code to send to the client. + """ + ), + ], + detail: Annotated[ + Any, + Doc( + """ + Any data to be sent to the client in the `detail` key of the JSON + response. + """ + ), + ] = None, + headers: Annotated[ + Optional[Dict[str, str]], + Doc( + """ + Any headers to send to the client in the response. + """ + ), + ] = None, + ) -> None: + super().__init__(status_code=status_code, detail=detail, headers=headers) + + +class WebSocketException(StarletteWebSocketException): + """ + A WebSocket exception you can raise in your own code to show errors to the client. + + This is for client errors, invalid authentication, invalid data, etc. Not for server + errors in your code. + + Read more about it in the + [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). + + ## Example + + ```python + from typing import Annotated + + from fastapi import ( + Cookie, + FastAPI, + WebSocket, + WebSocketException, + status, + ) + + app = FastAPI() + + @app.websocket("/items/{item_id}/ws") + async def websocket_endpoint( + *, + websocket: WebSocket, + session: Annotated[str | None, Cookie()] = None, + item_id: str, + ): + if session is None: + raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION) + await websocket.accept() + while True: + data = await websocket.receive_text() + await websocket.send_text(f"Session cookie is: {session}") + await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}") + ``` + """ + + def __init__( + self, + code: Annotated[ + int, + Doc( + """ + A closing code from the + [valid codes defined in the specification](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1). + """ + ), + ], + reason: Annotated[ + Union[str, None], + Doc( + """ + The reason to close the WebSocket connection. + + It is UTF-8-encoded data. The interpretation of the reason is up to the + application, it is not specified by the WebSocket specification. + + It could contain text that could be human-readable or interpretable + by the client code, etc. + """ + ), + ] = None, + ) -> None: + super().__init__(code=code, reason=reason) + + +RequestErrorModel: Type[BaseModel] = create_model("Request") +WebSocketErrorModel: Type[BaseModel] = create_model("WebSocket") + + +class FastAPIError(RuntimeError): + """ + A generic, FastAPI-specific error. + """ + + +class ValidationException(Exception): + def __init__(self, errors: Sequence[Any]) -> None: + self._errors = errors + + def errors(self) -> Sequence[Any]: + return self._errors + + +class RequestValidationError(ValidationException): + def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None: + super().__init__(errors) + self.body = body + + +class WebSocketRequestValidationError(ValidationException): + pass + + +class ResponseValidationError(ValidationException): + def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None: + super().__init__(errors) + self.body = body + + def __str__(self) -> str: + message = f"{len(self._errors)} validation errors:\n" + for err in self._errors: + message += f" {err}\n" + return message diff --git a/venv/Lib/site-packages/fastapi/logger.py b/venv/Lib/site-packages/fastapi/logger.py new file mode 100644 index 00000000..5b2c4ad5 --- /dev/null +++ b/venv/Lib/site-packages/fastapi/logger.py @@ -0,0 +1,3 @@ +import logging + +logger = logging.getLogger("fastapi") diff --git a/venv/Lib/site-packages/fastapi/middleware/__init__.py b/venv/Lib/site-packages/fastapi/middleware/__init__.py new file mode 100644 index 00000000..620296d5 --- /dev/null +++ b/venv/Lib/site-packages/fastapi/middleware/__init__.py @@ -0,0 +1 @@ +from starlette.middleware import Middleware as Middleware diff --git a/venv/Lib/site-packages/fastapi/middleware/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/fastapi/middleware/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..dc98e2f7 Binary files /dev/null and b/venv/Lib/site-packages/fastapi/middleware/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/middleware/__pycache__/cors.cpython-312.pyc b/venv/Lib/site-packages/fastapi/middleware/__pycache__/cors.cpython-312.pyc new file mode 100644 index 00000000..e6f0911e Binary files /dev/null and b/venv/Lib/site-packages/fastapi/middleware/__pycache__/cors.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/middleware/__pycache__/gzip.cpython-312.pyc b/venv/Lib/site-packages/fastapi/middleware/__pycache__/gzip.cpython-312.pyc new file mode 100644 index 00000000..7e97bc05 Binary files /dev/null and b/venv/Lib/site-packages/fastapi/middleware/__pycache__/gzip.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/middleware/__pycache__/httpsredirect.cpython-312.pyc b/venv/Lib/site-packages/fastapi/middleware/__pycache__/httpsredirect.cpython-312.pyc new file mode 100644 index 00000000..d87b370f Binary files /dev/null and b/venv/Lib/site-packages/fastapi/middleware/__pycache__/httpsredirect.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/middleware/__pycache__/trustedhost.cpython-312.pyc b/venv/Lib/site-packages/fastapi/middleware/__pycache__/trustedhost.cpython-312.pyc new file mode 100644 index 00000000..1a0d4890 Binary files /dev/null and b/venv/Lib/site-packages/fastapi/middleware/__pycache__/trustedhost.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/middleware/__pycache__/wsgi.cpython-312.pyc b/venv/Lib/site-packages/fastapi/middleware/__pycache__/wsgi.cpython-312.pyc new file mode 100644 index 00000000..a69526cf Binary files /dev/null and b/venv/Lib/site-packages/fastapi/middleware/__pycache__/wsgi.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/middleware/cors.py b/venv/Lib/site-packages/fastapi/middleware/cors.py new file mode 100644 index 00000000..8dfaad0d --- /dev/null +++ b/venv/Lib/site-packages/fastapi/middleware/cors.py @@ -0,0 +1 @@ +from starlette.middleware.cors import CORSMiddleware as CORSMiddleware # noqa diff --git a/venv/Lib/site-packages/fastapi/middleware/gzip.py b/venv/Lib/site-packages/fastapi/middleware/gzip.py new file mode 100644 index 00000000..bbeb2cc7 --- /dev/null +++ b/venv/Lib/site-packages/fastapi/middleware/gzip.py @@ -0,0 +1 @@ +from starlette.middleware.gzip import GZipMiddleware as GZipMiddleware # noqa diff --git a/venv/Lib/site-packages/fastapi/middleware/httpsredirect.py b/venv/Lib/site-packages/fastapi/middleware/httpsredirect.py new file mode 100644 index 00000000..b7a3d8e0 --- /dev/null +++ b/venv/Lib/site-packages/fastapi/middleware/httpsredirect.py @@ -0,0 +1,3 @@ +from starlette.middleware.httpsredirect import ( # noqa + HTTPSRedirectMiddleware as HTTPSRedirectMiddleware, +) diff --git a/venv/Lib/site-packages/fastapi/middleware/trustedhost.py b/venv/Lib/site-packages/fastapi/middleware/trustedhost.py new file mode 100644 index 00000000..08d7e035 --- /dev/null +++ b/venv/Lib/site-packages/fastapi/middleware/trustedhost.py @@ -0,0 +1,3 @@ +from starlette.middleware.trustedhost import ( # noqa + TrustedHostMiddleware as TrustedHostMiddleware, +) diff --git a/venv/Lib/site-packages/fastapi/middleware/wsgi.py b/venv/Lib/site-packages/fastapi/middleware/wsgi.py new file mode 100644 index 00000000..c4c6a797 --- /dev/null +++ b/venv/Lib/site-packages/fastapi/middleware/wsgi.py @@ -0,0 +1 @@ +from starlette.middleware.wsgi import WSGIMiddleware as WSGIMiddleware # noqa diff --git a/venv/Lib/site-packages/fastapi/openapi/__init__.py b/venv/Lib/site-packages/fastapi/openapi/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/venv/Lib/site-packages/fastapi/openapi/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/fastapi/openapi/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..4c2deaa5 Binary files /dev/null and b/venv/Lib/site-packages/fastapi/openapi/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/openapi/__pycache__/constants.cpython-312.pyc b/venv/Lib/site-packages/fastapi/openapi/__pycache__/constants.cpython-312.pyc new file mode 100644 index 00000000..17190f73 Binary files /dev/null and b/venv/Lib/site-packages/fastapi/openapi/__pycache__/constants.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/openapi/__pycache__/docs.cpython-312.pyc b/venv/Lib/site-packages/fastapi/openapi/__pycache__/docs.cpython-312.pyc new file mode 100644 index 00000000..f5694150 Binary files /dev/null and b/venv/Lib/site-packages/fastapi/openapi/__pycache__/docs.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/openapi/__pycache__/models.cpython-312.pyc b/venv/Lib/site-packages/fastapi/openapi/__pycache__/models.cpython-312.pyc new file mode 100644 index 00000000..e473898b Binary files /dev/null and b/venv/Lib/site-packages/fastapi/openapi/__pycache__/models.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/openapi/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/fastapi/openapi/__pycache__/utils.cpython-312.pyc new file mode 100644 index 00000000..cf99bb3a Binary files /dev/null and b/venv/Lib/site-packages/fastapi/openapi/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/openapi/constants.py b/venv/Lib/site-packages/fastapi/openapi/constants.py new file mode 100644 index 00000000..d724ee3c --- /dev/null +++ b/venv/Lib/site-packages/fastapi/openapi/constants.py @@ -0,0 +1,3 @@ +METHODS_WITH_BODY = {"GET", "HEAD", "POST", "PUT", "DELETE", "PATCH"} +REF_PREFIX = "#/components/schemas/" +REF_TEMPLATE = "#/components/schemas/{model}" diff --git a/venv/Lib/site-packages/fastapi/openapi/docs.py b/venv/Lib/site-packages/fastapi/openapi/docs.py new file mode 100644 index 00000000..f181b43c --- /dev/null +++ b/venv/Lib/site-packages/fastapi/openapi/docs.py @@ -0,0 +1,344 @@ +import json +from typing import Any, Dict, Optional + +from fastapi.encoders import jsonable_encoder +from starlette.responses import HTMLResponse +from typing_extensions import Annotated, Doc + +swagger_ui_default_parameters: Annotated[ + Dict[str, Any], + Doc( + """ + Default configurations for Swagger UI. + + You can use it as a template to add any other configurations needed. + """ + ), +] = { + "dom_id": "#swagger-ui", + "layout": "BaseLayout", + "deepLinking": True, + "showExtensions": True, + "showCommonExtensions": True, +} + + +def get_swagger_ui_html( + *, + openapi_url: Annotated[ + str, + Doc( + """ + The OpenAPI URL that Swagger UI should load and use. + + This is normally done automatically by FastAPI using the default URL + `/openapi.json`. + """ + ), + ], + title: Annotated[ + str, + Doc( + """ + The HTML `` content, normally shown in the browser tab. + """ + ), + ], + swagger_js_url: Annotated[ + str, + Doc( + """ + The URL to use to load the Swagger UI JavaScript. + + It is normally set to a CDN URL. + """ + ), + ] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js", + swagger_css_url: Annotated[ + str, + Doc( + """ + The URL to use to load the Swagger UI CSS. + + It is normally set to a CDN URL. + """ + ), + ] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css", + swagger_favicon_url: Annotated[ + str, + Doc( + """ + The URL of the favicon to use. It is normally shown in the browser tab. + """ + ), + ] = "https://fastapi.tiangolo.com/img/favicon.png", + oauth2_redirect_url: Annotated[ + Optional[str], + Doc( + """ + The OAuth2 redirect URL, it is normally automatically handled by FastAPI. + """ + ), + ] = None, + init_oauth: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + A dictionary with Swagger UI OAuth2 initialization configurations. + """ + ), + ] = None, + swagger_ui_parameters: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Configuration parameters for Swagger UI. + + It defaults to [swagger_ui_default_parameters][fastapi.openapi.docs.swagger_ui_default_parameters]. + """ + ), + ] = None, +) -> HTMLResponse: + """ + Generate and return the HTML that loads Swagger UI for the interactive + API docs (normally served at `/docs`). + + You would only call this function yourself if you needed to override some parts, + for example the URLs to use to load Swagger UI's JavaScript and CSS. + + Read more about it in the + [FastAPI docs for Configure Swagger UI](https://fastapi.tiangolo.com/how-to/configure-swagger-ui/) + and the [FastAPI docs for Custom Docs UI Static Assets (Self-Hosting)](https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets/). + """ + current_swagger_ui_parameters = swagger_ui_default_parameters.copy() + if swagger_ui_parameters: + current_swagger_ui_parameters.update(swagger_ui_parameters) + + html = f""" + <!DOCTYPE html> + <html> + <head> + <link type="text/css" rel="stylesheet" href="{swagger_css_url}"> + <link rel="shortcut icon" href="{swagger_favicon_url}"> + <title>{title} + + +
+
+ + + + + + """ + return HTMLResponse(html) + + +def get_redoc_html( + *, + openapi_url: Annotated[ + str, + Doc( + """ + The OpenAPI URL that ReDoc should load and use. + + This is normally done automatically by FastAPI using the default URL + `/openapi.json`. + """ + ), + ], + title: Annotated[ + str, + Doc( + """ + The HTML `` content, normally shown in the browser tab. + """ + ), + ], + redoc_js_url: Annotated[ + str, + Doc( + """ + The URL to use to load the ReDoc JavaScript. + + It is normally set to a CDN URL. + """ + ), + ] = "https://cdn.jsdelivr.net/npm/redoc@2/bundles/redoc.standalone.js", + redoc_favicon_url: Annotated[ + str, + Doc( + """ + The URL of the favicon to use. It is normally shown in the browser tab. + """ + ), + ] = "https://fastapi.tiangolo.com/img/favicon.png", + with_google_fonts: Annotated[ + bool, + Doc( + """ + Load and use Google Fonts. + """ + ), + ] = True, +) -> HTMLResponse: + """ + Generate and return the HTML response that loads ReDoc for the alternative + API docs (normally served at `/redoc`). + + You would only call this function yourself if you needed to override some parts, + for example the URLs to use to load ReDoc's JavaScript and CSS. + + Read more about it in the + [FastAPI docs for Custom Docs UI Static Assets (Self-Hosting)](https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets/). + """ + html = f""" + <!DOCTYPE html> + <html> + <head> + <title>{title} + + + + """ + if with_google_fonts: + html += """ + + """ + html += f""" + + + + + + + + + + + """ + return HTMLResponse(html) + + +def get_swagger_ui_oauth2_redirect_html() -> HTMLResponse: + """ + Generate the HTML response with the OAuth2 redirection for Swagger UI. + + You normally don't need to use or change this. + """ + # copied from https://github.com/swagger-api/swagger-ui/blob/v4.14.0/dist/oauth2-redirect.html + html = """ + + + + Swagger UI: OAuth2 Redirect + + + + + + """ + return HTMLResponse(content=html) diff --git a/venv/Lib/site-packages/fastapi/openapi/models.py b/venv/Lib/site-packages/fastapi/openapi/models.py new file mode 100644 index 00000000..ed07b40f --- /dev/null +++ b/venv/Lib/site-packages/fastapi/openapi/models.py @@ -0,0 +1,445 @@ +from enum import Enum +from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Type, Union + +from fastapi._compat import ( + PYDANTIC_V2, + CoreSchema, + GetJsonSchemaHandler, + JsonSchemaValue, + _model_rebuild, + with_info_plain_validator_function, +) +from fastapi.logger import logger +from pydantic import AnyUrl, BaseModel, Field +from typing_extensions import Annotated, Literal, TypedDict +from typing_extensions import deprecated as typing_deprecated + +try: + import email_validator + + assert email_validator # make autoflake ignore the unused import + from pydantic import EmailStr +except ImportError: # pragma: no cover + + class EmailStr(str): # type: ignore + @classmethod + def __get_validators__(cls) -> Iterable[Callable[..., Any]]: + yield cls.validate + + @classmethod + def validate(cls, v: Any) -> str: + logger.warning( + "email-validator not installed, email fields will be treated as str.\n" + "To install, run: pip install email-validator" + ) + return str(v) + + @classmethod + def _validate(cls, __input_value: Any, _: Any) -> str: + logger.warning( + "email-validator not installed, email fields will be treated as str.\n" + "To install, run: pip install email-validator" + ) + return str(__input_value) + + @classmethod + def __get_pydantic_json_schema__( + cls, core_schema: CoreSchema, handler: GetJsonSchemaHandler + ) -> JsonSchemaValue: + return {"type": "string", "format": "email"} + + @classmethod + def __get_pydantic_core_schema__( + cls, source: Type[Any], handler: Callable[[Any], CoreSchema] + ) -> CoreSchema: + return with_info_plain_validator_function(cls._validate) + + +class BaseModelWithConfig(BaseModel): + if PYDANTIC_V2: + model_config = {"extra": "allow"} + + else: + + class Config: + extra = "allow" + + +class Contact(BaseModelWithConfig): + name: Optional[str] = None + url: Optional[AnyUrl] = None + email: Optional[EmailStr] = None + + +class License(BaseModelWithConfig): + name: str + identifier: Optional[str] = None + url: Optional[AnyUrl] = None + + +class Info(BaseModelWithConfig): + title: str + summary: Optional[str] = None + description: Optional[str] = None + termsOfService: Optional[str] = None + contact: Optional[Contact] = None + license: Optional[License] = None + version: str + + +class ServerVariable(BaseModelWithConfig): + enum: Annotated[Optional[List[str]], Field(min_length=1)] = None + default: str + description: Optional[str] = None + + +class Server(BaseModelWithConfig): + url: Union[AnyUrl, str] + description: Optional[str] = None + variables: Optional[Dict[str, ServerVariable]] = None + + +class Reference(BaseModel): + ref: str = Field(alias="$ref") + + +class Discriminator(BaseModel): + propertyName: str + mapping: Optional[Dict[str, str]] = None + + +class XML(BaseModelWithConfig): + name: Optional[str] = None + namespace: Optional[str] = None + prefix: Optional[str] = None + attribute: Optional[bool] = None + wrapped: Optional[bool] = None + + +class ExternalDocumentation(BaseModelWithConfig): + description: Optional[str] = None + url: AnyUrl + + +class Schema(BaseModelWithConfig): + # Ref: JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-core.html#name-the-json-schema-core-vocabu + # Core Vocabulary + schema_: Optional[str] = Field(default=None, alias="$schema") + vocabulary: Optional[str] = Field(default=None, alias="$vocabulary") + id: Optional[str] = Field(default=None, alias="$id") + anchor: Optional[str] = Field(default=None, alias="$anchor") + dynamicAnchor: Optional[str] = Field(default=None, alias="$dynamicAnchor") + ref: Optional[str] = Field(default=None, alias="$ref") + dynamicRef: Optional[str] = Field(default=None, alias="$dynamicRef") + defs: Optional[Dict[str, "SchemaOrBool"]] = Field(default=None, alias="$defs") + comment: Optional[str] = Field(default=None, alias="$comment") + # Ref: JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-core.html#name-a-vocabulary-for-applying-s + # A Vocabulary for Applying Subschemas + allOf: Optional[List["SchemaOrBool"]] = None + anyOf: Optional[List["SchemaOrBool"]] = None + oneOf: Optional[List["SchemaOrBool"]] = None + not_: Optional["SchemaOrBool"] = Field(default=None, alias="not") + if_: Optional["SchemaOrBool"] = Field(default=None, alias="if") + then: Optional["SchemaOrBool"] = None + else_: Optional["SchemaOrBool"] = Field(default=None, alias="else") + dependentSchemas: Optional[Dict[str, "SchemaOrBool"]] = None + prefixItems: Optional[List["SchemaOrBool"]] = None + # TODO: uncomment and remove below when deprecating Pydantic v1 + # It generales a list of schemas for tuples, before prefixItems was available + # items: Optional["SchemaOrBool"] = None + items: Optional[Union["SchemaOrBool", List["SchemaOrBool"]]] = None + contains: Optional["SchemaOrBool"] = None + properties: Optional[Dict[str, "SchemaOrBool"]] = None + patternProperties: Optional[Dict[str, "SchemaOrBool"]] = None + additionalProperties: Optional["SchemaOrBool"] = None + propertyNames: Optional["SchemaOrBool"] = None + unevaluatedItems: Optional["SchemaOrBool"] = None + unevaluatedProperties: Optional["SchemaOrBool"] = None + # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-structural + # A Vocabulary for Structural Validation + type: Optional[str] = None + enum: Optional[List[Any]] = None + const: Optional[Any] = None + multipleOf: Optional[float] = Field(default=None, gt=0) + maximum: Optional[float] = None + exclusiveMaximum: Optional[float] = None + minimum: Optional[float] = None + exclusiveMinimum: Optional[float] = None + maxLength: Optional[int] = Field(default=None, ge=0) + minLength: Optional[int] = Field(default=None, ge=0) + pattern: Optional[str] = None + maxItems: Optional[int] = Field(default=None, ge=0) + minItems: Optional[int] = Field(default=None, ge=0) + uniqueItems: Optional[bool] = None + maxContains: Optional[int] = Field(default=None, ge=0) + minContains: Optional[int] = Field(default=None, ge=0) + maxProperties: Optional[int] = Field(default=None, ge=0) + minProperties: Optional[int] = Field(default=None, ge=0) + required: Optional[List[str]] = None + dependentRequired: Optional[Dict[str, Set[str]]] = None + # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-vocabularies-for-semantic-c + # Vocabularies for Semantic Content With "format" + format: Optional[str] = None + # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-the-conten + # A Vocabulary for the Contents of String-Encoded Data + contentEncoding: Optional[str] = None + contentMediaType: Optional[str] = None + contentSchema: Optional["SchemaOrBool"] = None + # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-basic-meta + # A Vocabulary for Basic Meta-Data Annotations + title: Optional[str] = None + description: Optional[str] = None + default: Optional[Any] = None + deprecated: Optional[bool] = None + readOnly: Optional[bool] = None + writeOnly: Optional[bool] = None + examples: Optional[List[Any]] = None + # Ref: OpenAPI 3.1.0: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object + # Schema Object + discriminator: Optional[Discriminator] = None + xml: Optional[XML] = None + externalDocs: Optional[ExternalDocumentation] = None + example: Annotated[ + Optional[Any], + typing_deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = None + + +# Ref: https://json-schema.org/draft/2020-12/json-schema-core.html#name-json-schema-documents +# A JSON Schema MUST be an object or a boolean. +SchemaOrBool = Union[Schema, bool] + + +class Example(TypedDict, total=False): + summary: Optional[str] + description: Optional[str] + value: Optional[Any] + externalValue: Optional[AnyUrl] + + if PYDANTIC_V2: # type: ignore [misc] + __pydantic_config__ = {"extra": "allow"} + + else: + + class Config: + extra = "allow" + + +class ParameterInType(Enum): + query = "query" + header = "header" + path = "path" + cookie = "cookie" + + +class Encoding(BaseModelWithConfig): + contentType: Optional[str] = None + headers: Optional[Dict[str, Union["Header", Reference]]] = None + style: Optional[str] = None + explode: Optional[bool] = None + allowReserved: Optional[bool] = None + + +class MediaType(BaseModelWithConfig): + schema_: Optional[Union[Schema, Reference]] = Field(default=None, alias="schema") + example: Optional[Any] = None + examples: Optional[Dict[str, Union[Example, Reference]]] = None + encoding: Optional[Dict[str, Encoding]] = None + + +class ParameterBase(BaseModelWithConfig): + description: Optional[str] = None + required: Optional[bool] = None + deprecated: Optional[bool] = None + # Serialization rules for simple scenarios + style: Optional[str] = None + explode: Optional[bool] = None + allowReserved: Optional[bool] = None + schema_: Optional[Union[Schema, Reference]] = Field(default=None, alias="schema") + example: Optional[Any] = None + examples: Optional[Dict[str, Union[Example, Reference]]] = None + # Serialization rules for more complex scenarios + content: Optional[Dict[str, MediaType]] = None + + +class Parameter(ParameterBase): + name: str + in_: ParameterInType = Field(alias="in") + + +class Header(ParameterBase): + pass + + +class RequestBody(BaseModelWithConfig): + description: Optional[str] = None + content: Dict[str, MediaType] + required: Optional[bool] = None + + +class Link(BaseModelWithConfig): + operationRef: Optional[str] = None + operationId: Optional[str] = None + parameters: Optional[Dict[str, Union[Any, str]]] = None + requestBody: Optional[Union[Any, str]] = None + description: Optional[str] = None + server: Optional[Server] = None + + +class Response(BaseModelWithConfig): + description: str + headers: Optional[Dict[str, Union[Header, Reference]]] = None + content: Optional[Dict[str, MediaType]] = None + links: Optional[Dict[str, Union[Link, Reference]]] = None + + +class Operation(BaseModelWithConfig): + tags: Optional[List[str]] = None + summary: Optional[str] = None + description: Optional[str] = None + externalDocs: Optional[ExternalDocumentation] = None + operationId: Optional[str] = None + parameters: Optional[List[Union[Parameter, Reference]]] = None + requestBody: Optional[Union[RequestBody, Reference]] = None + # Using Any for Specification Extensions + responses: Optional[Dict[str, Union[Response, Any]]] = None + callbacks: Optional[Dict[str, Union[Dict[str, "PathItem"], Reference]]] = None + deprecated: Optional[bool] = None + security: Optional[List[Dict[str, List[str]]]] = None + servers: Optional[List[Server]] = None + + +class PathItem(BaseModelWithConfig): + ref: Optional[str] = Field(default=None, alias="$ref") + summary: Optional[str] = None + description: Optional[str] = None + get: Optional[Operation] = None + put: Optional[Operation] = None + post: Optional[Operation] = None + delete: Optional[Operation] = None + options: Optional[Operation] = None + head: Optional[Operation] = None + patch: Optional[Operation] = None + trace: Optional[Operation] = None + servers: Optional[List[Server]] = None + parameters: Optional[List[Union[Parameter, Reference]]] = None + + +class SecuritySchemeType(Enum): + apiKey = "apiKey" + http = "http" + oauth2 = "oauth2" + openIdConnect = "openIdConnect" + + +class SecurityBase(BaseModelWithConfig): + type_: SecuritySchemeType = Field(alias="type") + description: Optional[str] = None + + +class APIKeyIn(Enum): + query = "query" + header = "header" + cookie = "cookie" + + +class APIKey(SecurityBase): + type_: SecuritySchemeType = Field(default=SecuritySchemeType.apiKey, alias="type") + in_: APIKeyIn = Field(alias="in") + name: str + + +class HTTPBase(SecurityBase): + type_: SecuritySchemeType = Field(default=SecuritySchemeType.http, alias="type") + scheme: str + + +class HTTPBearer(HTTPBase): + scheme: Literal["bearer"] = "bearer" + bearerFormat: Optional[str] = None + + +class OAuthFlow(BaseModelWithConfig): + refreshUrl: Optional[str] = None + scopes: Dict[str, str] = {} + + +class OAuthFlowImplicit(OAuthFlow): + authorizationUrl: str + + +class OAuthFlowPassword(OAuthFlow): + tokenUrl: str + + +class OAuthFlowClientCredentials(OAuthFlow): + tokenUrl: str + + +class OAuthFlowAuthorizationCode(OAuthFlow): + authorizationUrl: str + tokenUrl: str + + +class OAuthFlows(BaseModelWithConfig): + implicit: Optional[OAuthFlowImplicit] = None + password: Optional[OAuthFlowPassword] = None + clientCredentials: Optional[OAuthFlowClientCredentials] = None + authorizationCode: Optional[OAuthFlowAuthorizationCode] = None + + +class OAuth2(SecurityBase): + type_: SecuritySchemeType = Field(default=SecuritySchemeType.oauth2, alias="type") + flows: OAuthFlows + + +class OpenIdConnect(SecurityBase): + type_: SecuritySchemeType = Field( + default=SecuritySchemeType.openIdConnect, alias="type" + ) + openIdConnectUrl: str + + +SecurityScheme = Union[APIKey, HTTPBase, OAuth2, OpenIdConnect, HTTPBearer] + + +class Components(BaseModelWithConfig): + schemas: Optional[Dict[str, Union[Schema, Reference]]] = None + responses: Optional[Dict[str, Union[Response, Reference]]] = None + parameters: Optional[Dict[str, Union[Parameter, Reference]]] = None + examples: Optional[Dict[str, Union[Example, Reference]]] = None + requestBodies: Optional[Dict[str, Union[RequestBody, Reference]]] = None + headers: Optional[Dict[str, Union[Header, Reference]]] = None + securitySchemes: Optional[Dict[str, Union[SecurityScheme, Reference]]] = None + links: Optional[Dict[str, Union[Link, Reference]]] = None + # Using Any for Specification Extensions + callbacks: Optional[Dict[str, Union[Dict[str, PathItem], Reference, Any]]] = None + pathItems: Optional[Dict[str, Union[PathItem, Reference]]] = None + + +class Tag(BaseModelWithConfig): + name: str + description: Optional[str] = None + externalDocs: Optional[ExternalDocumentation] = None + + +class OpenAPI(BaseModelWithConfig): + openapi: str + info: Info + jsonSchemaDialect: Optional[str] = None + servers: Optional[List[Server]] = None + # Using Any for Specification Extensions + paths: Optional[Dict[str, Union[PathItem, Any]]] = None + webhooks: Optional[Dict[str, Union[PathItem, Reference]]] = None + components: Optional[Components] = None + security: Optional[List[Dict[str, List[str]]]] = None + tags: Optional[List[Tag]] = None + externalDocs: Optional[ExternalDocumentation] = None + + +_model_rebuild(Schema) +_model_rebuild(Operation) +_model_rebuild(Encoding) diff --git a/venv/Lib/site-packages/fastapi/openapi/utils.py b/venv/Lib/site-packages/fastapi/openapi/utils.py new file mode 100644 index 00000000..808646cc --- /dev/null +++ b/venv/Lib/site-packages/fastapi/openapi/utils.py @@ -0,0 +1,569 @@ +import http.client +import inspect +import warnings +from typing import Any, Dict, List, Optional, Sequence, Set, Tuple, Type, Union, cast + +from fastapi import routing +from fastapi._compat import ( + GenerateJsonSchema, + JsonSchemaValue, + ModelField, + Undefined, + get_compat_model_name_map, + get_definitions, + get_schema_from_model_field, + lenient_issubclass, +) +from fastapi.datastructures import DefaultPlaceholder +from fastapi.dependencies.models import Dependant +from fastapi.dependencies.utils import ( + _get_flat_fields_from_params, + get_flat_dependant, + get_flat_params, +) +from fastapi.encoders import jsonable_encoder +from fastapi.openapi.constants import METHODS_WITH_BODY, REF_PREFIX, REF_TEMPLATE +from fastapi.openapi.models import OpenAPI +from fastapi.params import Body, ParamTypes +from fastapi.responses import Response +from fastapi.types import ModelNameMap +from fastapi.utils import ( + deep_dict_update, + generate_operation_id_for_path, + is_body_allowed_for_status_code, +) +from pydantic import BaseModel +from starlette.responses import JSONResponse +from starlette.routing import BaseRoute +from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY +from typing_extensions import Literal + +validation_error_definition = { + "title": "ValidationError", + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": {"anyOf": [{"type": "string"}, {"type": "integer"}]}, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + "required": ["loc", "msg", "type"], +} + +validation_error_response_definition = { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": REF_PREFIX + "ValidationError"}, + } + }, +} + +status_code_ranges: Dict[str, str] = { + "1XX": "Information", + "2XX": "Success", + "3XX": "Redirection", + "4XX": "Client Error", + "5XX": "Server Error", + "DEFAULT": "Default Response", +} + + +def get_openapi_security_definitions( + flat_dependant: Dependant, +) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: + security_definitions = {} + operation_security = [] + for security_requirement in flat_dependant.security_requirements: + security_definition = jsonable_encoder( + security_requirement.security_scheme.model, + by_alias=True, + exclude_none=True, + ) + security_name = security_requirement.security_scheme.scheme_name + security_definitions[security_name] = security_definition + operation_security.append({security_name: security_requirement.scopes}) + return security_definitions, operation_security + + +def _get_openapi_operation_parameters( + *, + dependant: Dependant, + schema_generator: GenerateJsonSchema, + model_name_map: ModelNameMap, + field_mapping: Dict[ + Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue + ], + separate_input_output_schemas: bool = True, +) -> List[Dict[str, Any]]: + parameters = [] + flat_dependant = get_flat_dependant(dependant, skip_repeats=True) + path_params = _get_flat_fields_from_params(flat_dependant.path_params) + query_params = _get_flat_fields_from_params(flat_dependant.query_params) + header_params = _get_flat_fields_from_params(flat_dependant.header_params) + cookie_params = _get_flat_fields_from_params(flat_dependant.cookie_params) + parameter_groups = [ + (ParamTypes.path, path_params), + (ParamTypes.query, query_params), + (ParamTypes.header, header_params), + (ParamTypes.cookie, cookie_params), + ] + default_convert_underscores = True + if len(flat_dependant.header_params) == 1: + first_field = flat_dependant.header_params[0] + if lenient_issubclass(first_field.type_, BaseModel): + default_convert_underscores = getattr( + first_field.field_info, "convert_underscores", True + ) + for param_type, param_group in parameter_groups: + for param in param_group: + field_info = param.field_info + # field_info = cast(Param, field_info) + if not getattr(field_info, "include_in_schema", True): + continue + param_schema = get_schema_from_model_field( + field=param, + schema_generator=schema_generator, + model_name_map=model_name_map, + field_mapping=field_mapping, + separate_input_output_schemas=separate_input_output_schemas, + ) + name = param.alias + convert_underscores = getattr( + param.field_info, + "convert_underscores", + default_convert_underscores, + ) + if ( + param_type == ParamTypes.header + and param.alias == param.name + and convert_underscores + ): + name = param.name.replace("_", "-") + + parameter = { + "name": name, + "in": param_type.value, + "required": param.required, + "schema": param_schema, + } + if field_info.description: + parameter["description"] = field_info.description + openapi_examples = getattr(field_info, "openapi_examples", None) + example = getattr(field_info, "example", None) + if openapi_examples: + parameter["examples"] = jsonable_encoder(openapi_examples) + elif example != Undefined: + parameter["example"] = jsonable_encoder(example) + if getattr(field_info, "deprecated", None): + parameter["deprecated"] = True + parameters.append(parameter) + return parameters + + +def get_openapi_operation_request_body( + *, + body_field: Optional[ModelField], + schema_generator: GenerateJsonSchema, + model_name_map: ModelNameMap, + field_mapping: Dict[ + Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue + ], + separate_input_output_schemas: bool = True, +) -> Optional[Dict[str, Any]]: + if not body_field: + return None + assert isinstance(body_field, ModelField) + body_schema = get_schema_from_model_field( + field=body_field, + schema_generator=schema_generator, + model_name_map=model_name_map, + field_mapping=field_mapping, + separate_input_output_schemas=separate_input_output_schemas, + ) + field_info = cast(Body, body_field.field_info) + request_media_type = field_info.media_type + required = body_field.required + request_body_oai: Dict[str, Any] = {} + if required: + request_body_oai["required"] = required + request_media_content: Dict[str, Any] = {"schema": body_schema} + if field_info.openapi_examples: + request_media_content["examples"] = jsonable_encoder( + field_info.openapi_examples + ) + elif field_info.example != Undefined: + request_media_content["example"] = jsonable_encoder(field_info.example) + request_body_oai["content"] = {request_media_type: request_media_content} + return request_body_oai + + +def generate_operation_id( + *, route: routing.APIRoute, method: str +) -> str: # pragma: nocover + warnings.warn( + "fastapi.openapi.utils.generate_operation_id() was deprecated, " + "it is not used internally, and will be removed soon", + DeprecationWarning, + stacklevel=2, + ) + if route.operation_id: + return route.operation_id + path: str = route.path_format + return generate_operation_id_for_path(name=route.name, path=path, method=method) + + +def generate_operation_summary(*, route: routing.APIRoute, method: str) -> str: + if route.summary: + return route.summary + return route.name.replace("_", " ").title() + + +def get_openapi_operation_metadata( + *, route: routing.APIRoute, method: str, operation_ids: Set[str] +) -> Dict[str, Any]: + operation: Dict[str, Any] = {} + if route.tags: + operation["tags"] = route.tags + operation["summary"] = generate_operation_summary(route=route, method=method) + if route.description: + operation["description"] = route.description + operation_id = route.operation_id or route.unique_id + if operation_id in operation_ids: + message = ( + f"Duplicate Operation ID {operation_id} for function " + + f"{route.endpoint.__name__}" + ) + file_name = getattr(route.endpoint, "__globals__", {}).get("__file__") + if file_name: + message += f" at {file_name}" + warnings.warn(message, stacklevel=1) + operation_ids.add(operation_id) + operation["operationId"] = operation_id + if route.deprecated: + operation["deprecated"] = route.deprecated + return operation + + +def get_openapi_path( + *, + route: routing.APIRoute, + operation_ids: Set[str], + schema_generator: GenerateJsonSchema, + model_name_map: ModelNameMap, + field_mapping: Dict[ + Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue + ], + separate_input_output_schemas: bool = True, +) -> Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any]]: + path = {} + security_schemes: Dict[str, Any] = {} + definitions: Dict[str, Any] = {} + assert route.methods is not None, "Methods must be a list" + if isinstance(route.response_class, DefaultPlaceholder): + current_response_class: Type[Response] = route.response_class.value + else: + current_response_class = route.response_class + assert current_response_class, "A response class is needed to generate OpenAPI" + route_response_media_type: Optional[str] = current_response_class.media_type + if route.include_in_schema: + for method in route.methods: + operation = get_openapi_operation_metadata( + route=route, method=method, operation_ids=operation_ids + ) + parameters: List[Dict[str, Any]] = [] + flat_dependant = get_flat_dependant(route.dependant, skip_repeats=True) + security_definitions, operation_security = get_openapi_security_definitions( + flat_dependant=flat_dependant + ) + if operation_security: + operation.setdefault("security", []).extend(operation_security) + if security_definitions: + security_schemes.update(security_definitions) + operation_parameters = _get_openapi_operation_parameters( + dependant=route.dependant, + schema_generator=schema_generator, + model_name_map=model_name_map, + field_mapping=field_mapping, + separate_input_output_schemas=separate_input_output_schemas, + ) + parameters.extend(operation_parameters) + if parameters: + all_parameters = { + (param["in"], param["name"]): param for param in parameters + } + required_parameters = { + (param["in"], param["name"]): param + for param in parameters + if param.get("required") + } + # Make sure required definitions of the same parameter take precedence + # over non-required definitions + all_parameters.update(required_parameters) + operation["parameters"] = list(all_parameters.values()) + if method in METHODS_WITH_BODY: + request_body_oai = get_openapi_operation_request_body( + body_field=route.body_field, + schema_generator=schema_generator, + model_name_map=model_name_map, + field_mapping=field_mapping, + separate_input_output_schemas=separate_input_output_schemas, + ) + if request_body_oai: + operation["requestBody"] = request_body_oai + if route.callbacks: + callbacks = {} + for callback in route.callbacks: + if isinstance(callback, routing.APIRoute): + ( + cb_path, + cb_security_schemes, + cb_definitions, + ) = get_openapi_path( + route=callback, + operation_ids=operation_ids, + schema_generator=schema_generator, + model_name_map=model_name_map, + field_mapping=field_mapping, + separate_input_output_schemas=separate_input_output_schemas, + ) + callbacks[callback.name] = {callback.path: cb_path} + operation["callbacks"] = callbacks + if route.status_code is not None: + status_code = str(route.status_code) + else: + # It would probably make more sense for all response classes to have an + # explicit default status_code, and to extract it from them, instead of + # doing this inspection tricks, that would probably be in the future + # TODO: probably make status_code a default class attribute for all + # responses in Starlette + response_signature = inspect.signature(current_response_class.__init__) + status_code_param = response_signature.parameters.get("status_code") + if status_code_param is not None: + if isinstance(status_code_param.default, int): + status_code = str(status_code_param.default) + operation.setdefault("responses", {}).setdefault(status_code, {})[ + "description" + ] = route.response_description + if route_response_media_type and is_body_allowed_for_status_code( + route.status_code + ): + response_schema = {"type": "string"} + if lenient_issubclass(current_response_class, JSONResponse): + if route.response_field: + response_schema = get_schema_from_model_field( + field=route.response_field, + schema_generator=schema_generator, + model_name_map=model_name_map, + field_mapping=field_mapping, + separate_input_output_schemas=separate_input_output_schemas, + ) + else: + response_schema = {} + operation.setdefault("responses", {}).setdefault( + status_code, {} + ).setdefault("content", {}).setdefault(route_response_media_type, {})[ + "schema" + ] = response_schema + if route.responses: + operation_responses = operation.setdefault("responses", {}) + for ( + additional_status_code, + additional_response, + ) in route.responses.items(): + process_response = additional_response.copy() + process_response.pop("model", None) + status_code_key = str(additional_status_code).upper() + if status_code_key == "DEFAULT": + status_code_key = "default" + openapi_response = operation_responses.setdefault( + status_code_key, {} + ) + assert isinstance(process_response, dict), ( + "An additional response must be a dict" + ) + field = route.response_fields.get(additional_status_code) + additional_field_schema: Optional[Dict[str, Any]] = None + if field: + additional_field_schema = get_schema_from_model_field( + field=field, + schema_generator=schema_generator, + model_name_map=model_name_map, + field_mapping=field_mapping, + separate_input_output_schemas=separate_input_output_schemas, + ) + media_type = route_response_media_type or "application/json" + additional_schema = ( + process_response.setdefault("content", {}) + .setdefault(media_type, {}) + .setdefault("schema", {}) + ) + deep_dict_update(additional_schema, additional_field_schema) + status_text: Optional[str] = status_code_ranges.get( + str(additional_status_code).upper() + ) or http.client.responses.get(int(additional_status_code)) + description = ( + process_response.get("description") + or openapi_response.get("description") + or status_text + or "Additional Response" + ) + deep_dict_update(openapi_response, process_response) + openapi_response["description"] = description + http422 = str(HTTP_422_UNPROCESSABLE_ENTITY) + all_route_params = get_flat_params(route.dependant) + if (all_route_params or route.body_field) and not any( + status in operation["responses"] + for status in [http422, "4XX", "default"] + ): + operation["responses"][http422] = { + "description": "Validation Error", + "content": { + "application/json": { + "schema": {"$ref": REF_PREFIX + "HTTPValidationError"} + } + }, + } + if "ValidationError" not in definitions: + definitions.update( + { + "ValidationError": validation_error_definition, + "HTTPValidationError": validation_error_response_definition, + } + ) + if route.openapi_extra: + deep_dict_update(operation, route.openapi_extra) + path[method.lower()] = operation + return path, security_schemes, definitions + + +def get_fields_from_routes( + routes: Sequence[BaseRoute], +) -> List[ModelField]: + body_fields_from_routes: List[ModelField] = [] + responses_from_routes: List[ModelField] = [] + request_fields_from_routes: List[ModelField] = [] + callback_flat_models: List[ModelField] = [] + for route in routes: + if getattr(route, "include_in_schema", None) and isinstance( + route, routing.APIRoute + ): + if route.body_field: + assert isinstance(route.body_field, ModelField), ( + "A request body must be a Pydantic Field" + ) + body_fields_from_routes.append(route.body_field) + if route.response_field: + responses_from_routes.append(route.response_field) + if route.response_fields: + responses_from_routes.extend(route.response_fields.values()) + if route.callbacks: + callback_flat_models.extend(get_fields_from_routes(route.callbacks)) + params = get_flat_params(route.dependant) + request_fields_from_routes.extend(params) + + flat_models = callback_flat_models + list( + body_fields_from_routes + responses_from_routes + request_fields_from_routes + ) + return flat_models + + +def get_openapi( + *, + title: str, + version: str, + openapi_version: str = "3.1.0", + summary: Optional[str] = None, + description: Optional[str] = None, + routes: Sequence[BaseRoute], + webhooks: Optional[Sequence[BaseRoute]] = None, + tags: Optional[List[Dict[str, Any]]] = None, + servers: Optional[List[Dict[str, Union[str, Any]]]] = None, + terms_of_service: Optional[str] = None, + contact: Optional[Dict[str, Union[str, Any]]] = None, + license_info: Optional[Dict[str, Union[str, Any]]] = None, + separate_input_output_schemas: bool = True, +) -> Dict[str, Any]: + info: Dict[str, Any] = {"title": title, "version": version} + if summary: + info["summary"] = summary + if description: + info["description"] = description + if terms_of_service: + info["termsOfService"] = terms_of_service + if contact: + info["contact"] = contact + if license_info: + info["license"] = license_info + output: Dict[str, Any] = {"openapi": openapi_version, "info": info} + if servers: + output["servers"] = servers + components: Dict[str, Dict[str, Any]] = {} + paths: Dict[str, Dict[str, Any]] = {} + webhook_paths: Dict[str, Dict[str, Any]] = {} + operation_ids: Set[str] = set() + all_fields = get_fields_from_routes(list(routes or []) + list(webhooks or [])) + model_name_map = get_compat_model_name_map(all_fields) + schema_generator = GenerateJsonSchema(ref_template=REF_TEMPLATE) + field_mapping, definitions = get_definitions( + fields=all_fields, + schema_generator=schema_generator, + model_name_map=model_name_map, + separate_input_output_schemas=separate_input_output_schemas, + ) + for route in routes or []: + if isinstance(route, routing.APIRoute): + result = get_openapi_path( + route=route, + operation_ids=operation_ids, + schema_generator=schema_generator, + model_name_map=model_name_map, + field_mapping=field_mapping, + separate_input_output_schemas=separate_input_output_schemas, + ) + if result: + path, security_schemes, path_definitions = result + if path: + paths.setdefault(route.path_format, {}).update(path) + if security_schemes: + components.setdefault("securitySchemes", {}).update( + security_schemes + ) + if path_definitions: + definitions.update(path_definitions) + for webhook in webhooks or []: + if isinstance(webhook, routing.APIRoute): + result = get_openapi_path( + route=webhook, + operation_ids=operation_ids, + schema_generator=schema_generator, + model_name_map=model_name_map, + field_mapping=field_mapping, + separate_input_output_schemas=separate_input_output_schemas, + ) + if result: + path, security_schemes, path_definitions = result + if path: + webhook_paths.setdefault(webhook.path_format, {}).update(path) + if security_schemes: + components.setdefault("securitySchemes", {}).update( + security_schemes + ) + if path_definitions: + definitions.update(path_definitions) + if definitions: + components["schemas"] = {k: definitions[k] for k in sorted(definitions)} + if components: + output["components"] = components + output["paths"] = paths + if webhook_paths: + output["webhooks"] = webhook_paths + if tags: + output["tags"] = tags + return jsonable_encoder(OpenAPI(**output), by_alias=True, exclude_none=True) # type: ignore diff --git a/venv/Lib/site-packages/fastapi/param_functions.py b/venv/Lib/site-packages/fastapi/param_functions.py new file mode 100644 index 00000000..b3621626 --- /dev/null +++ b/venv/Lib/site-packages/fastapi/param_functions.py @@ -0,0 +1,2360 @@ +from typing import Any, Callable, Dict, List, Optional, Sequence, Union + +from fastapi import params +from fastapi._compat import Undefined +from fastapi.openapi.models import Example +from typing_extensions import Annotated, Doc, deprecated + +_Unset: Any = Undefined + + +def Path( # noqa: N802 + default: Annotated[ + Any, + Doc( + """ + Default value if the parameter field is not set. + + This doesn't affect `Path` parameters as the value is always required. + The parameter is available only for compatibility. + """ + ), + ] = ..., + *, + default_factory: Annotated[ + Union[Callable[[], Any], None], + Doc( + """ + A callable to generate the default value. + + This doesn't affect `Path` parameters as the value is always required. + The parameter is available only for compatibility. + """ + ), + ] = _Unset, + alias: Annotated[ + Optional[str], + Doc( + """ + An alternative name for the parameter field. + + This will be used to extract the data and for the generated OpenAPI. + It is particularly useful when you can't use the name you want because it + is a Python reserved keyword or similar. + """ + ), + ] = None, + alias_priority: Annotated[ + Union[int, None], + Doc( + """ + Priority of the alias. This affects whether an alias generator is used. + """ + ), + ] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Whitelist' validation step. The parameter field will be the single one + allowed by the alias or set of aliases defined. + """ + ), + ] = None, + serialization_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Blacklist' validation step. The vanilla parameter field will be the + single one of the alias' or set of aliases' fields and all the other + fields will be ignored at serialization time. + """ + ), + ] = None, + title: Annotated[ + Optional[str], + Doc( + """ + Human-readable title. + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Human-readable description. + """ + ), + ] = None, + gt: Annotated[ + Optional[float], + Doc( + """ + Greater than. If set, value must be greater than this. Only applicable to + numbers. + """ + ), + ] = None, + ge: Annotated[ + Optional[float], + Doc( + """ + Greater than or equal. If set, value must be greater than or equal to + this. Only applicable to numbers. + """ + ), + ] = None, + lt: Annotated[ + Optional[float], + Doc( + """ + Less than. If set, value must be less than this. Only applicable to numbers. + """ + ), + ] = None, + le: Annotated[ + Optional[float], + Doc( + """ + Less than or equal. If set, value must be less than or equal to this. + Only applicable to numbers. + """ + ), + ] = None, + min_length: Annotated[ + Optional[int], + Doc( + """ + Minimum length for strings. + """ + ), + ] = None, + max_length: Annotated[ + Optional[int], + Doc( + """ + Maximum length for strings. + """ + ), + ] = None, + pattern: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + ] = None, + regex: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Annotated[ + Union[str, None], + Doc( + """ + Parameter field name for discriminating the type in a tagged union. + """ + ), + ] = None, + strict: Annotated[ + Union[bool, None], + Doc( + """ + If `True`, strict validation is applied to the field. + """ + ), + ] = _Unset, + multiple_of: Annotated[ + Union[float, None], + Doc( + """ + Value must be a multiple of this. Only applicable to numbers. + """ + ), + ] = _Unset, + allow_inf_nan: Annotated[ + Union[bool, None], + Doc( + """ + Allow `inf`, `-inf`, `nan`. Only applicable to numbers. + """ + ), + ] = _Unset, + max_digits: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of allow digits for strings. + """ + ), + ] = _Unset, + decimal_places: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of decimal places allowed for numbers. + """ + ), + ] = _Unset, + examples: Annotated[ + Optional[List[Any]], + Doc( + """ + Example values for this field. + """ + ), + ] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Annotated[ + Optional[Dict[str, Example]], + Doc( + """ + OpenAPI-specific examples. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Swagger UI (that provides the `/docs` interface) has better support for the + OpenAPI-specific examples than the JSON Schema `examples`, that's the main + use case for this. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). + """ + ), + ] = None, + deprecated: Annotated[ + Union[deprecated, str, bool, None], + Doc( + """ + Mark this parameter field as deprecated. + + It will affect the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) this parameter field in the generated OpenAPI. + You probably don't need it, but it's available. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = True, + json_schema_extra: Annotated[ + Union[Dict[str, Any], None], + Doc( + """ + Any additional JSON schema data. + """ + ), + ] = None, + **extra: Annotated[ + Any, + Doc( + """ + Include extra fields used by the JSON Schema. + """ + ), + deprecated( + """ + The `extra` kwargs is deprecated. Use `json_schema_extra` instead. + """ + ), + ], +) -> Any: + """ + Declare a path parameter for a *path operation*. + + Read more about it in the + [FastAPI docs for Path Parameters and Numeric Validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/). + + ```python + from typing import Annotated + + from fastapi import FastAPI, Path + + app = FastAPI() + + + @app.get("/items/{item_id}") + async def read_items( + item_id: Annotated[int, Path(title="The ID of the item to get")], + ): + return {"item_id": item_id} + ``` + """ + return params.Path( + default=default, + default_factory=default_factory, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + example=example, + examples=examples, + openapi_examples=openapi_examples, + deprecated=deprecated, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +def Query( # noqa: N802 + default: Annotated[ + Any, + Doc( + """ + Default value if the parameter field is not set. + """ + ), + ] = Undefined, + *, + default_factory: Annotated[ + Union[Callable[[], Any], None], + Doc( + """ + A callable to generate the default value. + + This doesn't affect `Path` parameters as the value is always required. + The parameter is available only for compatibility. + """ + ), + ] = _Unset, + alias: Annotated[ + Optional[str], + Doc( + """ + An alternative name for the parameter field. + + This will be used to extract the data and for the generated OpenAPI. + It is particularly useful when you can't use the name you want because it + is a Python reserved keyword or similar. + """ + ), + ] = None, + alias_priority: Annotated[ + Union[int, None], + Doc( + """ + Priority of the alias. This affects whether an alias generator is used. + """ + ), + ] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Whitelist' validation step. The parameter field will be the single one + allowed by the alias or set of aliases defined. + """ + ), + ] = None, + serialization_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Blacklist' validation step. The vanilla parameter field will be the + single one of the alias' or set of aliases' fields and all the other + fields will be ignored at serialization time. + """ + ), + ] = None, + title: Annotated[ + Optional[str], + Doc( + """ + Human-readable title. + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Human-readable description. + """ + ), + ] = None, + gt: Annotated[ + Optional[float], + Doc( + """ + Greater than. If set, value must be greater than this. Only applicable to + numbers. + """ + ), + ] = None, + ge: Annotated[ + Optional[float], + Doc( + """ + Greater than or equal. If set, value must be greater than or equal to + this. Only applicable to numbers. + """ + ), + ] = None, + lt: Annotated[ + Optional[float], + Doc( + """ + Less than. If set, value must be less than this. Only applicable to numbers. + """ + ), + ] = None, + le: Annotated[ + Optional[float], + Doc( + """ + Less than or equal. If set, value must be less than or equal to this. + Only applicable to numbers. + """ + ), + ] = None, + min_length: Annotated[ + Optional[int], + Doc( + """ + Minimum length for strings. + """ + ), + ] = None, + max_length: Annotated[ + Optional[int], + Doc( + """ + Maximum length for strings. + """ + ), + ] = None, + pattern: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + ] = None, + regex: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Annotated[ + Union[str, None], + Doc( + """ + Parameter field name for discriminating the type in a tagged union. + """ + ), + ] = None, + strict: Annotated[ + Union[bool, None], + Doc( + """ + If `True`, strict validation is applied to the field. + """ + ), + ] = _Unset, + multiple_of: Annotated[ + Union[float, None], + Doc( + """ + Value must be a multiple of this. Only applicable to numbers. + """ + ), + ] = _Unset, + allow_inf_nan: Annotated[ + Union[bool, None], + Doc( + """ + Allow `inf`, `-inf`, `nan`. Only applicable to numbers. + """ + ), + ] = _Unset, + max_digits: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of allow digits for strings. + """ + ), + ] = _Unset, + decimal_places: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of decimal places allowed for numbers. + """ + ), + ] = _Unset, + examples: Annotated[ + Optional[List[Any]], + Doc( + """ + Example values for this field. + """ + ), + ] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Annotated[ + Optional[Dict[str, Example]], + Doc( + """ + OpenAPI-specific examples. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Swagger UI (that provides the `/docs` interface) has better support for the + OpenAPI-specific examples than the JSON Schema `examples`, that's the main + use case for this. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). + """ + ), + ] = None, + deprecated: Annotated[ + Union[deprecated, str, bool, None], + Doc( + """ + Mark this parameter field as deprecated. + + It will affect the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) this parameter field in the generated OpenAPI. + You probably don't need it, but it's available. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = True, + json_schema_extra: Annotated[ + Union[Dict[str, Any], None], + Doc( + """ + Any additional JSON schema data. + """ + ), + ] = None, + **extra: Annotated[ + Any, + Doc( + """ + Include extra fields used by the JSON Schema. + """ + ), + deprecated( + """ + The `extra` kwargs is deprecated. Use `json_schema_extra` instead. + """ + ), + ], +) -> Any: + return params.Query( + default=default, + default_factory=default_factory, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + example=example, + examples=examples, + openapi_examples=openapi_examples, + deprecated=deprecated, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +def Header( # noqa: N802 + default: Annotated[ + Any, + Doc( + """ + Default value if the parameter field is not set. + """ + ), + ] = Undefined, + *, + default_factory: Annotated[ + Union[Callable[[], Any], None], + Doc( + """ + A callable to generate the default value. + + This doesn't affect `Path` parameters as the value is always required. + The parameter is available only for compatibility. + """ + ), + ] = _Unset, + alias: Annotated[ + Optional[str], + Doc( + """ + An alternative name for the parameter field. + + This will be used to extract the data and for the generated OpenAPI. + It is particularly useful when you can't use the name you want because it + is a Python reserved keyword or similar. + """ + ), + ] = None, + alias_priority: Annotated[ + Union[int, None], + Doc( + """ + Priority of the alias. This affects whether an alias generator is used. + """ + ), + ] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Whitelist' validation step. The parameter field will be the single one + allowed by the alias or set of aliases defined. + """ + ), + ] = None, + serialization_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Blacklist' validation step. The vanilla parameter field will be the + single one of the alias' or set of aliases' fields and all the other + fields will be ignored at serialization time. + """ + ), + ] = None, + convert_underscores: Annotated[ + bool, + Doc( + """ + Automatically convert underscores to hyphens in the parameter field name. + + Read more about it in the + [FastAPI docs for Header Parameters](https://fastapi.tiangolo.com/tutorial/header-params/#automatic-conversion) + """ + ), + ] = True, + title: Annotated[ + Optional[str], + Doc( + """ + Human-readable title. + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Human-readable description. + """ + ), + ] = None, + gt: Annotated[ + Optional[float], + Doc( + """ + Greater than. If set, value must be greater than this. Only applicable to + numbers. + """ + ), + ] = None, + ge: Annotated[ + Optional[float], + Doc( + """ + Greater than or equal. If set, value must be greater than or equal to + this. Only applicable to numbers. + """ + ), + ] = None, + lt: Annotated[ + Optional[float], + Doc( + """ + Less than. If set, value must be less than this. Only applicable to numbers. + """ + ), + ] = None, + le: Annotated[ + Optional[float], + Doc( + """ + Less than or equal. If set, value must be less than or equal to this. + Only applicable to numbers. + """ + ), + ] = None, + min_length: Annotated[ + Optional[int], + Doc( + """ + Minimum length for strings. + """ + ), + ] = None, + max_length: Annotated[ + Optional[int], + Doc( + """ + Maximum length for strings. + """ + ), + ] = None, + pattern: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + ] = None, + regex: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Annotated[ + Union[str, None], + Doc( + """ + Parameter field name for discriminating the type in a tagged union. + """ + ), + ] = None, + strict: Annotated[ + Union[bool, None], + Doc( + """ + If `True`, strict validation is applied to the field. + """ + ), + ] = _Unset, + multiple_of: Annotated[ + Union[float, None], + Doc( + """ + Value must be a multiple of this. Only applicable to numbers. + """ + ), + ] = _Unset, + allow_inf_nan: Annotated[ + Union[bool, None], + Doc( + """ + Allow `inf`, `-inf`, `nan`. Only applicable to numbers. + """ + ), + ] = _Unset, + max_digits: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of allow digits for strings. + """ + ), + ] = _Unset, + decimal_places: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of decimal places allowed for numbers. + """ + ), + ] = _Unset, + examples: Annotated[ + Optional[List[Any]], + Doc( + """ + Example values for this field. + """ + ), + ] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Annotated[ + Optional[Dict[str, Example]], + Doc( + """ + OpenAPI-specific examples. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Swagger UI (that provides the `/docs` interface) has better support for the + OpenAPI-specific examples than the JSON Schema `examples`, that's the main + use case for this. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). + """ + ), + ] = None, + deprecated: Annotated[ + Union[deprecated, str, bool, None], + Doc( + """ + Mark this parameter field as deprecated. + + It will affect the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) this parameter field in the generated OpenAPI. + You probably don't need it, but it's available. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = True, + json_schema_extra: Annotated[ + Union[Dict[str, Any], None], + Doc( + """ + Any additional JSON schema data. + """ + ), + ] = None, + **extra: Annotated[ + Any, + Doc( + """ + Include extra fields used by the JSON Schema. + """ + ), + deprecated( + """ + The `extra` kwargs is deprecated. Use `json_schema_extra` instead. + """ + ), + ], +) -> Any: + return params.Header( + default=default, + default_factory=default_factory, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + convert_underscores=convert_underscores, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + example=example, + examples=examples, + openapi_examples=openapi_examples, + deprecated=deprecated, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +def Cookie( # noqa: N802 + default: Annotated[ + Any, + Doc( + """ + Default value if the parameter field is not set. + """ + ), + ] = Undefined, + *, + default_factory: Annotated[ + Union[Callable[[], Any], None], + Doc( + """ + A callable to generate the default value. + + This doesn't affect `Path` parameters as the value is always required. + The parameter is available only for compatibility. + """ + ), + ] = _Unset, + alias: Annotated[ + Optional[str], + Doc( + """ + An alternative name for the parameter field. + + This will be used to extract the data and for the generated OpenAPI. + It is particularly useful when you can't use the name you want because it + is a Python reserved keyword or similar. + """ + ), + ] = None, + alias_priority: Annotated[ + Union[int, None], + Doc( + """ + Priority of the alias. This affects whether an alias generator is used. + """ + ), + ] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Whitelist' validation step. The parameter field will be the single one + allowed by the alias or set of aliases defined. + """ + ), + ] = None, + serialization_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Blacklist' validation step. The vanilla parameter field will be the + single one of the alias' or set of aliases' fields and all the other + fields will be ignored at serialization time. + """ + ), + ] = None, + title: Annotated[ + Optional[str], + Doc( + """ + Human-readable title. + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Human-readable description. + """ + ), + ] = None, + gt: Annotated[ + Optional[float], + Doc( + """ + Greater than. If set, value must be greater than this. Only applicable to + numbers. + """ + ), + ] = None, + ge: Annotated[ + Optional[float], + Doc( + """ + Greater than or equal. If set, value must be greater than or equal to + this. Only applicable to numbers. + """ + ), + ] = None, + lt: Annotated[ + Optional[float], + Doc( + """ + Less than. If set, value must be less than this. Only applicable to numbers. + """ + ), + ] = None, + le: Annotated[ + Optional[float], + Doc( + """ + Less than or equal. If set, value must be less than or equal to this. + Only applicable to numbers. + """ + ), + ] = None, + min_length: Annotated[ + Optional[int], + Doc( + """ + Minimum length for strings. + """ + ), + ] = None, + max_length: Annotated[ + Optional[int], + Doc( + """ + Maximum length for strings. + """ + ), + ] = None, + pattern: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + ] = None, + regex: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Annotated[ + Union[str, None], + Doc( + """ + Parameter field name for discriminating the type in a tagged union. + """ + ), + ] = None, + strict: Annotated[ + Union[bool, None], + Doc( + """ + If `True`, strict validation is applied to the field. + """ + ), + ] = _Unset, + multiple_of: Annotated[ + Union[float, None], + Doc( + """ + Value must be a multiple of this. Only applicable to numbers. + """ + ), + ] = _Unset, + allow_inf_nan: Annotated[ + Union[bool, None], + Doc( + """ + Allow `inf`, `-inf`, `nan`. Only applicable to numbers. + """ + ), + ] = _Unset, + max_digits: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of allow digits for strings. + """ + ), + ] = _Unset, + decimal_places: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of decimal places allowed for numbers. + """ + ), + ] = _Unset, + examples: Annotated[ + Optional[List[Any]], + Doc( + """ + Example values for this field. + """ + ), + ] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Annotated[ + Optional[Dict[str, Example]], + Doc( + """ + OpenAPI-specific examples. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Swagger UI (that provides the `/docs` interface) has better support for the + OpenAPI-specific examples than the JSON Schema `examples`, that's the main + use case for this. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). + """ + ), + ] = None, + deprecated: Annotated[ + Union[deprecated, str, bool, None], + Doc( + """ + Mark this parameter field as deprecated. + + It will affect the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) this parameter field in the generated OpenAPI. + You probably don't need it, but it's available. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = True, + json_schema_extra: Annotated[ + Union[Dict[str, Any], None], + Doc( + """ + Any additional JSON schema data. + """ + ), + ] = None, + **extra: Annotated[ + Any, + Doc( + """ + Include extra fields used by the JSON Schema. + """ + ), + deprecated( + """ + The `extra` kwargs is deprecated. Use `json_schema_extra` instead. + """ + ), + ], +) -> Any: + return params.Cookie( + default=default, + default_factory=default_factory, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + example=example, + examples=examples, + openapi_examples=openapi_examples, + deprecated=deprecated, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +def Body( # noqa: N802 + default: Annotated[ + Any, + Doc( + """ + Default value if the parameter field is not set. + """ + ), + ] = Undefined, + *, + default_factory: Annotated[ + Union[Callable[[], Any], None], + Doc( + """ + A callable to generate the default value. + + This doesn't affect `Path` parameters as the value is always required. + The parameter is available only for compatibility. + """ + ), + ] = _Unset, + embed: Annotated[ + Union[bool, None], + Doc( + """ + When `embed` is `True`, the parameter will be expected in a JSON body as a + key instead of being the JSON body itself. + + This happens automatically when more than one `Body` parameter is declared. + + Read more about it in the + [FastAPI docs for Body - Multiple Parameters](https://fastapi.tiangolo.com/tutorial/body-multiple-params/#embed-a-single-body-parameter). + """ + ), + ] = None, + media_type: Annotated[ + str, + Doc( + """ + The media type of this parameter field. Changing it would affect the + generated OpenAPI, but currently it doesn't affect the parsing of the data. + """ + ), + ] = "application/json", + alias: Annotated[ + Optional[str], + Doc( + """ + An alternative name for the parameter field. + + This will be used to extract the data and for the generated OpenAPI. + It is particularly useful when you can't use the name you want because it + is a Python reserved keyword or similar. + """ + ), + ] = None, + alias_priority: Annotated[ + Union[int, None], + Doc( + """ + Priority of the alias. This affects whether an alias generator is used. + """ + ), + ] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Whitelist' validation step. The parameter field will be the single one + allowed by the alias or set of aliases defined. + """ + ), + ] = None, + serialization_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Blacklist' validation step. The vanilla parameter field will be the + single one of the alias' or set of aliases' fields and all the other + fields will be ignored at serialization time. + """ + ), + ] = None, + title: Annotated[ + Optional[str], + Doc( + """ + Human-readable title. + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Human-readable description. + """ + ), + ] = None, + gt: Annotated[ + Optional[float], + Doc( + """ + Greater than. If set, value must be greater than this. Only applicable to + numbers. + """ + ), + ] = None, + ge: Annotated[ + Optional[float], + Doc( + """ + Greater than or equal. If set, value must be greater than or equal to + this. Only applicable to numbers. + """ + ), + ] = None, + lt: Annotated[ + Optional[float], + Doc( + """ + Less than. If set, value must be less than this. Only applicable to numbers. + """ + ), + ] = None, + le: Annotated[ + Optional[float], + Doc( + """ + Less than or equal. If set, value must be less than or equal to this. + Only applicable to numbers. + """ + ), + ] = None, + min_length: Annotated[ + Optional[int], + Doc( + """ + Minimum length for strings. + """ + ), + ] = None, + max_length: Annotated[ + Optional[int], + Doc( + """ + Maximum length for strings. + """ + ), + ] = None, + pattern: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + ] = None, + regex: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Annotated[ + Union[str, None], + Doc( + """ + Parameter field name for discriminating the type in a tagged union. + """ + ), + ] = None, + strict: Annotated[ + Union[bool, None], + Doc( + """ + If `True`, strict validation is applied to the field. + """ + ), + ] = _Unset, + multiple_of: Annotated[ + Union[float, None], + Doc( + """ + Value must be a multiple of this. Only applicable to numbers. + """ + ), + ] = _Unset, + allow_inf_nan: Annotated[ + Union[bool, None], + Doc( + """ + Allow `inf`, `-inf`, `nan`. Only applicable to numbers. + """ + ), + ] = _Unset, + max_digits: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of allow digits for strings. + """ + ), + ] = _Unset, + decimal_places: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of decimal places allowed for numbers. + """ + ), + ] = _Unset, + examples: Annotated[ + Optional[List[Any]], + Doc( + """ + Example values for this field. + """ + ), + ] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Annotated[ + Optional[Dict[str, Example]], + Doc( + """ + OpenAPI-specific examples. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Swagger UI (that provides the `/docs` interface) has better support for the + OpenAPI-specific examples than the JSON Schema `examples`, that's the main + use case for this. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). + """ + ), + ] = None, + deprecated: Annotated[ + Union[deprecated, str, bool, None], + Doc( + """ + Mark this parameter field as deprecated. + + It will affect the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) this parameter field in the generated OpenAPI. + You probably don't need it, but it's available. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = True, + json_schema_extra: Annotated[ + Union[Dict[str, Any], None], + Doc( + """ + Any additional JSON schema data. + """ + ), + ] = None, + **extra: Annotated[ + Any, + Doc( + """ + Include extra fields used by the JSON Schema. + """ + ), + deprecated( + """ + The `extra` kwargs is deprecated. Use `json_schema_extra` instead. + """ + ), + ], +) -> Any: + return params.Body( + default=default, + default_factory=default_factory, + embed=embed, + media_type=media_type, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + example=example, + examples=examples, + openapi_examples=openapi_examples, + deprecated=deprecated, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +def Form( # noqa: N802 + default: Annotated[ + Any, + Doc( + """ + Default value if the parameter field is not set. + """ + ), + ] = Undefined, + *, + default_factory: Annotated[ + Union[Callable[[], Any], None], + Doc( + """ + A callable to generate the default value. + + This doesn't affect `Path` parameters as the value is always required. + The parameter is available only for compatibility. + """ + ), + ] = _Unset, + media_type: Annotated[ + str, + Doc( + """ + The media type of this parameter field. Changing it would affect the + generated OpenAPI, but currently it doesn't affect the parsing of the data. + """ + ), + ] = "application/x-www-form-urlencoded", + alias: Annotated[ + Optional[str], + Doc( + """ + An alternative name for the parameter field. + + This will be used to extract the data and for the generated OpenAPI. + It is particularly useful when you can't use the name you want because it + is a Python reserved keyword or similar. + """ + ), + ] = None, + alias_priority: Annotated[ + Union[int, None], + Doc( + """ + Priority of the alias. This affects whether an alias generator is used. + """ + ), + ] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Whitelist' validation step. The parameter field will be the single one + allowed by the alias or set of aliases defined. + """ + ), + ] = None, + serialization_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Blacklist' validation step. The vanilla parameter field will be the + single one of the alias' or set of aliases' fields and all the other + fields will be ignored at serialization time. + """ + ), + ] = None, + title: Annotated[ + Optional[str], + Doc( + """ + Human-readable title. + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Human-readable description. + """ + ), + ] = None, + gt: Annotated[ + Optional[float], + Doc( + """ + Greater than. If set, value must be greater than this. Only applicable to + numbers. + """ + ), + ] = None, + ge: Annotated[ + Optional[float], + Doc( + """ + Greater than or equal. If set, value must be greater than or equal to + this. Only applicable to numbers. + """ + ), + ] = None, + lt: Annotated[ + Optional[float], + Doc( + """ + Less than. If set, value must be less than this. Only applicable to numbers. + """ + ), + ] = None, + le: Annotated[ + Optional[float], + Doc( + """ + Less than or equal. If set, value must be less than or equal to this. + Only applicable to numbers. + """ + ), + ] = None, + min_length: Annotated[ + Optional[int], + Doc( + """ + Minimum length for strings. + """ + ), + ] = None, + max_length: Annotated[ + Optional[int], + Doc( + """ + Maximum length for strings. + """ + ), + ] = None, + pattern: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + ] = None, + regex: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Annotated[ + Union[str, None], + Doc( + """ + Parameter field name for discriminating the type in a tagged union. + """ + ), + ] = None, + strict: Annotated[ + Union[bool, None], + Doc( + """ + If `True`, strict validation is applied to the field. + """ + ), + ] = _Unset, + multiple_of: Annotated[ + Union[float, None], + Doc( + """ + Value must be a multiple of this. Only applicable to numbers. + """ + ), + ] = _Unset, + allow_inf_nan: Annotated[ + Union[bool, None], + Doc( + """ + Allow `inf`, `-inf`, `nan`. Only applicable to numbers. + """ + ), + ] = _Unset, + max_digits: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of allow digits for strings. + """ + ), + ] = _Unset, + decimal_places: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of decimal places allowed for numbers. + """ + ), + ] = _Unset, + examples: Annotated[ + Optional[List[Any]], + Doc( + """ + Example values for this field. + """ + ), + ] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Annotated[ + Optional[Dict[str, Example]], + Doc( + """ + OpenAPI-specific examples. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Swagger UI (that provides the `/docs` interface) has better support for the + OpenAPI-specific examples than the JSON Schema `examples`, that's the main + use case for this. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). + """ + ), + ] = None, + deprecated: Annotated[ + Union[deprecated, str, bool, None], + Doc( + """ + Mark this parameter field as deprecated. + + It will affect the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) this parameter field in the generated OpenAPI. + You probably don't need it, but it's available. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = True, + json_schema_extra: Annotated[ + Union[Dict[str, Any], None], + Doc( + """ + Any additional JSON schema data. + """ + ), + ] = None, + **extra: Annotated[ + Any, + Doc( + """ + Include extra fields used by the JSON Schema. + """ + ), + deprecated( + """ + The `extra` kwargs is deprecated. Use `json_schema_extra` instead. + """ + ), + ], +) -> Any: + return params.Form( + default=default, + default_factory=default_factory, + media_type=media_type, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + example=example, + examples=examples, + openapi_examples=openapi_examples, + deprecated=deprecated, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +def File( # noqa: N802 + default: Annotated[ + Any, + Doc( + """ + Default value if the parameter field is not set. + """ + ), + ] = Undefined, + *, + default_factory: Annotated[ + Union[Callable[[], Any], None], + Doc( + """ + A callable to generate the default value. + + This doesn't affect `Path` parameters as the value is always required. + The parameter is available only for compatibility. + """ + ), + ] = _Unset, + media_type: Annotated[ + str, + Doc( + """ + The media type of this parameter field. Changing it would affect the + generated OpenAPI, but currently it doesn't affect the parsing of the data. + """ + ), + ] = "multipart/form-data", + alias: Annotated[ + Optional[str], + Doc( + """ + An alternative name for the parameter field. + + This will be used to extract the data and for the generated OpenAPI. + It is particularly useful when you can't use the name you want because it + is a Python reserved keyword or similar. + """ + ), + ] = None, + alias_priority: Annotated[ + Union[int, None], + Doc( + """ + Priority of the alias. This affects whether an alias generator is used. + """ + ), + ] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Whitelist' validation step. The parameter field will be the single one + allowed by the alias or set of aliases defined. + """ + ), + ] = None, + serialization_alias: Annotated[ + Union[str, None], + Doc( + """ + 'Blacklist' validation step. The vanilla parameter field will be the + single one of the alias' or set of aliases' fields and all the other + fields will be ignored at serialization time. + """ + ), + ] = None, + title: Annotated[ + Optional[str], + Doc( + """ + Human-readable title. + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Human-readable description. + """ + ), + ] = None, + gt: Annotated[ + Optional[float], + Doc( + """ + Greater than. If set, value must be greater than this. Only applicable to + numbers. + """ + ), + ] = None, + ge: Annotated[ + Optional[float], + Doc( + """ + Greater than or equal. If set, value must be greater than or equal to + this. Only applicable to numbers. + """ + ), + ] = None, + lt: Annotated[ + Optional[float], + Doc( + """ + Less than. If set, value must be less than this. Only applicable to numbers. + """ + ), + ] = None, + le: Annotated[ + Optional[float], + Doc( + """ + Less than or equal. If set, value must be less than or equal to this. + Only applicable to numbers. + """ + ), + ] = None, + min_length: Annotated[ + Optional[int], + Doc( + """ + Minimum length for strings. + """ + ), + ] = None, + max_length: Annotated[ + Optional[int], + Doc( + """ + Maximum length for strings. + """ + ), + ] = None, + pattern: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + ] = None, + regex: Annotated[ + Optional[str], + Doc( + """ + RegEx pattern for strings. + """ + ), + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Annotated[ + Union[str, None], + Doc( + """ + Parameter field name for discriminating the type in a tagged union. + """ + ), + ] = None, + strict: Annotated[ + Union[bool, None], + Doc( + """ + If `True`, strict validation is applied to the field. + """ + ), + ] = _Unset, + multiple_of: Annotated[ + Union[float, None], + Doc( + """ + Value must be a multiple of this. Only applicable to numbers. + """ + ), + ] = _Unset, + allow_inf_nan: Annotated[ + Union[bool, None], + Doc( + """ + Allow `inf`, `-inf`, `nan`. Only applicable to numbers. + """ + ), + ] = _Unset, + max_digits: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of allow digits for strings. + """ + ), + ] = _Unset, + decimal_places: Annotated[ + Union[int, None], + Doc( + """ + Maximum number of decimal places allowed for numbers. + """ + ), + ] = _Unset, + examples: Annotated[ + Optional[List[Any]], + Doc( + """ + Example values for this field. + """ + ), + ] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Annotated[ + Optional[Dict[str, Example]], + Doc( + """ + OpenAPI-specific examples. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Swagger UI (that provides the `/docs` interface) has better support for the + OpenAPI-specific examples than the JSON Schema `examples`, that's the main + use case for this. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). + """ + ), + ] = None, + deprecated: Annotated[ + Union[deprecated, str, bool, None], + Doc( + """ + Mark this parameter field as deprecated. + + It will affect the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) this parameter field in the generated OpenAPI. + You probably don't need it, but it's available. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = True, + json_schema_extra: Annotated[ + Union[Dict[str, Any], None], + Doc( + """ + Any additional JSON schema data. + """ + ), + ] = None, + **extra: Annotated[ + Any, + Doc( + """ + Include extra fields used by the JSON Schema. + """ + ), + deprecated( + """ + The `extra` kwargs is deprecated. Use `json_schema_extra` instead. + """ + ), + ], +) -> Any: + return params.File( + default=default, + default_factory=default_factory, + media_type=media_type, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + example=example, + examples=examples, + openapi_examples=openapi_examples, + deprecated=deprecated, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +def Depends( # noqa: N802 + dependency: Annotated[ + Optional[Callable[..., Any]], + Doc( + """ + A "dependable" callable (like a function). + + Don't call it directly, FastAPI will call it for you, just pass the object + directly. + """ + ), + ] = None, + *, + use_cache: Annotated[ + bool, + Doc( + """ + By default, after a dependency is called the first time in a request, if + the dependency is declared again for the rest of the request (for example + if the dependency is needed by several dependencies), the value will be + re-used for the rest of the request. + + Set `use_cache` to `False` to disable this behavior and ensure the + dependency is called again (if declared more than once) in the same request. + """ + ), + ] = True, +) -> Any: + """ + Declare a FastAPI dependency. + + It takes a single "dependable" callable (like a function). + + Don't call it directly, FastAPI will call it for you. + + Read more about it in the + [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/). + + **Example** + + ```python + from typing import Annotated + + from fastapi import Depends, FastAPI + + app = FastAPI() + + + async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100): + return {"q": q, "skip": skip, "limit": limit} + + + @app.get("/items/") + async def read_items(commons: Annotated[dict, Depends(common_parameters)]): + return commons + ``` + """ + return params.Depends(dependency=dependency, use_cache=use_cache) + + +def Security( # noqa: N802 + dependency: Annotated[ + Optional[Callable[..., Any]], + Doc( + """ + A "dependable" callable (like a function). + + Don't call it directly, FastAPI will call it for you, just pass the object + directly. + """ + ), + ] = None, + *, + scopes: Annotated[ + Optional[Sequence[str]], + Doc( + """ + OAuth2 scopes required for the *path operation* that uses this Security + dependency. + + The term "scope" comes from the OAuth2 specification, it seems to be + intentionally vague and interpretable. It normally refers to permissions, + in cases to roles. + + These scopes are integrated with OpenAPI (and the API docs at `/docs`). + So they are visible in the OpenAPI specification. + ) + """ + ), + ] = None, + use_cache: Annotated[ + bool, + Doc( + """ + By default, after a dependency is called the first time in a request, if + the dependency is declared again for the rest of the request (for example + if the dependency is needed by several dependencies), the value will be + re-used for the rest of the request. + + Set `use_cache` to `False` to disable this behavior and ensure the + dependency is called again (if declared more than once) in the same request. + """ + ), + ] = True, +) -> Any: + """ + Declare a FastAPI Security dependency. + + The only difference with a regular dependency is that it can declare OAuth2 + scopes that will be integrated with OpenAPI and the automatic UI docs (by default + at `/docs`). + + It takes a single "dependable" callable (like a function). + + Don't call it directly, FastAPI will call it for you. + + Read more about it in the + [FastAPI docs for Security](https://fastapi.tiangolo.com/tutorial/security/) and + in the + [FastAPI docs for OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/). + + **Example** + + ```python + from typing import Annotated + + from fastapi import Security, FastAPI + + from .db import User + from .security import get_current_active_user + + app = FastAPI() + + @app.get("/users/me/items/") + async def read_own_items( + current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])] + ): + return [{"item_id": "Foo", "owner": current_user.username}] + ``` + """ + return params.Security(dependency=dependency, scopes=scopes, use_cache=use_cache) diff --git a/venv/Lib/site-packages/fastapi/params.py b/venv/Lib/site-packages/fastapi/params.py new file mode 100644 index 00000000..8f5601dd --- /dev/null +++ b/venv/Lib/site-packages/fastapi/params.py @@ -0,0 +1,786 @@ +import warnings +from enum import Enum +from typing import Any, Callable, Dict, List, Optional, Sequence, Union + +from fastapi.openapi.models import Example +from pydantic.fields import FieldInfo +from typing_extensions import Annotated, deprecated + +from ._compat import ( + PYDANTIC_V2, + PYDANTIC_VERSION_MINOR_TUPLE, + Undefined, +) + +_Unset: Any = Undefined + + +class ParamTypes(Enum): + query = "query" + header = "header" + path = "path" + cookie = "cookie" + + +class Param(FieldInfo): + in_: ParamTypes + + def __init__( + self, + default: Any = Undefined, + *, + default_factory: Union[Callable[[], Any], None] = _Unset, + annotation: Optional[Any] = None, + alias: Optional[str] = None, + alias_priority: Union[int, None] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Union[str, None] = None, + serialization_alias: Union[str, None] = None, + title: Optional[str] = None, + description: Optional[str] = None, + gt: Optional[float] = None, + ge: Optional[float] = None, + lt: Optional[float] = None, + le: Optional[float] = None, + min_length: Optional[int] = None, + max_length: Optional[int] = None, + pattern: Optional[str] = None, + regex: Annotated[ + Optional[str], + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Union[str, None] = None, + strict: Union[bool, None] = _Unset, + multiple_of: Union[float, None] = _Unset, + allow_inf_nan: Union[bool, None] = _Unset, + max_digits: Union[int, None] = _Unset, + decimal_places: Union[int, None] = _Unset, + examples: Optional[List[Any]] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Optional[Dict[str, Example]] = None, + deprecated: Union[deprecated, str, bool, None] = None, + include_in_schema: bool = True, + json_schema_extra: Union[Dict[str, Any], None] = None, + **extra: Any, + ): + if example is not _Unset: + warnings.warn( + "`example` has been deprecated, please use `examples` instead", + category=DeprecationWarning, + stacklevel=4, + ) + self.example = example + self.include_in_schema = include_in_schema + self.openapi_examples = openapi_examples + kwargs = dict( + default=default, + default_factory=default_factory, + alias=alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + discriminator=discriminator, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + **extra, + ) + if examples is not None: + kwargs["examples"] = examples + if regex is not None: + warnings.warn( + "`regex` has been deprecated, please use `pattern` instead", + category=DeprecationWarning, + stacklevel=4, + ) + current_json_schema_extra = json_schema_extra or extra + if PYDANTIC_VERSION_MINOR_TUPLE < (2, 7): + self.deprecated = deprecated + else: + kwargs["deprecated"] = deprecated + if PYDANTIC_V2: + kwargs.update( + { + "annotation": annotation, + "alias_priority": alias_priority, + "validation_alias": validation_alias, + "serialization_alias": serialization_alias, + "strict": strict, + "json_schema_extra": current_json_schema_extra, + } + ) + kwargs["pattern"] = pattern or regex + else: + kwargs["regex"] = pattern or regex + kwargs.update(**current_json_schema_extra) + use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset} + + super().__init__(**use_kwargs) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.default})" + + +class Path(Param): + in_ = ParamTypes.path + + def __init__( + self, + default: Any = ..., + *, + default_factory: Union[Callable[[], Any], None] = _Unset, + annotation: Optional[Any] = None, + alias: Optional[str] = None, + alias_priority: Union[int, None] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Union[str, None] = None, + serialization_alias: Union[str, None] = None, + title: Optional[str] = None, + description: Optional[str] = None, + gt: Optional[float] = None, + ge: Optional[float] = None, + lt: Optional[float] = None, + le: Optional[float] = None, + min_length: Optional[int] = None, + max_length: Optional[int] = None, + pattern: Optional[str] = None, + regex: Annotated[ + Optional[str], + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Union[str, None] = None, + strict: Union[bool, None] = _Unset, + multiple_of: Union[float, None] = _Unset, + allow_inf_nan: Union[bool, None] = _Unset, + max_digits: Union[int, None] = _Unset, + decimal_places: Union[int, None] = _Unset, + examples: Optional[List[Any]] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Optional[Dict[str, Example]] = None, + deprecated: Union[deprecated, str, bool, None] = None, + include_in_schema: bool = True, + json_schema_extra: Union[Dict[str, Any], None] = None, + **extra: Any, + ): + assert default is ..., "Path parameters cannot have a default value" + self.in_ = self.in_ + super().__init__( + default=default, + default_factory=default_factory, + annotation=annotation, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + deprecated=deprecated, + example=example, + examples=examples, + openapi_examples=openapi_examples, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +class Query(Param): + in_ = ParamTypes.query + + def __init__( + self, + default: Any = Undefined, + *, + default_factory: Union[Callable[[], Any], None] = _Unset, + annotation: Optional[Any] = None, + alias: Optional[str] = None, + alias_priority: Union[int, None] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Union[str, None] = None, + serialization_alias: Union[str, None] = None, + title: Optional[str] = None, + description: Optional[str] = None, + gt: Optional[float] = None, + ge: Optional[float] = None, + lt: Optional[float] = None, + le: Optional[float] = None, + min_length: Optional[int] = None, + max_length: Optional[int] = None, + pattern: Optional[str] = None, + regex: Annotated[ + Optional[str], + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Union[str, None] = None, + strict: Union[bool, None] = _Unset, + multiple_of: Union[float, None] = _Unset, + allow_inf_nan: Union[bool, None] = _Unset, + max_digits: Union[int, None] = _Unset, + decimal_places: Union[int, None] = _Unset, + examples: Optional[List[Any]] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Optional[Dict[str, Example]] = None, + deprecated: Union[deprecated, str, bool, None] = None, + include_in_schema: bool = True, + json_schema_extra: Union[Dict[str, Any], None] = None, + **extra: Any, + ): + super().__init__( + default=default, + default_factory=default_factory, + annotation=annotation, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + deprecated=deprecated, + example=example, + examples=examples, + openapi_examples=openapi_examples, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +class Header(Param): + in_ = ParamTypes.header + + def __init__( + self, + default: Any = Undefined, + *, + default_factory: Union[Callable[[], Any], None] = _Unset, + annotation: Optional[Any] = None, + alias: Optional[str] = None, + alias_priority: Union[int, None] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Union[str, None] = None, + serialization_alias: Union[str, None] = None, + convert_underscores: bool = True, + title: Optional[str] = None, + description: Optional[str] = None, + gt: Optional[float] = None, + ge: Optional[float] = None, + lt: Optional[float] = None, + le: Optional[float] = None, + min_length: Optional[int] = None, + max_length: Optional[int] = None, + pattern: Optional[str] = None, + regex: Annotated[ + Optional[str], + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Union[str, None] = None, + strict: Union[bool, None] = _Unset, + multiple_of: Union[float, None] = _Unset, + allow_inf_nan: Union[bool, None] = _Unset, + max_digits: Union[int, None] = _Unset, + decimal_places: Union[int, None] = _Unset, + examples: Optional[List[Any]] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Optional[Dict[str, Example]] = None, + deprecated: Union[deprecated, str, bool, None] = None, + include_in_schema: bool = True, + json_schema_extra: Union[Dict[str, Any], None] = None, + **extra: Any, + ): + self.convert_underscores = convert_underscores + super().__init__( + default=default, + default_factory=default_factory, + annotation=annotation, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + deprecated=deprecated, + example=example, + examples=examples, + openapi_examples=openapi_examples, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +class Cookie(Param): + in_ = ParamTypes.cookie + + def __init__( + self, + default: Any = Undefined, + *, + default_factory: Union[Callable[[], Any], None] = _Unset, + annotation: Optional[Any] = None, + alias: Optional[str] = None, + alias_priority: Union[int, None] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Union[str, None] = None, + serialization_alias: Union[str, None] = None, + title: Optional[str] = None, + description: Optional[str] = None, + gt: Optional[float] = None, + ge: Optional[float] = None, + lt: Optional[float] = None, + le: Optional[float] = None, + min_length: Optional[int] = None, + max_length: Optional[int] = None, + pattern: Optional[str] = None, + regex: Annotated[ + Optional[str], + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Union[str, None] = None, + strict: Union[bool, None] = _Unset, + multiple_of: Union[float, None] = _Unset, + allow_inf_nan: Union[bool, None] = _Unset, + max_digits: Union[int, None] = _Unset, + decimal_places: Union[int, None] = _Unset, + examples: Optional[List[Any]] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Optional[Dict[str, Example]] = None, + deprecated: Union[deprecated, str, bool, None] = None, + include_in_schema: bool = True, + json_schema_extra: Union[Dict[str, Any], None] = None, + **extra: Any, + ): + super().__init__( + default=default, + default_factory=default_factory, + annotation=annotation, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + deprecated=deprecated, + example=example, + examples=examples, + openapi_examples=openapi_examples, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +class Body(FieldInfo): + def __init__( + self, + default: Any = Undefined, + *, + default_factory: Union[Callable[[], Any], None] = _Unset, + annotation: Optional[Any] = None, + embed: Union[bool, None] = None, + media_type: str = "application/json", + alias: Optional[str] = None, + alias_priority: Union[int, None] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Union[str, None] = None, + serialization_alias: Union[str, None] = None, + title: Optional[str] = None, + description: Optional[str] = None, + gt: Optional[float] = None, + ge: Optional[float] = None, + lt: Optional[float] = None, + le: Optional[float] = None, + min_length: Optional[int] = None, + max_length: Optional[int] = None, + pattern: Optional[str] = None, + regex: Annotated[ + Optional[str], + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Union[str, None] = None, + strict: Union[bool, None] = _Unset, + multiple_of: Union[float, None] = _Unset, + allow_inf_nan: Union[bool, None] = _Unset, + max_digits: Union[int, None] = _Unset, + decimal_places: Union[int, None] = _Unset, + examples: Optional[List[Any]] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Optional[Dict[str, Example]] = None, + deprecated: Union[deprecated, str, bool, None] = None, + include_in_schema: bool = True, + json_schema_extra: Union[Dict[str, Any], None] = None, + **extra: Any, + ): + self.embed = embed + self.media_type = media_type + if example is not _Unset: + warnings.warn( + "`example` has been deprecated, please use `examples` instead", + category=DeprecationWarning, + stacklevel=4, + ) + self.example = example + self.include_in_schema = include_in_schema + self.openapi_examples = openapi_examples + kwargs = dict( + default=default, + default_factory=default_factory, + alias=alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + discriminator=discriminator, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + **extra, + ) + if examples is not None: + kwargs["examples"] = examples + if regex is not None: + warnings.warn( + "`regex` has been deprecated, please use `pattern` instead", + category=DeprecationWarning, + stacklevel=4, + ) + current_json_schema_extra = json_schema_extra or extra + if PYDANTIC_VERSION_MINOR_TUPLE < (2, 7): + self.deprecated = deprecated + else: + kwargs["deprecated"] = deprecated + if PYDANTIC_V2: + kwargs.update( + { + "annotation": annotation, + "alias_priority": alias_priority, + "validation_alias": validation_alias, + "serialization_alias": serialization_alias, + "strict": strict, + "json_schema_extra": current_json_schema_extra, + } + ) + kwargs["pattern"] = pattern or regex + else: + kwargs["regex"] = pattern or regex + kwargs.update(**current_json_schema_extra) + + use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset} + + super().__init__(**use_kwargs) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.default})" + + +class Form(Body): + def __init__( + self, + default: Any = Undefined, + *, + default_factory: Union[Callable[[], Any], None] = _Unset, + annotation: Optional[Any] = None, + media_type: str = "application/x-www-form-urlencoded", + alias: Optional[str] = None, + alias_priority: Union[int, None] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Union[str, None] = None, + serialization_alias: Union[str, None] = None, + title: Optional[str] = None, + description: Optional[str] = None, + gt: Optional[float] = None, + ge: Optional[float] = None, + lt: Optional[float] = None, + le: Optional[float] = None, + min_length: Optional[int] = None, + max_length: Optional[int] = None, + pattern: Optional[str] = None, + regex: Annotated[ + Optional[str], + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Union[str, None] = None, + strict: Union[bool, None] = _Unset, + multiple_of: Union[float, None] = _Unset, + allow_inf_nan: Union[bool, None] = _Unset, + max_digits: Union[int, None] = _Unset, + decimal_places: Union[int, None] = _Unset, + examples: Optional[List[Any]] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Optional[Dict[str, Example]] = None, + deprecated: Union[deprecated, str, bool, None] = None, + include_in_schema: bool = True, + json_schema_extra: Union[Dict[str, Any], None] = None, + **extra: Any, + ): + super().__init__( + default=default, + default_factory=default_factory, + annotation=annotation, + media_type=media_type, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + deprecated=deprecated, + example=example, + examples=examples, + openapi_examples=openapi_examples, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +class File(Form): + def __init__( + self, + default: Any = Undefined, + *, + default_factory: Union[Callable[[], Any], None] = _Unset, + annotation: Optional[Any] = None, + media_type: str = "multipart/form-data", + alias: Optional[str] = None, + alias_priority: Union[int, None] = _Unset, + # TODO: update when deprecating Pydantic v1, import these types + # validation_alias: str | AliasPath | AliasChoices | None + validation_alias: Union[str, None] = None, + serialization_alias: Union[str, None] = None, + title: Optional[str] = None, + description: Optional[str] = None, + gt: Optional[float] = None, + ge: Optional[float] = None, + lt: Optional[float] = None, + le: Optional[float] = None, + min_length: Optional[int] = None, + max_length: Optional[int] = None, + pattern: Optional[str] = None, + regex: Annotated[ + Optional[str], + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Union[str, None] = None, + strict: Union[bool, None] = _Unset, + multiple_of: Union[float, None] = _Unset, + allow_inf_nan: Union[bool, None] = _Unset, + max_digits: Union[int, None] = _Unset, + decimal_places: Union[int, None] = _Unset, + examples: Optional[List[Any]] = None, + example: Annotated[ + Optional[Any], + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Optional[Dict[str, Example]] = None, + deprecated: Union[deprecated, str, bool, None] = None, + include_in_schema: bool = True, + json_schema_extra: Union[Dict[str, Any], None] = None, + **extra: Any, + ): + super().__init__( + default=default, + default_factory=default_factory, + annotation=annotation, + media_type=media_type, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + deprecated=deprecated, + example=example, + examples=examples, + openapi_examples=openapi_examples, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +class Depends: + def __init__( + self, dependency: Optional[Callable[..., Any]] = None, *, use_cache: bool = True + ): + self.dependency = dependency + self.use_cache = use_cache + + def __repr__(self) -> str: + attr = getattr(self.dependency, "__name__", type(self.dependency).__name__) + cache = "" if self.use_cache else ", use_cache=False" + return f"{self.__class__.__name__}({attr}{cache})" + + +class Security(Depends): + def __init__( + self, + dependency: Optional[Callable[..., Any]] = None, + *, + scopes: Optional[Sequence[str]] = None, + use_cache: bool = True, + ): + super().__init__(dependency=dependency, use_cache=use_cache) + self.scopes = scopes or [] diff --git a/venv/Lib/site-packages/fastapi/py.typed b/venv/Lib/site-packages/fastapi/py.typed new file mode 100644 index 00000000..e69de29b diff --git a/venv/Lib/site-packages/fastapi/requests.py b/venv/Lib/site-packages/fastapi/requests.py new file mode 100644 index 00000000..d16552c0 --- /dev/null +++ b/venv/Lib/site-packages/fastapi/requests.py @@ -0,0 +1,2 @@ +from starlette.requests import HTTPConnection as HTTPConnection # noqa: F401 +from starlette.requests import Request as Request # noqa: F401 diff --git a/venv/Lib/site-packages/fastapi/responses.py b/venv/Lib/site-packages/fastapi/responses.py new file mode 100644 index 00000000..6c8db6f3 --- /dev/null +++ b/venv/Lib/site-packages/fastapi/responses.py @@ -0,0 +1,48 @@ +from typing import Any + +from starlette.responses import FileResponse as FileResponse # noqa +from starlette.responses import HTMLResponse as HTMLResponse # noqa +from starlette.responses import JSONResponse as JSONResponse # noqa +from starlette.responses import PlainTextResponse as PlainTextResponse # noqa +from starlette.responses import RedirectResponse as RedirectResponse # noqa +from starlette.responses import Response as Response # noqa +from starlette.responses import StreamingResponse as StreamingResponse # noqa + +try: + import ujson +except ImportError: # pragma: nocover + ujson = None # type: ignore + + +try: + import orjson +except ImportError: # pragma: nocover + orjson = None # type: ignore + + +class UJSONResponse(JSONResponse): + """ + JSON response using the high-performance ujson library to serialize data to JSON. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/). + """ + + def render(self, content: Any) -> bytes: + assert ujson is not None, "ujson must be installed to use UJSONResponse" + return ujson.dumps(content, ensure_ascii=False).encode("utf-8") + + +class ORJSONResponse(JSONResponse): + """ + JSON response using the high-performance orjson library to serialize data to JSON. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/). + """ + + def render(self, content: Any) -> bytes: + assert orjson is not None, "orjson must be installed to use ORJSONResponse" + return orjson.dumps( + content, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY + ) diff --git a/venv/Lib/site-packages/fastapi/routing.py b/venv/Lib/site-packages/fastapi/routing.py new file mode 100644 index 00000000..bf61a65c --- /dev/null +++ b/venv/Lib/site-packages/fastapi/routing.py @@ -0,0 +1,4439 @@ +import asyncio +import dataclasses +import email.message +import inspect +import json +from contextlib import AsyncExitStack, asynccontextmanager +from enum import Enum, IntEnum +from typing import ( + Any, + AsyncIterator, + Callable, + Coroutine, + Dict, + List, + Mapping, + Optional, + Sequence, + Set, + Tuple, + Type, + Union, +) + +from fastapi import params +from fastapi._compat import ( + ModelField, + Undefined, + _get_model_config, + _model_dump, + _normalize_errors, + lenient_issubclass, +) +from fastapi.datastructures import Default, DefaultPlaceholder +from fastapi.dependencies.models import Dependant +from fastapi.dependencies.utils import ( + _should_embed_body_fields, + get_body_field, + get_dependant, + get_flat_dependant, + get_parameterless_sub_dependant, + get_typed_return_annotation, + solve_dependencies, +) +from fastapi.encoders import jsonable_encoder +from fastapi.exceptions import ( + FastAPIError, + RequestValidationError, + ResponseValidationError, + WebSocketRequestValidationError, +) +from fastapi.types import DecoratedCallable, IncEx +from fastapi.utils import ( + create_cloned_field, + create_model_field, + generate_unique_id, + get_value_or_default, + is_body_allowed_for_status_code, +) +from pydantic import BaseModel +from starlette import routing +from starlette.concurrency import run_in_threadpool +from starlette.exceptions import HTTPException +from starlette.requests import Request +from starlette.responses import JSONResponse, Response +from starlette.routing import ( + BaseRoute, + Match, + compile_path, + get_name, + request_response, + websocket_session, +) +from starlette.routing import Mount as Mount # noqa +from starlette.types import AppType, ASGIApp, Lifespan, Scope +from starlette.websockets import WebSocket +from typing_extensions import Annotated, Doc, deprecated + + +def _prepare_response_content( + res: Any, + *, + exclude_unset: bool, + exclude_defaults: bool = False, + exclude_none: bool = False, +) -> Any: + if isinstance(res, BaseModel): + read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) + if read_with_orm_mode: + # Let from_orm extract the data from this model instead of converting + # it now to a dict. + # Otherwise, there's no way to extract lazy data that requires attribute + # access instead of dict iteration, e.g. lazy relationships. + return res + return _model_dump( + res, + by_alias=True, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + elif isinstance(res, list): + return [ + _prepare_response_content( + item, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + for item in res + ] + elif isinstance(res, dict): + return { + k: _prepare_response_content( + v, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + for k, v in res.items() + } + elif dataclasses.is_dataclass(res): + return dataclasses.asdict(res) + return res + + +def _merge_lifespan_context( + original_context: Lifespan[Any], nested_context: Lifespan[Any] +) -> Lifespan[Any]: + @asynccontextmanager + async def merged_lifespan( + app: AppType, + ) -> AsyncIterator[Optional[Mapping[str, Any]]]: + async with original_context(app) as maybe_original_state: + async with nested_context(app) as maybe_nested_state: + if maybe_nested_state is None and maybe_original_state is None: + yield None # old ASGI compatibility + else: + yield {**(maybe_nested_state or {}), **(maybe_original_state or {})} + + return merged_lifespan # type: ignore[return-value] + + +async def serialize_response( + *, + field: Optional[ModelField] = None, + response_content: Any, + include: Optional[IncEx] = None, + exclude: Optional[IncEx] = None, + by_alias: bool = True, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + is_coroutine: bool = True, +) -> Any: + if field: + errors = [] + if not hasattr(field, "serialize"): + # pydantic v1 + response_content = _prepare_response_content( + response_content, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + if is_coroutine: + value, errors_ = field.validate(response_content, {}, loc=("response",)) + else: + value, errors_ = await run_in_threadpool( + field.validate, response_content, {}, loc=("response",) + ) + if isinstance(errors_, list): + errors.extend(errors_) + elif errors_: + errors.append(errors_) + if errors: + raise ResponseValidationError( + errors=_normalize_errors(errors), body=response_content + ) + + if hasattr(field, "serialize"): + return field.serialize( + value, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + + return jsonable_encoder( + value, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + else: + return jsonable_encoder(response_content) + + +async def run_endpoint_function( + *, dependant: Dependant, values: Dict[str, Any], is_coroutine: bool +) -> Any: + # Only called by get_request_handler. Has been split into its own function to + # facilitate profiling endpoints, since inner functions are harder to profile. + assert dependant.call is not None, "dependant.call must be a function" + + if is_coroutine: + return await dependant.call(**values) + else: + return await run_in_threadpool(dependant.call, **values) + + +def get_request_handler( + dependant: Dependant, + body_field: Optional[ModelField] = None, + status_code: Optional[int] = None, + response_class: Union[Type[Response], DefaultPlaceholder] = Default(JSONResponse), + response_field: Optional[ModelField] = None, + response_model_include: Optional[IncEx] = None, + response_model_exclude: Optional[IncEx] = None, + response_model_by_alias: bool = True, + response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, + dependency_overrides_provider: Optional[Any] = None, + embed_body_fields: bool = False, +) -> Callable[[Request], Coroutine[Any, Any, Response]]: + assert dependant.call is not None, "dependant.call must be a function" + is_coroutine = asyncio.iscoroutinefunction(dependant.call) + is_body_form = body_field and isinstance(body_field.field_info, params.Form) + if isinstance(response_class, DefaultPlaceholder): + actual_response_class: Type[Response] = response_class.value + else: + actual_response_class = response_class + + async def app(request: Request) -> Response: + response: Union[Response, None] = None + async with AsyncExitStack() as file_stack: + try: + body: Any = None + if body_field: + if is_body_form: + body = await request.form() + file_stack.push_async_callback(body.close) + else: + body_bytes = await request.body() + if body_bytes: + json_body: Any = Undefined + content_type_value = request.headers.get("content-type") + if not content_type_value: + json_body = await request.json() + else: + message = email.message.Message() + message["content-type"] = content_type_value + if message.get_content_maintype() == "application": + subtype = message.get_content_subtype() + if subtype == "json" or subtype.endswith("+json"): + json_body = await request.json() + if json_body != Undefined: + body = json_body + else: + body = body_bytes + except json.JSONDecodeError as e: + validation_error = RequestValidationError( + [ + { + "type": "json_invalid", + "loc": ("body", e.pos), + "msg": "JSON decode error", + "input": {}, + "ctx": {"error": e.msg}, + } + ], + body=e.doc, + ) + raise validation_error from e + except HTTPException: + # If a middleware raises an HTTPException, it should be raised again + raise + except Exception as e: + http_error = HTTPException( + status_code=400, detail="There was an error parsing the body" + ) + raise http_error from e + errors: List[Any] = [] + async with AsyncExitStack() as async_exit_stack: + solved_result = await solve_dependencies( + request=request, + dependant=dependant, + body=body, + dependency_overrides_provider=dependency_overrides_provider, + async_exit_stack=async_exit_stack, + embed_body_fields=embed_body_fields, + ) + errors = solved_result.errors + if not errors: + raw_response = await run_endpoint_function( + dependant=dependant, + values=solved_result.values, + is_coroutine=is_coroutine, + ) + if isinstance(raw_response, Response): + if raw_response.background is None: + raw_response.background = solved_result.background_tasks + response = raw_response + else: + response_args: Dict[str, Any] = { + "background": solved_result.background_tasks + } + # If status_code was set, use it, otherwise use the default from the + # response class, in the case of redirect it's 307 + current_status_code = ( + status_code + if status_code + else solved_result.response.status_code + ) + if current_status_code is not None: + response_args["status_code"] = current_status_code + if solved_result.response.status_code: + response_args["status_code"] = ( + solved_result.response.status_code + ) + content = await serialize_response( + field=response_field, + response_content=raw_response, + include=response_model_include, + exclude=response_model_exclude, + by_alias=response_model_by_alias, + exclude_unset=response_model_exclude_unset, + exclude_defaults=response_model_exclude_defaults, + exclude_none=response_model_exclude_none, + is_coroutine=is_coroutine, + ) + response = actual_response_class(content, **response_args) + if not is_body_allowed_for_status_code(response.status_code): + response.body = b"" + response.headers.raw.extend(solved_result.response.headers.raw) + if errors: + validation_error = RequestValidationError( + _normalize_errors(errors), body=body + ) + raise validation_error + if response is None: + raise FastAPIError( + "No response object was returned. There's a high chance that the " + "application code is raising an exception and a dependency with yield " + "has a block with a bare except, or a block with except Exception, " + "and is not raising the exception again. Read more about it in the " + "docs: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-except" + ) + return response + + return app + + +def get_websocket_app( + dependant: Dependant, + dependency_overrides_provider: Optional[Any] = None, + embed_body_fields: bool = False, +) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]: + async def app(websocket: WebSocket) -> None: + async with AsyncExitStack() as async_exit_stack: + # TODO: remove this scope later, after a few releases + # This scope fastapi_astack is no longer used by FastAPI, kept for + # compatibility, just in case + websocket.scope["fastapi_astack"] = async_exit_stack + solved_result = await solve_dependencies( + request=websocket, + dependant=dependant, + dependency_overrides_provider=dependency_overrides_provider, + async_exit_stack=async_exit_stack, + embed_body_fields=embed_body_fields, + ) + if solved_result.errors: + raise WebSocketRequestValidationError( + _normalize_errors(solved_result.errors) + ) + assert dependant.call is not None, "dependant.call must be a function" + await dependant.call(**solved_result.values) + + return app + + +class APIWebSocketRoute(routing.WebSocketRoute): + def __init__( + self, + path: str, + endpoint: Callable[..., Any], + *, + name: Optional[str] = None, + dependencies: Optional[Sequence[params.Depends]] = None, + dependency_overrides_provider: Optional[Any] = None, + ) -> None: + self.path = path + self.endpoint = endpoint + self.name = get_name(endpoint) if name is None else name + self.dependencies = list(dependencies or []) + self.path_regex, self.path_format, self.param_convertors = compile_path(path) + self.dependant = get_dependant(path=self.path_format, call=self.endpoint) + for depends in self.dependencies[::-1]: + self.dependant.dependencies.insert( + 0, + get_parameterless_sub_dependant(depends=depends, path=self.path_format), + ) + self._flat_dependant = get_flat_dependant(self.dependant) + self._embed_body_fields = _should_embed_body_fields( + self._flat_dependant.body_params + ) + self.app = websocket_session( + get_websocket_app( + dependant=self.dependant, + dependency_overrides_provider=dependency_overrides_provider, + embed_body_fields=self._embed_body_fields, + ) + ) + + def matches(self, scope: Scope) -> Tuple[Match, Scope]: + match, child_scope = super().matches(scope) + if match != Match.NONE: + child_scope["route"] = self + return match, child_scope + + +class APIRoute(routing.Route): + def __init__( + self, + path: str, + endpoint: Callable[..., Any], + *, + response_model: Any = Default(None), + status_code: Optional[int] = None, + tags: Optional[List[Union[str, Enum]]] = None, + dependencies: Optional[Sequence[params.Depends]] = None, + summary: Optional[str] = None, + description: Optional[str] = None, + response_description: str = "Successful Response", + responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, + deprecated: Optional[bool] = None, + name: Optional[str] = None, + methods: Optional[Union[Set[str], List[str]]] = None, + operation_id: Optional[str] = None, + response_model_include: Optional[IncEx] = None, + response_model_exclude: Optional[IncEx] = None, + response_model_by_alias: bool = True, + response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, + include_in_schema: bool = True, + response_class: Union[Type[Response], DefaultPlaceholder] = Default( + JSONResponse + ), + dependency_overrides_provider: Optional[Any] = None, + callbacks: Optional[List[BaseRoute]] = None, + openapi_extra: Optional[Dict[str, Any]] = None, + generate_unique_id_function: Union[ + Callable[["APIRoute"], str], DefaultPlaceholder + ] = Default(generate_unique_id), + ) -> None: + self.path = path + self.endpoint = endpoint + if isinstance(response_model, DefaultPlaceholder): + return_annotation = get_typed_return_annotation(endpoint) + if lenient_issubclass(return_annotation, Response): + response_model = None + else: + response_model = return_annotation + self.response_model = response_model + self.summary = summary + self.response_description = response_description + self.deprecated = deprecated + self.operation_id = operation_id + self.response_model_include = response_model_include + self.response_model_exclude = response_model_exclude + self.response_model_by_alias = response_model_by_alias + self.response_model_exclude_unset = response_model_exclude_unset + self.response_model_exclude_defaults = response_model_exclude_defaults + self.response_model_exclude_none = response_model_exclude_none + self.include_in_schema = include_in_schema + self.response_class = response_class + self.dependency_overrides_provider = dependency_overrides_provider + self.callbacks = callbacks + self.openapi_extra = openapi_extra + self.generate_unique_id_function = generate_unique_id_function + self.tags = tags or [] + self.responses = responses or {} + self.name = get_name(endpoint) if name is None else name + self.path_regex, self.path_format, self.param_convertors = compile_path(path) + if methods is None: + methods = ["GET"] + self.methods: Set[str] = {method.upper() for method in methods} + if isinstance(generate_unique_id_function, DefaultPlaceholder): + current_generate_unique_id: Callable[[APIRoute], str] = ( + generate_unique_id_function.value + ) + else: + current_generate_unique_id = generate_unique_id_function + self.unique_id = self.operation_id or current_generate_unique_id(self) + # normalize enums e.g. http.HTTPStatus + if isinstance(status_code, IntEnum): + status_code = int(status_code) + self.status_code = status_code + if self.response_model: + assert is_body_allowed_for_status_code(status_code), ( + f"Status code {status_code} must not have a response body" + ) + response_name = "Response_" + self.unique_id + self.response_field = create_model_field( + name=response_name, + type_=self.response_model, + mode="serialization", + ) + # Create a clone of the field, so that a Pydantic submodel is not returned + # as is just because it's an instance of a subclass of a more limited class + # e.g. UserInDB (containing hashed_password) could be a subclass of User + # that doesn't have the hashed_password. But because it's a subclass, it + # would pass the validation and be returned as is. + # By being a new field, no inheritance will be passed as is. A new model + # will always be created. + # TODO: remove when deprecating Pydantic v1 + self.secure_cloned_response_field: Optional[ModelField] = ( + create_cloned_field(self.response_field) + ) + else: + self.response_field = None # type: ignore + self.secure_cloned_response_field = None + self.dependencies = list(dependencies or []) + self.description = description or inspect.cleandoc(self.endpoint.__doc__ or "") + # if a "form feed" character (page break) is found in the description text, + # truncate description text to the content preceding the first "form feed" + self.description = self.description.split("\f")[0].strip() + response_fields = {} + for additional_status_code, response in self.responses.items(): + assert isinstance(response, dict), "An additional response must be a dict" + model = response.get("model") + if model: + assert is_body_allowed_for_status_code(additional_status_code), ( + f"Status code {additional_status_code} must not have a response body" + ) + response_name = f"Response_{additional_status_code}_{self.unique_id}" + response_field = create_model_field( + name=response_name, type_=model, mode="serialization" + ) + response_fields[additional_status_code] = response_field + if response_fields: + self.response_fields: Dict[Union[int, str], ModelField] = response_fields + else: + self.response_fields = {} + + assert callable(endpoint), "An endpoint must be a callable" + self.dependant = get_dependant(path=self.path_format, call=self.endpoint) + for depends in self.dependencies[::-1]: + self.dependant.dependencies.insert( + 0, + get_parameterless_sub_dependant(depends=depends, path=self.path_format), + ) + self._flat_dependant = get_flat_dependant(self.dependant) + self._embed_body_fields = _should_embed_body_fields( + self._flat_dependant.body_params + ) + self.body_field = get_body_field( + flat_dependant=self._flat_dependant, + name=self.unique_id, + embed_body_fields=self._embed_body_fields, + ) + self.app = request_response(self.get_route_handler()) + + def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]: + return get_request_handler( + dependant=self.dependant, + body_field=self.body_field, + status_code=self.status_code, + response_class=self.response_class, + response_field=self.secure_cloned_response_field, + response_model_include=self.response_model_include, + response_model_exclude=self.response_model_exclude, + response_model_by_alias=self.response_model_by_alias, + response_model_exclude_unset=self.response_model_exclude_unset, + response_model_exclude_defaults=self.response_model_exclude_defaults, + response_model_exclude_none=self.response_model_exclude_none, + dependency_overrides_provider=self.dependency_overrides_provider, + embed_body_fields=self._embed_body_fields, + ) + + def matches(self, scope: Scope) -> Tuple[Match, Scope]: + match, child_scope = super().matches(scope) + if match != Match.NONE: + child_scope["route"] = self + return match, child_scope + + +class APIRouter(routing.Router): + """ + `APIRouter` class, used to group *path operations*, for example to structure + an app in multiple files. It would then be included in the `FastAPI` app, or + in another `APIRouter` (ultimately included in the app). + + Read more about it in the + [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/). + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + + app = FastAPI() + router = APIRouter() + + + @router.get("/users/", tags=["users"]) + async def read_users(): + return [{"username": "Rick"}, {"username": "Morty"}] + + + app.include_router(router) + ``` + """ + + def __init__( + self, + *, + prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "", + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to all the *path operations* in this + router. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[params.Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to all the + *path operations* in this router. + + Read more about it in the + [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). + """ + ), + ] = None, + default_response_class: Annotated[ + Type[Response], + Doc( + """ + The default response class to be used. + + Read more in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class). + """ + ), + ] = Default(JSONResponse), + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses to be shown in OpenAPI. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/). + + And in the + [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + OpenAPI callbacks that should apply to all *path operations* in this + router. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + routes: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Starlette and supported for compatibility. + + --- + + A list of routes to serve incoming HTTP and WebSocket requests. + """ + ), + deprecated( + """ + You normally wouldn't use this parameter with FastAPI, it is inherited + from Starlette and supported for compatibility. + + In FastAPI, you normally would use the *path operation methods*, + like `router.get()`, `router.post()`, etc. + """ + ), + ] = None, + redirect_slashes: Annotated[ + bool, + Doc( + """ + Whether to detect and redirect slashes in URLs when the client doesn't + use the same format. + """ + ), + ] = True, + default: Annotated[ + Optional[ASGIApp], + Doc( + """ + Default function handler for this router. Used to handle + 404 Not Found errors. + """ + ), + ] = None, + dependency_overrides_provider: Annotated[ + Optional[Any], + Doc( + """ + Only used internally by FastAPI to handle dependency overrides. + + You shouldn't need to use it. It normally points to the `FastAPI` app + object. + """ + ), + ] = None, + route_class: Annotated[ + Type[APIRoute], + Doc( + """ + Custom route (*path operation*) class to be used by this router. + + Read more about it in the + [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). + """ + ), + ] = APIRoute, + on_startup: Annotated[ + Optional[Sequence[Callable[[], Any]]], + Doc( + """ + A list of startup event handler functions. + + You should instead use the `lifespan` handlers. + + Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). + """ + ), + ] = None, + on_shutdown: Annotated[ + Optional[Sequence[Callable[[], Any]]], + Doc( + """ + A list of shutdown event handler functions. + + You should instead use the `lifespan` handlers. + + Read more in the + [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). + """ + ), + ] = None, + # the generic to Lifespan[AppType] is the type of the top level application + # which the router cannot know statically, so we use typing.Any + lifespan: Annotated[ + Optional[Lifespan[Any]], + Doc( + """ + A `Lifespan` context manager handler. This replaces `startup` and + `shutdown` functions with a single context manager. + + Read more in the + [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark all *path operations* in this router as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) all the *path operations* in this router in the + generated OpenAPI. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> None: + super().__init__( + routes=routes, + redirect_slashes=redirect_slashes, + default=default, + on_startup=on_startup, + on_shutdown=on_shutdown, + lifespan=lifespan, + ) + if prefix: + assert prefix.startswith("/"), "A path prefix must start with '/'" + assert not prefix.endswith("/"), ( + "A path prefix must not end with '/', as the routes will start with '/'" + ) + self.prefix = prefix + self.tags: List[Union[str, Enum]] = tags or [] + self.dependencies = list(dependencies or []) + self.deprecated = deprecated + self.include_in_schema = include_in_schema + self.responses = responses or {} + self.callbacks = callbacks or [] + self.dependency_overrides_provider = dependency_overrides_provider + self.route_class = route_class + self.default_response_class = default_response_class + self.generate_unique_id_function = generate_unique_id_function + + def route( + self, + path: str, + methods: Optional[List[str]] = None, + name: Optional[str] = None, + include_in_schema: bool = True, + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + def decorator(func: DecoratedCallable) -> DecoratedCallable: + self.add_route( + path, + func, + methods=methods, + name=name, + include_in_schema=include_in_schema, + ) + return func + + return decorator + + def add_api_route( + self, + path: str, + endpoint: Callable[..., Any], + *, + response_model: Any = Default(None), + status_code: Optional[int] = None, + tags: Optional[List[Union[str, Enum]]] = None, + dependencies: Optional[Sequence[params.Depends]] = None, + summary: Optional[str] = None, + description: Optional[str] = None, + response_description: str = "Successful Response", + responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, + deprecated: Optional[bool] = None, + methods: Optional[Union[Set[str], List[str]]] = None, + operation_id: Optional[str] = None, + response_model_include: Optional[IncEx] = None, + response_model_exclude: Optional[IncEx] = None, + response_model_by_alias: bool = True, + response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, + include_in_schema: bool = True, + response_class: Union[Type[Response], DefaultPlaceholder] = Default( + JSONResponse + ), + name: Optional[str] = None, + route_class_override: Optional[Type[APIRoute]] = None, + callbacks: Optional[List[BaseRoute]] = None, + openapi_extra: Optional[Dict[str, Any]] = None, + generate_unique_id_function: Union[ + Callable[[APIRoute], str], DefaultPlaceholder + ] = Default(generate_unique_id), + ) -> None: + route_class = route_class_override or self.route_class + responses = responses or {} + combined_responses = {**self.responses, **responses} + current_response_class = get_value_or_default( + response_class, self.default_response_class + ) + current_tags = self.tags.copy() + if tags: + current_tags.extend(tags) + current_dependencies = self.dependencies.copy() + if dependencies: + current_dependencies.extend(dependencies) + current_callbacks = self.callbacks.copy() + if callbacks: + current_callbacks.extend(callbacks) + current_generate_unique_id = get_value_or_default( + generate_unique_id_function, self.generate_unique_id_function + ) + route = route_class( + self.prefix + path, + endpoint=endpoint, + response_model=response_model, + status_code=status_code, + tags=current_tags, + dependencies=current_dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=combined_responses, + deprecated=deprecated or self.deprecated, + methods=methods, + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema and self.include_in_schema, + response_class=current_response_class, + name=name, + dependency_overrides_provider=self.dependency_overrides_provider, + callbacks=current_callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=current_generate_unique_id, + ) + self.routes.append(route) + + def api_route( + self, + path: str, + *, + response_model: Any = Default(None), + status_code: Optional[int] = None, + tags: Optional[List[Union[str, Enum]]] = None, + dependencies: Optional[Sequence[params.Depends]] = None, + summary: Optional[str] = None, + description: Optional[str] = None, + response_description: str = "Successful Response", + responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, + deprecated: Optional[bool] = None, + methods: Optional[List[str]] = None, + operation_id: Optional[str] = None, + response_model_include: Optional[IncEx] = None, + response_model_exclude: Optional[IncEx] = None, + response_model_by_alias: bool = True, + response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, + include_in_schema: bool = True, + response_class: Type[Response] = Default(JSONResponse), + name: Optional[str] = None, + callbacks: Optional[List[BaseRoute]] = None, + openapi_extra: Optional[Dict[str, Any]] = None, + generate_unique_id_function: Callable[[APIRoute], str] = Default( + generate_unique_id + ), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + def decorator(func: DecoratedCallable) -> DecoratedCallable: + self.add_api_route( + path, + func, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + methods=methods, + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + return func + + return decorator + + def add_api_websocket_route( + self, + path: str, + endpoint: Callable[..., Any], + name: Optional[str] = None, + *, + dependencies: Optional[Sequence[params.Depends]] = None, + ) -> None: + current_dependencies = self.dependencies.copy() + if dependencies: + current_dependencies.extend(dependencies) + + route = APIWebSocketRoute( + self.prefix + path, + endpoint=endpoint, + name=name, + dependencies=current_dependencies, + dependency_overrides_provider=self.dependency_overrides_provider, + ) + self.routes.append(route) + + def websocket( + self, + path: Annotated[ + str, + Doc( + """ + WebSocket path. + """ + ), + ], + name: Annotated[ + Optional[str], + Doc( + """ + A name for the WebSocket. Only used internally. + """ + ), + ] = None, + *, + dependencies: Annotated[ + Optional[Sequence[params.Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be used for this + WebSocket. + + Read more about it in the + [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). + """ + ), + ] = None, + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Decorate a WebSocket function. + + Read more about it in the + [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). + + **Example** + + ## Example + + ```python + from fastapi import APIRouter, FastAPI, WebSocket + + app = FastAPI() + router = APIRouter() + + @router.websocket("/ws") + async def websocket_endpoint(websocket: WebSocket): + await websocket.accept() + while True: + data = await websocket.receive_text() + await websocket.send_text(f"Message text was: {data}") + + app.include_router(router) + ``` + """ + + def decorator(func: DecoratedCallable) -> DecoratedCallable: + self.add_api_websocket_route( + path, func, name=name, dependencies=dependencies + ) + return func + + return decorator + + def websocket_route( + self, path: str, name: Union[str, None] = None + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + def decorator(func: DecoratedCallable) -> DecoratedCallable: + self.add_websocket_route(path, func, name=name) + return func + + return decorator + + def include_router( + self, + router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], + *, + prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "", + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to all the *path operations* in this + router. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[params.Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to all the + *path operations* in this router. + + Read more about it in the + [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). + """ + ), + ] = None, + default_response_class: Annotated[ + Type[Response], + Doc( + """ + The default response class to be used. + + Read more in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class). + """ + ), + ] = Default(JSONResponse), + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses to be shown in OpenAPI. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/). + + And in the + [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + OpenAPI callbacks that should apply to all *path operations* in this + router. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark all *path operations* in this router as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include (or not) all the *path operations* in this router in the + generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = True, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> None: + """ + Include another `APIRouter` in the same current `APIRouter`. + + Read more about it in the + [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + + app = FastAPI() + internal_router = APIRouter() + users_router = APIRouter() + + @users_router.get("/users/") + def read_users(): + return [{"name": "Rick"}, {"name": "Morty"}] + + internal_router.include_router(users_router) + app.include_router(internal_router) + ``` + """ + if prefix: + assert prefix.startswith("/"), "A path prefix must start with '/'" + assert not prefix.endswith("/"), ( + "A path prefix must not end with '/', as the routes will start with '/'" + ) + else: + for r in router.routes: + path = getattr(r, "path") # noqa: B009 + name = getattr(r, "name", "unknown") + if path is not None and not path: + raise FastAPIError( + f"Prefix and path cannot be both empty (path operation: {name})" + ) + if responses is None: + responses = {} + for route in router.routes: + if isinstance(route, APIRoute): + combined_responses = {**responses, **route.responses} + use_response_class = get_value_or_default( + route.response_class, + router.default_response_class, + default_response_class, + self.default_response_class, + ) + current_tags = [] + if tags: + current_tags.extend(tags) + if route.tags: + current_tags.extend(route.tags) + current_dependencies: List[params.Depends] = [] + if dependencies: + current_dependencies.extend(dependencies) + if route.dependencies: + current_dependencies.extend(route.dependencies) + current_callbacks = [] + if callbacks: + current_callbacks.extend(callbacks) + if route.callbacks: + current_callbacks.extend(route.callbacks) + current_generate_unique_id = get_value_or_default( + route.generate_unique_id_function, + router.generate_unique_id_function, + generate_unique_id_function, + self.generate_unique_id_function, + ) + self.add_api_route( + prefix + route.path, + route.endpoint, + response_model=route.response_model, + status_code=route.status_code, + tags=current_tags, + dependencies=current_dependencies, + summary=route.summary, + description=route.description, + response_description=route.response_description, + responses=combined_responses, + deprecated=route.deprecated or deprecated or self.deprecated, + methods=route.methods, + operation_id=route.operation_id, + response_model_include=route.response_model_include, + response_model_exclude=route.response_model_exclude, + response_model_by_alias=route.response_model_by_alias, + response_model_exclude_unset=route.response_model_exclude_unset, + response_model_exclude_defaults=route.response_model_exclude_defaults, + response_model_exclude_none=route.response_model_exclude_none, + include_in_schema=route.include_in_schema + and self.include_in_schema + and include_in_schema, + response_class=use_response_class, + name=route.name, + route_class_override=type(route), + callbacks=current_callbacks, + openapi_extra=route.openapi_extra, + generate_unique_id_function=current_generate_unique_id, + ) + elif isinstance(route, routing.Route): + methods = list(route.methods or []) + self.add_route( + prefix + route.path, + route.endpoint, + methods=methods, + include_in_schema=route.include_in_schema, + name=route.name, + ) + elif isinstance(route, APIWebSocketRoute): + current_dependencies = [] + if dependencies: + current_dependencies.extend(dependencies) + if route.dependencies: + current_dependencies.extend(route.dependencies) + self.add_api_websocket_route( + prefix + route.path, + route.endpoint, + dependencies=current_dependencies, + name=route.name, + ) + elif isinstance(route, routing.WebSocketRoute): + self.add_websocket_route( + prefix + route.path, route.endpoint, name=route.name + ) + for handler in router.on_startup: + self.add_event_handler("startup", handler) + for handler in router.on_shutdown: + self.add_event_handler("shutdown", handler) + self.lifespan_context = _merge_lifespan_context( + self.lifespan_context, + router.lifespan_context, + ) + + def get( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[params.Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP GET operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + + app = FastAPI() + router = APIRouter() + + @router.get("/items/") + def read_items(): + return [{"name": "Empanada"}, {"name": "Arepa"}] + + app.include_router(router) + ``` + """ + return self.api_route( + path=path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + methods=["GET"], + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def put( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[params.Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP PUT operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + router = APIRouter() + + @router.put("/items/{item_id}") + def replace_item(item_id: str, item: Item): + return {"message": "Item replaced", "id": item_id} + + app.include_router(router) + ``` + """ + return self.api_route( + path=path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + methods=["PUT"], + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def post( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[params.Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP POST operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + router = APIRouter() + + @router.post("/items/") + def create_item(item: Item): + return {"message": "Item created"} + + app.include_router(router) + ``` + """ + return self.api_route( + path=path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + methods=["POST"], + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def delete( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[params.Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP DELETE operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + + app = FastAPI() + router = APIRouter() + + @router.delete("/items/{item_id}") + def delete_item(item_id: str): + return {"message": "Item deleted"} + + app.include_router(router) + ``` + """ + return self.api_route( + path=path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + methods=["DELETE"], + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def options( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[params.Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP OPTIONS operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + + app = FastAPI() + router = APIRouter() + + @router.options("/items/") + def get_item_options(): + return {"additions": ["Aji", "Guacamole"]} + + app.include_router(router) + ``` + """ + return self.api_route( + path=path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + methods=["OPTIONS"], + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def head( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[params.Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP HEAD operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + router = APIRouter() + + @router.head("/items/", status_code=204) + def get_items_headers(response: Response): + response.headers["X-Cat-Dog"] = "Alone in the world" + + app.include_router(router) + ``` + """ + return self.api_route( + path=path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + methods=["HEAD"], + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def patch( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[params.Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP PATCH operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + router = APIRouter() + + @router.patch("/items/") + def update_item(item: Item): + return {"message": "Item updated in place"} + + app.include_router(router) + ``` + """ + return self.api_route( + path=path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + methods=["PATCH"], + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def trace( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + Optional[int], + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + Optional[List[Union[str, Enum]]], + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Optional[Sequence[params.Depends]], + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + Optional[str], + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + Optional[Dict[Union[int, str], Dict[str, Any]]], + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + Optional[bool], + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + Optional[str], + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + Optional[IncEx], + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + Type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + Optional[str], + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + Optional[List[BaseRoute]], + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + Optional[Dict[str, Any]], + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP TRACE operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + router = APIRouter() + + @router.trace("/items/{item_id}") + def trace_item(item_id: str): + return None + + app.include_router(router) + ``` + """ + return self.api_route( + path=path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + methods=["TRACE"], + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + @deprecated( + """ + on_event is deprecated, use lifespan event handlers instead. + + Read more about it in the + [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). + """ + ) + def on_event( + self, + event_type: Annotated[ + str, + Doc( + """ + The type of event. `startup` or `shutdown`. + """ + ), + ], + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add an event handler for the router. + + `on_event` is deprecated, use `lifespan` event handlers instead. + + Read more about it in the + [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). + """ + + def decorator(func: DecoratedCallable) -> DecoratedCallable: + self.add_event_handler(event_type, func) + return func + + return decorator diff --git a/venv/Lib/site-packages/fastapi/security/__init__.py b/venv/Lib/site-packages/fastapi/security/__init__.py new file mode 100644 index 00000000..3aa6bf21 --- /dev/null +++ b/venv/Lib/site-packages/fastapi/security/__init__.py @@ -0,0 +1,15 @@ +from .api_key import APIKeyCookie as APIKeyCookie +from .api_key import APIKeyHeader as APIKeyHeader +from .api_key import APIKeyQuery as APIKeyQuery +from .http import HTTPAuthorizationCredentials as HTTPAuthorizationCredentials +from .http import HTTPBasic as HTTPBasic +from .http import HTTPBasicCredentials as HTTPBasicCredentials +from .http import HTTPBearer as HTTPBearer +from .http import HTTPDigest as HTTPDigest +from .oauth2 import OAuth2 as OAuth2 +from .oauth2 import OAuth2AuthorizationCodeBearer as OAuth2AuthorizationCodeBearer +from .oauth2 import OAuth2PasswordBearer as OAuth2PasswordBearer +from .oauth2 import OAuth2PasswordRequestForm as OAuth2PasswordRequestForm +from .oauth2 import OAuth2PasswordRequestFormStrict as OAuth2PasswordRequestFormStrict +from .oauth2 import SecurityScopes as SecurityScopes +from .open_id_connect_url import OpenIdConnect as OpenIdConnect diff --git a/venv/Lib/site-packages/fastapi/security/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/fastapi/security/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..cabfb59b Binary files /dev/null and b/venv/Lib/site-packages/fastapi/security/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/security/__pycache__/api_key.cpython-312.pyc b/venv/Lib/site-packages/fastapi/security/__pycache__/api_key.cpython-312.pyc new file mode 100644 index 00000000..893e6d23 Binary files /dev/null and b/venv/Lib/site-packages/fastapi/security/__pycache__/api_key.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/security/__pycache__/base.cpython-312.pyc b/venv/Lib/site-packages/fastapi/security/__pycache__/base.cpython-312.pyc new file mode 100644 index 00000000..160b70cb Binary files /dev/null and b/venv/Lib/site-packages/fastapi/security/__pycache__/base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/security/__pycache__/http.cpython-312.pyc b/venv/Lib/site-packages/fastapi/security/__pycache__/http.cpython-312.pyc new file mode 100644 index 00000000..bf2faeea Binary files /dev/null and b/venv/Lib/site-packages/fastapi/security/__pycache__/http.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/security/__pycache__/oauth2.cpython-312.pyc b/venv/Lib/site-packages/fastapi/security/__pycache__/oauth2.cpython-312.pyc new file mode 100644 index 00000000..7375ee09 Binary files /dev/null and b/venv/Lib/site-packages/fastapi/security/__pycache__/oauth2.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/security/__pycache__/open_id_connect_url.cpython-312.pyc b/venv/Lib/site-packages/fastapi/security/__pycache__/open_id_connect_url.cpython-312.pyc new file mode 100644 index 00000000..b835322e Binary files /dev/null and b/venv/Lib/site-packages/fastapi/security/__pycache__/open_id_connect_url.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/security/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/fastapi/security/__pycache__/utils.cpython-312.pyc new file mode 100644 index 00000000..60a96ebe Binary files /dev/null and b/venv/Lib/site-packages/fastapi/security/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/fastapi/security/api_key.py b/venv/Lib/site-packages/fastapi/security/api_key.py new file mode 100644 index 00000000..70c2dca8 --- /dev/null +++ b/venv/Lib/site-packages/fastapi/security/api_key.py @@ -0,0 +1,288 @@ +from typing import Optional + +from fastapi.openapi.models import APIKey, APIKeyIn +from fastapi.security.base import SecurityBase +from starlette.exceptions import HTTPException +from starlette.requests import Request +from starlette.status import HTTP_403_FORBIDDEN +from typing_extensions import Annotated, Doc + + +class APIKeyBase(SecurityBase): + @staticmethod + def check_api_key(api_key: Optional[str], auto_error: bool) -> Optional[str]: + if not api_key: + if auto_error: + raise HTTPException( + status_code=HTTP_403_FORBIDDEN, detail="Not authenticated" + ) + return None + return api_key + + +class APIKeyQuery(APIKeyBase): + """ + API key authentication using a query parameter. + + This defines the name of the query parameter that should be provided in the request + with the API key and integrates that into the OpenAPI documentation. It extracts + the key value sent in the query parameter automatically and provides it as the + dependency result. But it doesn't define how to send that API key to the client. + + ## Usage + + Create an instance object and use that object as the dependency in `Depends()`. + + The dependency result will be a string containing the key value. + + ## Example + + ```python + from fastapi import Depends, FastAPI + from fastapi.security import APIKeyQuery + + app = FastAPI() + + query_scheme = APIKeyQuery(name="api_key") + + + @app.get("/items/") + async def read_items(api_key: str = Depends(query_scheme)): + return {"api_key": api_key} + ``` + """ + + def __init__( + self, + *, + name: Annotated[ + str, + Doc("Query parameter name."), + ], + scheme_name: Annotated[ + Optional[str], + Doc( + """ + Security scheme name. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Security scheme description. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + auto_error: Annotated[ + bool, + Doc( + """ + By default, if the query parameter is not provided, `APIKeyQuery` will + automatically cancel the request and send the client an error. + + If `auto_error` is set to `False`, when the query parameter is not + available, instead of erroring out, the dependency result will be + `None`. + + This is useful when you want to have optional authentication. + + It is also useful when you want to have authentication that can be + provided in one of multiple optional ways (for example, in a query + parameter or in an HTTP Bearer token). + """ + ), + ] = True, + ): + self.model: APIKey = APIKey( + **{"in": APIKeyIn.query}, # type: ignore[arg-type] + name=name, + description=description, + ) + self.scheme_name = scheme_name or self.__class__.__name__ + self.auto_error = auto_error + + async def __call__(self, request: Request) -> Optional[str]: + api_key = request.query_params.get(self.model.name) + return self.check_api_key(api_key, self.auto_error) + + +class APIKeyHeader(APIKeyBase): + """ + API key authentication using a header. + + This defines the name of the header that should be provided in the request with + the API key and integrates that into the OpenAPI documentation. It extracts + the key value sent in the header automatically and provides it as the dependency + result. But it doesn't define how to send that key to the client. + + ## Usage + + Create an instance object and use that object as the dependency in `Depends()`. + + The dependency result will be a string containing the key value. + + ## Example + + ```python + from fastapi import Depends, FastAPI + from fastapi.security import APIKeyHeader + + app = FastAPI() + + header_scheme = APIKeyHeader(name="x-key") + + + @app.get("/items/") + async def read_items(key: str = Depends(header_scheme)): + return {"key": key} + ``` + """ + + def __init__( + self, + *, + name: Annotated[str, Doc("Header name.")], + scheme_name: Annotated[ + Optional[str], + Doc( + """ + Security scheme name. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Security scheme description. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + auto_error: Annotated[ + bool, + Doc( + """ + By default, if the header is not provided, `APIKeyHeader` will + automatically cancel the request and send the client an error. + + If `auto_error` is set to `False`, when the header is not available, + instead of erroring out, the dependency result will be `None`. + + This is useful when you want to have optional authentication. + + It is also useful when you want to have authentication that can be + provided in one of multiple optional ways (for example, in a header or + in an HTTP Bearer token). + """ + ), + ] = True, + ): + self.model: APIKey = APIKey( + **{"in": APIKeyIn.header}, # type: ignore[arg-type] + name=name, + description=description, + ) + self.scheme_name = scheme_name or self.__class__.__name__ + self.auto_error = auto_error + + async def __call__(self, request: Request) -> Optional[str]: + api_key = request.headers.get(self.model.name) + return self.check_api_key(api_key, self.auto_error) + + +class APIKeyCookie(APIKeyBase): + """ + API key authentication using a cookie. + + This defines the name of the cookie that should be provided in the request with + the API key and integrates that into the OpenAPI documentation. It extracts + the key value sent in the cookie automatically and provides it as the dependency + result. But it doesn't define how to set that cookie. + + ## Usage + + Create an instance object and use that object as the dependency in `Depends()`. + + The dependency result will be a string containing the key value. + + ## Example + + ```python + from fastapi import Depends, FastAPI + from fastapi.security import APIKeyCookie + + app = FastAPI() + + cookie_scheme = APIKeyCookie(name="session") + + + @app.get("/items/") + async def read_items(session: str = Depends(cookie_scheme)): + return {"session": session} + ``` + """ + + def __init__( + self, + *, + name: Annotated[str, Doc("Cookie name.")], + scheme_name: Annotated[ + Optional[str], + Doc( + """ + Security scheme name. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Security scheme description. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + auto_error: Annotated[ + bool, + Doc( + """ + By default, if the cookie is not provided, `APIKeyCookie` will + automatically cancel the request and send the client an error. + + If `auto_error` is set to `False`, when the cookie is not available, + instead of erroring out, the dependency result will be `None`. + + This is useful when you want to have optional authentication. + + It is also useful when you want to have authentication that can be + provided in one of multiple optional ways (for example, in a cookie or + in an HTTP Bearer token). + """ + ), + ] = True, + ): + self.model: APIKey = APIKey( + **{"in": APIKeyIn.cookie}, # type: ignore[arg-type] + name=name, + description=description, + ) + self.scheme_name = scheme_name or self.__class__.__name__ + self.auto_error = auto_error + + async def __call__(self, request: Request) -> Optional[str]: + api_key = request.cookies.get(self.model.name) + return self.check_api_key(api_key, self.auto_error) diff --git a/venv/Lib/site-packages/fastapi/security/base.py b/venv/Lib/site-packages/fastapi/security/base.py new file mode 100644 index 00000000..c43555de --- /dev/null +++ b/venv/Lib/site-packages/fastapi/security/base.py @@ -0,0 +1,6 @@ +from fastapi.openapi.models import SecurityBase as SecurityBaseModel + + +class SecurityBase: + model: SecurityBaseModel + scheme_name: str diff --git a/venv/Lib/site-packages/fastapi/security/http.py b/venv/Lib/site-packages/fastapi/security/http.py new file mode 100644 index 00000000..9ab2df3c --- /dev/null +++ b/venv/Lib/site-packages/fastapi/security/http.py @@ -0,0 +1,423 @@ +import binascii +from base64 import b64decode +from typing import Optional + +from fastapi.exceptions import HTTPException +from fastapi.openapi.models import HTTPBase as HTTPBaseModel +from fastapi.openapi.models import HTTPBearer as HTTPBearerModel +from fastapi.security.base import SecurityBase +from fastapi.security.utils import get_authorization_scheme_param +from pydantic import BaseModel +from starlette.requests import Request +from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN +from typing_extensions import Annotated, Doc + + +class HTTPBasicCredentials(BaseModel): + """ + The HTTP Basic credentials given as the result of using `HTTPBasic` in a + dependency. + + Read more about it in the + [FastAPI docs for HTTP Basic Auth](https://fastapi.tiangolo.com/advanced/security/http-basic-auth/). + """ + + username: Annotated[str, Doc("The HTTP Basic username.")] + password: Annotated[str, Doc("The HTTP Basic password.")] + + +class HTTPAuthorizationCredentials(BaseModel): + """ + The HTTP authorization credentials in the result of using `HTTPBearer` or + `HTTPDigest` in a dependency. + + The HTTP authorization header value is split by the first space. + + The first part is the `scheme`, the second part is the `credentials`. + + For example, in an HTTP Bearer token scheme, the client will send a header + like: + + ``` + Authorization: Bearer deadbeef12346 + ``` + + In this case: + + * `scheme` will have the value `"Bearer"` + * `credentials` will have the value `"deadbeef12346"` + """ + + scheme: Annotated[ + str, + Doc( + """ + The HTTP authorization scheme extracted from the header value. + """ + ), + ] + credentials: Annotated[ + str, + Doc( + """ + The HTTP authorization credentials extracted from the header value. + """ + ), + ] + + +class HTTPBase(SecurityBase): + def __init__( + self, + *, + scheme: str, + scheme_name: Optional[str] = None, + description: Optional[str] = None, + auto_error: bool = True, + ): + self.model = HTTPBaseModel(scheme=scheme, description=description) + self.scheme_name = scheme_name or self.__class__.__name__ + self.auto_error = auto_error + + async def __call__( + self, request: Request + ) -> Optional[HTTPAuthorizationCredentials]: + authorization = request.headers.get("Authorization") + scheme, credentials = get_authorization_scheme_param(authorization) + if not (authorization and scheme and credentials): + if self.auto_error: + raise HTTPException( + status_code=HTTP_403_FORBIDDEN, detail="Not authenticated" + ) + else: + return None + return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials) + + +class HTTPBasic(HTTPBase): + """ + HTTP Basic authentication. + + ## Usage + + Create an instance object and use that object as the dependency in `Depends()`. + + The dependency result will be an `HTTPBasicCredentials` object containing the + `username` and the `password`. + + Read more about it in the + [FastAPI docs for HTTP Basic Auth](https://fastapi.tiangolo.com/advanced/security/http-basic-auth/). + + ## Example + + ```python + from typing import Annotated + + from fastapi import Depends, FastAPI + from fastapi.security import HTTPBasic, HTTPBasicCredentials + + app = FastAPI() + + security = HTTPBasic() + + + @app.get("/users/me") + def read_current_user(credentials: Annotated[HTTPBasicCredentials, Depends(security)]): + return {"username": credentials.username, "password": credentials.password} + ``` + """ + + def __init__( + self, + *, + scheme_name: Annotated[ + Optional[str], + Doc( + """ + Security scheme name. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + realm: Annotated[ + Optional[str], + Doc( + """ + HTTP Basic authentication realm. + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Security scheme description. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + auto_error: Annotated[ + bool, + Doc( + """ + By default, if the HTTP Basic authentication is not provided (a + header), `HTTPBasic` will automatically cancel the request and send the + client an error. + + If `auto_error` is set to `False`, when the HTTP Basic authentication + is not available, instead of erroring out, the dependency result will + be `None`. + + This is useful when you want to have optional authentication. + + It is also useful when you want to have authentication that can be + provided in one of multiple optional ways (for example, in HTTP Basic + authentication or in an HTTP Bearer token). + """ + ), + ] = True, + ): + self.model = HTTPBaseModel(scheme="basic", description=description) + self.scheme_name = scheme_name or self.__class__.__name__ + self.realm = realm + self.auto_error = auto_error + + async def __call__( # type: ignore + self, request: Request + ) -> Optional[HTTPBasicCredentials]: + authorization = request.headers.get("Authorization") + scheme, param = get_authorization_scheme_param(authorization) + if self.realm: + unauthorized_headers = {"WWW-Authenticate": f'Basic realm="{self.realm}"'} + else: + unauthorized_headers = {"WWW-Authenticate": "Basic"} + if not authorization or scheme.lower() != "basic": + if self.auto_error: + raise HTTPException( + status_code=HTTP_401_UNAUTHORIZED, + detail="Not authenticated", + headers=unauthorized_headers, + ) + else: + return None + invalid_user_credentials_exc = HTTPException( + status_code=HTTP_401_UNAUTHORIZED, + detail="Invalid authentication credentials", + headers=unauthorized_headers, + ) + try: + data = b64decode(param).decode("ascii") + except (ValueError, UnicodeDecodeError, binascii.Error): + raise invalid_user_credentials_exc # noqa: B904 + username, separator, password = data.partition(":") + if not separator: + raise invalid_user_credentials_exc + return HTTPBasicCredentials(username=username, password=password) + + +class HTTPBearer(HTTPBase): + """ + HTTP Bearer token authentication. + + ## Usage + + Create an instance object and use that object as the dependency in `Depends()`. + + The dependency result will be an `HTTPAuthorizationCredentials` object containing + the `scheme` and the `credentials`. + + ## Example + + ```python + from typing import Annotated + + from fastapi import Depends, FastAPI + from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer + + app = FastAPI() + + security = HTTPBearer() + + + @app.get("/users/me") + def read_current_user( + credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)] + ): + return {"scheme": credentials.scheme, "credentials": credentials.credentials} + ``` + """ + + def __init__( + self, + *, + bearerFormat: Annotated[Optional[str], Doc("Bearer token format.")] = None, + scheme_name: Annotated[ + Optional[str], + Doc( + """ + Security scheme name. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Security scheme description. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + auto_error: Annotated[ + bool, + Doc( + """ + By default, if the HTTP Bearer token is not provided (in an + `Authorization` header), `HTTPBearer` will automatically cancel the + request and send the client an error. + + If `auto_error` is set to `False`, when the HTTP Bearer token + is not available, instead of erroring out, the dependency result will + be `None`. + + This is useful when you want to have optional authentication. + + It is also useful when you want to have authentication that can be + provided in one of multiple optional ways (for example, in an HTTP + Bearer token or in a cookie). + """ + ), + ] = True, + ): + self.model = HTTPBearerModel(bearerFormat=bearerFormat, description=description) + self.scheme_name = scheme_name or self.__class__.__name__ + self.auto_error = auto_error + + async def __call__( + self, request: Request + ) -> Optional[HTTPAuthorizationCredentials]: + authorization = request.headers.get("Authorization") + scheme, credentials = get_authorization_scheme_param(authorization) + if not (authorization and scheme and credentials): + if self.auto_error: + raise HTTPException( + status_code=HTTP_403_FORBIDDEN, detail="Not authenticated" + ) + else: + return None + if scheme.lower() != "bearer": + if self.auto_error: + raise HTTPException( + status_code=HTTP_403_FORBIDDEN, + detail="Invalid authentication credentials", + ) + else: + return None + return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials) + + +class HTTPDigest(HTTPBase): + """ + HTTP Digest authentication. + + ## Usage + + Create an instance object and use that object as the dependency in `Depends()`. + + The dependency result will be an `HTTPAuthorizationCredentials` object containing + the `scheme` and the `credentials`. + + ## Example + + ```python + from typing import Annotated + + from fastapi import Depends, FastAPI + from fastapi.security import HTTPAuthorizationCredentials, HTTPDigest + + app = FastAPI() + + security = HTTPDigest() + + + @app.get("/users/me") + def read_current_user( + credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)] + ): + return {"scheme": credentials.scheme, "credentials": credentials.credentials} + ``` + """ + + def __init__( + self, + *, + scheme_name: Annotated[ + Optional[str], + Doc( + """ + Security scheme name. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Security scheme description. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + auto_error: Annotated[ + bool, + Doc( + """ + By default, if the HTTP Digest is not provided, `HTTPDigest` will + automatically cancel the request and send the client an error. + + If `auto_error` is set to `False`, when the HTTP Digest is not + available, instead of erroring out, the dependency result will + be `None`. + + This is useful when you want to have optional authentication. + + It is also useful when you want to have authentication that can be + provided in one of multiple optional ways (for example, in HTTP + Digest or in a cookie). + """ + ), + ] = True, + ): + self.model = HTTPBaseModel(scheme="digest", description=description) + self.scheme_name = scheme_name or self.__class__.__name__ + self.auto_error = auto_error + + async def __call__( + self, request: Request + ) -> Optional[HTTPAuthorizationCredentials]: + authorization = request.headers.get("Authorization") + scheme, credentials = get_authorization_scheme_param(authorization) + if not (authorization and scheme and credentials): + if self.auto_error: + raise HTTPException( + status_code=HTTP_403_FORBIDDEN, detail="Not authenticated" + ) + else: + return None + if scheme.lower() != "digest": + if self.auto_error: + raise HTTPException( + status_code=HTTP_403_FORBIDDEN, + detail="Invalid authentication credentials", + ) + else: + return None + return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials) diff --git a/venv/Lib/site-packages/fastapi/security/oauth2.py b/venv/Lib/site-packages/fastapi/security/oauth2.py new file mode 100644 index 00000000..88e394db --- /dev/null +++ b/venv/Lib/site-packages/fastapi/security/oauth2.py @@ -0,0 +1,653 @@ +from typing import Any, Dict, List, Optional, Union, cast + +from fastapi.exceptions import HTTPException +from fastapi.openapi.models import OAuth2 as OAuth2Model +from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel +from fastapi.param_functions import Form +from fastapi.security.base import SecurityBase +from fastapi.security.utils import get_authorization_scheme_param +from starlette.requests import Request +from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN + +# TODO: import from typing when deprecating Python 3.9 +from typing_extensions import Annotated, Doc + + +class OAuth2PasswordRequestForm: + """ + This is a dependency class to collect the `username` and `password` as form data + for an OAuth2 password flow. + + The OAuth2 specification dictates that for a password flow the data should be + collected using form data (instead of JSON) and that it should have the specific + fields `username` and `password`. + + All the initialization parameters are extracted from the request. + + Read more about it in the + [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). + + ## Example + + ```python + from typing import Annotated + + from fastapi import Depends, FastAPI + from fastapi.security import OAuth2PasswordRequestForm + + app = FastAPI() + + + @app.post("/login") + def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]): + data = {} + data["scopes"] = [] + for scope in form_data.scopes: + data["scopes"].append(scope) + if form_data.client_id: + data["client_id"] = form_data.client_id + if form_data.client_secret: + data["client_secret"] = form_data.client_secret + return data + ``` + + Note that for OAuth2 the scope `items:read` is a single scope in an opaque string. + You could have custom internal logic to separate it by colon characters (`:`) or + similar, and get the two parts `items` and `read`. Many applications do that to + group and organize permissions, you could do it as well in your application, just + know that that it is application specific, it's not part of the specification. + """ + + def __init__( + self, + *, + grant_type: Annotated[ + Union[str, None], + Form(pattern="^password$"), + Doc( + """ + The OAuth2 spec says it is required and MUST be the fixed string + "password". Nevertheless, this dependency class is permissive and + allows not passing it. If you want to enforce it, use instead the + `OAuth2PasswordRequestFormStrict` dependency. + """ + ), + ] = None, + username: Annotated[ + str, + Form(), + Doc( + """ + `username` string. The OAuth2 spec requires the exact field name + `username`. + """ + ), + ], + password: Annotated[ + str, + Form(json_schema_extra={"format": "password"}), + Doc( + """ + `password` string. The OAuth2 spec requires the exact field name + `password". + """ + ), + ], + scope: Annotated[ + str, + Form(), + Doc( + """ + A single string with actually several scopes separated by spaces. Each + scope is also a string. + + For example, a single string with: + + ```python + "items:read items:write users:read profile openid" + ```` + + would represent the scopes: + + * `items:read` + * `items:write` + * `users:read` + * `profile` + * `openid` + """ + ), + ] = "", + client_id: Annotated[ + Union[str, None], + Form(), + Doc( + """ + If there's a `client_id`, it can be sent as part of the form fields. + But the OAuth2 specification recommends sending the `client_id` and + `client_secret` (if any) using HTTP Basic auth. + """ + ), + ] = None, + client_secret: Annotated[ + Union[str, None], + Form(json_schema_extra={"format": "password"}), + Doc( + """ + If there's a `client_password` (and a `client_id`), they can be sent + as part of the form fields. But the OAuth2 specification recommends + sending the `client_id` and `client_secret` (if any) using HTTP Basic + auth. + """ + ), + ] = None, + ): + self.grant_type = grant_type + self.username = username + self.password = password + self.scopes = scope.split() + self.client_id = client_id + self.client_secret = client_secret + + +class OAuth2PasswordRequestFormStrict(OAuth2PasswordRequestForm): + """ + This is a dependency class to collect the `username` and `password` as form data + for an OAuth2 password flow. + + The OAuth2 specification dictates that for a password flow the data should be + collected using form data (instead of JSON) and that it should have the specific + fields `username` and `password`. + + All the initialization parameters are extracted from the request. + + The only difference between `OAuth2PasswordRequestFormStrict` and + `OAuth2PasswordRequestForm` is that `OAuth2PasswordRequestFormStrict` requires the + client to send the form field `grant_type` with the value `"password"`, which + is required in the OAuth2 specification (it seems that for no particular reason), + while for `OAuth2PasswordRequestForm` `grant_type` is optional. + + Read more about it in the + [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). + + ## Example + + ```python + from typing import Annotated + + from fastapi import Depends, FastAPI + from fastapi.security import OAuth2PasswordRequestForm + + app = FastAPI() + + + @app.post("/login") + def login(form_data: Annotated[OAuth2PasswordRequestFormStrict, Depends()]): + data = {} + data["scopes"] = [] + for scope in form_data.scopes: + data["scopes"].append(scope) + if form_data.client_id: + data["client_id"] = form_data.client_id + if form_data.client_secret: + data["client_secret"] = form_data.client_secret + return data + ``` + + Note that for OAuth2 the scope `items:read` is a single scope in an opaque string. + You could have custom internal logic to separate it by colon characters (`:`) or + similar, and get the two parts `items` and `read`. Many applications do that to + group and organize permissions, you could do it as well in your application, just + know that that it is application specific, it's not part of the specification. + + + grant_type: the OAuth2 spec says it is required and MUST be the fixed string "password". + This dependency is strict about it. If you want to be permissive, use instead the + OAuth2PasswordRequestForm dependency class. + username: username string. The OAuth2 spec requires the exact field name "username". + password: password string. The OAuth2 spec requires the exact field name "password". + scope: Optional string. Several scopes (each one a string) separated by spaces. E.g. + "items:read items:write users:read profile openid" + client_id: optional string. OAuth2 recommends sending the client_id and client_secret (if any) + using HTTP Basic auth, as: client_id:client_secret + client_secret: optional string. OAuth2 recommends sending the client_id and client_secret (if any) + using HTTP Basic auth, as: client_id:client_secret + """ + + def __init__( + self, + grant_type: Annotated[ + str, + Form(pattern="^password$"), + Doc( + """ + The OAuth2 spec says it is required and MUST be the fixed string + "password". This dependency is strict about it. If you want to be + permissive, use instead the `OAuth2PasswordRequestForm` dependency + class. + """ + ), + ], + username: Annotated[ + str, + Form(), + Doc( + """ + `username` string. The OAuth2 spec requires the exact field name + `username`. + """ + ), + ], + password: Annotated[ + str, + Form(), + Doc( + """ + `password` string. The OAuth2 spec requires the exact field name + `password". + """ + ), + ], + scope: Annotated[ + str, + Form(), + Doc( + """ + A single string with actually several scopes separated by spaces. Each + scope is also a string. + + For example, a single string with: + + ```python + "items:read items:write users:read profile openid" + ```` + + would represent the scopes: + + * `items:read` + * `items:write` + * `users:read` + * `profile` + * `openid` + """ + ), + ] = "", + client_id: Annotated[ + Union[str, None], + Form(), + Doc( + """ + If there's a `client_id`, it can be sent as part of the form fields. + But the OAuth2 specification recommends sending the `client_id` and + `client_secret` (if any) using HTTP Basic auth. + """ + ), + ] = None, + client_secret: Annotated[ + Union[str, None], + Form(), + Doc( + """ + If there's a `client_password` (and a `client_id`), they can be sent + as part of the form fields. But the OAuth2 specification recommends + sending the `client_id` and `client_secret` (if any) using HTTP Basic + auth. + """ + ), + ] = None, + ): + super().__init__( + grant_type=grant_type, + username=username, + password=password, + scope=scope, + client_id=client_id, + client_secret=client_secret, + ) + + +class OAuth2(SecurityBase): + """ + This is the base class for OAuth2 authentication, an instance of it would be used + as a dependency. All other OAuth2 classes inherit from it and customize it for + each OAuth2 flow. + + You normally would not create a new class inheriting from it but use one of the + existing subclasses, and maybe compose them if you want to support multiple flows. + + Read more about it in the + [FastAPI docs for Security](https://fastapi.tiangolo.com/tutorial/security/). + """ + + def __init__( + self, + *, + flows: Annotated[ + Union[OAuthFlowsModel, Dict[str, Dict[str, Any]]], + Doc( + """ + The dictionary of OAuth2 flows. + """ + ), + ] = OAuthFlowsModel(), + scheme_name: Annotated[ + Optional[str], + Doc( + """ + Security scheme name. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Security scheme description. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + auto_error: Annotated[ + bool, + Doc( + """ + By default, if no HTTP Authorization header is provided, required for + OAuth2 authentication, it will automatically cancel the request and + send the client an error. + + If `auto_error` is set to `False`, when the HTTP Authorization header + is not available, instead of erroring out, the dependency result will + be `None`. + + This is useful when you want to have optional authentication. + + It is also useful when you want to have authentication that can be + provided in one of multiple optional ways (for example, with OAuth2 + or in a cookie). + """ + ), + ] = True, + ): + self.model = OAuth2Model( + flows=cast(OAuthFlowsModel, flows), description=description + ) + self.scheme_name = scheme_name or self.__class__.__name__ + self.auto_error = auto_error + + async def __call__(self, request: Request) -> Optional[str]: + authorization = request.headers.get("Authorization") + if not authorization: + if self.auto_error: + raise HTTPException( + status_code=HTTP_403_FORBIDDEN, detail="Not authenticated" + ) + else: + return None + return authorization + + +class OAuth2PasswordBearer(OAuth2): + """ + OAuth2 flow for authentication using a bearer token obtained with a password. + An instance of it would be used as a dependency. + + Read more about it in the + [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). + """ + + def __init__( + self, + tokenUrl: Annotated[ + str, + Doc( + """ + The URL to obtain the OAuth2 token. This would be the *path operation* + that has `OAuth2PasswordRequestForm` as a dependency. + """ + ), + ], + scheme_name: Annotated[ + Optional[str], + Doc( + """ + Security scheme name. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + scopes: Annotated[ + Optional[Dict[str, str]], + Doc( + """ + The OAuth2 scopes that would be required by the *path operations* that + use this dependency. + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Security scheme description. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + auto_error: Annotated[ + bool, + Doc( + """ + By default, if no HTTP Authorization header is provided, required for + OAuth2 authentication, it will automatically cancel the request and + send the client an error. + + If `auto_error` is set to `False`, when the HTTP Authorization header + is not available, instead of erroring out, the dependency result will + be `None`. + + This is useful when you want to have optional authentication. + + It is also useful when you want to have authentication that can be + provided in one of multiple optional ways (for example, with OAuth2 + or in a cookie). + """ + ), + ] = True, + refreshUrl: Annotated[ + Optional[str], + Doc( + """ + The URL to refresh the token and obtain a new one. + """ + ), + ] = None, + ): + if not scopes: + scopes = {} + flows = OAuthFlowsModel( + password=cast( + Any, + { + "tokenUrl": tokenUrl, + "refreshUrl": refreshUrl, + "scopes": scopes, + }, + ) + ) + super().__init__( + flows=flows, + scheme_name=scheme_name, + description=description, + auto_error=auto_error, + ) + + async def __call__(self, request: Request) -> Optional[str]: + authorization = request.headers.get("Authorization") + scheme, param = get_authorization_scheme_param(authorization) + if not authorization or scheme.lower() != "bearer": + if self.auto_error: + raise HTTPException( + status_code=HTTP_401_UNAUTHORIZED, + detail="Not authenticated", + headers={"WWW-Authenticate": "Bearer"}, + ) + else: + return None + return param + + +class OAuth2AuthorizationCodeBearer(OAuth2): + """ + OAuth2 flow for authentication using a bearer token obtained with an OAuth2 code + flow. An instance of it would be used as a dependency. + """ + + def __init__( + self, + authorizationUrl: str, + tokenUrl: Annotated[ + str, + Doc( + """ + The URL to obtain the OAuth2 token. + """ + ), + ], + refreshUrl: Annotated[ + Optional[str], + Doc( + """ + The URL to refresh the token and obtain a new one. + """ + ), + ] = None, + scheme_name: Annotated[ + Optional[str], + Doc( + """ + Security scheme name. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + scopes: Annotated[ + Optional[Dict[str, str]], + Doc( + """ + The OAuth2 scopes that would be required by the *path operations* that + use this dependency. + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Security scheme description. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + auto_error: Annotated[ + bool, + Doc( + """ + By default, if no HTTP Authorization header is provided, required for + OAuth2 authentication, it will automatically cancel the request and + send the client an error. + + If `auto_error` is set to `False`, when the HTTP Authorization header + is not available, instead of erroring out, the dependency result will + be `None`. + + This is useful when you want to have optional authentication. + + It is also useful when you want to have authentication that can be + provided in one of multiple optional ways (for example, with OAuth2 + or in a cookie). + """ + ), + ] = True, + ): + if not scopes: + scopes = {} + flows = OAuthFlowsModel( + authorizationCode=cast( + Any, + { + "authorizationUrl": authorizationUrl, + "tokenUrl": tokenUrl, + "refreshUrl": refreshUrl, + "scopes": scopes, + }, + ) + ) + super().__init__( + flows=flows, + scheme_name=scheme_name, + description=description, + auto_error=auto_error, + ) + + async def __call__(self, request: Request) -> Optional[str]: + authorization = request.headers.get("Authorization") + scheme, param = get_authorization_scheme_param(authorization) + if not authorization or scheme.lower() != "bearer": + if self.auto_error: + raise HTTPException( + status_code=HTTP_401_UNAUTHORIZED, + detail="Not authenticated", + headers={"WWW-Authenticate": "Bearer"}, + ) + else: + return None # pragma: nocover + return param + + +class SecurityScopes: + """ + This is a special class that you can define in a parameter in a dependency to + obtain the OAuth2 scopes required by all the dependencies in the same chain. + + This way, multiple dependencies can have different scopes, even when used in the + same *path operation*. And with this, you can access all the scopes required in + all those dependencies in a single place. + + Read more about it in the + [FastAPI docs for OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/). + """ + + def __init__( + self, + scopes: Annotated[ + Optional[List[str]], + Doc( + """ + This will be filled by FastAPI. + """ + ), + ] = None, + ): + self.scopes: Annotated[ + List[str], + Doc( + """ + The list of all the scopes required by dependencies. + """ + ), + ] = scopes or [] + self.scope_str: Annotated[ + str, + Doc( + """ + All the scopes required by all the dependencies in a single string + separated by spaces, as defined in the OAuth2 specification. + """ + ), + ] = " ".join(self.scopes) diff --git a/venv/Lib/site-packages/fastapi/security/open_id_connect_url.py b/venv/Lib/site-packages/fastapi/security/open_id_connect_url.py new file mode 100644 index 00000000..c8cceb91 --- /dev/null +++ b/venv/Lib/site-packages/fastapi/security/open_id_connect_url.py @@ -0,0 +1,84 @@ +from typing import Optional + +from fastapi.openapi.models import OpenIdConnect as OpenIdConnectModel +from fastapi.security.base import SecurityBase +from starlette.exceptions import HTTPException +from starlette.requests import Request +from starlette.status import HTTP_403_FORBIDDEN +from typing_extensions import Annotated, Doc + + +class OpenIdConnect(SecurityBase): + """ + OpenID Connect authentication class. An instance of it would be used as a + dependency. + """ + + def __init__( + self, + *, + openIdConnectUrl: Annotated[ + str, + Doc( + """ + The OpenID Connect URL. + """ + ), + ], + scheme_name: Annotated[ + Optional[str], + Doc( + """ + Security scheme name. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + description: Annotated[ + Optional[str], + Doc( + """ + Security scheme description. + + It will be included in the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + auto_error: Annotated[ + bool, + Doc( + """ + By default, if no HTTP Authorization header is provided, required for + OpenID Connect authentication, it will automatically cancel the request + and send the client an error. + + If `auto_error` is set to `False`, when the HTTP Authorization header + is not available, instead of erroring out, the dependency result will + be `None`. + + This is useful when you want to have optional authentication. + + It is also useful when you want to have authentication that can be + provided in one of multiple optional ways (for example, with OpenID + Connect or in a cookie). + """ + ), + ] = True, + ): + self.model = OpenIdConnectModel( + openIdConnectUrl=openIdConnectUrl, description=description + ) + self.scheme_name = scheme_name or self.__class__.__name__ + self.auto_error = auto_error + + async def __call__(self, request: Request) -> Optional[str]: + authorization = request.headers.get("Authorization") + if not authorization: + if self.auto_error: + raise HTTPException( + status_code=HTTP_403_FORBIDDEN, detail="Not authenticated" + ) + else: + return None + return authorization diff --git a/venv/Lib/site-packages/fastapi/security/utils.py b/venv/Lib/site-packages/fastapi/security/utils.py new file mode 100644 index 00000000..fa7a450b --- /dev/null +++ b/venv/Lib/site-packages/fastapi/security/utils.py @@ -0,0 +1,10 @@ +from typing import Optional, Tuple + + +def get_authorization_scheme_param( + authorization_header_value: Optional[str], +) -> Tuple[str, str]: + if not authorization_header_value: + return "", "" + scheme, _, param = authorization_header_value.partition(" ") + return scheme, param diff --git a/venv/Lib/site-packages/fastapi/staticfiles.py b/venv/Lib/site-packages/fastapi/staticfiles.py new file mode 100644 index 00000000..299015d4 --- /dev/null +++ b/venv/Lib/site-packages/fastapi/staticfiles.py @@ -0,0 +1 @@ +from starlette.staticfiles import StaticFiles as StaticFiles # noqa diff --git a/venv/Lib/site-packages/fastapi/templating.py b/venv/Lib/site-packages/fastapi/templating.py new file mode 100644 index 00000000..0cb86848 --- /dev/null +++ b/venv/Lib/site-packages/fastapi/templating.py @@ -0,0 +1 @@ +from starlette.templating import Jinja2Templates as Jinja2Templates # noqa diff --git a/venv/Lib/site-packages/fastapi/testclient.py b/venv/Lib/site-packages/fastapi/testclient.py new file mode 100644 index 00000000..4012406a --- /dev/null +++ b/venv/Lib/site-packages/fastapi/testclient.py @@ -0,0 +1 @@ +from starlette.testclient import TestClient as TestClient # noqa diff --git a/venv/Lib/site-packages/fastapi/types.py b/venv/Lib/site-packages/fastapi/types.py new file mode 100644 index 00000000..3205654c --- /dev/null +++ b/venv/Lib/site-packages/fastapi/types.py @@ -0,0 +1,10 @@ +import types +from enum import Enum +from typing import Any, Callable, Dict, Set, Type, TypeVar, Union + +from pydantic import BaseModel + +DecoratedCallable = TypeVar("DecoratedCallable", bound=Callable[..., Any]) +UnionType = getattr(types, "UnionType", Union) +ModelNameMap = Dict[Union[Type[BaseModel], Type[Enum]], str] +IncEx = Union[Set[int], Set[str], Dict[int, Any], Dict[str, Any]] diff --git a/venv/Lib/site-packages/fastapi/utils.py b/venv/Lib/site-packages/fastapi/utils.py new file mode 100644 index 00000000..4c7350fe --- /dev/null +++ b/venv/Lib/site-packages/fastapi/utils.py @@ -0,0 +1,220 @@ +import re +import warnings +from dataclasses import is_dataclass +from typing import ( + TYPE_CHECKING, + Any, + Dict, + MutableMapping, + Optional, + Set, + Type, + Union, + cast, +) +from weakref import WeakKeyDictionary + +import fastapi +from fastapi._compat import ( + PYDANTIC_V2, + BaseConfig, + ModelField, + PydanticSchemaGenerationError, + Undefined, + UndefinedType, + Validator, + lenient_issubclass, +) +from fastapi.datastructures import DefaultPlaceholder, DefaultType +from pydantic import BaseModel, create_model +from pydantic.fields import FieldInfo +from typing_extensions import Literal + +if TYPE_CHECKING: # pragma: nocover + from .routing import APIRoute + +# Cache for `create_cloned_field` +_CLONED_TYPES_CACHE: MutableMapping[Type[BaseModel], Type[BaseModel]] = ( + WeakKeyDictionary() +) + + +def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool: + if status_code is None: + return True + # Ref: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#patterned-fields-1 + if status_code in { + "default", + "1XX", + "2XX", + "3XX", + "4XX", + "5XX", + }: + return True + current_status_code = int(status_code) + return not (current_status_code < 200 or current_status_code in {204, 205, 304}) + + +def get_path_param_names(path: str) -> Set[str]: + return set(re.findall("{(.*?)}", path)) + + +def create_model_field( + name: str, + type_: Any, + class_validators: Optional[Dict[str, Validator]] = None, + default: Optional[Any] = Undefined, + required: Union[bool, UndefinedType] = Undefined, + model_config: Type[BaseConfig] = BaseConfig, + field_info: Optional[FieldInfo] = None, + alias: Optional[str] = None, + mode: Literal["validation", "serialization"] = "validation", +) -> ModelField: + class_validators = class_validators or {} + if PYDANTIC_V2: + field_info = field_info or FieldInfo( + annotation=type_, default=default, alias=alias + ) + else: + field_info = field_info or FieldInfo() + kwargs = {"name": name, "field_info": field_info} + if PYDANTIC_V2: + kwargs.update({"mode": mode}) + else: + kwargs.update( + { + "type_": type_, + "class_validators": class_validators, + "default": default, + "required": required, + "model_config": model_config, + "alias": alias, + } + ) + try: + return ModelField(**kwargs) # type: ignore[arg-type] + except (RuntimeError, PydanticSchemaGenerationError): + raise fastapi.exceptions.FastAPIError( + "Invalid args for response field! Hint: " + f"check that {type_} is a valid Pydantic field type. " + "If you are using a return type annotation that is not a valid Pydantic " + "field (e.g. Union[Response, dict, None]) you can disable generating the " + "response model from the type annotation with the path operation decorator " + "parameter response_model=None. Read more: " + "https://fastapi.tiangolo.com/tutorial/response-model/" + ) from None + + +def create_cloned_field( + field: ModelField, + *, + cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, +) -> ModelField: + if PYDANTIC_V2: + return field + # cloned_types caches already cloned types to support recursive models and improve + # performance by avoiding unnecessary cloning + if cloned_types is None: + cloned_types = _CLONED_TYPES_CACHE + + original_type = field.type_ + if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): + original_type = original_type.__pydantic_model__ + use_type = original_type + if lenient_issubclass(original_type, BaseModel): + original_type = cast(Type[BaseModel], original_type) + use_type = cloned_types.get(original_type) + if use_type is None: + use_type = create_model(original_type.__name__, __base__=original_type) + cloned_types[original_type] = use_type + for f in original_type.__fields__.values(): + use_type.__fields__[f.name] = create_cloned_field( + f, cloned_types=cloned_types + ) + new_field = create_model_field(name=field.name, type_=use_type) + new_field.has_alias = field.has_alias # type: ignore[attr-defined] + new_field.alias = field.alias # type: ignore[misc] + new_field.class_validators = field.class_validators # type: ignore[attr-defined] + new_field.default = field.default # type: ignore[misc] + new_field.required = field.required # type: ignore[misc] + new_field.model_config = field.model_config # type: ignore[attr-defined] + new_field.field_info = field.field_info + new_field.allow_none = field.allow_none # type: ignore[attr-defined] + new_field.validate_always = field.validate_always # type: ignore[attr-defined] + if field.sub_fields: # type: ignore[attr-defined] + new_field.sub_fields = [ # type: ignore[attr-defined] + create_cloned_field(sub_field, cloned_types=cloned_types) + for sub_field in field.sub_fields # type: ignore[attr-defined] + ] + if field.key_field: # type: ignore[attr-defined] + new_field.key_field = create_cloned_field( # type: ignore[attr-defined] + field.key_field, # type: ignore[attr-defined] + cloned_types=cloned_types, + ) + new_field.validators = field.validators # type: ignore[attr-defined] + new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] + new_field.post_validators = field.post_validators # type: ignore[attr-defined] + new_field.parse_json = field.parse_json # type: ignore[attr-defined] + new_field.shape = field.shape # type: ignore[attr-defined] + new_field.populate_validators() # type: ignore[attr-defined] + return new_field + + +def generate_operation_id_for_path( + *, name: str, path: str, method: str +) -> str: # pragma: nocover + warnings.warn( + "fastapi.utils.generate_operation_id_for_path() was deprecated, " + "it is not used internally, and will be removed soon", + DeprecationWarning, + stacklevel=2, + ) + operation_id = f"{name}{path}" + operation_id = re.sub(r"\W", "_", operation_id) + operation_id = f"{operation_id}_{method.lower()}" + return operation_id + + +def generate_unique_id(route: "APIRoute") -> str: + operation_id = f"{route.name}{route.path_format}" + operation_id = re.sub(r"\W", "_", operation_id) + assert route.methods + operation_id = f"{operation_id}_{list(route.methods)[0].lower()}" + return operation_id + + +def deep_dict_update(main_dict: Dict[Any, Any], update_dict: Dict[Any, Any]) -> None: + for key, value in update_dict.items(): + if ( + key in main_dict + and isinstance(main_dict[key], dict) + and isinstance(value, dict) + ): + deep_dict_update(main_dict[key], value) + elif ( + key in main_dict + and isinstance(main_dict[key], list) + and isinstance(update_dict[key], list) + ): + main_dict[key] = main_dict[key] + update_dict[key] + else: + main_dict[key] = value + + +def get_value_or_default( + first_item: Union[DefaultPlaceholder, DefaultType], + *extra_items: Union[DefaultPlaceholder, DefaultType], +) -> Union[DefaultPlaceholder, DefaultType]: + """ + Pass items or `DefaultPlaceholder`s by descending priority. + + The first one to _not_ be a `DefaultPlaceholder` will be returned. + + Otherwise, the first item (a `DefaultPlaceholder`) will be returned. + """ + items = (first_item,) + extra_items + for item in items: + if not isinstance(item, DefaultPlaceholder): + return item + return first_item diff --git a/venv/Lib/site-packages/fastapi/websockets.py b/venv/Lib/site-packages/fastapi/websockets.py new file mode 100644 index 00000000..55a4ac4a --- /dev/null +++ b/venv/Lib/site-packages/fastapi/websockets.py @@ -0,0 +1,3 @@ +from starlette.websockets import WebSocket as WebSocket # noqa +from starlette.websockets import WebSocketDisconnect as WebSocketDisconnect # noqa +from starlette.websockets import WebSocketState as WebSocketState # noqa diff --git a/venv/Lib/site-packages/frozenlist/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/frozenlist/__pycache__/__init__.cpython-312.pyc index ab7c3113..fbfe40ff 100644 Binary files a/venv/Lib/site-packages/frozenlist/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/frozenlist/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/__pycache__/__init__.cpython-312.pyc index 4cec3467..acbff829 100644 Binary files a/venv/Lib/site-packages/google/protobuf/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/__pycache__/descriptor.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/__pycache__/descriptor.cpython-312.pyc index dc4d89f4..b35453a5 100644 Binary files a/venv/Lib/site-packages/google/protobuf/__pycache__/descriptor.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/__pycache__/descriptor.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/__pycache__/descriptor_database.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/__pycache__/descriptor_database.cpython-312.pyc index 005b53da..02e675cf 100644 Binary files a/venv/Lib/site-packages/google/protobuf/__pycache__/descriptor_database.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/__pycache__/descriptor_database.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/__pycache__/descriptor_pool.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/__pycache__/descriptor_pool.cpython-312.pyc index c7bf79f4..ad3ddde4 100644 Binary files a/venv/Lib/site-packages/google/protobuf/__pycache__/descriptor_pool.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/__pycache__/descriptor_pool.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/__pycache__/duration_pb2.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/__pycache__/duration_pb2.cpython-312.pyc index 31aaa6b9..27ff694c 100644 Binary files a/venv/Lib/site-packages/google/protobuf/__pycache__/duration_pb2.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/__pycache__/duration_pb2.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/__pycache__/empty_pb2.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/__pycache__/empty_pb2.cpython-312.pyc index bbc81cfa..bda40a1e 100644 Binary files a/venv/Lib/site-packages/google/protobuf/__pycache__/empty_pb2.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/__pycache__/empty_pb2.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/__pycache__/json_format.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/__pycache__/json_format.cpython-312.pyc index 3d74a6e0..a48c287d 100644 Binary files a/venv/Lib/site-packages/google/protobuf/__pycache__/json_format.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/__pycache__/json_format.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/__pycache__/message.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/__pycache__/message.cpython-312.pyc index 6a044949..8db29042 100644 Binary files a/venv/Lib/site-packages/google/protobuf/__pycache__/message.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/__pycache__/message.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/__pycache__/message_factory.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/__pycache__/message_factory.cpython-312.pyc index 89f8f494..cb0a2f06 100644 Binary files a/venv/Lib/site-packages/google/protobuf/__pycache__/message_factory.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/__pycache__/message_factory.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/__pycache__/reflection.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/__pycache__/reflection.cpython-312.pyc index e07ff188..f1634060 100644 Binary files a/venv/Lib/site-packages/google/protobuf/__pycache__/reflection.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/__pycache__/reflection.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/__pycache__/runtime_version.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/__pycache__/runtime_version.cpython-312.pyc index 6caf8027..feaa2e96 100644 Binary files a/venv/Lib/site-packages/google/protobuf/__pycache__/runtime_version.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/__pycache__/runtime_version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/__pycache__/symbol_database.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/__pycache__/symbol_database.cpython-312.pyc index 3baf061f..2318fcec 100644 Binary files a/venv/Lib/site-packages/google/protobuf/__pycache__/symbol_database.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/__pycache__/symbol_database.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/__pycache__/text_encoding.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/__pycache__/text_encoding.cpython-312.pyc index 0d4a0aa5..b0fff9bc 100644 Binary files a/venv/Lib/site-packages/google/protobuf/__pycache__/text_encoding.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/__pycache__/text_encoding.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/__pycache__/text_format.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/__pycache__/text_format.cpython-312.pyc index 6eacd6c2..58dfeb3d 100644 Binary files a/venv/Lib/site-packages/google/protobuf/__pycache__/text_format.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/__pycache__/text_format.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/__pycache__/timestamp_pb2.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/__pycache__/timestamp_pb2.cpython-312.pyc index c84504dc..7643bbb7 100644 Binary files a/venv/Lib/site-packages/google/protobuf/__pycache__/timestamp_pb2.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/__pycache__/timestamp_pb2.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/__pycache__/unknown_fields.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/__pycache__/unknown_fields.cpython-312.pyc index 9f5d95b8..3db00309 100644 Binary files a/venv/Lib/site-packages/google/protobuf/__pycache__/unknown_fields.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/__pycache__/unknown_fields.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/__init__.cpython-312.pyc index 1dd68a21..e1c22b85 100644 Binary files a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/api_implementation.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/api_implementation.cpython-312.pyc index 4d963975..60f48eef 100644 Binary files a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/api_implementation.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/api_implementation.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/builder.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/builder.cpython-312.pyc index 6f42d514..931855d8 100644 Binary files a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/builder.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/builder.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/containers.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/containers.cpython-312.pyc index eba8d290..0c672332 100644 Binary files a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/containers.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/containers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/decoder.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/decoder.cpython-312.pyc index 464f6475..4f4c82c1 100644 Binary files a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/decoder.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/decoder.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/encoder.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/encoder.cpython-312.pyc index 46c5303b..346940be 100644 Binary files a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/encoder.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/encoder.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/enum_type_wrapper.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/enum_type_wrapper.cpython-312.pyc index aa73bda5..6287b9db 100644 Binary files a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/enum_type_wrapper.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/enum_type_wrapper.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/extension_dict.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/extension_dict.cpython-312.pyc index 910ebb75..45d196ce 100644 Binary files a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/extension_dict.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/extension_dict.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/field_mask.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/field_mask.cpython-312.pyc index e9af34a9..89cd011d 100644 Binary files a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/field_mask.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/field_mask.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/message_listener.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/message_listener.cpython-312.pyc index 01a946a7..13bd47c2 100644 Binary files a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/message_listener.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/message_listener.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/python_edition_defaults.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/python_edition_defaults.cpython-312.pyc index 148fec00..dcbe5719 100644 Binary files a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/python_edition_defaults.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/python_edition_defaults.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/python_message.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/python_message.cpython-312.pyc index 54f79047..3d82241e 100644 Binary files a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/python_message.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/python_message.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/type_checkers.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/type_checkers.cpython-312.pyc index f10e21be..dc37f5b3 100644 Binary files a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/type_checkers.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/type_checkers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/well_known_types.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/well_known_types.cpython-312.pyc index c56b7d67..529b1d9a 100644 Binary files a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/well_known_types.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/well_known_types.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/wire_format.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/wire_format.cpython-312.pyc index 478158e8..18588d38 100644 Binary files a/venv/Lib/site-packages/google/protobuf/internal/__pycache__/wire_format.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/internal/__pycache__/wire_format.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/pyext/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/pyext/__pycache__/__init__.cpython-312.pyc index 8acaef3b..d9239b94 100644 Binary files a/venv/Lib/site-packages/google/protobuf/pyext/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/pyext/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/google/protobuf/pyext/__pycache__/cpp_message.cpython-312.pyc b/venv/Lib/site-packages/google/protobuf/pyext/__pycache__/cpp_message.cpython-312.pyc index 74c5d9d5..e48e123d 100644 Binary files a/venv/Lib/site-packages/google/protobuf/pyext/__pycache__/cpp_message.cpython-312.pyc and b/venv/Lib/site-packages/google/protobuf/pyext/__pycache__/cpp_message.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/h11/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/h11/__pycache__/__init__.cpython-312.pyc index e6e0b3a1..1a57fd0d 100644 Binary files a/venv/Lib/site-packages/h11/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/h11/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/h11/__pycache__/_abnf.cpython-312.pyc b/venv/Lib/site-packages/h11/__pycache__/_abnf.cpython-312.pyc index 61b5aa53..71dd85fc 100644 Binary files a/venv/Lib/site-packages/h11/__pycache__/_abnf.cpython-312.pyc and b/venv/Lib/site-packages/h11/__pycache__/_abnf.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/h11/__pycache__/_connection.cpython-312.pyc b/venv/Lib/site-packages/h11/__pycache__/_connection.cpython-312.pyc index 21f15fe9..3af04d3c 100644 Binary files a/venv/Lib/site-packages/h11/__pycache__/_connection.cpython-312.pyc and b/venv/Lib/site-packages/h11/__pycache__/_connection.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/h11/__pycache__/_events.cpython-312.pyc b/venv/Lib/site-packages/h11/__pycache__/_events.cpython-312.pyc index dd454e97..65cfe71e 100644 Binary files a/venv/Lib/site-packages/h11/__pycache__/_events.cpython-312.pyc and b/venv/Lib/site-packages/h11/__pycache__/_events.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/h11/__pycache__/_headers.cpython-312.pyc b/venv/Lib/site-packages/h11/__pycache__/_headers.cpython-312.pyc index 1c7ef164..b9cdc53f 100644 Binary files a/venv/Lib/site-packages/h11/__pycache__/_headers.cpython-312.pyc and b/venv/Lib/site-packages/h11/__pycache__/_headers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/h11/__pycache__/_readers.cpython-312.pyc b/venv/Lib/site-packages/h11/__pycache__/_readers.cpython-312.pyc index 84745bbb..95acb44f 100644 Binary files a/venv/Lib/site-packages/h11/__pycache__/_readers.cpython-312.pyc and b/venv/Lib/site-packages/h11/__pycache__/_readers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/h11/__pycache__/_receivebuffer.cpython-312.pyc b/venv/Lib/site-packages/h11/__pycache__/_receivebuffer.cpython-312.pyc index 28826197..d27d6e78 100644 Binary files a/venv/Lib/site-packages/h11/__pycache__/_receivebuffer.cpython-312.pyc and b/venv/Lib/site-packages/h11/__pycache__/_receivebuffer.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/h11/__pycache__/_state.cpython-312.pyc b/venv/Lib/site-packages/h11/__pycache__/_state.cpython-312.pyc index 1602c623..63f583b8 100644 Binary files a/venv/Lib/site-packages/h11/__pycache__/_state.cpython-312.pyc and b/venv/Lib/site-packages/h11/__pycache__/_state.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/h11/__pycache__/_util.cpython-312.pyc b/venv/Lib/site-packages/h11/__pycache__/_util.cpython-312.pyc index 87e3b470..e51952bc 100644 Binary files a/venv/Lib/site-packages/h11/__pycache__/_util.cpython-312.pyc and b/venv/Lib/site-packages/h11/__pycache__/_util.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/h11/__pycache__/_version.cpython-312.pyc b/venv/Lib/site-packages/h11/__pycache__/_version.cpython-312.pyc index f948d9c8..cc2a69a4 100644 Binary files a/venv/Lib/site-packages/h11/__pycache__/_version.cpython-312.pyc and b/venv/Lib/site-packages/h11/__pycache__/_version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/h11/__pycache__/_writers.cpython-312.pyc b/venv/Lib/site-packages/h11/__pycache__/_writers.cpython-312.pyc index e7538f10..1fa94c44 100644 Binary files a/venv/Lib/site-packages/h11/__pycache__/_writers.cpython-312.pyc and b/venv/Lib/site-packages/h11/__pycache__/_writers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/httpcore/__pycache__/__init__.cpython-312.pyc index 55a826cf..87c31c25 100644 Binary files a/venv/Lib/site-packages/httpcore/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/__pycache__/_api.cpython-312.pyc b/venv/Lib/site-packages/httpcore/__pycache__/_api.cpython-312.pyc index 8f48a618..ce5d1d6b 100644 Binary files a/venv/Lib/site-packages/httpcore/__pycache__/_api.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/__pycache__/_api.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/__pycache__/_exceptions.cpython-312.pyc b/venv/Lib/site-packages/httpcore/__pycache__/_exceptions.cpython-312.pyc index ea6c953a..473b886a 100644 Binary files a/venv/Lib/site-packages/httpcore/__pycache__/_exceptions.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/__pycache__/_exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/__pycache__/_models.cpython-312.pyc b/venv/Lib/site-packages/httpcore/__pycache__/_models.cpython-312.pyc index e1ef7b1e..7776d9b2 100644 Binary files a/venv/Lib/site-packages/httpcore/__pycache__/_models.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/__pycache__/_models.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/__pycache__/_ssl.cpython-312.pyc b/venv/Lib/site-packages/httpcore/__pycache__/_ssl.cpython-312.pyc index cd0b9ba9..b1875ace 100644 Binary files a/venv/Lib/site-packages/httpcore/__pycache__/_ssl.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/__pycache__/_ssl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/__pycache__/_synchronization.cpython-312.pyc b/venv/Lib/site-packages/httpcore/__pycache__/_synchronization.cpython-312.pyc index a8e6f670..0a72721f 100644 Binary files a/venv/Lib/site-packages/httpcore/__pycache__/_synchronization.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/__pycache__/_synchronization.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/__pycache__/_trace.cpython-312.pyc b/venv/Lib/site-packages/httpcore/__pycache__/_trace.cpython-312.pyc index fdb518ff..b75086a1 100644 Binary files a/venv/Lib/site-packages/httpcore/__pycache__/_trace.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/__pycache__/_trace.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/__pycache__/_utils.cpython-312.pyc b/venv/Lib/site-packages/httpcore/__pycache__/_utils.cpython-312.pyc index 6bc68b29..b461dd07 100644 Binary files a/venv/Lib/site-packages/httpcore/__pycache__/_utils.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/__pycache__/_utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/_async/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/httpcore/_async/__pycache__/__init__.cpython-312.pyc index b9a94f26..69cd0978 100644 Binary files a/venv/Lib/site-packages/httpcore/_async/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/_async/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/_async/__pycache__/connection.cpython-312.pyc b/venv/Lib/site-packages/httpcore/_async/__pycache__/connection.cpython-312.pyc index 5b26db49..442eb81a 100644 Binary files a/venv/Lib/site-packages/httpcore/_async/__pycache__/connection.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/_async/__pycache__/connection.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/_async/__pycache__/connection_pool.cpython-312.pyc b/venv/Lib/site-packages/httpcore/_async/__pycache__/connection_pool.cpython-312.pyc index 09ebd7ed..d123747f 100644 Binary files a/venv/Lib/site-packages/httpcore/_async/__pycache__/connection_pool.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/_async/__pycache__/connection_pool.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/_async/__pycache__/http11.cpython-312.pyc b/venv/Lib/site-packages/httpcore/_async/__pycache__/http11.cpython-312.pyc index 5bd5bfbb..bde7a8d3 100644 Binary files a/venv/Lib/site-packages/httpcore/_async/__pycache__/http11.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/_async/__pycache__/http11.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/_async/__pycache__/http2.cpython-312.pyc b/venv/Lib/site-packages/httpcore/_async/__pycache__/http2.cpython-312.pyc index ccc28a97..a79f6995 100644 Binary files a/venv/Lib/site-packages/httpcore/_async/__pycache__/http2.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/_async/__pycache__/http2.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/_async/__pycache__/http_proxy.cpython-312.pyc b/venv/Lib/site-packages/httpcore/_async/__pycache__/http_proxy.cpython-312.pyc index 5dbd7164..6d1c773f 100644 Binary files a/venv/Lib/site-packages/httpcore/_async/__pycache__/http_proxy.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/_async/__pycache__/http_proxy.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/_async/__pycache__/interfaces.cpython-312.pyc b/venv/Lib/site-packages/httpcore/_async/__pycache__/interfaces.cpython-312.pyc index 61d9d01c..703935ed 100644 Binary files a/venv/Lib/site-packages/httpcore/_async/__pycache__/interfaces.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/_async/__pycache__/interfaces.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/_async/__pycache__/socks_proxy.cpython-312.pyc b/venv/Lib/site-packages/httpcore/_async/__pycache__/socks_proxy.cpython-312.pyc index 43a2aaf6..86d04f92 100644 Binary files a/venv/Lib/site-packages/httpcore/_async/__pycache__/socks_proxy.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/_async/__pycache__/socks_proxy.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/_backends/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/httpcore/_backends/__pycache__/__init__.cpython-312.pyc index 894437d8..9ae64c6f 100644 Binary files a/venv/Lib/site-packages/httpcore/_backends/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/_backends/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/_backends/__pycache__/anyio.cpython-312.pyc b/venv/Lib/site-packages/httpcore/_backends/__pycache__/anyio.cpython-312.pyc index 7ed9d0b0..bd7dc66d 100644 Binary files a/venv/Lib/site-packages/httpcore/_backends/__pycache__/anyio.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/_backends/__pycache__/anyio.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/_backends/__pycache__/auto.cpython-312.pyc b/venv/Lib/site-packages/httpcore/_backends/__pycache__/auto.cpython-312.pyc index 529d97cf..6b0bcdfa 100644 Binary files a/venv/Lib/site-packages/httpcore/_backends/__pycache__/auto.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/_backends/__pycache__/auto.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/_backends/__pycache__/base.cpython-312.pyc b/venv/Lib/site-packages/httpcore/_backends/__pycache__/base.cpython-312.pyc index c77e153c..403e62cc 100644 Binary files a/venv/Lib/site-packages/httpcore/_backends/__pycache__/base.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/_backends/__pycache__/base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/_backends/__pycache__/mock.cpython-312.pyc b/venv/Lib/site-packages/httpcore/_backends/__pycache__/mock.cpython-312.pyc index 9fd9c8d0..e1d323c2 100644 Binary files a/venv/Lib/site-packages/httpcore/_backends/__pycache__/mock.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/_backends/__pycache__/mock.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/_backends/__pycache__/sync.cpython-312.pyc b/venv/Lib/site-packages/httpcore/_backends/__pycache__/sync.cpython-312.pyc index a3500bc6..049ed0b8 100644 Binary files a/venv/Lib/site-packages/httpcore/_backends/__pycache__/sync.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/_backends/__pycache__/sync.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/_backends/__pycache__/trio.cpython-312.pyc b/venv/Lib/site-packages/httpcore/_backends/__pycache__/trio.cpython-312.pyc index 16429032..2fe24ad7 100644 Binary files a/venv/Lib/site-packages/httpcore/_backends/__pycache__/trio.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/_backends/__pycache__/trio.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/_sync/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/httpcore/_sync/__pycache__/__init__.cpython-312.pyc index dbf24c7a..ef09017b 100644 Binary files a/venv/Lib/site-packages/httpcore/_sync/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/_sync/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/_sync/__pycache__/connection.cpython-312.pyc b/venv/Lib/site-packages/httpcore/_sync/__pycache__/connection.cpython-312.pyc index 7dd24cd5..fb743a67 100644 Binary files a/venv/Lib/site-packages/httpcore/_sync/__pycache__/connection.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/_sync/__pycache__/connection.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/_sync/__pycache__/connection_pool.cpython-312.pyc b/venv/Lib/site-packages/httpcore/_sync/__pycache__/connection_pool.cpython-312.pyc index 6084e5c7..081cfc3c 100644 Binary files a/venv/Lib/site-packages/httpcore/_sync/__pycache__/connection_pool.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/_sync/__pycache__/connection_pool.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/_sync/__pycache__/http11.cpython-312.pyc b/venv/Lib/site-packages/httpcore/_sync/__pycache__/http11.cpython-312.pyc index 8d2629a7..45607510 100644 Binary files a/venv/Lib/site-packages/httpcore/_sync/__pycache__/http11.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/_sync/__pycache__/http11.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/_sync/__pycache__/http2.cpython-312.pyc b/venv/Lib/site-packages/httpcore/_sync/__pycache__/http2.cpython-312.pyc index fa2d17d3..a014fef8 100644 Binary files a/venv/Lib/site-packages/httpcore/_sync/__pycache__/http2.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/_sync/__pycache__/http2.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/_sync/__pycache__/http_proxy.cpython-312.pyc b/venv/Lib/site-packages/httpcore/_sync/__pycache__/http_proxy.cpython-312.pyc index f0d1fcea..4e668fd9 100644 Binary files a/venv/Lib/site-packages/httpcore/_sync/__pycache__/http_proxy.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/_sync/__pycache__/http_proxy.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/_sync/__pycache__/interfaces.cpython-312.pyc b/venv/Lib/site-packages/httpcore/_sync/__pycache__/interfaces.cpython-312.pyc index 30364159..be87defb 100644 Binary files a/venv/Lib/site-packages/httpcore/_sync/__pycache__/interfaces.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/_sync/__pycache__/interfaces.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpcore/_sync/__pycache__/socks_proxy.cpython-312.pyc b/venv/Lib/site-packages/httpcore/_sync/__pycache__/socks_proxy.cpython-312.pyc index 4b9c364d..9609bb46 100644 Binary files a/venv/Lib/site-packages/httpcore/_sync/__pycache__/socks_proxy.cpython-312.pyc and b/venv/Lib/site-packages/httpcore/_sync/__pycache__/socks_proxy.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpx/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/httpx/__pycache__/__init__.cpython-312.pyc index fca42c0c..48d4c896 100644 Binary files a/venv/Lib/site-packages/httpx/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/httpx/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpx/__pycache__/__version__.cpython-312.pyc b/venv/Lib/site-packages/httpx/__pycache__/__version__.cpython-312.pyc index c25dcaf3..c7618fa7 100644 Binary files a/venv/Lib/site-packages/httpx/__pycache__/__version__.cpython-312.pyc and b/venv/Lib/site-packages/httpx/__pycache__/__version__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpx/__pycache__/_api.cpython-312.pyc b/venv/Lib/site-packages/httpx/__pycache__/_api.cpython-312.pyc index 59bbd01e..4d4c2ff2 100644 Binary files a/venv/Lib/site-packages/httpx/__pycache__/_api.cpython-312.pyc and b/venv/Lib/site-packages/httpx/__pycache__/_api.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpx/__pycache__/_auth.cpython-312.pyc b/venv/Lib/site-packages/httpx/__pycache__/_auth.cpython-312.pyc index c4413bcd..083f90aa 100644 Binary files a/venv/Lib/site-packages/httpx/__pycache__/_auth.cpython-312.pyc and b/venv/Lib/site-packages/httpx/__pycache__/_auth.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpx/__pycache__/_client.cpython-312.pyc b/venv/Lib/site-packages/httpx/__pycache__/_client.cpython-312.pyc index 1bf3ba12..8b48e1e6 100644 Binary files a/venv/Lib/site-packages/httpx/__pycache__/_client.cpython-312.pyc and b/venv/Lib/site-packages/httpx/__pycache__/_client.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpx/__pycache__/_config.cpython-312.pyc b/venv/Lib/site-packages/httpx/__pycache__/_config.cpython-312.pyc index a17d5693..649a10b4 100644 Binary files a/venv/Lib/site-packages/httpx/__pycache__/_config.cpython-312.pyc and b/venv/Lib/site-packages/httpx/__pycache__/_config.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpx/__pycache__/_content.cpython-312.pyc b/venv/Lib/site-packages/httpx/__pycache__/_content.cpython-312.pyc index a2d08e4c..ab6afbe0 100644 Binary files a/venv/Lib/site-packages/httpx/__pycache__/_content.cpython-312.pyc and b/venv/Lib/site-packages/httpx/__pycache__/_content.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpx/__pycache__/_decoders.cpython-312.pyc b/venv/Lib/site-packages/httpx/__pycache__/_decoders.cpython-312.pyc index 1106f61b..8bc5daa6 100644 Binary files a/venv/Lib/site-packages/httpx/__pycache__/_decoders.cpython-312.pyc and b/venv/Lib/site-packages/httpx/__pycache__/_decoders.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpx/__pycache__/_exceptions.cpython-312.pyc b/venv/Lib/site-packages/httpx/__pycache__/_exceptions.cpython-312.pyc index 2bcc0f5d..61e61b76 100644 Binary files a/venv/Lib/site-packages/httpx/__pycache__/_exceptions.cpython-312.pyc and b/venv/Lib/site-packages/httpx/__pycache__/_exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpx/__pycache__/_main.cpython-312.pyc b/venv/Lib/site-packages/httpx/__pycache__/_main.cpython-312.pyc index 9a820a7c..a88a19f2 100644 Binary files a/venv/Lib/site-packages/httpx/__pycache__/_main.cpython-312.pyc and b/venv/Lib/site-packages/httpx/__pycache__/_main.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpx/__pycache__/_models.cpython-312.pyc b/venv/Lib/site-packages/httpx/__pycache__/_models.cpython-312.pyc index 18a99338..0ebb5779 100644 Binary files a/venv/Lib/site-packages/httpx/__pycache__/_models.cpython-312.pyc and b/venv/Lib/site-packages/httpx/__pycache__/_models.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpx/__pycache__/_multipart.cpython-312.pyc b/venv/Lib/site-packages/httpx/__pycache__/_multipart.cpython-312.pyc index d5b9d187..41f186ec 100644 Binary files a/venv/Lib/site-packages/httpx/__pycache__/_multipart.cpython-312.pyc and b/venv/Lib/site-packages/httpx/__pycache__/_multipart.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpx/__pycache__/_status_codes.cpython-312.pyc b/venv/Lib/site-packages/httpx/__pycache__/_status_codes.cpython-312.pyc index 3c882f26..be2c4c5a 100644 Binary files a/venv/Lib/site-packages/httpx/__pycache__/_status_codes.cpython-312.pyc and b/venv/Lib/site-packages/httpx/__pycache__/_status_codes.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpx/__pycache__/_types.cpython-312.pyc b/venv/Lib/site-packages/httpx/__pycache__/_types.cpython-312.pyc index bc008da7..edc7f666 100644 Binary files a/venv/Lib/site-packages/httpx/__pycache__/_types.cpython-312.pyc and b/venv/Lib/site-packages/httpx/__pycache__/_types.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpx/__pycache__/_urlparse.cpython-312.pyc b/venv/Lib/site-packages/httpx/__pycache__/_urlparse.cpython-312.pyc index 613f89a6..79e844b6 100644 Binary files a/venv/Lib/site-packages/httpx/__pycache__/_urlparse.cpython-312.pyc and b/venv/Lib/site-packages/httpx/__pycache__/_urlparse.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpx/__pycache__/_urls.cpython-312.pyc b/venv/Lib/site-packages/httpx/__pycache__/_urls.cpython-312.pyc index a0033f9a..1a139a53 100644 Binary files a/venv/Lib/site-packages/httpx/__pycache__/_urls.cpython-312.pyc and b/venv/Lib/site-packages/httpx/__pycache__/_urls.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpx/__pycache__/_utils.cpython-312.pyc b/venv/Lib/site-packages/httpx/__pycache__/_utils.cpython-312.pyc index 68d53fa0..a1575771 100644 Binary files a/venv/Lib/site-packages/httpx/__pycache__/_utils.cpython-312.pyc and b/venv/Lib/site-packages/httpx/__pycache__/_utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpx/_transports/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/httpx/_transports/__pycache__/__init__.cpython-312.pyc index 2f689500..2603e5cd 100644 Binary files a/venv/Lib/site-packages/httpx/_transports/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/httpx/_transports/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpx/_transports/__pycache__/asgi.cpython-312.pyc b/venv/Lib/site-packages/httpx/_transports/__pycache__/asgi.cpython-312.pyc index 57b04808..88f3a7c8 100644 Binary files a/venv/Lib/site-packages/httpx/_transports/__pycache__/asgi.cpython-312.pyc and b/venv/Lib/site-packages/httpx/_transports/__pycache__/asgi.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpx/_transports/__pycache__/base.cpython-312.pyc b/venv/Lib/site-packages/httpx/_transports/__pycache__/base.cpython-312.pyc index 6f903175..8923a961 100644 Binary files a/venv/Lib/site-packages/httpx/_transports/__pycache__/base.cpython-312.pyc and b/venv/Lib/site-packages/httpx/_transports/__pycache__/base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpx/_transports/__pycache__/default.cpython-312.pyc b/venv/Lib/site-packages/httpx/_transports/__pycache__/default.cpython-312.pyc index 2d757e63..67129ca5 100644 Binary files a/venv/Lib/site-packages/httpx/_transports/__pycache__/default.cpython-312.pyc and b/venv/Lib/site-packages/httpx/_transports/__pycache__/default.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpx/_transports/__pycache__/mock.cpython-312.pyc b/venv/Lib/site-packages/httpx/_transports/__pycache__/mock.cpython-312.pyc index 6b8bb16e..52482ee0 100644 Binary files a/venv/Lib/site-packages/httpx/_transports/__pycache__/mock.cpython-312.pyc and b/venv/Lib/site-packages/httpx/_transports/__pycache__/mock.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/httpx/_transports/__pycache__/wsgi.cpython-312.pyc b/venv/Lib/site-packages/httpx/_transports/__pycache__/wsgi.cpython-312.pyc index 6dcb055b..e0f2a854 100644 Binary files a/venv/Lib/site-packages/httpx/_transports/__pycache__/wsgi.cpython-312.pyc and b/venv/Lib/site-packages/httpx/_transports/__pycache__/wsgi.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/idna/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/idna/__pycache__/__init__.cpython-312.pyc index b741a48c..863466ea 100644 Binary files a/venv/Lib/site-packages/idna/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/idna/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/idna/__pycache__/core.cpython-312.pyc b/venv/Lib/site-packages/idna/__pycache__/core.cpython-312.pyc index f2791514..6f0a4907 100644 Binary files a/venv/Lib/site-packages/idna/__pycache__/core.cpython-312.pyc and b/venv/Lib/site-packages/idna/__pycache__/core.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/idna/__pycache__/idnadata.cpython-312.pyc b/venv/Lib/site-packages/idna/__pycache__/idnadata.cpython-312.pyc index 1ac20710..003adc0e 100644 Binary files a/venv/Lib/site-packages/idna/__pycache__/idnadata.cpython-312.pyc and b/venv/Lib/site-packages/idna/__pycache__/idnadata.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/idna/__pycache__/intranges.cpython-312.pyc b/venv/Lib/site-packages/idna/__pycache__/intranges.cpython-312.pyc index a66af7ad..4a199b38 100644 Binary files a/venv/Lib/site-packages/idna/__pycache__/intranges.cpython-312.pyc and b/venv/Lib/site-packages/idna/__pycache__/intranges.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/idna/__pycache__/package_data.cpython-312.pyc b/venv/Lib/site-packages/idna/__pycache__/package_data.cpython-312.pyc index 9488a73a..73d556b0 100644 Binary files a/venv/Lib/site-packages/idna/__pycache__/package_data.cpython-312.pyc and b/venv/Lib/site-packages/idna/__pycache__/package_data.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/jiter/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/jiter/__pycache__/__init__.cpython-312.pyc index fdd55e34..7c9b1c50 100644 Binary files a/venv/Lib/site-packages/jiter/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/jiter/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/jwt/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/jwt/__pycache__/__init__.cpython-312.pyc index 884231fc..e91692ff 100644 Binary files a/venv/Lib/site-packages/jwt/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/jwt/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/jwt/__pycache__/algorithms.cpython-312.pyc b/venv/Lib/site-packages/jwt/__pycache__/algorithms.cpython-312.pyc index 25cc12a3..b5453f1d 100644 Binary files a/venv/Lib/site-packages/jwt/__pycache__/algorithms.cpython-312.pyc and b/venv/Lib/site-packages/jwt/__pycache__/algorithms.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/jwt/__pycache__/api_jwk.cpython-312.pyc b/venv/Lib/site-packages/jwt/__pycache__/api_jwk.cpython-312.pyc index 95dba171..e5c9884b 100644 Binary files a/venv/Lib/site-packages/jwt/__pycache__/api_jwk.cpython-312.pyc and b/venv/Lib/site-packages/jwt/__pycache__/api_jwk.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/jwt/__pycache__/api_jws.cpython-312.pyc b/venv/Lib/site-packages/jwt/__pycache__/api_jws.cpython-312.pyc index eb5783da..e063e89c 100644 Binary files a/venv/Lib/site-packages/jwt/__pycache__/api_jws.cpython-312.pyc and b/venv/Lib/site-packages/jwt/__pycache__/api_jws.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/jwt/__pycache__/api_jwt.cpython-312.pyc b/venv/Lib/site-packages/jwt/__pycache__/api_jwt.cpython-312.pyc index aa1b05d8..15f0d03f 100644 Binary files a/venv/Lib/site-packages/jwt/__pycache__/api_jwt.cpython-312.pyc and b/venv/Lib/site-packages/jwt/__pycache__/api_jwt.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/jwt/__pycache__/exceptions.cpython-312.pyc b/venv/Lib/site-packages/jwt/__pycache__/exceptions.cpython-312.pyc index d1684f8f..b88a60ac 100644 Binary files a/venv/Lib/site-packages/jwt/__pycache__/exceptions.cpython-312.pyc and b/venv/Lib/site-packages/jwt/__pycache__/exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/jwt/__pycache__/jwk_set_cache.cpython-312.pyc b/venv/Lib/site-packages/jwt/__pycache__/jwk_set_cache.cpython-312.pyc index 0940b80d..e923b5a5 100644 Binary files a/venv/Lib/site-packages/jwt/__pycache__/jwk_set_cache.cpython-312.pyc and b/venv/Lib/site-packages/jwt/__pycache__/jwk_set_cache.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/jwt/__pycache__/jwks_client.cpython-312.pyc b/venv/Lib/site-packages/jwt/__pycache__/jwks_client.cpython-312.pyc index 1e475ff0..db37ae61 100644 Binary files a/venv/Lib/site-packages/jwt/__pycache__/jwks_client.cpython-312.pyc and b/venv/Lib/site-packages/jwt/__pycache__/jwks_client.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/jwt/__pycache__/types.cpython-312.pyc b/venv/Lib/site-packages/jwt/__pycache__/types.cpython-312.pyc index 3b573fbe..aef58581 100644 Binary files a/venv/Lib/site-packages/jwt/__pycache__/types.cpython-312.pyc and b/venv/Lib/site-packages/jwt/__pycache__/types.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/jwt/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/jwt/__pycache__/utils.cpython-312.pyc index 0cd57b3e..d719c33b 100644 Binary files a/venv/Lib/site-packages/jwt/__pycache__/utils.cpython-312.pyc and b/venv/Lib/site-packages/jwt/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/jwt/__pycache__/warnings.cpython-312.pyc b/venv/Lib/site-packages/jwt/__pycache__/warnings.cpython-312.pyc index 3f21c9c4..94f380fb 100644 Binary files a/venv/Lib/site-packages/jwt/__pycache__/warnings.cpython-312.pyc and b/venv/Lib/site-packages/jwt/__pycache__/warnings.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/__pycache__/__init__.cpython-312.pyc index 54718518..ce346daf 100644 Binary files a/venv/Lib/site-packages/livekit/agents/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/__pycache__/_exceptions.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/__pycache__/_exceptions.cpython-312.pyc index 94ce46f0..d570cee8 100644 Binary files a/venv/Lib/site-packages/livekit/agents/__pycache__/_exceptions.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/__pycache__/_exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/__pycache__/http_server.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/__pycache__/http_server.cpython-312.pyc index b6eeb119..7d10acdc 100644 Binary files a/venv/Lib/site-packages/livekit/agents/__pycache__/http_server.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/__pycache__/http_server.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/__pycache__/inference_runner.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/__pycache__/inference_runner.cpython-312.pyc index d648e83a..1fec5e08 100644 Binary files a/venv/Lib/site-packages/livekit/agents/__pycache__/inference_runner.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/__pycache__/inference_runner.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/__pycache__/job.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/__pycache__/job.cpython-312.pyc index 6300e88f..42261acb 100644 Binary files a/venv/Lib/site-packages/livekit/agents/__pycache__/job.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/__pycache__/job.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/__pycache__/log.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/__pycache__/log.cpython-312.pyc index ad29163d..8f3e57af 100644 Binary files a/venv/Lib/site-packages/livekit/agents/__pycache__/log.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/__pycache__/log.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/__pycache__/plugin.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/__pycache__/plugin.cpython-312.pyc index 608a6989..a2d9da68 100644 Binary files a/venv/Lib/site-packages/livekit/agents/__pycache__/plugin.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/__pycache__/plugin.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/__pycache__/types.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/__pycache__/types.cpython-312.pyc index 29b60f45..9bf73f10 100644 Binary files a/venv/Lib/site-packages/livekit/agents/__pycache__/types.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/__pycache__/types.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/__pycache__/vad.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/__pycache__/vad.cpython-312.pyc index 62c606b2..e73ee63d 100644 Binary files a/venv/Lib/site-packages/livekit/agents/__pycache__/vad.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/__pycache__/vad.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/__pycache__/version.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/__pycache__/version.cpython-312.pyc index d16ced18..59d65bb0 100644 Binary files a/venv/Lib/site-packages/livekit/agents/__pycache__/version.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/__pycache__/version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/__pycache__/worker.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/__pycache__/worker.cpython-312.pyc index 58d20f4e..9d2f965f 100644 Binary files a/venv/Lib/site-packages/livekit/agents/__pycache__/worker.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/__pycache__/worker.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/cli/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/cli/__pycache__/__init__.cpython-312.pyc index 2be00816..5f31a92e 100644 Binary files a/venv/Lib/site-packages/livekit/agents/cli/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/cli/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/cli/__pycache__/_run.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/cli/__pycache__/_run.cpython-312.pyc index 661fdbf0..9ea93a9b 100644 Binary files a/venv/Lib/site-packages/livekit/agents/cli/__pycache__/_run.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/cli/__pycache__/_run.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/cli/__pycache__/cli.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/cli/__pycache__/cli.cpython-312.pyc index 7aa3680b..7e53c687 100644 Binary files a/venv/Lib/site-packages/livekit/agents/cli/__pycache__/cli.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/cli/__pycache__/cli.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/cli/__pycache__/log.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/cli/__pycache__/log.cpython-312.pyc index dff74e14..2e8347ef 100644 Binary files a/venv/Lib/site-packages/livekit/agents/cli/__pycache__/log.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/cli/__pycache__/log.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/cli/__pycache__/proto.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/cli/__pycache__/proto.cpython-312.pyc index 98f87cdc..b7794fff 100644 Binary files a/venv/Lib/site-packages/livekit/agents/cli/__pycache__/proto.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/cli/__pycache__/proto.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/debug/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/debug/__pycache__/__init__.cpython-312.pyc index 01221af9..58f7a6b2 100644 Binary files a/venv/Lib/site-packages/livekit/agents/debug/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/debug/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/debug/__pycache__/tracing.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/debug/__pycache__/tracing.cpython-312.pyc index 6b0c9664..efdba5a9 100644 Binary files a/venv/Lib/site-packages/livekit/agents/debug/__pycache__/tracing.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/debug/__pycache__/tracing.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/__init__.cpython-312.pyc index c5412a43..d31f1dd5 100644 Binary files a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/channel.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/channel.cpython-312.pyc index cbedd69b..5a72a03b 100644 Binary files a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/channel.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/channel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/inference_executor.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/inference_executor.cpython-312.pyc index fe5bc183..5a186095 100644 Binary files a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/inference_executor.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/inference_executor.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/inference_proc_executor.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/inference_proc_executor.cpython-312.pyc index ec26bd29..877b6baf 100644 Binary files a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/inference_proc_executor.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/inference_proc_executor.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/inference_proc_lazy_main.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/inference_proc_lazy_main.cpython-312.pyc index b56aa93c..5eff6ba7 100644 Binary files a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/inference_proc_lazy_main.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/inference_proc_lazy_main.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/job_executor.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/job_executor.cpython-312.pyc index be0a7446..46b94171 100644 Binary files a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/job_executor.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/job_executor.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/job_proc_executor.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/job_proc_executor.cpython-312.pyc index d140a631..e91569fb 100644 Binary files a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/job_proc_executor.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/job_proc_executor.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/job_proc_lazy_main.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/job_proc_lazy_main.cpython-312.pyc index f3173aba..42a3e544 100644 Binary files a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/job_proc_lazy_main.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/job_proc_lazy_main.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/job_thread_executor.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/job_thread_executor.cpython-312.pyc index 7122b7af..ce1225e5 100644 Binary files a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/job_thread_executor.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/job_thread_executor.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/log_queue.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/log_queue.cpython-312.pyc index 16a90185..f59fc696 100644 Binary files a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/log_queue.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/log_queue.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/proc_client.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/proc_client.cpython-312.pyc index 5e65567c..87b3e479 100644 Binary files a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/proc_client.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/proc_client.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/proc_pool.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/proc_pool.cpython-312.pyc index b710e500..6516c522 100644 Binary files a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/proc_pool.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/proc_pool.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/proto.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/proto.cpython-312.pyc index 1115ab5d..b4b51ec8 100644 Binary files a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/proto.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/proto.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/supervised_proc.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/supervised_proc.cpython-312.pyc index 7a5d1b5e..046865a5 100644 Binary files a/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/supervised_proc.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/ipc/__pycache__/supervised_proc.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/llm/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/llm/__pycache__/__init__.cpython-312.pyc index 3462db80..e46008cc 100644 Binary files a/venv/Lib/site-packages/livekit/agents/llm/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/llm/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/llm/__pycache__/_strict.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/llm/__pycache__/_strict.cpython-312.pyc index 644fdaff..ae8c4408 100644 Binary files a/venv/Lib/site-packages/livekit/agents/llm/__pycache__/_strict.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/llm/__pycache__/_strict.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/llm/__pycache__/chat_context.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/llm/__pycache__/chat_context.cpython-312.pyc index 0d18be07..9a3b7443 100644 Binary files a/venv/Lib/site-packages/livekit/agents/llm/__pycache__/chat_context.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/llm/__pycache__/chat_context.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/llm/__pycache__/fallback_adapter.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/llm/__pycache__/fallback_adapter.cpython-312.pyc index ad663215..adadd888 100644 Binary files a/venv/Lib/site-packages/livekit/agents/llm/__pycache__/fallback_adapter.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/llm/__pycache__/fallback_adapter.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/llm/__pycache__/llm.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/llm/__pycache__/llm.cpython-312.pyc index c42d6878..0061d2eb 100644 Binary files a/venv/Lib/site-packages/livekit/agents/llm/__pycache__/llm.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/llm/__pycache__/llm.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/llm/__pycache__/realtime.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/llm/__pycache__/realtime.cpython-312.pyc index d18e1aa6..52ca60be 100644 Binary files a/venv/Lib/site-packages/livekit/agents/llm/__pycache__/realtime.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/llm/__pycache__/realtime.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/llm/__pycache__/remote_chat_context.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/llm/__pycache__/remote_chat_context.cpython-312.pyc index 92a64281..b26d86f7 100644 Binary files a/venv/Lib/site-packages/livekit/agents/llm/__pycache__/remote_chat_context.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/llm/__pycache__/remote_chat_context.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/llm/__pycache__/tool_context.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/llm/__pycache__/tool_context.cpython-312.pyc index af641594..352733f5 100644 Binary files a/venv/Lib/site-packages/livekit/agents/llm/__pycache__/tool_context.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/llm/__pycache__/tool_context.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/llm/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/llm/__pycache__/utils.cpython-312.pyc index b6fcf74f..0045216c 100644 Binary files a/venv/Lib/site-packages/livekit/agents/llm/__pycache__/utils.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/llm/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/metrics/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/metrics/__pycache__/__init__.cpython-312.pyc index 950f1a1b..491c6705 100644 Binary files a/venv/Lib/site-packages/livekit/agents/metrics/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/metrics/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/metrics/__pycache__/base.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/metrics/__pycache__/base.cpython-312.pyc index fde7d3ec..61e21049 100644 Binary files a/venv/Lib/site-packages/livekit/agents/metrics/__pycache__/base.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/metrics/__pycache__/base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/metrics/__pycache__/usage_collector.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/metrics/__pycache__/usage_collector.cpython-312.pyc index bcc6d70c..b5e28dae 100644 Binary files a/venv/Lib/site-packages/livekit/agents/metrics/__pycache__/usage_collector.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/metrics/__pycache__/usage_collector.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/metrics/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/metrics/__pycache__/utils.cpython-312.pyc index d495c04f..c81398bd 100644 Binary files a/venv/Lib/site-packages/livekit/agents/metrics/__pycache__/utils.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/metrics/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/stt/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/stt/__pycache__/__init__.cpython-312.pyc index e95ea2c1..d05969f9 100644 Binary files a/venv/Lib/site-packages/livekit/agents/stt/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/stt/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/stt/__pycache__/fallback_adapter.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/stt/__pycache__/fallback_adapter.cpython-312.pyc index ce72394d..cd978960 100644 Binary files a/venv/Lib/site-packages/livekit/agents/stt/__pycache__/fallback_adapter.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/stt/__pycache__/fallback_adapter.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/stt/__pycache__/stream_adapter.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/stt/__pycache__/stream_adapter.cpython-312.pyc index b904dd3f..e247f69a 100644 Binary files a/venv/Lib/site-packages/livekit/agents/stt/__pycache__/stream_adapter.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/stt/__pycache__/stream_adapter.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/stt/__pycache__/stt.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/stt/__pycache__/stt.cpython-312.pyc index 8fb3c332..3c3c744a 100644 Binary files a/venv/Lib/site-packages/livekit/agents/stt/__pycache__/stt.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/stt/__pycache__/stt.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/__init__.cpython-312.pyc index 6418cea1..547abf0f 100644 Binary files a/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/_basic_hyphenator.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/_basic_hyphenator.cpython-312.pyc index f0a2be8e..4a8500ab 100644 Binary files a/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/_basic_hyphenator.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/_basic_hyphenator.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/_basic_paragraph.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/_basic_paragraph.cpython-312.pyc index f0cc844c..752c0972 100644 Binary files a/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/_basic_paragraph.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/_basic_paragraph.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/_basic_sent.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/_basic_sent.cpython-312.pyc index 7dc9c017..19a64800 100644 Binary files a/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/_basic_sent.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/_basic_sent.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/_basic_word.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/_basic_word.cpython-312.pyc index 8107019e..44d8d041 100644 Binary files a/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/_basic_word.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/_basic_word.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/basic.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/basic.cpython-312.pyc index e9571349..bc07536b 100644 Binary files a/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/basic.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/basic.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/token_stream.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/token_stream.cpython-312.pyc index cad51c1c..1de28416 100644 Binary files a/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/token_stream.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/token_stream.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/tokenizer.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/tokenizer.cpython-312.pyc index 0a869612..df4cd40b 100644 Binary files a/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/tokenizer.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/tokenizer.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/utils.cpython-312.pyc index 5665c8b4..861bad2c 100644 Binary files a/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/utils.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/tokenize/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/tts/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/tts/__pycache__/__init__.cpython-312.pyc index 1e783520..076ec5fd 100644 Binary files a/venv/Lib/site-packages/livekit/agents/tts/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/tts/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/tts/__pycache__/fallback_adapter.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/tts/__pycache__/fallback_adapter.cpython-312.pyc index 922c2479..341dd1a5 100644 Binary files a/venv/Lib/site-packages/livekit/agents/tts/__pycache__/fallback_adapter.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/tts/__pycache__/fallback_adapter.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/tts/__pycache__/stream_adapter.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/tts/__pycache__/stream_adapter.cpython-312.pyc index 4c37a589..af96da80 100644 Binary files a/venv/Lib/site-packages/livekit/agents/tts/__pycache__/stream_adapter.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/tts/__pycache__/stream_adapter.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/tts/__pycache__/tts.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/tts/__pycache__/tts.cpython-312.pyc index a97dd622..028b4539 100644 Binary files a/venv/Lib/site-packages/livekit/agents/tts/__pycache__/tts.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/tts/__pycache__/tts.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/__pycache__/__init__.cpython-312.pyc index db38b8fd..806f2df6 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/__pycache__/audio.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/__pycache__/audio.cpython-312.pyc index c76e4487..8f53c3c6 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/__pycache__/audio.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/__pycache__/audio.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/__pycache__/connection_pool.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/__pycache__/connection_pool.cpython-312.pyc index cb28c0b0..1ac35421 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/__pycache__/connection_pool.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/__pycache__/connection_pool.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/__pycache__/exp_filter.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/__pycache__/exp_filter.cpython-312.pyc index 60cf5e98..db5e3a61 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/__pycache__/exp_filter.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/__pycache__/exp_filter.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/__pycache__/http_context.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/__pycache__/http_context.cpython-312.pyc index f2ade4c5..ebf970eb 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/__pycache__/http_context.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/__pycache__/http_context.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/__pycache__/log.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/__pycache__/log.cpython-312.pyc index b7a82bc4..860832c0 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/__pycache__/log.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/__pycache__/log.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/__pycache__/misc.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/__pycache__/misc.cpython-312.pyc index 9c6b9aae..f4fe0ae0 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/__pycache__/misc.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/__pycache__/misc.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/__pycache__/moving_average.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/__pycache__/moving_average.cpython-312.pyc index 20cd2906..14651dc1 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/__pycache__/moving_average.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/__pycache__/moving_average.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/__pycache__/participant.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/__pycache__/participant.cpython-312.pyc index 820b6103..5f850008 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/__pycache__/participant.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/__pycache__/participant.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/__init__.cpython-312.pyc index 09229118..c7220c4f 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/channel.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/channel.cpython-312.pyc index 128decb2..afa4a6f0 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/channel.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/channel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/debug.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/debug.cpython-312.pyc index c6f4fd2f..baeb7909 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/debug.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/debug.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/duplex_unix.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/duplex_unix.cpython-312.pyc index 069bf7b1..4b994df5 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/duplex_unix.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/duplex_unix.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/interval.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/interval.cpython-312.pyc index 6f9b3987..55e103bc 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/interval.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/interval.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/itertools.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/itertools.cpython-312.pyc index a8ba4704..52dc640d 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/itertools.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/itertools.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/sleep.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/sleep.cpython-312.pyc index 393fff36..0c4b37ed 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/sleep.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/sleep.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/task_set.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/task_set.cpython-312.pyc index 3526c6f0..b8ce3697 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/task_set.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/task_set.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/utils.cpython-312.pyc index 1822030b..56c57673 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/utils.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/wait_group.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/wait_group.cpython-312.pyc index a91b5a83..f903c243 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/wait_group.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/aio/__pycache__/wait_group.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/codecs/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/codecs/__pycache__/__init__.cpython-312.pyc index 91f85ea1..150a6109 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/codecs/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/codecs/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/codecs/__pycache__/decoder.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/codecs/__pycache__/decoder.cpython-312.pyc index 150d741a..2ee1a002 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/codecs/__pycache__/decoder.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/codecs/__pycache__/decoder.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/hw/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/hw/__pycache__/__init__.cpython-312.pyc index a16bfc69..4109e73c 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/hw/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/hw/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/hw/__pycache__/cpu.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/hw/__pycache__/cpu.cpython-312.pyc index 0f4b6af9..11222650 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/hw/__pycache__/cpu.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/hw/__pycache__/cpu.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/images/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/images/__pycache__/__init__.cpython-312.pyc index 544ec851..cfd7ba6d 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/images/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/images/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/utils/images/__pycache__/image.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/utils/images/__pycache__/image.cpython-312.pyc index 39ef8fa7..b9b405c2 100644 Binary files a/venv/Lib/site-packages/livekit/agents/utils/images/__pycache__/image.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/utils/images/__pycache__/image.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/__pycache__/__init__.cpython-312.pyc index 2b3ef0f8..d14112a7 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/__pycache__/agent.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/__pycache__/agent.cpython-312.pyc index 93f02f18..3618c7a9 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/__pycache__/agent.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/__pycache__/agent.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/__pycache__/agent_activity.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/__pycache__/agent_activity.cpython-312.pyc index 8719cc87..f96e3223 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/__pycache__/agent_activity.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/__pycache__/agent_activity.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/__pycache__/agent_session.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/__pycache__/agent_session.cpython-312.pyc index b0fd9f56..7a24128e 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/__pycache__/agent_session.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/__pycache__/agent_session.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/__pycache__/audio_recognition.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/__pycache__/audio_recognition.cpython-312.pyc index 62f47a7b..c94c0bfa 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/__pycache__/audio_recognition.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/__pycache__/audio_recognition.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/__pycache__/background_audio.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/__pycache__/background_audio.cpython-312.pyc index 4030780e..87842463 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/__pycache__/background_audio.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/__pycache__/background_audio.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/__pycache__/chat_cli.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/__pycache__/chat_cli.cpython-312.pyc index 1df56606..4cd4c851 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/__pycache__/chat_cli.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/__pycache__/chat_cli.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/__pycache__/events.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/__pycache__/events.cpython-312.pyc index 6dca784b..47673744 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/__pycache__/events.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/__pycache__/events.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/__pycache__/generation.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/__pycache__/generation.cpython-312.pyc index f00184a3..3d5bd03d 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/__pycache__/generation.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/__pycache__/generation.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/__pycache__/io.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/__pycache__/io.cpython-312.pyc index d11bfa0d..4a1bbdbe 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/__pycache__/io.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/__pycache__/io.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/__pycache__/speech_handle.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/__pycache__/speech_handle.cpython-312.pyc index 325f7728..3b9d0b5f 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/__pycache__/speech_handle.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/__pycache__/speech_handle.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/avatar/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/avatar/__pycache__/__init__.cpython-312.pyc index 5cff87d9..4f6c2104 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/avatar/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/avatar/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/avatar/__pycache__/_datastream_io.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/avatar/__pycache__/_datastream_io.cpython-312.pyc index 0d674164..a4682271 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/avatar/__pycache__/_datastream_io.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/avatar/__pycache__/_datastream_io.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/avatar/__pycache__/_queue_io.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/avatar/__pycache__/_queue_io.cpython-312.pyc index 0654185d..4ccc7c2e 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/avatar/__pycache__/_queue_io.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/avatar/__pycache__/_queue_io.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/avatar/__pycache__/_runner.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/avatar/__pycache__/_runner.cpython-312.pyc index e0a57990..d563458c 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/avatar/__pycache__/_runner.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/avatar/__pycache__/_runner.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/avatar/__pycache__/_types.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/avatar/__pycache__/_types.cpython-312.pyc index c12bbf3c..538a258e 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/avatar/__pycache__/_types.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/avatar/__pycache__/_types.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/room_io/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/room_io/__pycache__/__init__.cpython-312.pyc index 022d2b39..fb948982 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/room_io/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/room_io/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/room_io/__pycache__/_input.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/room_io/__pycache__/_input.cpython-312.pyc index 4f65bb26..7a19f8ad 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/room_io/__pycache__/_input.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/room_io/__pycache__/_input.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/room_io/__pycache__/_output.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/room_io/__pycache__/_output.cpython-312.pyc index 513757c6..f8a52329 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/room_io/__pycache__/_output.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/room_io/__pycache__/_output.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/room_io/__pycache__/_pre_connect_audio.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/room_io/__pycache__/_pre_connect_audio.cpython-312.pyc index 1c4739be..dc0e3810 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/room_io/__pycache__/_pre_connect_audio.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/room_io/__pycache__/_pre_connect_audio.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/room_io/__pycache__/room_io.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/room_io/__pycache__/room_io.cpython-312.pyc index b84ef19b..ed66c582 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/room_io/__pycache__/room_io.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/room_io/__pycache__/room_io.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/transcription/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/transcription/__pycache__/__init__.cpython-312.pyc index 5b190445..8ea2b321 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/transcription/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/transcription/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/transcription/__pycache__/_speaking_rate.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/transcription/__pycache__/_speaking_rate.cpython-312.pyc index 9c71f2ae..200c9e49 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/transcription/__pycache__/_speaking_rate.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/transcription/__pycache__/_speaking_rate.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/transcription/__pycache__/_utils.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/transcription/__pycache__/_utils.cpython-312.pyc index fca0e850..be4639bd 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/transcription/__pycache__/_utils.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/transcription/__pycache__/_utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/agents/voice/transcription/__pycache__/synchronizer.cpython-312.pyc b/venv/Lib/site-packages/livekit/agents/voice/transcription/__pycache__/synchronizer.cpython-312.pyc index 0cee511e..1175bebf 100644 Binary files a/venv/Lib/site-packages/livekit/agents/voice/transcription/__pycache__/synchronizer.cpython-312.pyc and b/venv/Lib/site-packages/livekit/agents/voice/transcription/__pycache__/synchronizer.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/api/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/api/__pycache__/__init__.cpython-312.pyc index 5438a7c8..693d3937 100644 Binary files a/venv/Lib/site-packages/livekit/api/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/api/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/api/__pycache__/_service.cpython-312.pyc b/venv/Lib/site-packages/livekit/api/__pycache__/_service.cpython-312.pyc index 9779916c..99cc2989 100644 Binary files a/venv/Lib/site-packages/livekit/api/__pycache__/_service.cpython-312.pyc and b/venv/Lib/site-packages/livekit/api/__pycache__/_service.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/api/__pycache__/access_token.cpython-312.pyc b/venv/Lib/site-packages/livekit/api/__pycache__/access_token.cpython-312.pyc index a880b59f..54feeb67 100644 Binary files a/venv/Lib/site-packages/livekit/api/__pycache__/access_token.cpython-312.pyc and b/venv/Lib/site-packages/livekit/api/__pycache__/access_token.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/api/__pycache__/agent_dispatch_service.cpython-312.pyc b/venv/Lib/site-packages/livekit/api/__pycache__/agent_dispatch_service.cpython-312.pyc index aa5631e3..ddcf5a24 100644 Binary files a/venv/Lib/site-packages/livekit/api/__pycache__/agent_dispatch_service.cpython-312.pyc and b/venv/Lib/site-packages/livekit/api/__pycache__/agent_dispatch_service.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/api/__pycache__/egress_service.cpython-312.pyc b/venv/Lib/site-packages/livekit/api/__pycache__/egress_service.cpython-312.pyc index 2bee8f85..9c34ee90 100644 Binary files a/venv/Lib/site-packages/livekit/api/__pycache__/egress_service.cpython-312.pyc and b/venv/Lib/site-packages/livekit/api/__pycache__/egress_service.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/api/__pycache__/ingress_service.cpython-312.pyc b/venv/Lib/site-packages/livekit/api/__pycache__/ingress_service.cpython-312.pyc index f59b904e..0f81fdd0 100644 Binary files a/venv/Lib/site-packages/livekit/api/__pycache__/ingress_service.cpython-312.pyc and b/venv/Lib/site-packages/livekit/api/__pycache__/ingress_service.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/api/__pycache__/livekit_api.cpython-312.pyc b/venv/Lib/site-packages/livekit/api/__pycache__/livekit_api.cpython-312.pyc index 7e39cd87..91f9b198 100644 Binary files a/venv/Lib/site-packages/livekit/api/__pycache__/livekit_api.cpython-312.pyc and b/venv/Lib/site-packages/livekit/api/__pycache__/livekit_api.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/api/__pycache__/room_service.cpython-312.pyc b/venv/Lib/site-packages/livekit/api/__pycache__/room_service.cpython-312.pyc index 5b351149..6596b8b7 100644 Binary files a/venv/Lib/site-packages/livekit/api/__pycache__/room_service.cpython-312.pyc and b/venv/Lib/site-packages/livekit/api/__pycache__/room_service.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/api/__pycache__/sip_service.cpython-312.pyc b/venv/Lib/site-packages/livekit/api/__pycache__/sip_service.cpython-312.pyc index db320762..008b0a90 100644 Binary files a/venv/Lib/site-packages/livekit/api/__pycache__/sip_service.cpython-312.pyc and b/venv/Lib/site-packages/livekit/api/__pycache__/sip_service.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/api/__pycache__/twirp_client.cpython-312.pyc b/venv/Lib/site-packages/livekit/api/__pycache__/twirp_client.cpython-312.pyc index a3786c77..8316d5c4 100644 Binary files a/venv/Lib/site-packages/livekit/api/__pycache__/twirp_client.cpython-312.pyc and b/venv/Lib/site-packages/livekit/api/__pycache__/twirp_client.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/api/__pycache__/version.cpython-312.pyc b/venv/Lib/site-packages/livekit/api/__pycache__/version.cpython-312.pyc index 2d722e9f..ec38065a 100644 Binary files a/venv/Lib/site-packages/livekit/api/__pycache__/version.cpython-312.pyc and b/venv/Lib/site-packages/livekit/api/__pycache__/version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/api/__pycache__/webhook.cpython-312.pyc b/venv/Lib/site-packages/livekit/api/__pycache__/webhook.cpython-312.pyc index f49666e2..b226e9fd 100644 Binary files a/venv/Lib/site-packages/livekit/api/__pycache__/webhook.cpython-312.pyc and b/venv/Lib/site-packages/livekit/api/__pycache__/webhook.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/__init__.cpython-312.pyc index fb4d8ac3..cd8879c2 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/_utils.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/_utils.cpython-312.pyc index f976ea7d..86774e5d 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/_utils.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/_utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/log.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/log.cpython-312.pyc index 0374d101..5b673a69 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/log.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/log.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/models.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/models.cpython-312.pyc index e32c35fc..c5746a93 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/models.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/models.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/stt.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/stt.cpython-312.pyc index a3db768c..2e7e52bb 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/stt.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/stt.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/tts.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/tts.cpython-312.pyc index 8042c6eb..90ac0773 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/tts.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/tts.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/version.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/version.cpython-312.pyc index f1c9e3dc..6d49270a 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/version.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/deepgram/__pycache__/version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/elevenlabs/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/elevenlabs/__pycache__/__init__.cpython-312.pyc index 328a6f14..3f4adc5f 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/elevenlabs/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/elevenlabs/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/elevenlabs/__pycache__/log.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/elevenlabs/__pycache__/log.cpython-312.pyc index 22a0770e..a0d5aecd 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/elevenlabs/__pycache__/log.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/elevenlabs/__pycache__/log.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/elevenlabs/__pycache__/models.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/elevenlabs/__pycache__/models.cpython-312.pyc index decd96ab..95f0d6aa 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/elevenlabs/__pycache__/models.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/elevenlabs/__pycache__/models.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/elevenlabs/__pycache__/stt.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/elevenlabs/__pycache__/stt.cpython-312.pyc index 85109a69..d7a410ec 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/elevenlabs/__pycache__/stt.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/elevenlabs/__pycache__/stt.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/elevenlabs/__pycache__/tts.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/elevenlabs/__pycache__/tts.cpython-312.pyc index 37b0fed4..9519ade6 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/elevenlabs/__pycache__/tts.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/elevenlabs/__pycache__/tts.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/elevenlabs/__pycache__/version.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/elevenlabs/__pycache__/version.cpython-312.pyc index 93fcc9a1..5d2a3e07 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/elevenlabs/__pycache__/version.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/elevenlabs/__pycache__/version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/groq/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/groq/__pycache__/__init__.cpython-312.pyc index 6eba53d1..f254185f 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/groq/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/groq/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/groq/__pycache__/log.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/groq/__pycache__/log.cpython-312.pyc index 7645690b..6af6bcf6 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/groq/__pycache__/log.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/groq/__pycache__/log.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/groq/__pycache__/models.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/groq/__pycache__/models.cpython-312.pyc index 84e332ec..1c474c5e 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/groq/__pycache__/models.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/groq/__pycache__/models.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/groq/__pycache__/services.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/groq/__pycache__/services.cpython-312.pyc index 7ec1ff2b..3c9681f7 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/groq/__pycache__/services.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/groq/__pycache__/services.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/groq/__pycache__/tts.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/groq/__pycache__/tts.cpython-312.pyc index 87fe8f5a..76e665fe 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/groq/__pycache__/tts.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/groq/__pycache__/tts.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/groq/__pycache__/version.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/groq/__pycache__/version.cpython-312.pyc index 6cadfeda..c464dbb3 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/groq/__pycache__/version.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/groq/__pycache__/version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/__init__.cpython-312.pyc index 14845957..c4289be4 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/embeddings.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/embeddings.cpython-312.pyc index 7372ae7d..5d3f24bb 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/embeddings.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/embeddings.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/llm.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/llm.cpython-312.pyc index 0d086a00..9ff2711f 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/llm.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/llm.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/log.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/log.cpython-312.pyc index bb43e7ad..1ed2a314 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/log.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/log.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/models.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/models.cpython-312.pyc index c9e81045..92f2590e 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/models.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/models.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/stt.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/stt.cpython-312.pyc index cca65e1a..fd945eb0 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/stt.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/stt.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/tts.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/tts.cpython-312.pyc index 98eb4a93..145c71de 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/tts.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/tts.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/utils.cpython-312.pyc index eaddc0bf..84b9d78b 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/utils.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/version.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/version.cpython-312.pyc index 3ec6f901..161ba076 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/version.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/openai/__pycache__/version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/openai/realtime/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/openai/realtime/__pycache__/__init__.cpython-312.pyc index dd315f0c..b2f2ce04 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/openai/realtime/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/openai/realtime/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/openai/realtime/__pycache__/realtime_model.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/openai/realtime/__pycache__/realtime_model.cpython-312.pyc index 35b4e694..353aee7e 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/openai/realtime/__pycache__/realtime_model.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/openai/realtime/__pycache__/realtime_model.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/silero/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/silero/__pycache__/__init__.cpython-312.pyc index 5105335d..eae97fdf 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/silero/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/silero/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/silero/__pycache__/log.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/silero/__pycache__/log.cpython-312.pyc index 9688848e..527b8c99 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/silero/__pycache__/log.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/silero/__pycache__/log.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/silero/__pycache__/onnx_model.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/silero/__pycache__/onnx_model.cpython-312.pyc index d8d8b240..164a6a63 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/silero/__pycache__/onnx_model.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/silero/__pycache__/onnx_model.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/silero/__pycache__/vad.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/silero/__pycache__/vad.cpython-312.pyc index 18acdc12..db6888e6 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/silero/__pycache__/vad.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/silero/__pycache__/vad.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/silero/__pycache__/version.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/silero/__pycache__/version.cpython-312.pyc index 23c46d39..652faa3c 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/silero/__pycache__/version.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/silero/__pycache__/version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/plugins/silero/resources/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/plugins/silero/resources/__pycache__/__init__.cpython-312.pyc index 8a59e61d..f6d78cb8 100644 Binary files a/venv/Lib/site-packages/livekit/plugins/silero/resources/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/plugins/silero/resources/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/protocol/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/protocol/__pycache__/__init__.cpython-312.pyc index e986bb28..5563f066 100644 Binary files a/venv/Lib/site-packages/livekit/protocol/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/protocol/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/protocol/__pycache__/agent.cpython-312.pyc b/venv/Lib/site-packages/livekit/protocol/__pycache__/agent.cpython-312.pyc index c3ebad4f..27d14336 100644 Binary files a/venv/Lib/site-packages/livekit/protocol/__pycache__/agent.cpython-312.pyc and b/venv/Lib/site-packages/livekit/protocol/__pycache__/agent.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/protocol/__pycache__/agent_dispatch.cpython-312.pyc b/venv/Lib/site-packages/livekit/protocol/__pycache__/agent_dispatch.cpython-312.pyc index e31f02e7..a3de961f 100644 Binary files a/venv/Lib/site-packages/livekit/protocol/__pycache__/agent_dispatch.cpython-312.pyc and b/venv/Lib/site-packages/livekit/protocol/__pycache__/agent_dispatch.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/protocol/__pycache__/analytics.cpython-312.pyc b/venv/Lib/site-packages/livekit/protocol/__pycache__/analytics.cpython-312.pyc index 4937e3a7..2cefd298 100644 Binary files a/venv/Lib/site-packages/livekit/protocol/__pycache__/analytics.cpython-312.pyc and b/venv/Lib/site-packages/livekit/protocol/__pycache__/analytics.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/protocol/__pycache__/egress.cpython-312.pyc b/venv/Lib/site-packages/livekit/protocol/__pycache__/egress.cpython-312.pyc index 7c5e3092..f283fe5c 100644 Binary files a/venv/Lib/site-packages/livekit/protocol/__pycache__/egress.cpython-312.pyc and b/venv/Lib/site-packages/livekit/protocol/__pycache__/egress.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/protocol/__pycache__/ingress.cpython-312.pyc b/venv/Lib/site-packages/livekit/protocol/__pycache__/ingress.cpython-312.pyc index ede2c896..092f1fed 100644 Binary files a/venv/Lib/site-packages/livekit/protocol/__pycache__/ingress.cpython-312.pyc and b/venv/Lib/site-packages/livekit/protocol/__pycache__/ingress.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/protocol/__pycache__/metrics.cpython-312.pyc b/venv/Lib/site-packages/livekit/protocol/__pycache__/metrics.cpython-312.pyc index 10029e99..39e0e64e 100644 Binary files a/venv/Lib/site-packages/livekit/protocol/__pycache__/metrics.cpython-312.pyc and b/venv/Lib/site-packages/livekit/protocol/__pycache__/metrics.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/protocol/__pycache__/models.cpython-312.pyc b/venv/Lib/site-packages/livekit/protocol/__pycache__/models.cpython-312.pyc index abf3e54f..f788825b 100644 Binary files a/venv/Lib/site-packages/livekit/protocol/__pycache__/models.cpython-312.pyc and b/venv/Lib/site-packages/livekit/protocol/__pycache__/models.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/protocol/__pycache__/room.cpython-312.pyc b/venv/Lib/site-packages/livekit/protocol/__pycache__/room.cpython-312.pyc index fc41ec98..eb960883 100644 Binary files a/venv/Lib/site-packages/livekit/protocol/__pycache__/room.cpython-312.pyc and b/venv/Lib/site-packages/livekit/protocol/__pycache__/room.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/protocol/__pycache__/sip.cpython-312.pyc b/venv/Lib/site-packages/livekit/protocol/__pycache__/sip.cpython-312.pyc index 50b11947..f40d7d26 100644 Binary files a/venv/Lib/site-packages/livekit/protocol/__pycache__/sip.cpython-312.pyc and b/venv/Lib/site-packages/livekit/protocol/__pycache__/sip.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/protocol/__pycache__/version.cpython-312.pyc b/venv/Lib/site-packages/livekit/protocol/__pycache__/version.cpython-312.pyc index 2abca779..0d3733d1 100644 Binary files a/venv/Lib/site-packages/livekit/protocol/__pycache__/version.cpython-312.pyc and b/venv/Lib/site-packages/livekit/protocol/__pycache__/version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/protocol/__pycache__/webhook.cpython-312.pyc b/venv/Lib/site-packages/livekit/protocol/__pycache__/webhook.cpython-312.pyc index b5171eb1..8569661d 100644 Binary files a/venv/Lib/site-packages/livekit/protocol/__pycache__/webhook.cpython-312.pyc and b/venv/Lib/site-packages/livekit/protocol/__pycache__/webhook.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/__init__.cpython-312.pyc index fd2f2eac..723727e6 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/_ffi_client.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/_ffi_client.cpython-312.pyc index 1317b9be..56fc72af 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/_ffi_client.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/_ffi_client.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/_utils.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/_utils.cpython-312.pyc index 4a172f5d..54f0e79c 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/_utils.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/_utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/apm.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/apm.cpython-312.pyc index 26fdaa11..c737f4c1 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/apm.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/apm.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/audio_filter.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/audio_filter.cpython-312.pyc index 3dade8d3..54263a1a 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/audio_filter.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/audio_filter.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/audio_frame.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/audio_frame.cpython-312.pyc index 805b0677..0cccf714 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/audio_frame.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/audio_frame.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/audio_mixer.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/audio_mixer.cpython-312.pyc index 2a5326b1..43c2441b 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/audio_mixer.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/audio_mixer.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/audio_resampler.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/audio_resampler.cpython-312.pyc index 3316db3e..f793d796 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/audio_resampler.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/audio_resampler.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/audio_source.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/audio_source.cpython-312.pyc index 678d0b5c..bcf9c235 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/audio_source.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/audio_source.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/audio_stream.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/audio_stream.cpython-312.pyc index 74f0ba5c..c5254f2b 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/audio_stream.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/audio_stream.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/data_stream.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/data_stream.cpython-312.pyc index 4a990df4..67c97d95 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/data_stream.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/data_stream.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/e2ee.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/e2ee.cpython-312.pyc index 7ffbf8be..9cb47d89 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/e2ee.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/e2ee.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/event_emitter.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/event_emitter.cpython-312.pyc index 154263d3..9f0096ca 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/event_emitter.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/event_emitter.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/log.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/log.cpython-312.pyc index 60dc292a..aeefaeef 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/log.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/log.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/participant.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/participant.cpython-312.pyc index c12d9727..9f7a8f8a 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/participant.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/participant.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/room.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/room.cpython-312.pyc index 2cbf34c0..1c781152 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/room.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/room.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/rpc.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/rpc.cpython-312.pyc index bd291fc1..b18d4e12 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/rpc.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/rpc.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/synchronizer.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/synchronizer.cpython-312.pyc index 91125d51..3d4a7115 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/synchronizer.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/synchronizer.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/track.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/track.cpython-312.pyc index 56d478dc..9da438c9 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/track.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/track.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/track_publication.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/track_publication.cpython-312.pyc index 4d9d80d5..72968906 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/track_publication.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/track_publication.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/transcription.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/transcription.cpython-312.pyc index 29eefdad..b39aaf97 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/transcription.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/transcription.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/utils.cpython-312.pyc index fa4a26a8..97c99cef 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/utils.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/version.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/version.cpython-312.pyc index d99ef351..23287457 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/version.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/video_frame.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/video_frame.cpython-312.pyc index 1164bafb..8c71b117 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/video_frame.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/video_frame.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/video_source.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/video_source.cpython-312.pyc index 09c09dff..433c965d 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/video_source.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/video_source.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/__pycache__/video_stream.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/__pycache__/video_stream.cpython-312.pyc index c0926105..9a0e8a38 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/__pycache__/video_stream.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/__pycache__/video_stream.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/__init__.cpython-312.pyc index 73337100..8e877f01 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/audio_frame_pb2.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/audio_frame_pb2.cpython-312.pyc index 0a5b21a3..13db3bcd 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/audio_frame_pb2.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/audio_frame_pb2.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/data_stream_pb2.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/data_stream_pb2.cpython-312.pyc index cfa78e98..757fc23b 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/data_stream_pb2.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/data_stream_pb2.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/e2ee_pb2.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/e2ee_pb2.cpython-312.pyc index dea885b2..f2ed4490 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/e2ee_pb2.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/e2ee_pb2.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/ffi_pb2.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/ffi_pb2.cpython-312.pyc index afcf05fb..2d3dd94d 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/ffi_pb2.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/ffi_pb2.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/handle_pb2.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/handle_pb2.cpython-312.pyc index acec456f..74b0038a 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/handle_pb2.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/handle_pb2.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/participant_pb2.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/participant_pb2.cpython-312.pyc index abafb964..ffa81175 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/participant_pb2.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/participant_pb2.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/room_pb2.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/room_pb2.cpython-312.pyc index 71177624..93aa4a76 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/room_pb2.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/room_pb2.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/rpc_pb2.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/rpc_pb2.cpython-312.pyc index 86f247f2..ee727736 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/rpc_pb2.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/rpc_pb2.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/stats_pb2.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/stats_pb2.cpython-312.pyc index 71d16665..6cf8f41c 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/stats_pb2.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/stats_pb2.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/track_pb2.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/track_pb2.cpython-312.pyc index bd826208..61c08403 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/track_pb2.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/track_pb2.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/track_publication_pb2.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/track_publication_pb2.cpython-312.pyc index c368e0ae..f804b3a5 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/track_publication_pb2.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/track_publication_pb2.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/video_frame_pb2.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/video_frame_pb2.cpython-312.pyc index 711968d2..556ad5e0 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/video_frame_pb2.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/_proto/__pycache__/video_frame_pb2.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/livekit/rtc/resources/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/livekit/rtc/resources/__pycache__/__init__.cpython-312.pyc index be640f34..c54aacb9 100644 Binary files a/venv/Lib/site-packages/livekit/rtc/resources/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/livekit/rtc/resources/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/marshmallow/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/marshmallow/__pycache__/__init__.cpython-312.pyc index e4667ca6..8d18c073 100644 Binary files a/venv/Lib/site-packages/marshmallow/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/marshmallow/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/marshmallow/__pycache__/base.cpython-312.pyc b/venv/Lib/site-packages/marshmallow/__pycache__/base.cpython-312.pyc index 2737a356..af47f7c4 100644 Binary files a/venv/Lib/site-packages/marshmallow/__pycache__/base.cpython-312.pyc and b/venv/Lib/site-packages/marshmallow/__pycache__/base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/marshmallow/__pycache__/class_registry.cpython-312.pyc b/venv/Lib/site-packages/marshmallow/__pycache__/class_registry.cpython-312.pyc index 7ad18c1f..5f878b73 100644 Binary files a/venv/Lib/site-packages/marshmallow/__pycache__/class_registry.cpython-312.pyc and b/venv/Lib/site-packages/marshmallow/__pycache__/class_registry.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/marshmallow/__pycache__/decorators.cpython-312.pyc b/venv/Lib/site-packages/marshmallow/__pycache__/decorators.cpython-312.pyc index 4da8b33c..035ba138 100644 Binary files a/venv/Lib/site-packages/marshmallow/__pycache__/decorators.cpython-312.pyc and b/venv/Lib/site-packages/marshmallow/__pycache__/decorators.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/marshmallow/__pycache__/error_store.cpython-312.pyc b/venv/Lib/site-packages/marshmallow/__pycache__/error_store.cpython-312.pyc index 4ab6f61c..8cb4b16b 100644 Binary files a/venv/Lib/site-packages/marshmallow/__pycache__/error_store.cpython-312.pyc and b/venv/Lib/site-packages/marshmallow/__pycache__/error_store.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/marshmallow/__pycache__/exceptions.cpython-312.pyc b/venv/Lib/site-packages/marshmallow/__pycache__/exceptions.cpython-312.pyc index 60a9b8b7..d8d563de 100644 Binary files a/venv/Lib/site-packages/marshmallow/__pycache__/exceptions.cpython-312.pyc and b/venv/Lib/site-packages/marshmallow/__pycache__/exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/marshmallow/__pycache__/fields.cpython-312.pyc b/venv/Lib/site-packages/marshmallow/__pycache__/fields.cpython-312.pyc index 5b8c4ab1..1b2c9971 100644 Binary files a/venv/Lib/site-packages/marshmallow/__pycache__/fields.cpython-312.pyc and b/venv/Lib/site-packages/marshmallow/__pycache__/fields.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/marshmallow/__pycache__/orderedset.cpython-312.pyc b/venv/Lib/site-packages/marshmallow/__pycache__/orderedset.cpython-312.pyc index 38e12b58..619d4f6c 100644 Binary files a/venv/Lib/site-packages/marshmallow/__pycache__/orderedset.cpython-312.pyc and b/venv/Lib/site-packages/marshmallow/__pycache__/orderedset.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/marshmallow/__pycache__/schema.cpython-312.pyc b/venv/Lib/site-packages/marshmallow/__pycache__/schema.cpython-312.pyc index 4d18ebd4..715dc20c 100644 Binary files a/venv/Lib/site-packages/marshmallow/__pycache__/schema.cpython-312.pyc and b/venv/Lib/site-packages/marshmallow/__pycache__/schema.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/marshmallow/__pycache__/types.cpython-312.pyc b/venv/Lib/site-packages/marshmallow/__pycache__/types.cpython-312.pyc index aadd55e2..c4b10741 100644 Binary files a/venv/Lib/site-packages/marshmallow/__pycache__/types.cpython-312.pyc and b/venv/Lib/site-packages/marshmallow/__pycache__/types.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/marshmallow/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/marshmallow/__pycache__/utils.cpython-312.pyc index 5aa9afb7..7b81e24d 100644 Binary files a/venv/Lib/site-packages/marshmallow/__pycache__/utils.cpython-312.pyc and b/venv/Lib/site-packages/marshmallow/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/marshmallow/__pycache__/validate.cpython-312.pyc b/venv/Lib/site-packages/marshmallow/__pycache__/validate.cpython-312.pyc index 967f5faf..1b70836b 100644 Binary files a/venv/Lib/site-packages/marshmallow/__pycache__/validate.cpython-312.pyc and b/venv/Lib/site-packages/marshmallow/__pycache__/validate.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/marshmallow/__pycache__/warnings.cpython-312.pyc b/venv/Lib/site-packages/marshmallow/__pycache__/warnings.cpython-312.pyc index acd03b0c..f922d601 100644 Binary files a/venv/Lib/site-packages/marshmallow/__pycache__/warnings.cpython-312.pyc and b/venv/Lib/site-packages/marshmallow/__pycache__/warnings.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/multidict/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/multidict/__pycache__/__init__.cpython-312.pyc index d309a38b..05df2b4e 100644 Binary files a/venv/Lib/site-packages/multidict/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/multidict/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/multidict/__pycache__/_abc.cpython-312.pyc b/venv/Lib/site-packages/multidict/__pycache__/_abc.cpython-312.pyc index 5b08ccd6..e24a57b4 100644 Binary files a/venv/Lib/site-packages/multidict/__pycache__/_abc.cpython-312.pyc and b/venv/Lib/site-packages/multidict/__pycache__/_abc.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/multidict/__pycache__/_compat.cpython-312.pyc b/venv/Lib/site-packages/multidict/__pycache__/_compat.cpython-312.pyc index 08262129..3166251b 100644 Binary files a/venv/Lib/site-packages/multidict/__pycache__/_compat.cpython-312.pyc and b/venv/Lib/site-packages/multidict/__pycache__/_compat.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/multipart/__init__.py b/venv/Lib/site-packages/multipart/__init__.py new file mode 100644 index 00000000..67f0e5bb --- /dev/null +++ b/venv/Lib/site-packages/multipart/__init__.py @@ -0,0 +1,24 @@ +# This only works if using a file system, other loaders not implemented. + +import importlib.util +import sys +import warnings +from pathlib import Path + +for p in sys.path: + file_path = Path(p, "multipart.py") + try: + if file_path.is_file(): + spec = importlib.util.spec_from_file_location("multipart", file_path) + assert spec is not None, f"{file_path} found but not loadable!" + module = importlib.util.module_from_spec(spec) + sys.modules["multipart"] = module + assert spec.loader is not None, f"{file_path} must be loadable!" + spec.loader.exec_module(module) + break + except PermissionError: + pass +else: + warnings.warn("Please use `import python_multipart` instead.", PendingDeprecationWarning, stacklevel=2) + from python_multipart import * + from python_multipart import __all__, __author__, __copyright__, __license__, __version__ diff --git a/venv/Lib/site-packages/multipart/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/multipart/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..9f6d0f47 Binary files /dev/null and b/venv/Lib/site-packages/multipart/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/multipart/__pycache__/decoders.cpython-312.pyc b/venv/Lib/site-packages/multipart/__pycache__/decoders.cpython-312.pyc new file mode 100644 index 00000000..aa1ef546 Binary files /dev/null and b/venv/Lib/site-packages/multipart/__pycache__/decoders.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/multipart/__pycache__/exceptions.cpython-312.pyc b/venv/Lib/site-packages/multipart/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 00000000..fbc2f8ab Binary files /dev/null and b/venv/Lib/site-packages/multipart/__pycache__/exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/multipart/__pycache__/multipart.cpython-312.pyc b/venv/Lib/site-packages/multipart/__pycache__/multipart.cpython-312.pyc new file mode 100644 index 00000000..ac8b6466 Binary files /dev/null and b/venv/Lib/site-packages/multipart/__pycache__/multipart.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/multipart/decoders.py b/venv/Lib/site-packages/multipart/decoders.py new file mode 100644 index 00000000..31acdfbf --- /dev/null +++ b/venv/Lib/site-packages/multipart/decoders.py @@ -0,0 +1 @@ +from python_multipart.decoders import * diff --git a/venv/Lib/site-packages/multipart/exceptions.py b/venv/Lib/site-packages/multipart/exceptions.py new file mode 100644 index 00000000..36815d19 --- /dev/null +++ b/venv/Lib/site-packages/multipart/exceptions.py @@ -0,0 +1 @@ +from python_multipart.exceptions import * diff --git a/venv/Lib/site-packages/multipart/multipart.py b/venv/Lib/site-packages/multipart/multipart.py new file mode 100644 index 00000000..7bf567df --- /dev/null +++ b/venv/Lib/site-packages/multipart/multipart.py @@ -0,0 +1 @@ +from python_multipart.multipart import * diff --git a/venv/Lib/site-packages/numpy/__pycache__/__config__.cpython-312.pyc b/venv/Lib/site-packages/numpy/__pycache__/__config__.cpython-312.pyc index d376b59c..061d4ead 100644 Binary files a/venv/Lib/site-packages/numpy/__pycache__/__config__.cpython-312.pyc and b/venv/Lib/site-packages/numpy/__pycache__/__config__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/numpy/__pycache__/__init__.cpython-312.pyc index 380e5abd..ba72520e 100644 Binary files a/venv/Lib/site-packages/numpy/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/numpy/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/__pycache__/_array_api_info.cpython-312.pyc b/venv/Lib/site-packages/numpy/__pycache__/_array_api_info.cpython-312.pyc index f89a6c25..5a4ac402 100644 Binary files a/venv/Lib/site-packages/numpy/__pycache__/_array_api_info.cpython-312.pyc and b/venv/Lib/site-packages/numpy/__pycache__/_array_api_info.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/__pycache__/_distributor_init.cpython-312.pyc b/venv/Lib/site-packages/numpy/__pycache__/_distributor_init.cpython-312.pyc index d8ae2e55..ab53c3c8 100644 Binary files a/venv/Lib/site-packages/numpy/__pycache__/_distributor_init.cpython-312.pyc and b/venv/Lib/site-packages/numpy/__pycache__/_distributor_init.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/__pycache__/_expired_attrs_2_0.cpython-312.pyc b/venv/Lib/site-packages/numpy/__pycache__/_expired_attrs_2_0.cpython-312.pyc index 8a26236f..91b1ebf2 100644 Binary files a/venv/Lib/site-packages/numpy/__pycache__/_expired_attrs_2_0.cpython-312.pyc and b/venv/Lib/site-packages/numpy/__pycache__/_expired_attrs_2_0.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/__pycache__/_globals.cpython-312.pyc b/venv/Lib/site-packages/numpy/__pycache__/_globals.cpython-312.pyc index f8af03d8..616b5219 100644 Binary files a/venv/Lib/site-packages/numpy/__pycache__/_globals.cpython-312.pyc and b/venv/Lib/site-packages/numpy/__pycache__/_globals.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/__pycache__/_pytesttester.cpython-312.pyc b/venv/Lib/site-packages/numpy/__pycache__/_pytesttester.cpython-312.pyc index 17d32d68..30965b32 100644 Binary files a/venv/Lib/site-packages/numpy/__pycache__/_pytesttester.cpython-312.pyc and b/venv/Lib/site-packages/numpy/__pycache__/_pytesttester.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/__pycache__/dtypes.cpython-312.pyc b/venv/Lib/site-packages/numpy/__pycache__/dtypes.cpython-312.pyc index 0e7760ea..7da0011d 100644 Binary files a/venv/Lib/site-packages/numpy/__pycache__/dtypes.cpython-312.pyc and b/venv/Lib/site-packages/numpy/__pycache__/dtypes.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/__pycache__/exceptions.cpython-312.pyc b/venv/Lib/site-packages/numpy/__pycache__/exceptions.cpython-312.pyc index 655a7e43..620696f7 100644 Binary files a/venv/Lib/site-packages/numpy/__pycache__/exceptions.cpython-312.pyc and b/venv/Lib/site-packages/numpy/__pycache__/exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/__pycache__/version.cpython-312.pyc b/venv/Lib/site-packages/numpy/__pycache__/version.cpython-312.pyc index 6894cc39..73971925 100644 Binary files a/venv/Lib/site-packages/numpy/__pycache__/version.cpython-312.pyc and b/venv/Lib/site-packages/numpy/__pycache__/version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/__init__.cpython-312.pyc index 9a520392..5c335132 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/_add_newdocs.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/_add_newdocs.cpython-312.pyc index 3f7e1b31..2de3c4bb 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/_add_newdocs.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/_add_newdocs.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/_add_newdocs_scalars.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/_add_newdocs_scalars.cpython-312.pyc index 83248221..5704ee5a 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/_add_newdocs_scalars.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/_add_newdocs_scalars.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/_asarray.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/_asarray.cpython-312.pyc index 266aeafb..99e32b9c 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/_asarray.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/_asarray.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/_dtype.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/_dtype.cpython-312.pyc index 702bbced..7916a0d5 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/_dtype.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/_dtype.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/_dtype_ctypes.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/_dtype_ctypes.cpython-312.pyc index 204eff45..be46d2f2 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/_dtype_ctypes.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/_dtype_ctypes.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/_exceptions.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/_exceptions.cpython-312.pyc index 275755a8..bd6cd700 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/_exceptions.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/_exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/_internal.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/_internal.cpython-312.pyc index e1cb5786..4e0d60a5 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/_internal.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/_internal.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/_machar.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/_machar.cpython-312.pyc index 49017d64..f2bc06d6 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/_machar.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/_machar.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/_methods.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/_methods.cpython-312.pyc index fc8d35ce..bb1071be 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/_methods.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/_methods.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/_string_helpers.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/_string_helpers.cpython-312.pyc index b0e796e0..b5c60e04 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/_string_helpers.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/_string_helpers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/_type_aliases.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/_type_aliases.cpython-312.pyc index 5a91fb4d..4b250267 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/_type_aliases.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/_type_aliases.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/_ufunc_config.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/_ufunc_config.cpython-312.pyc index 7e30db22..60686339 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/_ufunc_config.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/_ufunc_config.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/arrayprint.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/arrayprint.cpython-312.pyc index eb5753eb..9a79d89c 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/arrayprint.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/arrayprint.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/einsumfunc.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/einsumfunc.cpython-312.pyc index 86242603..5eb700b9 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/einsumfunc.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/einsumfunc.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/fromnumeric.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/fromnumeric.cpython-312.pyc index 6008c054..0b34ebc9 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/fromnumeric.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/fromnumeric.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/function_base.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/function_base.cpython-312.pyc index d63d7a21..5da77aa8 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/function_base.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/function_base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/getlimits.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/getlimits.cpython-312.pyc index f942e8bb..feb4ae79 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/getlimits.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/getlimits.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/memmap.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/memmap.cpython-312.pyc index 7477906a..7ffbf017 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/memmap.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/memmap.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/multiarray.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/multiarray.cpython-312.pyc index 9597eff3..7d2a42bb 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/multiarray.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/multiarray.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/numeric.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/numeric.cpython-312.pyc index f755580b..7b3c1d5b 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/numeric.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/numeric.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/numerictypes.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/numerictypes.cpython-312.pyc index 615e5a65..22338c85 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/numerictypes.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/numerictypes.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/overrides.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/overrides.cpython-312.pyc index 62063bf1..f81ac6bf 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/overrides.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/overrides.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/printoptions.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/printoptions.cpython-312.pyc index 900f1e40..7b603860 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/printoptions.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/printoptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/records.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/records.cpython-312.pyc index 9c4ffb21..7fedca8e 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/records.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/records.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/shape_base.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/shape_base.cpython-312.pyc index b8a6c875..c5e8187e 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/shape_base.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/shape_base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_core/__pycache__/umath.cpython-312.pyc b/venv/Lib/site-packages/numpy/_core/__pycache__/umath.cpython-312.pyc index 8e8a2456..61788866 100644 Binary files a/venv/Lib/site-packages/numpy/_core/__pycache__/umath.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_core/__pycache__/umath.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_typing/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/numpy/_typing/__pycache__/__init__.cpython-312.pyc index 71f974a7..df691658 100644 Binary files a/venv/Lib/site-packages/numpy/_typing/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_typing/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_typing/__pycache__/_array_like.cpython-312.pyc b/venv/Lib/site-packages/numpy/_typing/__pycache__/_array_like.cpython-312.pyc index 0b0dc87d..bbed1857 100644 Binary files a/venv/Lib/site-packages/numpy/_typing/__pycache__/_array_like.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_typing/__pycache__/_array_like.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_typing/__pycache__/_char_codes.cpython-312.pyc b/venv/Lib/site-packages/numpy/_typing/__pycache__/_char_codes.cpython-312.pyc index 87c212ae..3d897bfe 100644 Binary files a/venv/Lib/site-packages/numpy/_typing/__pycache__/_char_codes.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_typing/__pycache__/_char_codes.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_typing/__pycache__/_dtype_like.cpython-312.pyc b/venv/Lib/site-packages/numpy/_typing/__pycache__/_dtype_like.cpython-312.pyc index feb63728..7dc22108 100644 Binary files a/venv/Lib/site-packages/numpy/_typing/__pycache__/_dtype_like.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_typing/__pycache__/_dtype_like.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_typing/__pycache__/_nbit.cpython-312.pyc b/venv/Lib/site-packages/numpy/_typing/__pycache__/_nbit.cpython-312.pyc index 00a21566..28e3b557 100644 Binary files a/venv/Lib/site-packages/numpy/_typing/__pycache__/_nbit.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_typing/__pycache__/_nbit.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_typing/__pycache__/_nbit_base.cpython-312.pyc b/venv/Lib/site-packages/numpy/_typing/__pycache__/_nbit_base.cpython-312.pyc index 44723c3f..8d39c126 100644 Binary files a/venv/Lib/site-packages/numpy/_typing/__pycache__/_nbit_base.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_typing/__pycache__/_nbit_base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_typing/__pycache__/_nested_sequence.cpython-312.pyc b/venv/Lib/site-packages/numpy/_typing/__pycache__/_nested_sequence.cpython-312.pyc index adb2da60..f888e607 100644 Binary files a/venv/Lib/site-packages/numpy/_typing/__pycache__/_nested_sequence.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_typing/__pycache__/_nested_sequence.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_typing/__pycache__/_scalars.cpython-312.pyc b/venv/Lib/site-packages/numpy/_typing/__pycache__/_scalars.cpython-312.pyc index 853ed171..97df2ebe 100644 Binary files a/venv/Lib/site-packages/numpy/_typing/__pycache__/_scalars.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_typing/__pycache__/_scalars.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_typing/__pycache__/_shape.cpython-312.pyc b/venv/Lib/site-packages/numpy/_typing/__pycache__/_shape.cpython-312.pyc index b3189608..16eca63f 100644 Binary files a/venv/Lib/site-packages/numpy/_typing/__pycache__/_shape.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_typing/__pycache__/_shape.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_typing/__pycache__/_ufunc.cpython-312.pyc b/venv/Lib/site-packages/numpy/_typing/__pycache__/_ufunc.cpython-312.pyc index 8f253f2f..fc8c9f74 100644 Binary files a/venv/Lib/site-packages/numpy/_typing/__pycache__/_ufunc.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_typing/__pycache__/_ufunc.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_utils/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/numpy/_utils/__pycache__/__init__.cpython-312.pyc index ae32e1c6..b7385736 100644 Binary files a/venv/Lib/site-packages/numpy/_utils/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_utils/__pycache__/_convertions.cpython-312.pyc b/venv/Lib/site-packages/numpy/_utils/__pycache__/_convertions.cpython-312.pyc index a7a8d5e1..037cb335 100644 Binary files a/venv/Lib/site-packages/numpy/_utils/__pycache__/_convertions.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_utils/__pycache__/_convertions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/_utils/__pycache__/_inspect.cpython-312.pyc b/venv/Lib/site-packages/numpy/_utils/__pycache__/_inspect.cpython-312.pyc index 3b5cc640..fb286fa3 100644 Binary files a/venv/Lib/site-packages/numpy/_utils/__pycache__/_inspect.cpython-312.pyc and b/venv/Lib/site-packages/numpy/_utils/__pycache__/_inspect.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/fft/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/numpy/fft/__pycache__/__init__.cpython-312.pyc index b0a2c42b..ba480a0d 100644 Binary files a/venv/Lib/site-packages/numpy/fft/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/numpy/fft/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/fft/__pycache__/_helper.cpython-312.pyc b/venv/Lib/site-packages/numpy/fft/__pycache__/_helper.cpython-312.pyc index b00a7be4..bf66f11e 100644 Binary files a/venv/Lib/site-packages/numpy/fft/__pycache__/_helper.cpython-312.pyc and b/venv/Lib/site-packages/numpy/fft/__pycache__/_helper.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/fft/__pycache__/_pocketfft.cpython-312.pyc b/venv/Lib/site-packages/numpy/fft/__pycache__/_pocketfft.cpython-312.pyc index 0975c82c..0217e7e9 100644 Binary files a/venv/Lib/site-packages/numpy/fft/__pycache__/_pocketfft.cpython-312.pyc and b/venv/Lib/site-packages/numpy/fft/__pycache__/_pocketfft.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/fft/__pycache__/helper.cpython-312.pyc b/venv/Lib/site-packages/numpy/fft/__pycache__/helper.cpython-312.pyc index fc33dc35..64632f96 100644 Binary files a/venv/Lib/site-packages/numpy/fft/__pycache__/helper.cpython-312.pyc and b/venv/Lib/site-packages/numpy/fft/__pycache__/helper.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/__init__.cpython-312.pyc index 2a9b08c0..ed1a68f1 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/_array_utils_impl.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/_array_utils_impl.cpython-312.pyc index 9d404cc1..a5f21142 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/_array_utils_impl.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/_array_utils_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/_arraypad_impl.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/_arraypad_impl.cpython-312.pyc index 28c5c345..1cac7873 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/_arraypad_impl.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/_arraypad_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/_arraysetops_impl.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/_arraysetops_impl.cpython-312.pyc index 687abdaf..1a47e2d8 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/_arraysetops_impl.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/_arraysetops_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/_arrayterator_impl.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/_arrayterator_impl.cpython-312.pyc index 50ba51ec..353bea5e 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/_arrayterator_impl.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/_arrayterator_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/_datasource.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/_datasource.cpython-312.pyc index 28d5ae2e..88c9d2e0 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/_datasource.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/_datasource.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/_format_impl.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/_format_impl.cpython-312.pyc index 6cb1fa1a..8f3bb439 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/_format_impl.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/_format_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/_function_base_impl.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/_function_base_impl.cpython-312.pyc index 8980791f..57e9f520 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/_function_base_impl.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/_function_base_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/_histograms_impl.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/_histograms_impl.cpython-312.pyc index bd82cbfe..f297fda0 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/_histograms_impl.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/_histograms_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/_index_tricks_impl.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/_index_tricks_impl.cpython-312.pyc index 33aba798..8e91e441 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/_index_tricks_impl.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/_index_tricks_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/_iotools.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/_iotools.cpython-312.pyc index 70044500..9c85bc58 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/_iotools.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/_iotools.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/_nanfunctions_impl.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/_nanfunctions_impl.cpython-312.pyc index 5208c54b..261fe4be 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/_nanfunctions_impl.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/_nanfunctions_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/_npyio_impl.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/_npyio_impl.cpython-312.pyc index e78ccdc2..86fe4aae 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/_npyio_impl.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/_npyio_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/_polynomial_impl.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/_polynomial_impl.cpython-312.pyc index 19cff001..30ed43aa 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/_polynomial_impl.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/_polynomial_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/_scimath_impl.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/_scimath_impl.cpython-312.pyc index beb4ee97..29737a27 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/_scimath_impl.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/_scimath_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/_shape_base_impl.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/_shape_base_impl.cpython-312.pyc index 7ac8be2f..084a6213 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/_shape_base_impl.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/_shape_base_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/_stride_tricks_impl.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/_stride_tricks_impl.cpython-312.pyc index 80d5d58c..b032f213 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/_stride_tricks_impl.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/_stride_tricks_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/_twodim_base_impl.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/_twodim_base_impl.cpython-312.pyc index 628ec4d6..8e3c5750 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/_twodim_base_impl.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/_twodim_base_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/_type_check_impl.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/_type_check_impl.cpython-312.pyc index 0216f65e..59898017 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/_type_check_impl.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/_type_check_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/_ufunclike_impl.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/_ufunclike_impl.cpython-312.pyc index 0ce90c87..a0c45000 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/_ufunclike_impl.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/_ufunclike_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/_utils_impl.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/_utils_impl.cpython-312.pyc index 0b6fc0c7..3a0baf82 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/_utils_impl.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/_utils_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/_version.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/_version.cpython-312.pyc index c287ef24..675b2628 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/_version.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/_version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/array_utils.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/array_utils.cpython-312.pyc index 5feb17ea..a2fcc88f 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/array_utils.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/array_utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/format.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/format.cpython-312.pyc index b5af0581..7204b9af 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/format.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/format.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/introspect.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/introspect.cpython-312.pyc index e5e6daec..33996aeb 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/introspect.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/introspect.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/mixins.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/mixins.cpython-312.pyc index 7a286af3..f280e2cf 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/mixins.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/mixins.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/npyio.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/npyio.cpython-312.pyc index 2f5f4572..52450a02 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/npyio.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/npyio.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/scimath.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/scimath.cpython-312.pyc index a635a262..4d45829d 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/scimath.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/scimath.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/lib/__pycache__/stride_tricks.cpython-312.pyc b/venv/Lib/site-packages/numpy/lib/__pycache__/stride_tricks.cpython-312.pyc index a2a6a5bf..1923f3bf 100644 Binary files a/venv/Lib/site-packages/numpy/lib/__pycache__/stride_tricks.cpython-312.pyc and b/venv/Lib/site-packages/numpy/lib/__pycache__/stride_tricks.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/linalg/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/numpy/linalg/__pycache__/__init__.cpython-312.pyc index 7c8bc8b4..4db3aee1 100644 Binary files a/venv/Lib/site-packages/numpy/linalg/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/numpy/linalg/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/linalg/__pycache__/_linalg.cpython-312.pyc b/venv/Lib/site-packages/numpy/linalg/__pycache__/_linalg.cpython-312.pyc index 13b7cf0c..f0f7f8e7 100644 Binary files a/venv/Lib/site-packages/numpy/linalg/__pycache__/_linalg.cpython-312.pyc and b/venv/Lib/site-packages/numpy/linalg/__pycache__/_linalg.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/linalg/__pycache__/linalg.cpython-312.pyc b/venv/Lib/site-packages/numpy/linalg/__pycache__/linalg.cpython-312.pyc index 7c5454d5..5388825d 100644 Binary files a/venv/Lib/site-packages/numpy/linalg/__pycache__/linalg.cpython-312.pyc and b/venv/Lib/site-packages/numpy/linalg/__pycache__/linalg.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/ma/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/numpy/ma/__pycache__/__init__.cpython-312.pyc index 7b197fe0..92df85ce 100644 Binary files a/venv/Lib/site-packages/numpy/ma/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/numpy/ma/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/ma/__pycache__/core.cpython-312.pyc b/venv/Lib/site-packages/numpy/ma/__pycache__/core.cpython-312.pyc index 6e6eff8b..e54b1bf5 100644 Binary files a/venv/Lib/site-packages/numpy/ma/__pycache__/core.cpython-312.pyc and b/venv/Lib/site-packages/numpy/ma/__pycache__/core.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/ma/__pycache__/extras.cpython-312.pyc b/venv/Lib/site-packages/numpy/ma/__pycache__/extras.cpython-312.pyc index 92185a4c..1fc7e427 100644 Binary files a/venv/Lib/site-packages/numpy/ma/__pycache__/extras.cpython-312.pyc and b/venv/Lib/site-packages/numpy/ma/__pycache__/extras.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/matrixlib/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/numpy/matrixlib/__pycache__/__init__.cpython-312.pyc index 4ab9b1dd..fbbc1c04 100644 Binary files a/venv/Lib/site-packages/numpy/matrixlib/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/numpy/matrixlib/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/matrixlib/__pycache__/defmatrix.cpython-312.pyc b/venv/Lib/site-packages/numpy/matrixlib/__pycache__/defmatrix.cpython-312.pyc index 309e6730..5c7b1f2e 100644 Binary files a/venv/Lib/site-packages/numpy/matrixlib/__pycache__/defmatrix.cpython-312.pyc and b/venv/Lib/site-packages/numpy/matrixlib/__pycache__/defmatrix.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/random/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/numpy/random/__pycache__/__init__.cpython-312.pyc index 81d25835..d8de0019 100644 Binary files a/venv/Lib/site-packages/numpy/random/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/numpy/random/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/random/__pycache__/_pickle.cpython-312.pyc b/venv/Lib/site-packages/numpy/random/__pycache__/_pickle.cpython-312.pyc index 5bec08d7..8cc77dea 100644 Binary files a/venv/Lib/site-packages/numpy/random/__pycache__/_pickle.cpython-312.pyc and b/venv/Lib/site-packages/numpy/random/__pycache__/_pickle.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/numpy/rec/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/numpy/rec/__pycache__/__init__.cpython-312.pyc index bff65ebc..5a35a0d5 100644 Binary files a/venv/Lib/site-packages/numpy/rec/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/numpy/rec/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/onnxruntime/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/onnxruntime/__pycache__/__init__.cpython-312.pyc index 6b629f8d..58e56d89 100644 Binary files a/venv/Lib/site-packages/onnxruntime/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/onnxruntime/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/onnxruntime/capi/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/onnxruntime/capi/__pycache__/__init__.cpython-312.pyc index c1d7d12a..a2bf241b 100644 Binary files a/venv/Lib/site-packages/onnxruntime/capi/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/onnxruntime/capi/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/onnxruntime/capi/__pycache__/_ld_preload.cpython-312.pyc b/venv/Lib/site-packages/onnxruntime/capi/__pycache__/_ld_preload.cpython-312.pyc index 2b706612..bf5eb49b 100644 Binary files a/venv/Lib/site-packages/onnxruntime/capi/__pycache__/_ld_preload.cpython-312.pyc and b/venv/Lib/site-packages/onnxruntime/capi/__pycache__/_ld_preload.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/onnxruntime/capi/__pycache__/_pybind_state.cpython-312.pyc b/venv/Lib/site-packages/onnxruntime/capi/__pycache__/_pybind_state.cpython-312.pyc index 0c2e1205..41d71d9b 100644 Binary files a/venv/Lib/site-packages/onnxruntime/capi/__pycache__/_pybind_state.cpython-312.pyc and b/venv/Lib/site-packages/onnxruntime/capi/__pycache__/_pybind_state.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/onnxruntime/capi/__pycache__/build_and_package_info.cpython-312.pyc b/venv/Lib/site-packages/onnxruntime/capi/__pycache__/build_and_package_info.cpython-312.pyc index f0e89ec4..6e756653 100644 Binary files a/venv/Lib/site-packages/onnxruntime/capi/__pycache__/build_and_package_info.cpython-312.pyc and b/venv/Lib/site-packages/onnxruntime/capi/__pycache__/build_and_package_info.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/onnxruntime/capi/__pycache__/onnxruntime_inference_collection.cpython-312.pyc b/venv/Lib/site-packages/onnxruntime/capi/__pycache__/onnxruntime_inference_collection.cpython-312.pyc index 04a81f28..a8a6a938 100644 Binary files a/venv/Lib/site-packages/onnxruntime/capi/__pycache__/onnxruntime_inference_collection.cpython-312.pyc and b/venv/Lib/site-packages/onnxruntime/capi/__pycache__/onnxruntime_inference_collection.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/onnxruntime/capi/__pycache__/onnxruntime_validation.cpython-312.pyc b/venv/Lib/site-packages/onnxruntime/capi/__pycache__/onnxruntime_validation.cpython-312.pyc index 14ff3784..13eb1345 100644 Binary files a/venv/Lib/site-packages/onnxruntime/capi/__pycache__/onnxruntime_validation.cpython-312.pyc and b/venv/Lib/site-packages/onnxruntime/capi/__pycache__/onnxruntime_validation.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/onnxruntime/capi/__pycache__/version_info.cpython-312.pyc b/venv/Lib/site-packages/onnxruntime/capi/__pycache__/version_info.cpython-312.pyc index f5ffd8e2..c863d53a 100644 Binary files a/venv/Lib/site-packages/onnxruntime/capi/__pycache__/version_info.cpython-312.pyc and b/venv/Lib/site-packages/onnxruntime/capi/__pycache__/version_info.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/__pycache__/__init__.cpython-312.pyc index 1e4153f5..153c459a 100644 Binary files a/venv/Lib/site-packages/openai/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/__pycache__/_base_client.cpython-312.pyc b/venv/Lib/site-packages/openai/__pycache__/_base_client.cpython-312.pyc index 45f9b4ca..b61f8786 100644 Binary files a/venv/Lib/site-packages/openai/__pycache__/_base_client.cpython-312.pyc and b/venv/Lib/site-packages/openai/__pycache__/_base_client.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/__pycache__/_client.cpython-312.pyc b/venv/Lib/site-packages/openai/__pycache__/_client.cpython-312.pyc index 974f5190..dac8bfbf 100644 Binary files a/venv/Lib/site-packages/openai/__pycache__/_client.cpython-312.pyc and b/venv/Lib/site-packages/openai/__pycache__/_client.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/__pycache__/_compat.cpython-312.pyc b/venv/Lib/site-packages/openai/__pycache__/_compat.cpython-312.pyc index 8961c563..7fefc7c8 100644 Binary files a/venv/Lib/site-packages/openai/__pycache__/_compat.cpython-312.pyc and b/venv/Lib/site-packages/openai/__pycache__/_compat.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/__pycache__/_constants.cpython-312.pyc b/venv/Lib/site-packages/openai/__pycache__/_constants.cpython-312.pyc index d289d6c1..3a551cc2 100644 Binary files a/venv/Lib/site-packages/openai/__pycache__/_constants.cpython-312.pyc and b/venv/Lib/site-packages/openai/__pycache__/_constants.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/__pycache__/_exceptions.cpython-312.pyc b/venv/Lib/site-packages/openai/__pycache__/_exceptions.cpython-312.pyc index 6ff14680..a632004d 100644 Binary files a/venv/Lib/site-packages/openai/__pycache__/_exceptions.cpython-312.pyc and b/venv/Lib/site-packages/openai/__pycache__/_exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/__pycache__/_files.cpython-312.pyc b/venv/Lib/site-packages/openai/__pycache__/_files.cpython-312.pyc index a97f4272..018cf509 100644 Binary files a/venv/Lib/site-packages/openai/__pycache__/_files.cpython-312.pyc and b/venv/Lib/site-packages/openai/__pycache__/_files.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/__pycache__/_legacy_response.cpython-312.pyc b/venv/Lib/site-packages/openai/__pycache__/_legacy_response.cpython-312.pyc index 4b6d383c..41fd9cdb 100644 Binary files a/venv/Lib/site-packages/openai/__pycache__/_legacy_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/__pycache__/_legacy_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/__pycache__/_models.cpython-312.pyc b/venv/Lib/site-packages/openai/__pycache__/_models.cpython-312.pyc index 8d944a43..2ccaba6b 100644 Binary files a/venv/Lib/site-packages/openai/__pycache__/_models.cpython-312.pyc and b/venv/Lib/site-packages/openai/__pycache__/_models.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/__pycache__/_module_client.cpython-312.pyc b/venv/Lib/site-packages/openai/__pycache__/_module_client.cpython-312.pyc index 98af929a..ae3ccc4d 100644 Binary files a/venv/Lib/site-packages/openai/__pycache__/_module_client.cpython-312.pyc and b/venv/Lib/site-packages/openai/__pycache__/_module_client.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/__pycache__/_qs.cpython-312.pyc b/venv/Lib/site-packages/openai/__pycache__/_qs.cpython-312.pyc index 90ec7e5a..746e45dd 100644 Binary files a/venv/Lib/site-packages/openai/__pycache__/_qs.cpython-312.pyc and b/venv/Lib/site-packages/openai/__pycache__/_qs.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/__pycache__/_resource.cpython-312.pyc b/venv/Lib/site-packages/openai/__pycache__/_resource.cpython-312.pyc index 4b7d2ec9..fdf4d532 100644 Binary files a/venv/Lib/site-packages/openai/__pycache__/_resource.cpython-312.pyc and b/venv/Lib/site-packages/openai/__pycache__/_resource.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/__pycache__/_response.cpython-312.pyc b/venv/Lib/site-packages/openai/__pycache__/_response.cpython-312.pyc index f952a99e..15b7bb99 100644 Binary files a/venv/Lib/site-packages/openai/__pycache__/_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/__pycache__/_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/__pycache__/_streaming.cpython-312.pyc b/venv/Lib/site-packages/openai/__pycache__/_streaming.cpython-312.pyc index f0716dd8..5cd87df2 100644 Binary files a/venv/Lib/site-packages/openai/__pycache__/_streaming.cpython-312.pyc and b/venv/Lib/site-packages/openai/__pycache__/_streaming.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/__pycache__/_types.cpython-312.pyc b/venv/Lib/site-packages/openai/__pycache__/_types.cpython-312.pyc index 152ac03e..a5a0de57 100644 Binary files a/venv/Lib/site-packages/openai/__pycache__/_types.cpython-312.pyc and b/venv/Lib/site-packages/openai/__pycache__/_types.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/__pycache__/_version.cpython-312.pyc b/venv/Lib/site-packages/openai/__pycache__/_version.cpython-312.pyc index 9aa90c79..3ac4730f 100644 Binary files a/venv/Lib/site-packages/openai/__pycache__/_version.cpython-312.pyc and b/venv/Lib/site-packages/openai/__pycache__/_version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/__pycache__/pagination.cpython-312.pyc b/venv/Lib/site-packages/openai/__pycache__/pagination.cpython-312.pyc index ac80b8dd..998601b7 100644 Binary files a/venv/Lib/site-packages/openai/__pycache__/pagination.cpython-312.pyc and b/venv/Lib/site-packages/openai/__pycache__/pagination.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/__pycache__/version.cpython-312.pyc b/venv/Lib/site-packages/openai/__pycache__/version.cpython-312.pyc index 47ba1e07..db4d1d0e 100644 Binary files a/venv/Lib/site-packages/openai/__pycache__/version.cpython-312.pyc and b/venv/Lib/site-packages/openai/__pycache__/version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/_extras/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/_extras/__pycache__/__init__.cpython-312.pyc index bbfe9f12..984d06fb 100644 Binary files a/venv/Lib/site-packages/openai/_extras/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/_extras/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/_extras/__pycache__/_common.cpython-312.pyc b/venv/Lib/site-packages/openai/_extras/__pycache__/_common.cpython-312.pyc index 16e2c6ed..8431c9cd 100644 Binary files a/venv/Lib/site-packages/openai/_extras/__pycache__/_common.cpython-312.pyc and b/venv/Lib/site-packages/openai/_extras/__pycache__/_common.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/_extras/__pycache__/numpy_proxy.cpython-312.pyc b/venv/Lib/site-packages/openai/_extras/__pycache__/numpy_proxy.cpython-312.pyc index 91a826b9..7c6e65f9 100644 Binary files a/venv/Lib/site-packages/openai/_extras/__pycache__/numpy_proxy.cpython-312.pyc and b/venv/Lib/site-packages/openai/_extras/__pycache__/numpy_proxy.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/_extras/__pycache__/pandas_proxy.cpython-312.pyc b/venv/Lib/site-packages/openai/_extras/__pycache__/pandas_proxy.cpython-312.pyc index ac6a4fdb..777b8d68 100644 Binary files a/venv/Lib/site-packages/openai/_extras/__pycache__/pandas_proxy.cpython-312.pyc and b/venv/Lib/site-packages/openai/_extras/__pycache__/pandas_proxy.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/_extras/__pycache__/sounddevice_proxy.cpython-312.pyc b/venv/Lib/site-packages/openai/_extras/__pycache__/sounddevice_proxy.cpython-312.pyc index 3030465d..eb4ebbf2 100644 Binary files a/venv/Lib/site-packages/openai/_extras/__pycache__/sounddevice_proxy.cpython-312.pyc and b/venv/Lib/site-packages/openai/_extras/__pycache__/sounddevice_proxy.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/_utils/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/_utils/__pycache__/__init__.cpython-312.pyc index f9c3fc8b..da07d679 100644 Binary files a/venv/Lib/site-packages/openai/_utils/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/_utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/_utils/__pycache__/_logs.cpython-312.pyc b/venv/Lib/site-packages/openai/_utils/__pycache__/_logs.cpython-312.pyc index eed7c516..0ca9ec6b 100644 Binary files a/venv/Lib/site-packages/openai/_utils/__pycache__/_logs.cpython-312.pyc and b/venv/Lib/site-packages/openai/_utils/__pycache__/_logs.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/_utils/__pycache__/_proxy.cpython-312.pyc b/venv/Lib/site-packages/openai/_utils/__pycache__/_proxy.cpython-312.pyc index 97cf220c..2a81cbe7 100644 Binary files a/venv/Lib/site-packages/openai/_utils/__pycache__/_proxy.cpython-312.pyc and b/venv/Lib/site-packages/openai/_utils/__pycache__/_proxy.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/_utils/__pycache__/_reflection.cpython-312.pyc b/venv/Lib/site-packages/openai/_utils/__pycache__/_reflection.cpython-312.pyc index 9f7881a6..3e3dde65 100644 Binary files a/venv/Lib/site-packages/openai/_utils/__pycache__/_reflection.cpython-312.pyc and b/venv/Lib/site-packages/openai/_utils/__pycache__/_reflection.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/_utils/__pycache__/_resources_proxy.cpython-312.pyc b/venv/Lib/site-packages/openai/_utils/__pycache__/_resources_proxy.cpython-312.pyc index ba4d55d0..a592fbf5 100644 Binary files a/venv/Lib/site-packages/openai/_utils/__pycache__/_resources_proxy.cpython-312.pyc and b/venv/Lib/site-packages/openai/_utils/__pycache__/_resources_proxy.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/_utils/__pycache__/_streams.cpython-312.pyc b/venv/Lib/site-packages/openai/_utils/__pycache__/_streams.cpython-312.pyc index 51e93c9f..88734b3b 100644 Binary files a/venv/Lib/site-packages/openai/_utils/__pycache__/_streams.cpython-312.pyc and b/venv/Lib/site-packages/openai/_utils/__pycache__/_streams.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/_utils/__pycache__/_sync.cpython-312.pyc b/venv/Lib/site-packages/openai/_utils/__pycache__/_sync.cpython-312.pyc index 8668ab46..67345964 100644 Binary files a/venv/Lib/site-packages/openai/_utils/__pycache__/_sync.cpython-312.pyc and b/venv/Lib/site-packages/openai/_utils/__pycache__/_sync.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/_utils/__pycache__/_transform.cpython-312.pyc b/venv/Lib/site-packages/openai/_utils/__pycache__/_transform.cpython-312.pyc index f0fec663..f1bb5b90 100644 Binary files a/venv/Lib/site-packages/openai/_utils/__pycache__/_transform.cpython-312.pyc and b/venv/Lib/site-packages/openai/_utils/__pycache__/_transform.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/_utils/__pycache__/_typing.cpython-312.pyc b/venv/Lib/site-packages/openai/_utils/__pycache__/_typing.cpython-312.pyc index 46326397..ae6b2025 100644 Binary files a/venv/Lib/site-packages/openai/_utils/__pycache__/_typing.cpython-312.pyc and b/venv/Lib/site-packages/openai/_utils/__pycache__/_typing.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/_utils/__pycache__/_utils.cpython-312.pyc b/venv/Lib/site-packages/openai/_utils/__pycache__/_utils.cpython-312.pyc index 4c525f9a..fc4f041c 100644 Binary files a/venv/Lib/site-packages/openai/_utils/__pycache__/_utils.cpython-312.pyc and b/venv/Lib/site-packages/openai/_utils/__pycache__/_utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/lib/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/lib/__pycache__/__init__.cpython-312.pyc index 75f53aa5..782d8c92 100644 Binary files a/venv/Lib/site-packages/openai/lib/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/lib/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/lib/__pycache__/_old_api.cpython-312.pyc b/venv/Lib/site-packages/openai/lib/__pycache__/_old_api.cpython-312.pyc index 1391b519..22c06433 100644 Binary files a/venv/Lib/site-packages/openai/lib/__pycache__/_old_api.cpython-312.pyc and b/venv/Lib/site-packages/openai/lib/__pycache__/_old_api.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/lib/__pycache__/_pydantic.cpython-312.pyc b/venv/Lib/site-packages/openai/lib/__pycache__/_pydantic.cpython-312.pyc index 39258f46..b7c0c0c2 100644 Binary files a/venv/Lib/site-packages/openai/lib/__pycache__/_pydantic.cpython-312.pyc and b/venv/Lib/site-packages/openai/lib/__pycache__/_pydantic.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/lib/__pycache__/_tools.cpython-312.pyc b/venv/Lib/site-packages/openai/lib/__pycache__/_tools.cpython-312.pyc index 870470de..0dd435fc 100644 Binary files a/venv/Lib/site-packages/openai/lib/__pycache__/_tools.cpython-312.pyc and b/venv/Lib/site-packages/openai/lib/__pycache__/_tools.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/lib/__pycache__/azure.cpython-312.pyc b/venv/Lib/site-packages/openai/lib/__pycache__/azure.cpython-312.pyc index eeacefd4..b134e21d 100644 Binary files a/venv/Lib/site-packages/openai/lib/__pycache__/azure.cpython-312.pyc and b/venv/Lib/site-packages/openai/lib/__pycache__/azure.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/lib/_parsing/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/lib/_parsing/__pycache__/__init__.cpython-312.pyc index 59e70e1f..634581d2 100644 Binary files a/venv/Lib/site-packages/openai/lib/_parsing/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/lib/_parsing/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/lib/_parsing/__pycache__/_completions.cpython-312.pyc b/venv/Lib/site-packages/openai/lib/_parsing/__pycache__/_completions.cpython-312.pyc index 70816ba8..a670d0e8 100644 Binary files a/venv/Lib/site-packages/openai/lib/_parsing/__pycache__/_completions.cpython-312.pyc and b/venv/Lib/site-packages/openai/lib/_parsing/__pycache__/_completions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/lib/streaming/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/lib/streaming/__pycache__/__init__.cpython-312.pyc index e17a5947..ea5b0d1b 100644 Binary files a/venv/Lib/site-packages/openai/lib/streaming/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/lib/streaming/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/lib/streaming/__pycache__/_assistants.cpython-312.pyc b/venv/Lib/site-packages/openai/lib/streaming/__pycache__/_assistants.cpython-312.pyc index d23ef650..d403a6b8 100644 Binary files a/venv/Lib/site-packages/openai/lib/streaming/__pycache__/_assistants.cpython-312.pyc and b/venv/Lib/site-packages/openai/lib/streaming/__pycache__/_assistants.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/lib/streaming/__pycache__/_deltas.cpython-312.pyc b/venv/Lib/site-packages/openai/lib/streaming/__pycache__/_deltas.cpython-312.pyc index b8fc8076..91946405 100644 Binary files a/venv/Lib/site-packages/openai/lib/streaming/__pycache__/_deltas.cpython-312.pyc and b/venv/Lib/site-packages/openai/lib/streaming/__pycache__/_deltas.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/lib/streaming/chat/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/lib/streaming/chat/__pycache__/__init__.cpython-312.pyc index e5d7cfe5..8a206cb9 100644 Binary files a/venv/Lib/site-packages/openai/lib/streaming/chat/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/lib/streaming/chat/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/lib/streaming/chat/__pycache__/_completions.cpython-312.pyc b/venv/Lib/site-packages/openai/lib/streaming/chat/__pycache__/_completions.cpython-312.pyc index 0b69ae36..7e44b67e 100644 Binary files a/venv/Lib/site-packages/openai/lib/streaming/chat/__pycache__/_completions.cpython-312.pyc and b/venv/Lib/site-packages/openai/lib/streaming/chat/__pycache__/_completions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/lib/streaming/chat/__pycache__/_events.cpython-312.pyc b/venv/Lib/site-packages/openai/lib/streaming/chat/__pycache__/_events.cpython-312.pyc index a0f33412..0ad7d0ff 100644 Binary files a/venv/Lib/site-packages/openai/lib/streaming/chat/__pycache__/_events.cpython-312.pyc and b/venv/Lib/site-packages/openai/lib/streaming/chat/__pycache__/_events.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/lib/streaming/chat/__pycache__/_types.cpython-312.pyc b/venv/Lib/site-packages/openai/lib/streaming/chat/__pycache__/_types.cpython-312.pyc index d49eb692..50d2997d 100644 Binary files a/venv/Lib/site-packages/openai/lib/streaming/chat/__pycache__/_types.cpython-312.pyc and b/venv/Lib/site-packages/openai/lib/streaming/chat/__pycache__/_types.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/__pycache__/__init__.cpython-312.pyc index b4d8e0d3..16fa001e 100644 Binary files a/venv/Lib/site-packages/openai/resources/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/__pycache__/batches.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/__pycache__/batches.cpython-312.pyc index 50f03cdf..77bb6204 100644 Binary files a/venv/Lib/site-packages/openai/resources/__pycache__/batches.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/__pycache__/batches.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/__pycache__/completions.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/__pycache__/completions.cpython-312.pyc index df5abd8f..499da7f9 100644 Binary files a/venv/Lib/site-packages/openai/resources/__pycache__/completions.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/__pycache__/completions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/__pycache__/embeddings.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/__pycache__/embeddings.cpython-312.pyc index 77857a6c..3560e804 100644 Binary files a/venv/Lib/site-packages/openai/resources/__pycache__/embeddings.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/__pycache__/embeddings.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/__pycache__/files.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/__pycache__/files.cpython-312.pyc index 7cb2d717..4ca3897f 100644 Binary files a/venv/Lib/site-packages/openai/resources/__pycache__/files.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/__pycache__/files.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/__pycache__/images.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/__pycache__/images.cpython-312.pyc index a0cded74..3b4e93d5 100644 Binary files a/venv/Lib/site-packages/openai/resources/__pycache__/images.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/__pycache__/images.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/__pycache__/models.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/__pycache__/models.cpython-312.pyc index 2f2d6595..1558ebeb 100644 Binary files a/venv/Lib/site-packages/openai/resources/__pycache__/models.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/__pycache__/models.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/__pycache__/moderations.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/__pycache__/moderations.cpython-312.pyc index 018a35b0..0156513a 100644 Binary files a/venv/Lib/site-packages/openai/resources/__pycache__/moderations.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/__pycache__/moderations.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/audio/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/audio/__pycache__/__init__.cpython-312.pyc index ff87f916..3826d0e7 100644 Binary files a/venv/Lib/site-packages/openai/resources/audio/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/audio/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/audio/__pycache__/audio.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/audio/__pycache__/audio.cpython-312.pyc index 556c04e4..e7c303b7 100644 Binary files a/venv/Lib/site-packages/openai/resources/audio/__pycache__/audio.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/audio/__pycache__/audio.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/audio/__pycache__/speech.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/audio/__pycache__/speech.cpython-312.pyc index 6c5fbbc7..14dc9d7e 100644 Binary files a/venv/Lib/site-packages/openai/resources/audio/__pycache__/speech.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/audio/__pycache__/speech.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/audio/__pycache__/transcriptions.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/audio/__pycache__/transcriptions.cpython-312.pyc index d9805122..00d8d23c 100644 Binary files a/venv/Lib/site-packages/openai/resources/audio/__pycache__/transcriptions.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/audio/__pycache__/transcriptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/audio/__pycache__/translations.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/audio/__pycache__/translations.cpython-312.pyc index d637c1b8..aab5c31b 100644 Binary files a/venv/Lib/site-packages/openai/resources/audio/__pycache__/translations.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/audio/__pycache__/translations.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/beta/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/beta/__pycache__/__init__.cpython-312.pyc index 546169eb..d2f9fdbb 100644 Binary files a/venv/Lib/site-packages/openai/resources/beta/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/beta/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/beta/__pycache__/assistants.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/beta/__pycache__/assistants.cpython-312.pyc index eb851777..2fb1f26c 100644 Binary files a/venv/Lib/site-packages/openai/resources/beta/__pycache__/assistants.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/beta/__pycache__/assistants.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/beta/__pycache__/beta.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/beta/__pycache__/beta.cpython-312.pyc index fc59ebaf..41d6520a 100644 Binary files a/venv/Lib/site-packages/openai/resources/beta/__pycache__/beta.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/beta/__pycache__/beta.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/beta/chat/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/beta/chat/__pycache__/__init__.cpython-312.pyc index 71ceac37..b0bc5c43 100644 Binary files a/venv/Lib/site-packages/openai/resources/beta/chat/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/beta/chat/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/beta/chat/__pycache__/chat.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/beta/chat/__pycache__/chat.cpython-312.pyc index f0af8069..6512f29e 100644 Binary files a/venv/Lib/site-packages/openai/resources/beta/chat/__pycache__/chat.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/beta/chat/__pycache__/chat.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/beta/chat/__pycache__/completions.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/beta/chat/__pycache__/completions.cpython-312.pyc index 130c6fae..7dc4a046 100644 Binary files a/venv/Lib/site-packages/openai/resources/beta/chat/__pycache__/completions.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/beta/chat/__pycache__/completions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/beta/realtime/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/beta/realtime/__pycache__/__init__.cpython-312.pyc index fb659674..be419920 100644 Binary files a/venv/Lib/site-packages/openai/resources/beta/realtime/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/beta/realtime/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/beta/realtime/__pycache__/realtime.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/beta/realtime/__pycache__/realtime.cpython-312.pyc index 0ff9f792..4e29d25e 100644 Binary files a/venv/Lib/site-packages/openai/resources/beta/realtime/__pycache__/realtime.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/beta/realtime/__pycache__/realtime.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/beta/realtime/__pycache__/sessions.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/beta/realtime/__pycache__/sessions.cpython-312.pyc index f7df4313..132a98b7 100644 Binary files a/venv/Lib/site-packages/openai/resources/beta/realtime/__pycache__/sessions.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/beta/realtime/__pycache__/sessions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/beta/realtime/__pycache__/transcription_sessions.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/beta/realtime/__pycache__/transcription_sessions.cpython-312.pyc index 904a49ed..97c7a640 100644 Binary files a/venv/Lib/site-packages/openai/resources/beta/realtime/__pycache__/transcription_sessions.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/beta/realtime/__pycache__/transcription_sessions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/beta/threads/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/beta/threads/__pycache__/__init__.cpython-312.pyc index abdf1488..8d55a4c8 100644 Binary files a/venv/Lib/site-packages/openai/resources/beta/threads/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/beta/threads/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/beta/threads/__pycache__/messages.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/beta/threads/__pycache__/messages.cpython-312.pyc index 28ec3fda..a135e8ec 100644 Binary files a/venv/Lib/site-packages/openai/resources/beta/threads/__pycache__/messages.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/beta/threads/__pycache__/messages.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/beta/threads/__pycache__/threads.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/beta/threads/__pycache__/threads.cpython-312.pyc index ec1a43bc..7f2150d0 100644 Binary files a/venv/Lib/site-packages/openai/resources/beta/threads/__pycache__/threads.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/beta/threads/__pycache__/threads.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/beta/threads/runs/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/beta/threads/runs/__pycache__/__init__.cpython-312.pyc index 275c6efd..83970d37 100644 Binary files a/venv/Lib/site-packages/openai/resources/beta/threads/runs/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/beta/threads/runs/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/beta/threads/runs/__pycache__/runs.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/beta/threads/runs/__pycache__/runs.cpython-312.pyc index b03afc8d..31f7de98 100644 Binary files a/venv/Lib/site-packages/openai/resources/beta/threads/runs/__pycache__/runs.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/beta/threads/runs/__pycache__/runs.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/beta/threads/runs/__pycache__/steps.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/beta/threads/runs/__pycache__/steps.cpython-312.pyc index 9ce2cb94..ef31e170 100644 Binary files a/venv/Lib/site-packages/openai/resources/beta/threads/runs/__pycache__/steps.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/beta/threads/runs/__pycache__/steps.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/chat/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/chat/__pycache__/__init__.cpython-312.pyc index 4ba5539a..f5c67d33 100644 Binary files a/venv/Lib/site-packages/openai/resources/chat/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/chat/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/chat/__pycache__/chat.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/chat/__pycache__/chat.cpython-312.pyc index fcf792e7..cfd3bf62 100644 Binary files a/venv/Lib/site-packages/openai/resources/chat/__pycache__/chat.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/chat/__pycache__/chat.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/chat/completions/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/chat/completions/__pycache__/__init__.cpython-312.pyc index fde4b7c9..be7585e7 100644 Binary files a/venv/Lib/site-packages/openai/resources/chat/completions/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/chat/completions/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/chat/completions/__pycache__/completions.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/chat/completions/__pycache__/completions.cpython-312.pyc index 8603abef..0802fbdf 100644 Binary files a/venv/Lib/site-packages/openai/resources/chat/completions/__pycache__/completions.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/chat/completions/__pycache__/completions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/chat/completions/__pycache__/messages.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/chat/completions/__pycache__/messages.cpython-312.pyc index 4c1df7b7..0248dd51 100644 Binary files a/venv/Lib/site-packages/openai/resources/chat/completions/__pycache__/messages.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/chat/completions/__pycache__/messages.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/containers/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/containers/__pycache__/__init__.cpython-312.pyc index e28996db..5e07b2f5 100644 Binary files a/venv/Lib/site-packages/openai/resources/containers/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/containers/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/containers/__pycache__/containers.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/containers/__pycache__/containers.cpython-312.pyc index e0d96217..4e27bcd1 100644 Binary files a/venv/Lib/site-packages/openai/resources/containers/__pycache__/containers.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/containers/__pycache__/containers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/containers/files/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/containers/files/__pycache__/__init__.cpython-312.pyc index f2caaa2d..1f1bd38e 100644 Binary files a/venv/Lib/site-packages/openai/resources/containers/files/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/containers/files/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/containers/files/__pycache__/content.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/containers/files/__pycache__/content.cpython-312.pyc index 0c5d65c4..bb70234c 100644 Binary files a/venv/Lib/site-packages/openai/resources/containers/files/__pycache__/content.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/containers/files/__pycache__/content.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/containers/files/__pycache__/files.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/containers/files/__pycache__/files.cpython-312.pyc index 9c6d88e3..f35056be 100644 Binary files a/venv/Lib/site-packages/openai/resources/containers/files/__pycache__/files.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/containers/files/__pycache__/files.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/evals/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/evals/__pycache__/__init__.cpython-312.pyc index a5bb28e2..b5fae06f 100644 Binary files a/venv/Lib/site-packages/openai/resources/evals/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/evals/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/evals/__pycache__/evals.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/evals/__pycache__/evals.cpython-312.pyc index 49c5410c..4e970f09 100644 Binary files a/venv/Lib/site-packages/openai/resources/evals/__pycache__/evals.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/evals/__pycache__/evals.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/evals/runs/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/evals/runs/__pycache__/__init__.cpython-312.pyc index 4e56fec3..e040b1ff 100644 Binary files a/venv/Lib/site-packages/openai/resources/evals/runs/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/evals/runs/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/evals/runs/__pycache__/output_items.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/evals/runs/__pycache__/output_items.cpython-312.pyc index 51339a30..2ad827db 100644 Binary files a/venv/Lib/site-packages/openai/resources/evals/runs/__pycache__/output_items.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/evals/runs/__pycache__/output_items.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/evals/runs/__pycache__/runs.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/evals/runs/__pycache__/runs.cpython-312.pyc index f501b834..8ab551be 100644 Binary files a/venv/Lib/site-packages/openai/resources/evals/runs/__pycache__/runs.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/evals/runs/__pycache__/runs.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/fine_tuning/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/fine_tuning/__pycache__/__init__.cpython-312.pyc index 32de1a1c..51c55230 100644 Binary files a/venv/Lib/site-packages/openai/resources/fine_tuning/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/fine_tuning/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/fine_tuning/__pycache__/fine_tuning.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/fine_tuning/__pycache__/fine_tuning.cpython-312.pyc index 64e2dbda..006ae711 100644 Binary files a/venv/Lib/site-packages/openai/resources/fine_tuning/__pycache__/fine_tuning.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/fine_tuning/__pycache__/fine_tuning.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/fine_tuning/alpha/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/fine_tuning/alpha/__pycache__/__init__.cpython-312.pyc index 3651cde3..a36b61f4 100644 Binary files a/venv/Lib/site-packages/openai/resources/fine_tuning/alpha/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/fine_tuning/alpha/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/fine_tuning/alpha/__pycache__/alpha.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/fine_tuning/alpha/__pycache__/alpha.cpython-312.pyc index acf2da4d..7fdf69f3 100644 Binary files a/venv/Lib/site-packages/openai/resources/fine_tuning/alpha/__pycache__/alpha.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/fine_tuning/alpha/__pycache__/alpha.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/fine_tuning/alpha/__pycache__/graders.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/fine_tuning/alpha/__pycache__/graders.cpython-312.pyc index 7c92c68b..1cfbee4e 100644 Binary files a/venv/Lib/site-packages/openai/resources/fine_tuning/alpha/__pycache__/graders.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/fine_tuning/alpha/__pycache__/graders.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/fine_tuning/checkpoints/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/fine_tuning/checkpoints/__pycache__/__init__.cpython-312.pyc index 9010377a..54fc6b30 100644 Binary files a/venv/Lib/site-packages/openai/resources/fine_tuning/checkpoints/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/fine_tuning/checkpoints/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/fine_tuning/checkpoints/__pycache__/checkpoints.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/fine_tuning/checkpoints/__pycache__/checkpoints.cpython-312.pyc index e4a4e4d6..245f8b5e 100644 Binary files a/venv/Lib/site-packages/openai/resources/fine_tuning/checkpoints/__pycache__/checkpoints.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/fine_tuning/checkpoints/__pycache__/checkpoints.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/fine_tuning/checkpoints/__pycache__/permissions.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/fine_tuning/checkpoints/__pycache__/permissions.cpython-312.pyc index edecbdc7..0524f46f 100644 Binary files a/venv/Lib/site-packages/openai/resources/fine_tuning/checkpoints/__pycache__/permissions.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/fine_tuning/checkpoints/__pycache__/permissions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/fine_tuning/jobs/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/fine_tuning/jobs/__pycache__/__init__.cpython-312.pyc index d6119544..551d1177 100644 Binary files a/venv/Lib/site-packages/openai/resources/fine_tuning/jobs/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/fine_tuning/jobs/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/fine_tuning/jobs/__pycache__/checkpoints.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/fine_tuning/jobs/__pycache__/checkpoints.cpython-312.pyc index 3f2ebe8c..ab5733ef 100644 Binary files a/venv/Lib/site-packages/openai/resources/fine_tuning/jobs/__pycache__/checkpoints.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/fine_tuning/jobs/__pycache__/checkpoints.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/fine_tuning/jobs/__pycache__/jobs.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/fine_tuning/jobs/__pycache__/jobs.cpython-312.pyc index e767a7ce..94c791a0 100644 Binary files a/venv/Lib/site-packages/openai/resources/fine_tuning/jobs/__pycache__/jobs.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/fine_tuning/jobs/__pycache__/jobs.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/uploads/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/uploads/__pycache__/__init__.cpython-312.pyc index 179aa0d5..6f7be8c8 100644 Binary files a/venv/Lib/site-packages/openai/resources/uploads/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/uploads/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/uploads/__pycache__/parts.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/uploads/__pycache__/parts.cpython-312.pyc index 44257870..a5741a90 100644 Binary files a/venv/Lib/site-packages/openai/resources/uploads/__pycache__/parts.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/uploads/__pycache__/parts.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/uploads/__pycache__/uploads.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/uploads/__pycache__/uploads.cpython-312.pyc index fb809f3a..fc50d829 100644 Binary files a/venv/Lib/site-packages/openai/resources/uploads/__pycache__/uploads.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/uploads/__pycache__/uploads.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/vector_stores/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/vector_stores/__pycache__/__init__.cpython-312.pyc index a6e738bb..502c0fe3 100644 Binary files a/venv/Lib/site-packages/openai/resources/vector_stores/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/vector_stores/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/vector_stores/__pycache__/file_batches.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/vector_stores/__pycache__/file_batches.cpython-312.pyc index 537044ec..04d0ab6d 100644 Binary files a/venv/Lib/site-packages/openai/resources/vector_stores/__pycache__/file_batches.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/vector_stores/__pycache__/file_batches.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/vector_stores/__pycache__/files.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/vector_stores/__pycache__/files.cpython-312.pyc index db77c6d8..bff7b74e 100644 Binary files a/venv/Lib/site-packages/openai/resources/vector_stores/__pycache__/files.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/vector_stores/__pycache__/files.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/resources/vector_stores/__pycache__/vector_stores.cpython-312.pyc b/venv/Lib/site-packages/openai/resources/vector_stores/__pycache__/vector_stores.cpython-312.pyc index 0d1467d8..5481af25 100644 Binary files a/venv/Lib/site-packages/openai/resources/vector_stores/__pycache__/vector_stores.cpython-312.pyc and b/venv/Lib/site-packages/openai/resources/vector_stores/__pycache__/vector_stores.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/__init__.cpython-312.pyc index 8561964d..ce80ff20 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/audio_model.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/audio_model.cpython-312.pyc index 2d7fe17b..1beb9ef7 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/audio_model.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/audio_model.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/audio_response_format.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/audio_response_format.cpython-312.pyc index 40dc665a..0bcfb34a 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/audio_response_format.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/audio_response_format.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/auto_file_chunking_strategy_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/auto_file_chunking_strategy_param.cpython-312.pyc index 923d1b1f..106c7e1f 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/auto_file_chunking_strategy_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/auto_file_chunking_strategy_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/batch.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/batch.cpython-312.pyc index e94b0e1b..a1db9e0c 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/batch.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/batch.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/batch_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/batch_create_params.cpython-312.pyc index aba2c197..7d7f7e47 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/batch_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/batch_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/batch_error.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/batch_error.cpython-312.pyc index 4e368b4f..3654da94 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/batch_error.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/batch_error.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/batch_list_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/batch_list_params.cpython-312.pyc index 3e72134d..c73166c4 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/batch_list_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/batch_list_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/batch_request_counts.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/batch_request_counts.cpython-312.pyc index d599b825..1618161c 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/batch_request_counts.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/batch_request_counts.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/chat_model.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/chat_model.cpython-312.pyc index e1f4ce17..f93dfaf9 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/chat_model.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/chat_model.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/completion.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/completion.cpython-312.pyc index 64c9bff7..cdf1d9ea 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/completion.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/completion.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/completion_choice.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/completion_choice.cpython-312.pyc index 29a66eef..7abef67e 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/completion_choice.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/completion_choice.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/completion_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/completion_create_params.cpython-312.pyc index aa11263d..e5a82ba3 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/completion_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/completion_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/completion_usage.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/completion_usage.cpython-312.pyc index 1d8a24d1..56db1642 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/completion_usage.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/completion_usage.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/container_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/container_create_params.cpython-312.pyc index 4f983182..df0b89cc 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/container_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/container_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/container_create_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/container_create_response.cpython-312.pyc index 72992a00..af3f41e6 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/container_create_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/container_create_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/container_list_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/container_list_params.cpython-312.pyc index c4371751..4069c565 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/container_list_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/container_list_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/container_list_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/container_list_response.cpython-312.pyc index 293cc6a6..86a0e5b8 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/container_list_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/container_list_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/container_retrieve_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/container_retrieve_response.cpython-312.pyc index f6c4b31d..617be090 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/container_retrieve_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/container_retrieve_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/create_embedding_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/create_embedding_response.cpython-312.pyc index eb0faf09..d54a9ea2 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/create_embedding_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/create_embedding_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/embedding.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/embedding.cpython-312.pyc index 2dea6f4e..2d770c5d 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/embedding.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/embedding.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/embedding_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/embedding_create_params.cpython-312.pyc index e2644985..751e0fd4 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/embedding_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/embedding_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/embedding_model.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/embedding_model.cpython-312.pyc index 702f6d9a..6503639e 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/embedding_model.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/embedding_model.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/eval_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/eval_create_params.cpython-312.pyc index 54d8ef5d..665a89ee 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/eval_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/eval_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/eval_create_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/eval_create_response.cpython-312.pyc index 99b013a2..36c8c74b 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/eval_create_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/eval_create_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/eval_custom_data_source_config.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/eval_custom_data_source_config.cpython-312.pyc index e041545c..fa4caaaf 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/eval_custom_data_source_config.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/eval_custom_data_source_config.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/eval_delete_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/eval_delete_response.cpython-312.pyc index b8e0485e..18bca7ae 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/eval_delete_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/eval_delete_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/eval_list_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/eval_list_params.cpython-312.pyc index 098bc420..62ab12f6 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/eval_list_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/eval_list_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/eval_list_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/eval_list_response.cpython-312.pyc index a0c6610e..07be1a28 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/eval_list_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/eval_list_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/eval_retrieve_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/eval_retrieve_response.cpython-312.pyc index 9bc0b642..738c542e 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/eval_retrieve_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/eval_retrieve_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/eval_stored_completions_data_source_config.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/eval_stored_completions_data_source_config.cpython-312.pyc index 4daafb66..05dd0b7a 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/eval_stored_completions_data_source_config.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/eval_stored_completions_data_source_config.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/eval_update_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/eval_update_params.cpython-312.pyc index edb7fdd7..6fdd537a 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/eval_update_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/eval_update_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/eval_update_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/eval_update_response.cpython-312.pyc index d9088e02..79d2ed1c 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/eval_update_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/eval_update_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/file_chunking_strategy.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/file_chunking_strategy.cpython-312.pyc index 08568a01..45cc16f2 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/file_chunking_strategy.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/file_chunking_strategy.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/file_chunking_strategy_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/file_chunking_strategy_param.cpython-312.pyc index be30e00d..4cc8462c 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/file_chunking_strategy_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/file_chunking_strategy_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/file_content.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/file_content.cpython-312.pyc index 2f724425..80cb2a10 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/file_content.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/file_content.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/file_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/file_create_params.cpython-312.pyc index f11a4a15..509a09cc 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/file_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/file_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/file_deleted.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/file_deleted.cpython-312.pyc index 017c600b..81e90415 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/file_deleted.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/file_deleted.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/file_list_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/file_list_params.cpython-312.pyc index f02e7465..fcde798b 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/file_list_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/file_list_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/file_object.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/file_object.cpython-312.pyc index b8a742a8..a0310208 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/file_object.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/file_object.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/file_purpose.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/file_purpose.cpython-312.pyc index 40e2e110..4542cc43 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/file_purpose.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/file_purpose.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/image.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/image.cpython-312.pyc index ddddbfc8..f82935ab 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/image.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/image.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/image_create_variation_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/image_create_variation_params.cpython-312.pyc index 845d0c6d..553b2ca0 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/image_create_variation_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/image_create_variation_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/image_edit_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/image_edit_params.cpython-312.pyc index a3c1fd14..97d3ff2b 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/image_edit_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/image_edit_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/image_generate_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/image_generate_params.cpython-312.pyc index 16437daa..f996a699 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/image_generate_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/image_generate_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/image_model.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/image_model.cpython-312.pyc index 9fc69650..e7f32b04 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/image_model.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/image_model.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/images_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/images_response.cpython-312.pyc index f1a31552..6c07d4a6 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/images_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/images_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/model.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/model.cpython-312.pyc index e11f0d6e..7a62c87d 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/model.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/model.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/model_deleted.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/model_deleted.cpython-312.pyc index 2e4463d1..cecb1535 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/model_deleted.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/model_deleted.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/moderation.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/moderation.cpython-312.pyc index 19fa6ad4..cb0f0efe 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/moderation.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/moderation.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/moderation_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/moderation_create_params.cpython-312.pyc index 96446ec6..c7172737 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/moderation_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/moderation_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/moderation_create_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/moderation_create_response.cpython-312.pyc index 3d5699cf..fefae7f3 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/moderation_create_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/moderation_create_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/moderation_image_url_input_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/moderation_image_url_input_param.cpython-312.pyc index 97e37285..90eacf06 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/moderation_image_url_input_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/moderation_image_url_input_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/moderation_model.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/moderation_model.cpython-312.pyc index 11a9f180..c51bbfa7 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/moderation_model.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/moderation_model.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/moderation_multi_modal_input_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/moderation_multi_modal_input_param.cpython-312.pyc index f165544e..732ada5e 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/moderation_multi_modal_input_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/moderation_multi_modal_input_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/moderation_text_input_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/moderation_text_input_param.cpython-312.pyc index d0ac10ce..c532cea2 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/moderation_text_input_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/moderation_text_input_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/other_file_chunking_strategy_object.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/other_file_chunking_strategy_object.cpython-312.pyc index 21555a14..f401665b 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/other_file_chunking_strategy_object.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/other_file_chunking_strategy_object.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/static_file_chunking_strategy.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/static_file_chunking_strategy.cpython-312.pyc index e9c6cd39..1aecfa3d 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/static_file_chunking_strategy.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/static_file_chunking_strategy.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/static_file_chunking_strategy_object.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/static_file_chunking_strategy_object.cpython-312.pyc index 395558be..2b6483c4 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/static_file_chunking_strategy_object.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/static_file_chunking_strategy_object.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/static_file_chunking_strategy_object_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/static_file_chunking_strategy_object_param.cpython-312.pyc index a51e1016..d2f2f535 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/static_file_chunking_strategy_object_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/static_file_chunking_strategy_object_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/static_file_chunking_strategy_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/static_file_chunking_strategy_param.cpython-312.pyc index 07c364a6..7b9cdaff 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/static_file_chunking_strategy_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/static_file_chunking_strategy_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/upload.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/upload.cpython-312.pyc index 3b14bf60..87918d36 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/upload.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/upload.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/upload_complete_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/upload_complete_params.cpython-312.pyc index 2b4a98f9..08013504 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/upload_complete_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/upload_complete_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/upload_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/upload_create_params.cpython-312.pyc index 5714552e..3a02df91 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/upload_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/upload_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/vector_store.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/vector_store.cpython-312.pyc index 31e11192..2572ea81 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/vector_store.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/vector_store.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/vector_store_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/vector_store_create_params.cpython-312.pyc index c37f1299..0f7d3070 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/vector_store_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/vector_store_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/vector_store_deleted.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/vector_store_deleted.cpython-312.pyc index ee5310b9..8e473f4c 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/vector_store_deleted.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/vector_store_deleted.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/vector_store_list_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/vector_store_list_params.cpython-312.pyc index 39cd5d17..be14e532 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/vector_store_list_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/vector_store_list_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/vector_store_search_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/vector_store_search_params.cpython-312.pyc index 4c203b4f..fb45e4c9 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/vector_store_search_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/vector_store_search_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/vector_store_search_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/vector_store_search_response.cpython-312.pyc index e3c47859..ef84d710 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/vector_store_search_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/vector_store_search_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/vector_store_update_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/vector_store_update_params.cpython-312.pyc index 8591d64b..5c955265 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/vector_store_update_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/vector_store_update_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/__pycache__/websocket_connection_options.cpython-312.pyc b/venv/Lib/site-packages/openai/types/__pycache__/websocket_connection_options.cpython-312.pyc index 6b01d469..941b1228 100644 Binary files a/venv/Lib/site-packages/openai/types/__pycache__/websocket_connection_options.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/__pycache__/websocket_connection_options.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/audio/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/types/audio/__pycache__/__init__.cpython-312.pyc index 684ff5fe..d9a72c2a 100644 Binary files a/venv/Lib/site-packages/openai/types/audio/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/audio/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/audio/__pycache__/speech_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/audio/__pycache__/speech_create_params.cpython-312.pyc index da04b1bb..1dc226b7 100644 Binary files a/venv/Lib/site-packages/openai/types/audio/__pycache__/speech_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/audio/__pycache__/speech_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/audio/__pycache__/speech_model.cpython-312.pyc b/venv/Lib/site-packages/openai/types/audio/__pycache__/speech_model.cpython-312.pyc index b86f8197..c8a607a2 100644 Binary files a/venv/Lib/site-packages/openai/types/audio/__pycache__/speech_model.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/audio/__pycache__/speech_model.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription.cpython-312.pyc b/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription.cpython-312.pyc index 04470d05..8c507d2d 100644 Binary files a/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_create_params.cpython-312.pyc index efbd5592..c7f24d92 100644 Binary files a/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_create_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_create_response.cpython-312.pyc index 5aabd19a..96c0b819 100644 Binary files a/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_create_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_create_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_include.cpython-312.pyc b/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_include.cpython-312.pyc index 8b879f7b..522415ee 100644 Binary files a/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_include.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_include.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_segment.cpython-312.pyc b/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_segment.cpython-312.pyc index cbd3adec..bd314104 100644 Binary files a/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_segment.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_segment.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_stream_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_stream_event.cpython-312.pyc index 385d6f32..133cf149 100644 Binary files a/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_stream_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_stream_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_text_delta_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_text_delta_event.cpython-312.pyc index ee9e4196..0a3cb380 100644 Binary files a/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_text_delta_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_text_delta_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_text_done_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_text_done_event.cpython-312.pyc index 8d858689..00aa3090 100644 Binary files a/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_text_done_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_text_done_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_verbose.cpython-312.pyc b/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_verbose.cpython-312.pyc index 9c92091e..77b264c6 100644 Binary files a/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_verbose.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_verbose.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_word.cpython-312.pyc b/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_word.cpython-312.pyc index acf738d1..e55b3ee7 100644 Binary files a/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_word.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/audio/__pycache__/transcription_word.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/audio/__pycache__/translation.cpython-312.pyc b/venv/Lib/site-packages/openai/types/audio/__pycache__/translation.cpython-312.pyc index 866ce01f..d8c12194 100644 Binary files a/venv/Lib/site-packages/openai/types/audio/__pycache__/translation.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/audio/__pycache__/translation.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/audio/__pycache__/translation_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/audio/__pycache__/translation_create_params.cpython-312.pyc index 6c17c6d3..4035d5d6 100644 Binary files a/venv/Lib/site-packages/openai/types/audio/__pycache__/translation_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/audio/__pycache__/translation_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/audio/__pycache__/translation_create_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/audio/__pycache__/translation_create_response.cpython-312.pyc index c44a70af..2920ab20 100644 Binary files a/venv/Lib/site-packages/openai/types/audio/__pycache__/translation_create_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/audio/__pycache__/translation_create_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/audio/__pycache__/translation_verbose.cpython-312.pyc b/venv/Lib/site-packages/openai/types/audio/__pycache__/translation_verbose.cpython-312.pyc index e0c71388..d13e92fa 100644 Binary files a/venv/Lib/site-packages/openai/types/audio/__pycache__/translation_verbose.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/audio/__pycache__/translation_verbose.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/__init__.cpython-312.pyc index 31d5a2e9..d72e7df7 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant.cpython-312.pyc index bc099d4b..60f563f6 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_create_params.cpython-312.pyc index 7884ab1e..cc488502 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_deleted.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_deleted.cpython-312.pyc index ad0224d9..bc522b4a 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_deleted.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_deleted.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_list_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_list_params.cpython-312.pyc index b01298ac..a611a17d 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_list_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_list_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_response_format_option.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_response_format_option.cpython-312.pyc index ace3d813..83104035 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_response_format_option.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_response_format_option.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_response_format_option_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_response_format_option_param.cpython-312.pyc index ecce9b9e..72145540 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_response_format_option_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_response_format_option_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_stream_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_stream_event.cpython-312.pyc index 9e1a7706..b10a6e29 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_stream_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_stream_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool.cpython-312.pyc index 81dd40c0..b82cd0de 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_choice.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_choice.cpython-312.pyc index 31d7d617..37b46b97 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_choice.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_choice.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_choice_function.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_choice_function.cpython-312.pyc index 62621fe4..45d02555 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_choice_function.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_choice_function.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_choice_function_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_choice_function_param.cpython-312.pyc index d9af1f92..ccd8365f 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_choice_function_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_choice_function_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_choice_option.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_choice_option.cpython-312.pyc index adaaaef1..a269171e 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_choice_option.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_choice_option.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_choice_option_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_choice_option_param.cpython-312.pyc index d4d90eb1..1062a4eb 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_choice_option_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_choice_option_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_choice_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_choice_param.cpython-312.pyc index ef981898..3ea048d4 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_choice_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_choice_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_param.cpython-312.pyc index 08e4417b..b76a8edf 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_tool_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_update_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_update_params.cpython-312.pyc index d5579296..687ad1b6 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_update_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/assistant_update_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/code_interpreter_tool.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/code_interpreter_tool.cpython-312.pyc index 049c13db..bee9ebff 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/code_interpreter_tool.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/code_interpreter_tool.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/code_interpreter_tool_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/code_interpreter_tool_param.cpython-312.pyc index 19229c10..1eb19cde 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/code_interpreter_tool_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/code_interpreter_tool_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/file_search_tool.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/file_search_tool.cpython-312.pyc index aa7712b3..38f06eac 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/file_search_tool.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/file_search_tool.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/file_search_tool_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/file_search_tool_param.cpython-312.pyc index e409e0a3..af60b124 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/file_search_tool_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/file_search_tool_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/function_tool.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/function_tool.cpython-312.pyc index 11526718..6afb10c9 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/function_tool.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/function_tool.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/function_tool_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/function_tool_param.cpython-312.pyc index 2f816780..2465b737 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/function_tool_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/function_tool_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/thread.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/thread.cpython-312.pyc index c759a591..1520893c 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/thread.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/thread.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/thread_create_and_run_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/thread_create_and_run_params.cpython-312.pyc index 3f7d3807..5a1467ec 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/thread_create_and_run_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/thread_create_and_run_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/thread_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/thread_create_params.cpython-312.pyc index 1fdb85ed..ef0c8de6 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/thread_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/thread_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/thread_deleted.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/thread_deleted.cpython-312.pyc index 1a9455d7..1f9c67f2 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/thread_deleted.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/thread_deleted.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/__pycache__/thread_update_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/__pycache__/thread_update_params.cpython-312.pyc index 76c7617f..1f031ae9 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/__pycache__/thread_update_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/__pycache__/thread_update_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/__init__.cpython-312.pyc index 263ada7e..444ae9bc 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_created_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_created_event.cpython-312.pyc index 91bebfb4..041f6a7e 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_created_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_created_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item.cpython-312.pyc index b9ee61e5..b3dd1c63 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_content.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_content.cpython-312.pyc index 7eaa8532..46146a3b 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_content.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_content.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_content_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_content_param.cpython-312.pyc index d84aa417..cb199dbc 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_content_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_content_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_create_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_create_event.cpython-312.pyc index 91a62f8b..ff9ecf4a 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_create_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_create_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_create_event_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_create_event_param.cpython-312.pyc index f4a06b6f..4c271876 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_create_event_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_create_event_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_created_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_created_event.cpython-312.pyc index 7c5fcc57..4346aa05 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_created_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_created_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_delete_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_delete_event.cpython-312.pyc index 3e79d206..12050cf2 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_delete_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_delete_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_delete_event_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_delete_event_param.cpython-312.pyc index e68d72a9..9167232c 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_delete_event_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_delete_event_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_deleted_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_deleted_event.cpython-312.pyc index 923c8d9d..b3122ff0 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_deleted_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_deleted_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_input_audio_transcription_completed_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_input_audio_transcription_completed_event.cpython-312.pyc index 3e8a0260..9a8bab80 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_input_audio_transcription_completed_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_input_audio_transcription_completed_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_input_audio_transcription_delta_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_input_audio_transcription_delta_event.cpython-312.pyc index b0a54df5..ee453302 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_input_audio_transcription_delta_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_input_audio_transcription_delta_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_input_audio_transcription_failed_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_input_audio_transcription_failed_event.cpython-312.pyc index 4ba9f4cb..48fa09bc 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_input_audio_transcription_failed_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_input_audio_transcription_failed_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_param.cpython-312.pyc index 2309c336..53b1d41f 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_retrieve_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_retrieve_event.cpython-312.pyc index 8b562acf..467a6561 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_retrieve_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_retrieve_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_retrieve_event_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_retrieve_event_param.cpython-312.pyc index d5d2d3d0..1ff8f081 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_retrieve_event_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_retrieve_event_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_truncate_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_truncate_event.cpython-312.pyc index 64ff9e70..1659d1c7 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_truncate_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_truncate_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_truncate_event_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_truncate_event_param.cpython-312.pyc index 7669b527..64cdf762 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_truncate_event_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_truncate_event_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_truncated_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_truncated_event.cpython-312.pyc index aee4c54c..6b1c9baf 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_truncated_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_truncated_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_with_reference.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_with_reference.cpython-312.pyc index 51df7a24..404aa87d 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_with_reference.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_with_reference.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_with_reference_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_with_reference_param.cpython-312.pyc index a3c87722..cd7dd144 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_with_reference_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/conversation_item_with_reference_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/error_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/error_event.cpython-312.pyc index 51d8ae76..4a60e36b 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/error_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/error_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_append_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_append_event.cpython-312.pyc index ea4e74da..26bb4634 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_append_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_append_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_append_event_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_append_event_param.cpython-312.pyc index 134cb85e..8de541be 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_append_event_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_append_event_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_clear_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_clear_event.cpython-312.pyc index 023f79a0..8d375490 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_clear_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_clear_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_clear_event_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_clear_event_param.cpython-312.pyc index bc8f975c..7d32a524 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_clear_event_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_clear_event_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_cleared_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_cleared_event.cpython-312.pyc index 91498053..36030f59 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_cleared_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_cleared_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_commit_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_commit_event.cpython-312.pyc index ec435d5b..f304e5bd 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_commit_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_commit_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_commit_event_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_commit_event_param.cpython-312.pyc index 1960d5e0..c7c35966 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_commit_event_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_commit_event_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_committed_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_committed_event.cpython-312.pyc index d7006a1f..f852448b 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_committed_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_committed_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_speech_started_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_speech_started_event.cpython-312.pyc index dc65f736..6a069f60 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_speech_started_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_speech_started_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_speech_stopped_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_speech_stopped_event.cpython-312.pyc index 2174fec5..5fa24715 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_speech_stopped_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/input_audio_buffer_speech_stopped_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/rate_limits_updated_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/rate_limits_updated_event.cpython-312.pyc index 063e0110..4ef4927a 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/rate_limits_updated_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/rate_limits_updated_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_client_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_client_event.cpython-312.pyc index 3d2b23da..6502c474 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_client_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_client_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_client_event_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_client_event_param.cpython-312.pyc index 158b3a21..8f2e6b2c 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_client_event_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_client_event_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_connect_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_connect_params.cpython-312.pyc index 0a748daa..caed9cab 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_connect_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_connect_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_response.cpython-312.pyc index 3d107693..1586d58a 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_response_status.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_response_status.cpython-312.pyc index 0483d423..2b6f4c91 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_response_status.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_response_status.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_response_usage.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_response_usage.cpython-312.pyc index 6c01b7d0..f006cb72 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_response_usage.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_response_usage.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_server_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_server_event.cpython-312.pyc index 70863629..2ce492ac 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_server_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/realtime_server_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_audio_delta_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_audio_delta_event.cpython-312.pyc index 8de5d17c..4462f4b8 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_audio_delta_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_audio_delta_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_audio_done_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_audio_done_event.cpython-312.pyc index 2ca6dcd1..d3fba8a6 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_audio_done_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_audio_done_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_audio_transcript_delta_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_audio_transcript_delta_event.cpython-312.pyc index d7d819ab..23c209da 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_audio_transcript_delta_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_audio_transcript_delta_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_audio_transcript_done_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_audio_transcript_done_event.cpython-312.pyc index 698d0296..2c8c351d 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_audio_transcript_done_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_audio_transcript_done_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_cancel_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_cancel_event.cpython-312.pyc index 3a7e903e..79ff7409 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_cancel_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_cancel_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_cancel_event_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_cancel_event_param.cpython-312.pyc index 2ddcda2c..a3e4e716 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_cancel_event_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_cancel_event_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_content_part_added_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_content_part_added_event.cpython-312.pyc index f83f974f..d0c3c203 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_content_part_added_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_content_part_added_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_content_part_done_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_content_part_done_event.cpython-312.pyc index d92fbf63..9a814946 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_content_part_done_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_content_part_done_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_create_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_create_event.cpython-312.pyc index f3f4149e..96c4a39c 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_create_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_create_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_create_event_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_create_event_param.cpython-312.pyc index f33b9981..1075faaa 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_create_event_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_create_event_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_created_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_created_event.cpython-312.pyc index ac95303d..989b824c 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_created_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_created_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_done_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_done_event.cpython-312.pyc index 4bcf08cf..eb933c90 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_done_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_done_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_function_call_arguments_delta_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_function_call_arguments_delta_event.cpython-312.pyc index 4902ff37..a8c5d639 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_function_call_arguments_delta_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_function_call_arguments_delta_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_function_call_arguments_done_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_function_call_arguments_done_event.cpython-312.pyc index 94ecc73a..24b2c3b1 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_function_call_arguments_done_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_function_call_arguments_done_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_output_item_added_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_output_item_added_event.cpython-312.pyc index 90c1a680..42dc8070 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_output_item_added_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_output_item_added_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_output_item_done_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_output_item_done_event.cpython-312.pyc index e384cdf3..184cd205 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_output_item_done_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_output_item_done_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_text_delta_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_text_delta_event.cpython-312.pyc index 6e9e9164..03983783 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_text_delta_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_text_delta_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_text_done_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_text_done_event.cpython-312.pyc index dd956dd7..c60dd2cc 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_text_done_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/response_text_done_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session.cpython-312.pyc index cc1766ef..4e6b33b9 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session_create_params.cpython-312.pyc index d05433ec..64c9ef9f 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session_create_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session_create_response.cpython-312.pyc index ba2bbce4..0912082b 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session_create_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session_create_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session_created_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session_created_event.cpython-312.pyc index bfff311b..1a63cdd1 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session_created_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session_created_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session_update_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session_update_event.cpython-312.pyc index 88a3103a..8339d788 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session_update_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session_update_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session_update_event_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session_update_event_param.cpython-312.pyc index 316cdcff..6aaa9fca 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session_update_event_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session_update_event_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session_updated_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session_updated_event.cpython-312.pyc index 173fa8ca..4edb2d46 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session_updated_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/session_updated_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/transcription_session.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/transcription_session.cpython-312.pyc index 1d8798d6..27ad0188 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/transcription_session.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/transcription_session.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/transcription_session_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/transcription_session_create_params.cpython-312.pyc index cde6f7f4..0309bdcd 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/transcription_session_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/transcription_session_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/transcription_session_update.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/transcription_session_update.cpython-312.pyc index a4adf1cf..a5fa8289 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/transcription_session_update.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/transcription_session_update.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/transcription_session_update_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/transcription_session_update_param.cpython-312.pyc index 93b18a7e..cd383a28 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/transcription_session_update_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/transcription_session_update_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/transcription_session_updated_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/transcription_session_updated_event.cpython-312.pyc index 9d1acc3c..da6d0d5b 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/transcription_session_updated_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/realtime/__pycache__/transcription_session_updated_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/__init__.cpython-312.pyc index ea60fc6c..9cde883d 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/annotation.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/annotation.cpython-312.pyc index 55e9ac68..d705ba08 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/annotation.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/annotation.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/annotation_delta.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/annotation_delta.cpython-312.pyc index ccdc45d4..4f44bbf7 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/annotation_delta.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/annotation_delta.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/file_citation_annotation.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/file_citation_annotation.cpython-312.pyc index 80f697ae..edc638dd 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/file_citation_annotation.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/file_citation_annotation.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/file_citation_delta_annotation.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/file_citation_delta_annotation.cpython-312.pyc index 98c4e313..03ca34e5 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/file_citation_delta_annotation.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/file_citation_delta_annotation.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/file_path_annotation.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/file_path_annotation.cpython-312.pyc index 10d0cb77..3b36997b 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/file_path_annotation.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/file_path_annotation.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/file_path_delta_annotation.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/file_path_delta_annotation.cpython-312.pyc index 86535b94..70933fe2 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/file_path_delta_annotation.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/file_path_delta_annotation.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_file.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_file.cpython-312.pyc index 34dae78c..f640f584 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_file.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_file.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_file_content_block.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_file_content_block.cpython-312.pyc index ef7fb7f4..d6a0c2f1 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_file_content_block.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_file_content_block.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_file_content_block_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_file_content_block_param.cpython-312.pyc index 48e9af28..ce666466 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_file_content_block_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_file_content_block_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_file_delta.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_file_delta.cpython-312.pyc index 1473f127..a45da30f 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_file_delta.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_file_delta.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_file_delta_block.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_file_delta_block.cpython-312.pyc index 556191d6..8fba3a08 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_file_delta_block.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_file_delta_block.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_file_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_file_param.cpython-312.pyc index f672b1ad..d31a088c 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_file_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_file_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_url.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_url.cpython-312.pyc index 6513355b..c5aceef1 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_url.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_url.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_url_content_block.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_url_content_block.cpython-312.pyc index e365b552..50b1e5fd 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_url_content_block.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_url_content_block.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_url_content_block_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_url_content_block_param.cpython-312.pyc index 83c29a51..f10f491e 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_url_content_block_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_url_content_block_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_url_delta.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_url_delta.cpython-312.pyc index 6cff6dce..64ddc8ed 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_url_delta.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_url_delta.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_url_delta_block.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_url_delta_block.cpython-312.pyc index 6990ed3d..9b5ffb2c 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_url_delta_block.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_url_delta_block.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_url_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_url_param.cpython-312.pyc index dc10f890..e8eec185 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_url_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/image_url_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message.cpython-312.pyc index adc18165..82d63faa 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_content.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_content.cpython-312.pyc index e28cfa73..6c47a3b6 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_content.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_content.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_content_delta.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_content_delta.cpython-312.pyc index b33c3176..a1a864d6 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_content_delta.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_content_delta.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_content_part_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_content_part_param.cpython-312.pyc index afe60e0e..94ae17d3 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_content_part_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_content_part_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_create_params.cpython-312.pyc index 4aab46d9..1dc5a3e7 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_deleted.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_deleted.cpython-312.pyc index ad7b61f8..f31f980e 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_deleted.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_deleted.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_delta.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_delta.cpython-312.pyc index fabd306c..4245607b 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_delta.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_delta.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_delta_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_delta_event.cpython-312.pyc index 0cf29c78..3d4ededc 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_delta_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_delta_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_list_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_list_params.cpython-312.pyc index ca87488e..e0f9cf95 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_list_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_list_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_update_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_update_params.cpython-312.pyc index d773bd06..07fe026b 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_update_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/message_update_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/refusal_content_block.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/refusal_content_block.cpython-312.pyc index 575095a0..78570730 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/refusal_content_block.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/refusal_content_block.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/refusal_delta_block.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/refusal_delta_block.cpython-312.pyc index df389756..0c22cc67 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/refusal_delta_block.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/refusal_delta_block.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/required_action_function_tool_call.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/required_action_function_tool_call.cpython-312.pyc index b5e49755..88284775 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/required_action_function_tool_call.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/required_action_function_tool_call.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/run.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/run.cpython-312.pyc index 35f7d88f..e148513e 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/run.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/run.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/run_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/run_create_params.cpython-312.pyc index 8c4849b9..a7aaac52 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/run_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/run_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/run_list_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/run_list_params.cpython-312.pyc index e846b319..8dc9a7eb 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/run_list_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/run_list_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/run_status.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/run_status.cpython-312.pyc index 624c7bee..44ba9447 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/run_status.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/run_status.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/run_submit_tool_outputs_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/run_submit_tool_outputs_params.cpython-312.pyc index 5af02e0f..f183c875 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/run_submit_tool_outputs_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/run_submit_tool_outputs_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/run_update_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/run_update_params.cpython-312.pyc index 86eb708b..7cbe922d 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/run_update_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/run_update_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/text.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/text.cpython-312.pyc index 0e7f368b..71981cf0 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/text.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/text.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/text_content_block.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/text_content_block.cpython-312.pyc index 66fd00a6..e98eafa9 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/text_content_block.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/text_content_block.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/text_content_block_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/text_content_block_param.cpython-312.pyc index bbb15df5..5492b14f 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/text_content_block_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/text_content_block_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/text_delta.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/text_delta.cpython-312.pyc index 7b828dc0..7884a142 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/text_delta.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/text_delta.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/text_delta_block.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/text_delta_block.cpython-312.pyc index 69ca20ae..a29f72b9 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/text_delta_block.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/__pycache__/text_delta_block.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/__init__.cpython-312.pyc index a68c6c23..d6f0f2fb 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/code_interpreter_logs.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/code_interpreter_logs.cpython-312.pyc index 69699f28..ebba2088 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/code_interpreter_logs.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/code_interpreter_logs.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/code_interpreter_output_image.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/code_interpreter_output_image.cpython-312.pyc index 0cb2ba78..cb6a0edf 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/code_interpreter_output_image.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/code_interpreter_output_image.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/code_interpreter_tool_call.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/code_interpreter_tool_call.cpython-312.pyc index 6a824c9e..cee409bf 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/code_interpreter_tool_call.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/code_interpreter_tool_call.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/code_interpreter_tool_call_delta.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/code_interpreter_tool_call_delta.cpython-312.pyc index ba467574..de6ab7dc 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/code_interpreter_tool_call_delta.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/code_interpreter_tool_call_delta.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/file_search_tool_call.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/file_search_tool_call.cpython-312.pyc index 7ee89fac..2cfe7d9a 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/file_search_tool_call.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/file_search_tool_call.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/file_search_tool_call_delta.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/file_search_tool_call_delta.cpython-312.pyc index 5235a70d..fb8d14cb 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/file_search_tool_call_delta.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/file_search_tool_call_delta.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/function_tool_call.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/function_tool_call.cpython-312.pyc index 47f5d06c..9bf757af 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/function_tool_call.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/function_tool_call.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/function_tool_call_delta.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/function_tool_call_delta.cpython-312.pyc index dc760619..2dee8c9d 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/function_tool_call_delta.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/function_tool_call_delta.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/message_creation_step_details.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/message_creation_step_details.cpython-312.pyc index 6ce72e0b..325fd824 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/message_creation_step_details.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/message_creation_step_details.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/run_step.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/run_step.cpython-312.pyc index 6c7ea537..91261e06 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/run_step.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/run_step.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_delta.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_delta.cpython-312.pyc index 76bde8c9..3677ffe4 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_delta.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_delta.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_delta_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_delta_event.cpython-312.pyc index 5db5b50e..df628f3c 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_delta_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_delta_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_delta_message_delta.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_delta_message_delta.cpython-312.pyc index dfa2aabe..7c7e979d 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_delta_message_delta.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_delta_message_delta.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_include.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_include.cpython-312.pyc index 7104aaa2..b42bf144 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_include.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_include.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/step_list_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/step_list_params.cpython-312.pyc index 5f7f0166..8dc4e97f 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/step_list_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/step_list_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/step_retrieve_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/step_retrieve_params.cpython-312.pyc index 5b8414b7..f24d8e88 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/step_retrieve_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/step_retrieve_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/tool_call.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/tool_call.cpython-312.pyc index 34beb3e6..b0c3a88e 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/tool_call.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/tool_call.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/tool_call_delta.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/tool_call_delta.cpython-312.pyc index f516c445..3b7c8828 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/tool_call_delta.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/tool_call_delta.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/tool_call_delta_object.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/tool_call_delta_object.cpython-312.pyc index 1e24491c..2c21f464 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/tool_call_delta_object.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/tool_call_delta_object.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/tool_calls_step_details.cpython-312.pyc b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/tool_calls_step_details.cpython-312.pyc index 0c6437cc..c170e085 100644 Binary files a/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/tool_calls_step_details.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/beta/threads/runs/__pycache__/tool_calls_step_details.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/__init__.cpython-312.pyc index 2e47f7ec..ec981fff 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion.cpython-312.pyc index ee9045b2..1f13640b 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_assistant_message_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_assistant_message_param.cpython-312.pyc index de82e4e0..a81221b9 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_assistant_message_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_assistant_message_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_audio.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_audio.cpython-312.pyc index 27b21979..5d2954ba 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_audio.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_audio.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_audio_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_audio_param.cpython-312.pyc index 6e210939..ccfe1d64 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_audio_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_audio_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_chunk.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_chunk.cpython-312.pyc index 620757b1..a2a6326c 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_chunk.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_chunk.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_image_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_image_param.cpython-312.pyc index a3c67d22..8f6bc356 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_image_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_image_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_input_audio_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_input_audio_param.cpython-312.pyc index dc42441e..f30a6ed8 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_input_audio_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_input_audio_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_param.cpython-312.pyc index a0c79931..f0096b54 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_refusal_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_refusal_param.cpython-312.pyc index 95564856..df410a43 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_refusal_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_refusal_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_text_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_text_param.cpython-312.pyc index 6c6f3244..b375307a 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_text_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_text_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_deleted.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_deleted.cpython-312.pyc index 963851a8..c7650dd1 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_deleted.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_deleted.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_developer_message_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_developer_message_param.cpython-312.pyc index 4554f314..6f9f66b2 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_developer_message_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_developer_message_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_function_call_option_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_function_call_option_param.cpython-312.pyc index 693b384d..4d4f1590 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_function_call_option_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_function_call_option_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_function_message_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_function_message_param.cpython-312.pyc index 76d40337..6a3e5e07 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_function_message_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_function_message_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_message.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_message.cpython-312.pyc index dd842de7..e41e14fc 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_message.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_message.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_message_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_message_param.cpython-312.pyc index 53530ae6..ad001b99 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_message_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_message_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_message_tool_call.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_message_tool_call.cpython-312.pyc index 33ea1549..cbe6e323 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_message_tool_call.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_message_tool_call.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_message_tool_call_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_message_tool_call_param.cpython-312.pyc index 8235b220..6ebca4c4 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_message_tool_call_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_message_tool_call_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_modality.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_modality.cpython-312.pyc index 8ca80406..30933fec 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_modality.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_modality.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_named_tool_choice_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_named_tool_choice_param.cpython-312.pyc index 297e94c2..63a341c4 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_named_tool_choice_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_named_tool_choice_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_prediction_content_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_prediction_content_param.cpython-312.pyc index a67906a9..a19d84e6 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_prediction_content_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_prediction_content_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_reasoning_effort.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_reasoning_effort.cpython-312.pyc index d292f2ef..06eb5ab7 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_reasoning_effort.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_reasoning_effort.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_role.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_role.cpython-312.pyc index 1d8c29dd..33f311fd 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_role.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_role.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_store_message.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_store_message.cpython-312.pyc index a9846ea0..fa8cfef0 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_store_message.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_store_message.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_stream_options_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_stream_options_param.cpython-312.pyc index 4e7423d4..da95e232 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_stream_options_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_stream_options_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_system_message_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_system_message_param.cpython-312.pyc index ae37d581..fe8bb688 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_system_message_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_system_message_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_token_logprob.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_token_logprob.cpython-312.pyc index b5c78fc5..7f80fbce 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_token_logprob.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_token_logprob.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_tool_choice_option_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_tool_choice_option_param.cpython-312.pyc index 5b08a497..19037650 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_tool_choice_option_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_tool_choice_option_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_tool_message_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_tool_message_param.cpython-312.pyc index 43517e1b..325ef122 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_tool_message_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_tool_message_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_tool_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_tool_param.cpython-312.pyc index 1b2cc300..ce3b7cea 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_tool_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_tool_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_user_message_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_user_message_param.cpython-312.pyc index 5f899c91..f714bb26 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_user_message_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/chat_completion_user_message_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/completion_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/completion_create_params.cpython-312.pyc index 4ab65aaa..59faa219 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/completion_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/completion_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/completion_list_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/completion_list_params.cpython-312.pyc index b6ac11a5..b1e7f49c 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/completion_list_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/completion_list_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/completion_update_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/completion_update_params.cpython-312.pyc index 76639768..445802f1 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/completion_update_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/completion_update_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/parsed_chat_completion.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/parsed_chat_completion.cpython-312.pyc index db08b21d..70394e85 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/parsed_chat_completion.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/parsed_chat_completion.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/__pycache__/parsed_function_tool_call.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/__pycache__/parsed_function_tool_call.cpython-312.pyc index 5284b3ab..7d241e2a 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/__pycache__/parsed_function_tool_call.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/__pycache__/parsed_function_tool_call.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/completions/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/completions/__pycache__/__init__.cpython-312.pyc index 91fc34e0..34eca900 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/completions/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/completions/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/chat/completions/__pycache__/message_list_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/chat/completions/__pycache__/message_list_params.cpython-312.pyc index b638f27d..08ad435f 100644 Binary files a/venv/Lib/site-packages/openai/types/chat/completions/__pycache__/message_list_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/chat/completions/__pycache__/message_list_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/containers/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/types/containers/__pycache__/__init__.cpython-312.pyc index 425073f3..bf147170 100644 Binary files a/venv/Lib/site-packages/openai/types/containers/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/containers/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/containers/__pycache__/file_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/containers/__pycache__/file_create_params.cpython-312.pyc index 5c7d1491..a46bec1a 100644 Binary files a/venv/Lib/site-packages/openai/types/containers/__pycache__/file_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/containers/__pycache__/file_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/containers/__pycache__/file_create_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/containers/__pycache__/file_create_response.cpython-312.pyc index dcd71039..00bac2f8 100644 Binary files a/venv/Lib/site-packages/openai/types/containers/__pycache__/file_create_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/containers/__pycache__/file_create_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/containers/__pycache__/file_list_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/containers/__pycache__/file_list_params.cpython-312.pyc index 77ab63c5..2abcfb0c 100644 Binary files a/venv/Lib/site-packages/openai/types/containers/__pycache__/file_list_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/containers/__pycache__/file_list_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/containers/__pycache__/file_list_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/containers/__pycache__/file_list_response.cpython-312.pyc index d6fb570a..42d6cf1e 100644 Binary files a/venv/Lib/site-packages/openai/types/containers/__pycache__/file_list_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/containers/__pycache__/file_list_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/containers/__pycache__/file_retrieve_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/containers/__pycache__/file_retrieve_response.cpython-312.pyc index 9e67ddba..a9124f51 100644 Binary files a/venv/Lib/site-packages/openai/types/containers/__pycache__/file_retrieve_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/containers/__pycache__/file_retrieve_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/evals/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/types/evals/__pycache__/__init__.cpython-312.pyc index fe7dd9ff..6112c049 100644 Binary files a/venv/Lib/site-packages/openai/types/evals/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/evals/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/evals/__pycache__/create_eval_completions_run_data_source.cpython-312.pyc b/venv/Lib/site-packages/openai/types/evals/__pycache__/create_eval_completions_run_data_source.cpython-312.pyc index 05cadd2c..9bd94695 100644 Binary files a/venv/Lib/site-packages/openai/types/evals/__pycache__/create_eval_completions_run_data_source.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/evals/__pycache__/create_eval_completions_run_data_source.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/evals/__pycache__/create_eval_completions_run_data_source_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/evals/__pycache__/create_eval_completions_run_data_source_param.cpython-312.pyc index 5afda967..6c997e75 100644 Binary files a/venv/Lib/site-packages/openai/types/evals/__pycache__/create_eval_completions_run_data_source_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/evals/__pycache__/create_eval_completions_run_data_source_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/evals/__pycache__/create_eval_jsonl_run_data_source.cpython-312.pyc b/venv/Lib/site-packages/openai/types/evals/__pycache__/create_eval_jsonl_run_data_source.cpython-312.pyc index 486b0a3d..6fde6c97 100644 Binary files a/venv/Lib/site-packages/openai/types/evals/__pycache__/create_eval_jsonl_run_data_source.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/evals/__pycache__/create_eval_jsonl_run_data_source.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/evals/__pycache__/create_eval_jsonl_run_data_source_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/evals/__pycache__/create_eval_jsonl_run_data_source_param.cpython-312.pyc index bdf68491..97bd7c08 100644 Binary files a/venv/Lib/site-packages/openai/types/evals/__pycache__/create_eval_jsonl_run_data_source_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/evals/__pycache__/create_eval_jsonl_run_data_source_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/evals/__pycache__/eval_api_error.cpython-312.pyc b/venv/Lib/site-packages/openai/types/evals/__pycache__/eval_api_error.cpython-312.pyc index 6f3904d6..d46e7f2c 100644 Binary files a/venv/Lib/site-packages/openai/types/evals/__pycache__/eval_api_error.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/evals/__pycache__/eval_api_error.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/evals/__pycache__/run_cancel_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/evals/__pycache__/run_cancel_response.cpython-312.pyc index 3aa28f9f..5e0b1834 100644 Binary files a/venv/Lib/site-packages/openai/types/evals/__pycache__/run_cancel_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/evals/__pycache__/run_cancel_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/evals/__pycache__/run_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/evals/__pycache__/run_create_params.cpython-312.pyc index 903b954f..3f51630e 100644 Binary files a/venv/Lib/site-packages/openai/types/evals/__pycache__/run_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/evals/__pycache__/run_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/evals/__pycache__/run_create_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/evals/__pycache__/run_create_response.cpython-312.pyc index 7ab324da..8b51f673 100644 Binary files a/venv/Lib/site-packages/openai/types/evals/__pycache__/run_create_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/evals/__pycache__/run_create_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/evals/__pycache__/run_delete_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/evals/__pycache__/run_delete_response.cpython-312.pyc index d19ffbf0..89c7aeb8 100644 Binary files a/venv/Lib/site-packages/openai/types/evals/__pycache__/run_delete_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/evals/__pycache__/run_delete_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/evals/__pycache__/run_list_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/evals/__pycache__/run_list_params.cpython-312.pyc index f984e3e0..a49976bb 100644 Binary files a/venv/Lib/site-packages/openai/types/evals/__pycache__/run_list_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/evals/__pycache__/run_list_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/evals/__pycache__/run_list_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/evals/__pycache__/run_list_response.cpython-312.pyc index 48ed45db..be199d39 100644 Binary files a/venv/Lib/site-packages/openai/types/evals/__pycache__/run_list_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/evals/__pycache__/run_list_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/evals/__pycache__/run_retrieve_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/evals/__pycache__/run_retrieve_response.cpython-312.pyc index a467edea..e45e4d15 100644 Binary files a/venv/Lib/site-packages/openai/types/evals/__pycache__/run_retrieve_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/evals/__pycache__/run_retrieve_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/evals/runs/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/types/evals/runs/__pycache__/__init__.cpython-312.pyc index cd7ebcef..12ede1ce 100644 Binary files a/venv/Lib/site-packages/openai/types/evals/runs/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/evals/runs/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/evals/runs/__pycache__/output_item_list_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/evals/runs/__pycache__/output_item_list_params.cpython-312.pyc index b9f360f5..cbab48b9 100644 Binary files a/venv/Lib/site-packages/openai/types/evals/runs/__pycache__/output_item_list_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/evals/runs/__pycache__/output_item_list_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/evals/runs/__pycache__/output_item_list_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/evals/runs/__pycache__/output_item_list_response.cpython-312.pyc index ea419610..5762ccea 100644 Binary files a/venv/Lib/site-packages/openai/types/evals/runs/__pycache__/output_item_list_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/evals/runs/__pycache__/output_item_list_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/evals/runs/__pycache__/output_item_retrieve_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/evals/runs/__pycache__/output_item_retrieve_response.cpython-312.pyc index c4ea0729..b5f64760 100644 Binary files a/venv/Lib/site-packages/openai/types/evals/runs/__pycache__/output_item_retrieve_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/evals/runs/__pycache__/output_item_retrieve_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/__init__.cpython-312.pyc index a57b8c73..4b2ed18e 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/dpo_hyperparameters.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/dpo_hyperparameters.cpython-312.pyc index f19217a8..cb228774 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/dpo_hyperparameters.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/dpo_hyperparameters.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/dpo_hyperparameters_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/dpo_hyperparameters_param.cpython-312.pyc index f456fdfe..541e1efd 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/dpo_hyperparameters_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/dpo_hyperparameters_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/dpo_method.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/dpo_method.cpython-312.pyc index e0deb357..7b75c3a0 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/dpo_method.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/dpo_method.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/dpo_method_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/dpo_method_param.cpython-312.pyc index 984780bf..c3bfe407 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/dpo_method_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/dpo_method_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job.cpython-312.pyc index 583bbc49..af6c84e3 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_event.cpython-312.pyc index e7fd61f4..a1f2470e 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_integration.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_integration.cpython-312.pyc index a8398406..c75cc453 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_integration.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_integration.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_wandb_integration.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_wandb_integration.cpython-312.pyc index d2522e1f..a5550834 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_wandb_integration.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_wandb_integration.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_wandb_integration_object.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_wandb_integration_object.cpython-312.pyc index ca733529..973cb6d0 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_wandb_integration_object.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_wandb_integration_object.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/job_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/job_create_params.cpython-312.pyc index b2dc4149..4960b156 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/job_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/job_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/job_list_events_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/job_list_events_params.cpython-312.pyc index 23e909d1..5deeee11 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/job_list_events_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/job_list_events_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/job_list_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/job_list_params.cpython-312.pyc index 4b4236cf..218846dd 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/job_list_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/job_list_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_hyperparameters.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_hyperparameters.cpython-312.pyc index 6c9add2f..889a1c7a 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_hyperparameters.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_hyperparameters.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_hyperparameters_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_hyperparameters_param.cpython-312.pyc index 27f3b822..c94ef2a1 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_hyperparameters_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_hyperparameters_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_method.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_method.cpython-312.pyc index 3b86ef92..116d9ed6 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_method.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_method.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_method_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_method_param.cpython-312.pyc index 1adaefe5..e774d27d 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_method_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_method_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/supervised_hyperparameters.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/supervised_hyperparameters.cpython-312.pyc index 82de440e..37d73b35 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/supervised_hyperparameters.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/supervised_hyperparameters.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/supervised_hyperparameters_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/supervised_hyperparameters_param.cpython-312.pyc index 829a75c7..a4bc6550 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/supervised_hyperparameters_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/supervised_hyperparameters_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/supervised_method.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/supervised_method.cpython-312.pyc index 9c47b06e..a20a209a 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/supervised_method.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/supervised_method.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/supervised_method_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/supervised_method_param.cpython-312.pyc index cf596fa5..4d1864eb 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/supervised_method_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/__pycache__/supervised_method_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/alpha/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/alpha/__pycache__/__init__.cpython-312.pyc index e10c051d..59efcd60 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/alpha/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/alpha/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_run_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_run_params.cpython-312.pyc index cedfc3c3..b5b63dec 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_run_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_run_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_run_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_run_response.cpython-312.pyc index a43fb1db..bdef61ce 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_run_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_run_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_validate_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_validate_params.cpython-312.pyc index eff05593..dfc3c906 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_validate_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_validate_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_validate_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_validate_response.cpython-312.pyc index 48588fa2..17150581 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_validate_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_validate_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/__init__.cpython-312.pyc index 63ad08e1..b70497d8 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_create_params.cpython-312.pyc index e88a6756..adaca66a 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_create_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_create_response.cpython-312.pyc index caac0687..4349e207 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_create_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_create_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_delete_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_delete_response.cpython-312.pyc index 85af888a..705c61c2 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_delete_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_delete_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_retrieve_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_retrieve_params.cpython-312.pyc index 1c94b9af..582d91b4 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_retrieve_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_retrieve_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_retrieve_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_retrieve_response.cpython-312.pyc index b3ee8fda..9b54ccfa 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_retrieve_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_retrieve_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/jobs/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/jobs/__pycache__/__init__.cpython-312.pyc index 354deb7c..9edfb8e6 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/jobs/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/jobs/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/jobs/__pycache__/checkpoint_list_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/jobs/__pycache__/checkpoint_list_params.cpython-312.pyc index 6ded6b13..54f1cac0 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/jobs/__pycache__/checkpoint_list_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/jobs/__pycache__/checkpoint_list_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/fine_tuning/jobs/__pycache__/fine_tuning_job_checkpoint.cpython-312.pyc b/venv/Lib/site-packages/openai/types/fine_tuning/jobs/__pycache__/fine_tuning_job_checkpoint.cpython-312.pyc index 7ac873f2..09042d4d 100644 Binary files a/venv/Lib/site-packages/openai/types/fine_tuning/jobs/__pycache__/fine_tuning_job_checkpoint.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/fine_tuning/jobs/__pycache__/fine_tuning_job_checkpoint.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/graders/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/types/graders/__pycache__/__init__.cpython-312.pyc index 3996184a..c8203f10 100644 Binary files a/venv/Lib/site-packages/openai/types/graders/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/graders/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/graders/__pycache__/label_model_grader.cpython-312.pyc b/venv/Lib/site-packages/openai/types/graders/__pycache__/label_model_grader.cpython-312.pyc index 03237b65..51f28478 100644 Binary files a/venv/Lib/site-packages/openai/types/graders/__pycache__/label_model_grader.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/graders/__pycache__/label_model_grader.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/graders/__pycache__/label_model_grader_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/graders/__pycache__/label_model_grader_param.cpython-312.pyc index e999f870..1d18d08d 100644 Binary files a/venv/Lib/site-packages/openai/types/graders/__pycache__/label_model_grader_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/graders/__pycache__/label_model_grader_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/graders/__pycache__/multi_grader.cpython-312.pyc b/venv/Lib/site-packages/openai/types/graders/__pycache__/multi_grader.cpython-312.pyc index 1f43d876..2da05ed1 100644 Binary files a/venv/Lib/site-packages/openai/types/graders/__pycache__/multi_grader.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/graders/__pycache__/multi_grader.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/graders/__pycache__/multi_grader_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/graders/__pycache__/multi_grader_param.cpython-312.pyc index f96f8719..36933602 100644 Binary files a/venv/Lib/site-packages/openai/types/graders/__pycache__/multi_grader_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/graders/__pycache__/multi_grader_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/graders/__pycache__/python_grader.cpython-312.pyc b/venv/Lib/site-packages/openai/types/graders/__pycache__/python_grader.cpython-312.pyc index 91480898..236a2f89 100644 Binary files a/venv/Lib/site-packages/openai/types/graders/__pycache__/python_grader.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/graders/__pycache__/python_grader.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/graders/__pycache__/python_grader_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/graders/__pycache__/python_grader_param.cpython-312.pyc index 31ac8615..1b4ffcb9 100644 Binary files a/venv/Lib/site-packages/openai/types/graders/__pycache__/python_grader_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/graders/__pycache__/python_grader_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/graders/__pycache__/score_model_grader.cpython-312.pyc b/venv/Lib/site-packages/openai/types/graders/__pycache__/score_model_grader.cpython-312.pyc index 6751f4e1..630298d2 100644 Binary files a/venv/Lib/site-packages/openai/types/graders/__pycache__/score_model_grader.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/graders/__pycache__/score_model_grader.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/graders/__pycache__/score_model_grader_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/graders/__pycache__/score_model_grader_param.cpython-312.pyc index f72d721e..78b68588 100644 Binary files a/venv/Lib/site-packages/openai/types/graders/__pycache__/score_model_grader_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/graders/__pycache__/score_model_grader_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/graders/__pycache__/string_check_grader.cpython-312.pyc b/venv/Lib/site-packages/openai/types/graders/__pycache__/string_check_grader.cpython-312.pyc index 4a3ad019..c8f51411 100644 Binary files a/venv/Lib/site-packages/openai/types/graders/__pycache__/string_check_grader.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/graders/__pycache__/string_check_grader.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/graders/__pycache__/string_check_grader_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/graders/__pycache__/string_check_grader_param.cpython-312.pyc index cb393983..7a97b06c 100644 Binary files a/venv/Lib/site-packages/openai/types/graders/__pycache__/string_check_grader_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/graders/__pycache__/string_check_grader_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/graders/__pycache__/text_similarity_grader.cpython-312.pyc b/venv/Lib/site-packages/openai/types/graders/__pycache__/text_similarity_grader.cpython-312.pyc index 0e07d1ee..f74a4b29 100644 Binary files a/venv/Lib/site-packages/openai/types/graders/__pycache__/text_similarity_grader.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/graders/__pycache__/text_similarity_grader.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/graders/__pycache__/text_similarity_grader_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/graders/__pycache__/text_similarity_grader_param.cpython-312.pyc index ccf68fe6..8826c5d5 100644 Binary files a/venv/Lib/site-packages/openai/types/graders/__pycache__/text_similarity_grader_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/graders/__pycache__/text_similarity_grader_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/__init__.cpython-312.pyc index 9e4f5440..436c077c 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/computer_tool.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/computer_tool.cpython-312.pyc index 112716be..fc092346 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/computer_tool.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/computer_tool.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/computer_tool_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/computer_tool_param.cpython-312.pyc index 52fa5171..56113d86 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/computer_tool_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/computer_tool_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/easy_input_message.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/easy_input_message.cpython-312.pyc index f7dbd1c0..d1e060e6 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/easy_input_message.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/easy_input_message.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/easy_input_message_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/easy_input_message_param.cpython-312.pyc index 687e768b..5aba9fa7 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/easy_input_message_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/easy_input_message_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/file_search_tool.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/file_search_tool.cpython-312.pyc index 506d1f64..7d573daa 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/file_search_tool.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/file_search_tool.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/file_search_tool_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/file_search_tool_param.cpython-312.pyc index 61b26351..8f23c39d 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/file_search_tool_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/file_search_tool_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/function_tool.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/function_tool.cpython-312.pyc index a0fa3027..e2eebfbb 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/function_tool.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/function_tool.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/function_tool_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/function_tool_param.cpython-312.pyc index 10787262..e8e6e19d 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/function_tool_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/function_tool_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/input_item_list_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/input_item_list_params.cpython-312.pyc index 7ac4d927..45a443b9 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/input_item_list_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/input_item_list_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/parsed_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/parsed_response.cpython-312.pyc index b4faf1b8..f5d6aa45 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/parsed_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/parsed_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response.cpython-312.pyc index 01dac2f6..e3c6fbe9 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_audio_delta_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_audio_delta_event.cpython-312.pyc index 248763bc..a8b84a62 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_audio_delta_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_audio_delta_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_audio_done_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_audio_done_event.cpython-312.pyc index 3c36e0b1..1fc3f2d7 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_audio_done_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_audio_done_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_audio_transcript_delta_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_audio_transcript_delta_event.cpython-312.pyc index b15c5e8d..fb5d31be 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_audio_transcript_delta_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_audio_transcript_delta_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_audio_transcript_done_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_audio_transcript_done_event.cpython-312.pyc index 5995888c..3d02ba42 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_audio_transcript_done_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_audio_transcript_done_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_code_delta_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_code_delta_event.cpython-312.pyc index 3c9342ee..30dcf9b9 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_code_delta_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_code_delta_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_code_done_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_code_done_event.cpython-312.pyc index 1f7d4a1d..86baa5e5 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_code_done_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_code_done_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_completed_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_completed_event.cpython-312.pyc index 1afc1a94..103f9b39 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_completed_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_completed_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_in_progress_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_in_progress_event.cpython-312.pyc index 723986d1..b7176ac4 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_in_progress_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_in_progress_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_interpreting_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_interpreting_event.cpython-312.pyc index a01d6d07..63e33728 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_interpreting_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_interpreting_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_tool_call.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_tool_call.cpython-312.pyc index 1e135560..27f0336e 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_tool_call.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_tool_call.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_tool_call_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_tool_call_param.cpython-312.pyc index 0e252c10..8ee66734 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_tool_call_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_code_interpreter_tool_call_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_completed_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_completed_event.cpython-312.pyc index 88a66845..f56f8767 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_completed_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_completed_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_computer_tool_call.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_computer_tool_call.cpython-312.pyc index 51ced2d7..80c8bb05 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_computer_tool_call.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_computer_tool_call.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_output_item.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_output_item.cpython-312.pyc index 79c7e9a3..6c49b883 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_output_item.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_output_item.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_output_screenshot.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_output_screenshot.cpython-312.pyc index 6084f81e..4d3d17e3 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_output_screenshot.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_output_screenshot.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_output_screenshot_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_output_screenshot_param.cpython-312.pyc index 5a348396..d7191ef7 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_output_screenshot_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_output_screenshot_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_param.cpython-312.pyc index ad5c305d..046432d2 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_content_part_added_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_content_part_added_event.cpython-312.pyc index 3933af10..3ecacf5c 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_content_part_added_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_content_part_added_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_content_part_done_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_content_part_done_event.cpython-312.pyc index df313d78..fb17f244 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_content_part_done_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_content_part_done_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_create_params.cpython-312.pyc index 4b3ecfdc..5de3b75a 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_created_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_created_event.cpython-312.pyc index d2217023..0a1ddd73 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_created_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_created_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_error.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_error.cpython-312.pyc index 05dec651..41abfcb1 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_error.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_error.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_error_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_error_event.cpython-312.pyc index a79724ab..26f38938 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_error_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_error_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_failed_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_failed_event.cpython-312.pyc index 3a58d347..149b3264 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_failed_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_failed_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_file_search_call_completed_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_file_search_call_completed_event.cpython-312.pyc index 5bb789f2..a0480dc3 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_file_search_call_completed_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_file_search_call_completed_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_file_search_call_in_progress_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_file_search_call_in_progress_event.cpython-312.pyc index 752d5ec9..01da1dcd 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_file_search_call_in_progress_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_file_search_call_in_progress_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_file_search_call_searching_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_file_search_call_searching_event.cpython-312.pyc index ff3d75d8..e8100c70 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_file_search_call_searching_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_file_search_call_searching_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_file_search_tool_call.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_file_search_tool_call.cpython-312.pyc index 0a03ac38..79f1d64f 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_file_search_tool_call.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_file_search_tool_call.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_file_search_tool_call_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_file_search_tool_call_param.cpython-312.pyc index f52a8148..61cd8862 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_file_search_tool_call_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_file_search_tool_call_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_format_text_config.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_format_text_config.cpython-312.pyc index 4c3a3402..b2682249 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_format_text_config.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_format_text_config.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_format_text_config_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_format_text_config_param.cpython-312.pyc index cba151fc..a71bb89b 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_format_text_config_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_format_text_config_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_format_text_json_schema_config.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_format_text_json_schema_config.cpython-312.pyc index 41b9bf9f..d075f841 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_format_text_json_schema_config.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_format_text_json_schema_config.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_format_text_json_schema_config_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_format_text_json_schema_config_param.cpython-312.pyc index 2792a60c..823aab5a 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_format_text_json_schema_config_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_format_text_json_schema_config_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_call_arguments_delta_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_call_arguments_delta_event.cpython-312.pyc index e6a86c87..f6f15352 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_call_arguments_delta_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_call_arguments_delta_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_call_arguments_done_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_call_arguments_done_event.cpython-312.pyc index af18a1f2..fb60a298 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_call_arguments_done_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_call_arguments_done_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_tool_call.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_tool_call.cpython-312.pyc index bf1b62c1..b6135a98 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_tool_call.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_tool_call.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_tool_call_item.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_tool_call_item.cpython-312.pyc index 1ba710c7..7670161b 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_tool_call_item.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_tool_call_item.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_tool_call_output_item.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_tool_call_output_item.cpython-312.pyc index 0fdfead8..cc73e619 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_tool_call_output_item.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_tool_call_output_item.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_tool_call_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_tool_call_param.cpython-312.pyc index b525a7b7..b9994d67 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_tool_call_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_tool_call_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_web_search.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_web_search.cpython-312.pyc index 5a01bd8d..b0a7260c 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_web_search.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_web_search.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_web_search_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_web_search_param.cpython-312.pyc index a92ae57a..3a58e5bb 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_web_search_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_function_web_search_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_image_gen_call_completed_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_image_gen_call_completed_event.cpython-312.pyc index b08a5851..e89abfc6 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_image_gen_call_completed_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_image_gen_call_completed_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_image_gen_call_generating_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_image_gen_call_generating_event.cpython-312.pyc index 226cfb4c..2a10b4e0 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_image_gen_call_generating_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_image_gen_call_generating_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_image_gen_call_in_progress_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_image_gen_call_in_progress_event.cpython-312.pyc index a379a96b..85dcfbff 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_image_gen_call_in_progress_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_image_gen_call_in_progress_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_image_gen_call_partial_image_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_image_gen_call_partial_image_event.cpython-312.pyc index 49bced25..1a1eac87 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_image_gen_call_partial_image_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_image_gen_call_partial_image_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_in_progress_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_in_progress_event.cpython-312.pyc index a33b9ef1..a3afef1e 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_in_progress_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_in_progress_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_includable.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_includable.cpython-312.pyc index 883d5089..a5f22560 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_includable.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_includable.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_incomplete_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_incomplete_event.cpython-312.pyc index b120f8e0..e38b94af 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_incomplete_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_incomplete_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_content.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_content.cpython-312.pyc index a3fe0f0b..b0b85300 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_content.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_content.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_content_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_content_param.cpython-312.pyc index 68f84bec..2e5956a8 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_content_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_content_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_file.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_file.cpython-312.pyc index 72718e1f..8e8e66f2 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_file.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_file.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_file_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_file_param.cpython-312.pyc index bd3eabb9..d6f1117d 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_file_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_file_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_image.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_image.cpython-312.pyc index f0f462a0..8ec313d7 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_image.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_image.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_image_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_image_param.cpython-312.pyc index 6d8fcac3..56c51502 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_image_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_image_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_item_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_item_param.cpython-312.pyc index 2fafb074..15e4e028 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_item_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_item_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_message_content_list.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_message_content_list.cpython-312.pyc index e22697ae..5fabbb38 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_message_content_list.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_message_content_list.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_message_content_list_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_message_content_list_param.cpython-312.pyc index 0e650472..091095d9 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_message_content_list_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_message_content_list_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_message_item.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_message_item.cpython-312.pyc index 3b62a9ce..63d9ebdd 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_message_item.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_message_item.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_param.cpython-312.pyc index a3fd0b15..13177a38 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_text.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_text.cpython-312.pyc index 509c9617..dfb18e6a 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_text.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_text.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_text_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_text_param.cpython-312.pyc index 36b29e57..d28b613a 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_text_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_input_text_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_item.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_item.cpython-312.pyc index 7ac266ee..81ab8ebf 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_item.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_item.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_item_list.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_item_list.cpython-312.pyc index 2c41a8dd..267dabc5 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_item_list.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_item_list.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_call_arguments_delta_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_call_arguments_delta_event.cpython-312.pyc index c910131f..bf90f668 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_call_arguments_delta_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_call_arguments_delta_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_call_arguments_done_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_call_arguments_done_event.cpython-312.pyc index c67aab3a..0523dc46 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_call_arguments_done_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_call_arguments_done_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_call_completed_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_call_completed_event.cpython-312.pyc index 35d09eb1..2e9e59eb 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_call_completed_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_call_completed_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_call_failed_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_call_failed_event.cpython-312.pyc index d050d21c..a0a1aee6 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_call_failed_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_call_failed_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_call_in_progress_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_call_in_progress_event.cpython-312.pyc index 8169deea..01e5c1be 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_call_in_progress_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_call_in_progress_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_list_tools_completed_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_list_tools_completed_event.cpython-312.pyc index e5b0e5ce..7e017735 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_list_tools_completed_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_list_tools_completed_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_list_tools_failed_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_list_tools_failed_event.cpython-312.pyc index cb9e14e7..62561be9 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_list_tools_failed_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_list_tools_failed_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_list_tools_in_progress_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_list_tools_in_progress_event.cpython-312.pyc index 5ce2b3c1..8210c504 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_list_tools_in_progress_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_mcp_list_tools_in_progress_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_item.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_item.cpython-312.pyc index d21a5228..8d3a0e91 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_item.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_item.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_item_added_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_item_added_event.cpython-312.pyc index 56b3ac04..2ecec0fc 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_item_added_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_item_added_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_item_done_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_item_done_event.cpython-312.pyc index 721e1d67..a473afd9 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_item_done_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_item_done_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_message.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_message.cpython-312.pyc index eb91d0a6..5de48874 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_message.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_message.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_message_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_message_param.cpython-312.pyc index 765aae78..527d7f5a 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_message_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_message_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_refusal.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_refusal.cpython-312.pyc index 1a17e06b..0060ac60 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_refusal.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_refusal.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_refusal_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_refusal_param.cpython-312.pyc index d2a3c8c6..90cc5d5b 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_refusal_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_refusal_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_text.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_text.cpython-312.pyc index 8e4852b9..412e732e 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_text.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_text.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_text_annotation_added_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_text_annotation_added_event.cpython-312.pyc index 7219295d..8f13227e 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_text_annotation_added_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_text_annotation_added_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_text_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_text_param.cpython-312.pyc index 299dc85b..d089e185 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_text_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_output_text_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_queued_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_queued_event.cpython-312.pyc index 89b17faa..925f435a 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_queued_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_queued_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_delta_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_delta_event.cpython-312.pyc index 5688bcb9..9c10bebb 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_delta_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_delta_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_done_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_done_event.cpython-312.pyc index 1e9fec9b..a228a405 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_done_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_done_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_item.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_item.cpython-312.pyc index 70f95f3c..9d8bb3b0 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_item.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_item.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_item_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_item_param.cpython-312.pyc index 931dcde4..3d712b27 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_item_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_item_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_delta_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_delta_event.cpython-312.pyc index a68fd7c0..7bc31292 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_delta_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_delta_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_done_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_done_event.cpython-312.pyc index d2166154..178802fe 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_done_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_done_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_part_added_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_part_added_event.cpython-312.pyc index 1343f368..56e9bfd4 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_part_added_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_part_added_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_part_done_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_part_done_event.cpython-312.pyc index 133516f4..7f99cdb1 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_part_done_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_part_done_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_text_delta_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_text_delta_event.cpython-312.pyc index 20145e0c..1f69ec0f 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_text_delta_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_text_delta_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_text_done_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_text_done_event.cpython-312.pyc index f12a82fe..016b6d1d 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_text_done_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_text_done_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_refusal_delta_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_refusal_delta_event.cpython-312.pyc index 2e551929..8da6764f 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_refusal_delta_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_refusal_delta_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_refusal_done_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_refusal_done_event.cpython-312.pyc index 6534bf5b..7382fabf 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_refusal_done_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_refusal_done_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_retrieve_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_retrieve_params.cpython-312.pyc index 3f58bbbd..bd979bd1 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_retrieve_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_retrieve_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_status.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_status.cpython-312.pyc index 07b4d1f0..d49d9eda 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_status.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_status.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_stream_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_stream_event.cpython-312.pyc index aa0208f4..576957a6 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_stream_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_stream_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_text_config.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_text_config.cpython-312.pyc index 32bbf9c2..f3d1a47f 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_text_config.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_text_config.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_text_config_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_text_config_param.cpython-312.pyc index 07f675ad..07c81e98 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_text_config_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_text_config_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_text_delta_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_text_delta_event.cpython-312.pyc index d34ee3a1..dd33d03b 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_text_delta_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_text_delta_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_text_done_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_text_done_event.cpython-312.pyc index 0cd6b847..505ff730 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_text_done_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_text_done_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_usage.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_usage.cpython-312.pyc index 608df305..1aa45664 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_usage.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_usage.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_web_search_call_completed_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_web_search_call_completed_event.cpython-312.pyc index f423c928..82da85b3 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_web_search_call_completed_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_web_search_call_completed_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_web_search_call_in_progress_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_web_search_call_in_progress_event.cpython-312.pyc index d38623cc..d1d16ddd 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_web_search_call_in_progress_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_web_search_call_in_progress_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_web_search_call_searching_event.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_web_search_call_searching_event.cpython-312.pyc index eeceeaf5..dd1ef923 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/response_web_search_call_searching_event.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/response_web_search_call_searching_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/tool.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/tool.cpython-312.pyc index 9623a62e..9b992b82 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/tool.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/tool.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/tool_choice_function.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/tool_choice_function.cpython-312.pyc index 197cbf4a..b93c1dfa 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/tool_choice_function.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/tool_choice_function.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/tool_choice_function_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/tool_choice_function_param.cpython-312.pyc index 9cf2bb80..ef2e8dba 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/tool_choice_function_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/tool_choice_function_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/tool_choice_options.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/tool_choice_options.cpython-312.pyc index 71f63da6..bf19a4ad 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/tool_choice_options.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/tool_choice_options.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/tool_choice_types.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/tool_choice_types.cpython-312.pyc index de4cf5f6..5ced58b9 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/tool_choice_types.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/tool_choice_types.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/tool_choice_types_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/tool_choice_types_param.cpython-312.pyc index bc76c0e0..3939847c 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/tool_choice_types_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/tool_choice_types_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/tool_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/tool_param.cpython-312.pyc index a58f2f50..34281def 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/tool_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/tool_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/web_search_tool.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/web_search_tool.cpython-312.pyc index af13e43d..56b41da8 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/web_search_tool.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/web_search_tool.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/responses/__pycache__/web_search_tool_param.cpython-312.pyc b/venv/Lib/site-packages/openai/types/responses/__pycache__/web_search_tool_param.cpython-312.pyc index 4bd92e3e..f88052f6 100644 Binary files a/venv/Lib/site-packages/openai/types/responses/__pycache__/web_search_tool_param.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/responses/__pycache__/web_search_tool_param.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared/__pycache__/__init__.cpython-312.pyc index 7295cad9..037d8bae 100644 Binary files a/venv/Lib/site-packages/openai/types/shared/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared/__pycache__/all_models.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared/__pycache__/all_models.cpython-312.pyc index 3a6dc889..b6f9e022 100644 Binary files a/venv/Lib/site-packages/openai/types/shared/__pycache__/all_models.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared/__pycache__/all_models.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared/__pycache__/chat_model.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared/__pycache__/chat_model.cpython-312.pyc index 94c412b8..8ec6c9f1 100644 Binary files a/venv/Lib/site-packages/openai/types/shared/__pycache__/chat_model.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared/__pycache__/chat_model.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared/__pycache__/comparison_filter.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared/__pycache__/comparison_filter.cpython-312.pyc index 8577c98e..851338c3 100644 Binary files a/venv/Lib/site-packages/openai/types/shared/__pycache__/comparison_filter.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared/__pycache__/comparison_filter.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared/__pycache__/compound_filter.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared/__pycache__/compound_filter.cpython-312.pyc index 3b509d29..06aa87bd 100644 Binary files a/venv/Lib/site-packages/openai/types/shared/__pycache__/compound_filter.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared/__pycache__/compound_filter.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared/__pycache__/error_object.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared/__pycache__/error_object.cpython-312.pyc index 3cde6951..102a0010 100644 Binary files a/venv/Lib/site-packages/openai/types/shared/__pycache__/error_object.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared/__pycache__/error_object.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared/__pycache__/function_definition.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared/__pycache__/function_definition.cpython-312.pyc index 020c1279..4ddcd306 100644 Binary files a/venv/Lib/site-packages/openai/types/shared/__pycache__/function_definition.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared/__pycache__/function_definition.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared/__pycache__/function_parameters.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared/__pycache__/function_parameters.cpython-312.pyc index 65fb310e..0c92f64e 100644 Binary files a/venv/Lib/site-packages/openai/types/shared/__pycache__/function_parameters.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared/__pycache__/function_parameters.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared/__pycache__/metadata.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared/__pycache__/metadata.cpython-312.pyc index b589371d..833d2369 100644 Binary files a/venv/Lib/site-packages/openai/types/shared/__pycache__/metadata.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared/__pycache__/metadata.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared/__pycache__/reasoning.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared/__pycache__/reasoning.cpython-312.pyc index 4b7809f7..f2e7c480 100644 Binary files a/venv/Lib/site-packages/openai/types/shared/__pycache__/reasoning.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared/__pycache__/reasoning.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared/__pycache__/reasoning_effort.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared/__pycache__/reasoning_effort.cpython-312.pyc index 3fa28a22..7058df28 100644 Binary files a/venv/Lib/site-packages/openai/types/shared/__pycache__/reasoning_effort.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared/__pycache__/reasoning_effort.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared/__pycache__/response_format_json_object.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared/__pycache__/response_format_json_object.cpython-312.pyc index fd9a7428..d67c2dbb 100644 Binary files a/venv/Lib/site-packages/openai/types/shared/__pycache__/response_format_json_object.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared/__pycache__/response_format_json_object.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared/__pycache__/response_format_json_schema.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared/__pycache__/response_format_json_schema.cpython-312.pyc index cd689f86..c9539c9c 100644 Binary files a/venv/Lib/site-packages/openai/types/shared/__pycache__/response_format_json_schema.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared/__pycache__/response_format_json_schema.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared/__pycache__/response_format_text.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared/__pycache__/response_format_text.cpython-312.pyc index cb6ae23f..c21e709b 100644 Binary files a/venv/Lib/site-packages/openai/types/shared/__pycache__/response_format_text.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared/__pycache__/response_format_text.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared/__pycache__/responses_model.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared/__pycache__/responses_model.cpython-312.pyc index 98fcc658..15a29b33 100644 Binary files a/venv/Lib/site-packages/openai/types/shared/__pycache__/responses_model.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared/__pycache__/responses_model.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/__init__.cpython-312.pyc index 8073afca..01f111d5 100644 Binary files a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/chat_model.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/chat_model.cpython-312.pyc index 2a1e4adc..19632f45 100644 Binary files a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/chat_model.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/chat_model.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/comparison_filter.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/comparison_filter.cpython-312.pyc index b00087a1..6267da94 100644 Binary files a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/comparison_filter.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/comparison_filter.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/compound_filter.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/compound_filter.cpython-312.pyc index d74f5e8a..9d47495c 100644 Binary files a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/compound_filter.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/compound_filter.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/function_definition.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/function_definition.cpython-312.pyc index a5a817bd..aa541c24 100644 Binary files a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/function_definition.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/function_definition.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/function_parameters.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/function_parameters.cpython-312.pyc index e4deea59..6e421dd8 100644 Binary files a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/function_parameters.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/function_parameters.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/metadata.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/metadata.cpython-312.pyc index 4722340c..c52ff181 100644 Binary files a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/metadata.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/metadata.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/reasoning.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/reasoning.cpython-312.pyc index 1670fbf7..bbf7e97c 100644 Binary files a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/reasoning.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/reasoning.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/reasoning_effort.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/reasoning_effort.cpython-312.pyc index 237da206..c869582b 100644 Binary files a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/reasoning_effort.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/reasoning_effort.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/response_format_json_object.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/response_format_json_object.cpython-312.pyc index 97498231..e1bd57a5 100644 Binary files a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/response_format_json_object.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/response_format_json_object.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/response_format_json_schema.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/response_format_json_schema.cpython-312.pyc index 3f1b54c1..95b8718b 100644 Binary files a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/response_format_json_schema.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/response_format_json_schema.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/response_format_text.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/response_format_text.cpython-312.pyc index 7ca3b511..c303beb1 100644 Binary files a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/response_format_text.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/response_format_text.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/responses_model.cpython-312.pyc b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/responses_model.cpython-312.pyc index d7225936..9ce8120f 100644 Binary files a/venv/Lib/site-packages/openai/types/shared_params/__pycache__/responses_model.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/shared_params/__pycache__/responses_model.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/uploads/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/types/uploads/__pycache__/__init__.cpython-312.pyc index e5096c45..81d5eca8 100644 Binary files a/venv/Lib/site-packages/openai/types/uploads/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/uploads/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/uploads/__pycache__/part_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/uploads/__pycache__/part_create_params.cpython-312.pyc index 98b5a115..f97a976c 100644 Binary files a/venv/Lib/site-packages/openai/types/uploads/__pycache__/part_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/uploads/__pycache__/part_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/uploads/__pycache__/upload_part.cpython-312.pyc b/venv/Lib/site-packages/openai/types/uploads/__pycache__/upload_part.cpython-312.pyc index cb9e26d2..e52499a9 100644 Binary files a/venv/Lib/site-packages/openai/types/uploads/__pycache__/upload_part.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/uploads/__pycache__/upload_part.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/__init__.cpython-312.pyc index fe61fa4c..9e0f6680 100644 Binary files a/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/file_batch_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/file_batch_create_params.cpython-312.pyc index f7754025..9a600457 100644 Binary files a/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/file_batch_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/file_batch_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/file_batch_list_files_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/file_batch_list_files_params.cpython-312.pyc index f767950a..66a65024 100644 Binary files a/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/file_batch_list_files_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/file_batch_list_files_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/file_content_response.cpython-312.pyc b/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/file_content_response.cpython-312.pyc index 741cc21f..bfa2ddcf 100644 Binary files a/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/file_content_response.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/file_content_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/file_create_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/file_create_params.cpython-312.pyc index 7989e832..19680e42 100644 Binary files a/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/file_create_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/file_create_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/file_list_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/file_list_params.cpython-312.pyc index 87a3b8d7..3cdaf375 100644 Binary files a/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/file_list_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/file_list_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/file_update_params.cpython-312.pyc b/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/file_update_params.cpython-312.pyc index ff11a986..aaba781c 100644 Binary files a/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/file_update_params.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/file_update_params.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/vector_store_file.cpython-312.pyc b/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/vector_store_file.cpython-312.pyc index 7515ea4d..ab259f79 100644 Binary files a/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/vector_store_file.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/vector_store_file.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/vector_store_file_batch.cpython-312.pyc b/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/vector_store_file_batch.cpython-312.pyc index f541ab3b..845f3308 100644 Binary files a/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/vector_store_file_batch.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/vector_store_file_batch.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/vector_store_file_deleted.cpython-312.pyc b/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/vector_store_file_deleted.cpython-312.pyc index c6fdfac4..98df5bbd 100644 Binary files a/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/vector_store_file_deleted.cpython-312.pyc and b/venv/Lib/site-packages/openai/types/vector_stores/__pycache__/vector_store_file_deleted.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/packaging/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/packaging/__pycache__/__init__.cpython-312.pyc index dbd9c7a6..ae13cb4e 100644 Binary files a/venv/Lib/site-packages/packaging/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/packaging/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/packaging/__pycache__/_structures.cpython-312.pyc b/venv/Lib/site-packages/packaging/__pycache__/_structures.cpython-312.pyc index 674dbe74..9588c2aa 100644 Binary files a/venv/Lib/site-packages/packaging/__pycache__/_structures.cpython-312.pyc and b/venv/Lib/site-packages/packaging/__pycache__/_structures.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/packaging/__pycache__/version.cpython-312.pyc b/venv/Lib/site-packages/packaging/__pycache__/version.cpython-312.pyc index c60ee08f..a8af9f8f 100644 Binary files a/venv/Lib/site-packages/packaging/__pycache__/version.cpython-312.pyc and b/venv/Lib/site-packages/packaging/__pycache__/version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/__pycache__/__init__.cpython-312.pyc index a8dabe00..27f1294a 100644 Binary files a/venv/Lib/site-packages/pandas/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/__pycache__/_typing.cpython-312.pyc b/venv/Lib/site-packages/pandas/__pycache__/_typing.cpython-312.pyc index 1430b631..e54db573 100644 Binary files a/venv/Lib/site-packages/pandas/__pycache__/_typing.cpython-312.pyc and b/venv/Lib/site-packages/pandas/__pycache__/_typing.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/__pycache__/_version_meson.cpython-312.pyc b/venv/Lib/site-packages/pandas/__pycache__/_version_meson.cpython-312.pyc index afcac67d..b59aa769 100644 Binary files a/venv/Lib/site-packages/pandas/__pycache__/_version_meson.cpython-312.pyc and b/venv/Lib/site-packages/pandas/__pycache__/_version_meson.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/__pycache__/testing.cpython-312.pyc b/venv/Lib/site-packages/pandas/__pycache__/testing.cpython-312.pyc index f9f656c9..a9328e9d 100644 Binary files a/venv/Lib/site-packages/pandas/__pycache__/testing.cpython-312.pyc and b/venv/Lib/site-packages/pandas/__pycache__/testing.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/_config/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/_config/__pycache__/__init__.cpython-312.pyc index ee08b98b..84703e2b 100644 Binary files a/venv/Lib/site-packages/pandas/_config/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/_config/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/_config/__pycache__/config.cpython-312.pyc b/venv/Lib/site-packages/pandas/_config/__pycache__/config.cpython-312.pyc index 3be9ab92..0a08428d 100644 Binary files a/venv/Lib/site-packages/pandas/_config/__pycache__/config.cpython-312.pyc and b/venv/Lib/site-packages/pandas/_config/__pycache__/config.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/_config/__pycache__/dates.cpython-312.pyc b/venv/Lib/site-packages/pandas/_config/__pycache__/dates.cpython-312.pyc index 3825eaac..8e89e4b7 100644 Binary files a/venv/Lib/site-packages/pandas/_config/__pycache__/dates.cpython-312.pyc and b/venv/Lib/site-packages/pandas/_config/__pycache__/dates.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/_config/__pycache__/display.cpython-312.pyc b/venv/Lib/site-packages/pandas/_config/__pycache__/display.cpython-312.pyc index 0ab740c4..0a38f161 100644 Binary files a/venv/Lib/site-packages/pandas/_config/__pycache__/display.cpython-312.pyc and b/venv/Lib/site-packages/pandas/_config/__pycache__/display.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/_config/__pycache__/localization.cpython-312.pyc b/venv/Lib/site-packages/pandas/_config/__pycache__/localization.cpython-312.pyc index 82cf4b26..34e7d82a 100644 Binary files a/venv/Lib/site-packages/pandas/_config/__pycache__/localization.cpython-312.pyc and b/venv/Lib/site-packages/pandas/_config/__pycache__/localization.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/_libs/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/_libs/__pycache__/__init__.cpython-312.pyc index 2086eb9a..5e5c7cd0 100644 Binary files a/venv/Lib/site-packages/pandas/_libs/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/_libs/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/_libs/tslibs/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/_libs/tslibs/__pycache__/__init__.cpython-312.pyc index 1ce01fa4..f12df524 100644 Binary files a/venv/Lib/site-packages/pandas/_libs/tslibs/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/_libs/tslibs/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/_libs/window/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/_libs/window/__pycache__/__init__.cpython-312.pyc index 2d11dfb4..050bd761 100644 Binary files a/venv/Lib/site-packages/pandas/_libs/window/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/_libs/window/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/_testing/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/_testing/__pycache__/__init__.cpython-312.pyc index 0de7880b..36a920a7 100644 Binary files a/venv/Lib/site-packages/pandas/_testing/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/_testing/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/_testing/__pycache__/_io.cpython-312.pyc b/venv/Lib/site-packages/pandas/_testing/__pycache__/_io.cpython-312.pyc index 25a20da0..24c95524 100644 Binary files a/venv/Lib/site-packages/pandas/_testing/__pycache__/_io.cpython-312.pyc and b/venv/Lib/site-packages/pandas/_testing/__pycache__/_io.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/_testing/__pycache__/_warnings.cpython-312.pyc b/venv/Lib/site-packages/pandas/_testing/__pycache__/_warnings.cpython-312.pyc index 6331d191..59bf535a 100644 Binary files a/venv/Lib/site-packages/pandas/_testing/__pycache__/_warnings.cpython-312.pyc and b/venv/Lib/site-packages/pandas/_testing/__pycache__/_warnings.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/_testing/__pycache__/asserters.cpython-312.pyc b/venv/Lib/site-packages/pandas/_testing/__pycache__/asserters.cpython-312.pyc index 0565e3d5..bc73ecd2 100644 Binary files a/venv/Lib/site-packages/pandas/_testing/__pycache__/asserters.cpython-312.pyc and b/venv/Lib/site-packages/pandas/_testing/__pycache__/asserters.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/_testing/__pycache__/compat.cpython-312.pyc b/venv/Lib/site-packages/pandas/_testing/__pycache__/compat.cpython-312.pyc index b6ce6cdf..2db98e40 100644 Binary files a/venv/Lib/site-packages/pandas/_testing/__pycache__/compat.cpython-312.pyc and b/venv/Lib/site-packages/pandas/_testing/__pycache__/compat.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/_testing/__pycache__/contexts.cpython-312.pyc b/venv/Lib/site-packages/pandas/_testing/__pycache__/contexts.cpython-312.pyc index 3cbaba23..8b78e02a 100644 Binary files a/venv/Lib/site-packages/pandas/_testing/__pycache__/contexts.cpython-312.pyc and b/venv/Lib/site-packages/pandas/_testing/__pycache__/contexts.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/api/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/api/__pycache__/__init__.cpython-312.pyc index 11283710..ead76063 100644 Binary files a/venv/Lib/site-packages/pandas/api/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/api/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/api/extensions/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/api/extensions/__pycache__/__init__.cpython-312.pyc index 5afc5b44..451a185a 100644 Binary files a/venv/Lib/site-packages/pandas/api/extensions/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/api/extensions/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/api/indexers/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/api/indexers/__pycache__/__init__.cpython-312.pyc index c087ed09..335e7abc 100644 Binary files a/venv/Lib/site-packages/pandas/api/indexers/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/api/indexers/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/api/interchange/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/api/interchange/__pycache__/__init__.cpython-312.pyc index 2fc9c4c6..c99238f1 100644 Binary files a/venv/Lib/site-packages/pandas/api/interchange/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/api/interchange/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/api/types/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/api/types/__pycache__/__init__.cpython-312.pyc index bcd1b7fc..ebfca396 100644 Binary files a/venv/Lib/site-packages/pandas/api/types/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/api/types/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/api/typing/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/api/typing/__pycache__/__init__.cpython-312.pyc index ca94794d..769c34cd 100644 Binary files a/venv/Lib/site-packages/pandas/api/typing/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/api/typing/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/arrays/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/arrays/__pycache__/__init__.cpython-312.pyc index 18f145a8..7c2d4c29 100644 Binary files a/venv/Lib/site-packages/pandas/arrays/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/arrays/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/compat/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/compat/__pycache__/__init__.cpython-312.pyc index 88be73eb..8f1fb9b9 100644 Binary files a/venv/Lib/site-packages/pandas/compat/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/compat/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/compat/__pycache__/_constants.cpython-312.pyc b/venv/Lib/site-packages/pandas/compat/__pycache__/_constants.cpython-312.pyc index 7ea94844..27fde434 100644 Binary files a/venv/Lib/site-packages/pandas/compat/__pycache__/_constants.cpython-312.pyc and b/venv/Lib/site-packages/pandas/compat/__pycache__/_constants.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/compat/__pycache__/_optional.cpython-312.pyc b/venv/Lib/site-packages/pandas/compat/__pycache__/_optional.cpython-312.pyc index 9f63f6c1..997eda23 100644 Binary files a/venv/Lib/site-packages/pandas/compat/__pycache__/_optional.cpython-312.pyc and b/venv/Lib/site-packages/pandas/compat/__pycache__/_optional.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/compat/__pycache__/compressors.cpython-312.pyc b/venv/Lib/site-packages/pandas/compat/__pycache__/compressors.cpython-312.pyc index 9c1fea6f..7fce2535 100644 Binary files a/venv/Lib/site-packages/pandas/compat/__pycache__/compressors.cpython-312.pyc and b/venv/Lib/site-packages/pandas/compat/__pycache__/compressors.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/compat/__pycache__/pickle_compat.cpython-312.pyc b/venv/Lib/site-packages/pandas/compat/__pycache__/pickle_compat.cpython-312.pyc index 2e7c71c6..325e4c67 100644 Binary files a/venv/Lib/site-packages/pandas/compat/__pycache__/pickle_compat.cpython-312.pyc and b/venv/Lib/site-packages/pandas/compat/__pycache__/pickle_compat.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/compat/__pycache__/pyarrow.cpython-312.pyc b/venv/Lib/site-packages/pandas/compat/__pycache__/pyarrow.cpython-312.pyc index 31ee405c..886100bc 100644 Binary files a/venv/Lib/site-packages/pandas/compat/__pycache__/pyarrow.cpython-312.pyc and b/venv/Lib/site-packages/pandas/compat/__pycache__/pyarrow.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/compat/numpy/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/compat/numpy/__pycache__/__init__.cpython-312.pyc index 55b55dc4..00827252 100644 Binary files a/venv/Lib/site-packages/pandas/compat/numpy/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/compat/numpy/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/compat/numpy/__pycache__/function.cpython-312.pyc b/venv/Lib/site-packages/pandas/compat/numpy/__pycache__/function.cpython-312.pyc index aa588651..d36bf4b9 100644 Binary files a/venv/Lib/site-packages/pandas/compat/numpy/__pycache__/function.cpython-312.pyc and b/venv/Lib/site-packages/pandas/compat/numpy/__pycache__/function.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/__pycache__/__init__.cpython-312.pyc index 26cf276e..04f8f658 100644 Binary files a/venv/Lib/site-packages/pandas/core/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/__pycache__/accessor.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/__pycache__/accessor.cpython-312.pyc index 9f9df5cb..86fcc555 100644 Binary files a/venv/Lib/site-packages/pandas/core/__pycache__/accessor.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/__pycache__/accessor.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/__pycache__/algorithms.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/__pycache__/algorithms.cpython-312.pyc index 12a3cea3..2cafff65 100644 Binary files a/venv/Lib/site-packages/pandas/core/__pycache__/algorithms.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/__pycache__/algorithms.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/__pycache__/api.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/__pycache__/api.cpython-312.pyc index f4c03879..87c1ec2f 100644 Binary files a/venv/Lib/site-packages/pandas/core/__pycache__/api.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/__pycache__/api.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/__pycache__/apply.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/__pycache__/apply.cpython-312.pyc index b24dd9f6..2643e258 100644 Binary files a/venv/Lib/site-packages/pandas/core/__pycache__/apply.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/__pycache__/apply.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/__pycache__/arraylike.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/__pycache__/arraylike.cpython-312.pyc index 1096c371..c286eb66 100644 Binary files a/venv/Lib/site-packages/pandas/core/__pycache__/arraylike.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/__pycache__/arraylike.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/__pycache__/base.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/__pycache__/base.cpython-312.pyc index 4595d50b..aab7d69e 100644 Binary files a/venv/Lib/site-packages/pandas/core/__pycache__/base.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/__pycache__/base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/__pycache__/common.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/__pycache__/common.cpython-312.pyc index e3ed7d01..a901d3a1 100644 Binary files a/venv/Lib/site-packages/pandas/core/__pycache__/common.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/__pycache__/common.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/__pycache__/config_init.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/__pycache__/config_init.cpython-312.pyc index c7172302..7fef0cbe 100644 Binary files a/venv/Lib/site-packages/pandas/core/__pycache__/config_init.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/__pycache__/config_init.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/__pycache__/construction.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/__pycache__/construction.cpython-312.pyc index 6a4f2b36..4f0569f6 100644 Binary files a/venv/Lib/site-packages/pandas/core/__pycache__/construction.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/__pycache__/construction.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/__pycache__/flags.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/__pycache__/flags.cpython-312.pyc index c000bcde..c0ace556 100644 Binary files a/venv/Lib/site-packages/pandas/core/__pycache__/flags.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/__pycache__/flags.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/__pycache__/frame.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/__pycache__/frame.cpython-312.pyc index 18879c43..03e21424 100644 Binary files a/venv/Lib/site-packages/pandas/core/__pycache__/frame.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/__pycache__/frame.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/__pycache__/generic.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/__pycache__/generic.cpython-312.pyc index 99fbadef..0af231ad 100644 Binary files a/venv/Lib/site-packages/pandas/core/__pycache__/generic.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/__pycache__/generic.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/__pycache__/indexing.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/__pycache__/indexing.cpython-312.pyc index 445a4a8f..b6d60704 100644 Binary files a/venv/Lib/site-packages/pandas/core/__pycache__/indexing.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/__pycache__/indexing.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/__pycache__/missing.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/__pycache__/missing.cpython-312.pyc index 1463cea2..a02ef3ea 100644 Binary files a/venv/Lib/site-packages/pandas/core/__pycache__/missing.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/__pycache__/missing.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/__pycache__/nanops.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/__pycache__/nanops.cpython-312.pyc index 15645769..c316a9c6 100644 Binary files a/venv/Lib/site-packages/pandas/core/__pycache__/nanops.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/__pycache__/nanops.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/__pycache__/resample.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/__pycache__/resample.cpython-312.pyc index 72ecaa49..6dfcd849 100644 Binary files a/venv/Lib/site-packages/pandas/core/__pycache__/resample.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/__pycache__/resample.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/__pycache__/roperator.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/__pycache__/roperator.cpython-312.pyc index 6a0fbec0..0ddc5d20 100644 Binary files a/venv/Lib/site-packages/pandas/core/__pycache__/roperator.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/__pycache__/roperator.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/__pycache__/sample.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/__pycache__/sample.cpython-312.pyc index 5ccf22ed..7ab17e71 100644 Binary files a/venv/Lib/site-packages/pandas/core/__pycache__/sample.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/__pycache__/sample.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/__pycache__/series.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/__pycache__/series.cpython-312.pyc index ebeecffc..e47b9578 100644 Binary files a/venv/Lib/site-packages/pandas/core/__pycache__/series.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/__pycache__/series.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/__pycache__/shared_docs.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/__pycache__/shared_docs.cpython-312.pyc index 3af54ea8..afeabfbc 100644 Binary files a/venv/Lib/site-packages/pandas/core/__pycache__/shared_docs.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/__pycache__/shared_docs.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/__pycache__/sorting.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/__pycache__/sorting.cpython-312.pyc index 5e05649e..3b1d869e 100644 Binary files a/venv/Lib/site-packages/pandas/core/__pycache__/sorting.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/__pycache__/sorting.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/_numba/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/_numba/__pycache__/__init__.cpython-312.pyc index b43a12c4..742e1d64 100644 Binary files a/venv/Lib/site-packages/pandas/core/_numba/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/_numba/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/_numba/__pycache__/executor.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/_numba/__pycache__/executor.cpython-312.pyc index 1b7445a6..c9e68316 100644 Binary files a/venv/Lib/site-packages/pandas/core/_numba/__pycache__/executor.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/_numba/__pycache__/executor.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/__init__.cpython-312.pyc index 6a444b8d..222d5193 100644 Binary files a/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/datetimelike_accumulations.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/datetimelike_accumulations.cpython-312.pyc index 8186c8fc..5da533bf 100644 Binary files a/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/datetimelike_accumulations.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/datetimelike_accumulations.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/masked_accumulations.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/masked_accumulations.cpython-312.pyc index 863f414c..4fda5f84 100644 Binary files a/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/masked_accumulations.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/masked_accumulations.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/masked_reductions.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/masked_reductions.cpython-312.pyc index 03ad3326..6b4c102a 100644 Binary files a/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/masked_reductions.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/masked_reductions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/putmask.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/putmask.cpython-312.pyc index dffb66b9..c9fb8b52 100644 Binary files a/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/putmask.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/putmask.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/quantile.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/quantile.cpython-312.pyc index d98ea7fe..68ed0b5c 100644 Binary files a/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/quantile.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/quantile.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/replace.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/replace.cpython-312.pyc index 1d463861..1dbcf519 100644 Binary files a/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/replace.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/replace.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/take.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/take.cpython-312.pyc index 4043faec..cdf01332 100644 Binary files a/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/take.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/take.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/transforms.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/transforms.cpython-312.pyc index 63136f8b..fedfce4a 100644 Binary files a/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/transforms.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/array_algos/__pycache__/transforms.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/__init__.cpython-312.pyc index e1533278..4261b003 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/_arrow_string_mixins.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/_arrow_string_mixins.cpython-312.pyc index f0aee8b1..b10cf2ab 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/_arrow_string_mixins.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/_arrow_string_mixins.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/_mixins.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/_mixins.cpython-312.pyc index 76658a97..cd6ee368 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/_mixins.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/_mixins.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/_ranges.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/_ranges.cpython-312.pyc index 55717ccb..a296be70 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/_ranges.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/_ranges.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/_utils.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/_utils.cpython-312.pyc index 0d1e587b..000c9272 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/_utils.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/_utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/base.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/base.cpython-312.pyc index f965d4da..f72d8f03 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/base.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/boolean.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/boolean.cpython-312.pyc index 2de505ac..900c92ed 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/boolean.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/boolean.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/categorical.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/categorical.cpython-312.pyc index f2623095..aad96b16 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/categorical.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/categorical.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/datetimelike.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/datetimelike.cpython-312.pyc index 02c4dc5f..b7267fd0 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/datetimelike.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/datetimelike.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/datetimes.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/datetimes.cpython-312.pyc index c787903a..152d2905 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/datetimes.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/datetimes.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/floating.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/floating.cpython-312.pyc index 13018344..cf739cb3 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/floating.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/floating.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/integer.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/integer.cpython-312.pyc index b036baf5..8818e47e 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/integer.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/integer.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/interval.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/interval.cpython-312.pyc index 1a7e441a..03a22461 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/interval.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/interval.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/masked.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/masked.cpython-312.pyc index bd1d0c95..c2147dfa 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/masked.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/masked.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/numeric.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/numeric.cpython-312.pyc index a05d2ee1..18f43752 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/numeric.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/numeric.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/numpy_.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/numpy_.cpython-312.pyc index 78c47afa..51942f7a 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/numpy_.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/numpy_.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/period.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/period.cpython-312.pyc index be70b90e..125ad79e 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/period.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/period.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/string_.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/string_.cpython-312.pyc index 2bc7a599..c7d9e18f 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/string_.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/string_.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/string_arrow.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/string_arrow.cpython-312.pyc index 7a53dcfa..587081b3 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/string_arrow.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/string_arrow.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/timedeltas.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/timedeltas.cpython-312.pyc index 2dfcfb31..f816b13d 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/__pycache__/timedeltas.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/__pycache__/timedeltas.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/arrow/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/arrow/__pycache__/__init__.cpython-312.pyc index 2d0c9ceb..4116987d 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/arrow/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/arrow/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/arrow/__pycache__/accessors.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/arrow/__pycache__/accessors.cpython-312.pyc index 4c797fc1..299037f1 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/arrow/__pycache__/accessors.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/arrow/__pycache__/accessors.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/arrow/__pycache__/array.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/arrow/__pycache__/array.cpython-312.pyc index bd3e3e6c..c23128ac 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/arrow/__pycache__/array.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/arrow/__pycache__/array.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/sparse/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/sparse/__pycache__/__init__.cpython-312.pyc index e4a8d05b..e3eb65ba 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/sparse/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/sparse/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/sparse/__pycache__/accessor.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/sparse/__pycache__/accessor.cpython-312.pyc index bdab3663..2baf301d 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/sparse/__pycache__/accessor.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/sparse/__pycache__/accessor.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/arrays/sparse/__pycache__/array.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/arrays/sparse/__pycache__/array.cpython-312.pyc index 13f5cefe..99c42c06 100644 Binary files a/venv/Lib/site-packages/pandas/core/arrays/sparse/__pycache__/array.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/arrays/sparse/__pycache__/array.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/computation/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/computation/__pycache__/__init__.cpython-312.pyc index 860b9c78..30332149 100644 Binary files a/venv/Lib/site-packages/pandas/core/computation/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/computation/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/computation/__pycache__/align.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/computation/__pycache__/align.cpython-312.pyc index 41769061..b98608c8 100644 Binary files a/venv/Lib/site-packages/pandas/core/computation/__pycache__/align.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/computation/__pycache__/align.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/computation/__pycache__/api.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/computation/__pycache__/api.cpython-312.pyc index 4f5f4638..ee0969b4 100644 Binary files a/venv/Lib/site-packages/pandas/core/computation/__pycache__/api.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/computation/__pycache__/api.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/computation/__pycache__/check.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/computation/__pycache__/check.cpython-312.pyc index 50d786b8..83cb50a8 100644 Binary files a/venv/Lib/site-packages/pandas/core/computation/__pycache__/check.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/computation/__pycache__/check.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/computation/__pycache__/common.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/computation/__pycache__/common.cpython-312.pyc index 1373ecdd..67a77075 100644 Binary files a/venv/Lib/site-packages/pandas/core/computation/__pycache__/common.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/computation/__pycache__/common.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/computation/__pycache__/engines.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/computation/__pycache__/engines.cpython-312.pyc index 4a511744..d6e60e2c 100644 Binary files a/venv/Lib/site-packages/pandas/core/computation/__pycache__/engines.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/computation/__pycache__/engines.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/computation/__pycache__/eval.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/computation/__pycache__/eval.cpython-312.pyc index c64fc542..41dbe0f0 100644 Binary files a/venv/Lib/site-packages/pandas/core/computation/__pycache__/eval.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/computation/__pycache__/eval.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/computation/__pycache__/expr.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/computation/__pycache__/expr.cpython-312.pyc index fc4482cf..49183f6f 100644 Binary files a/venv/Lib/site-packages/pandas/core/computation/__pycache__/expr.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/computation/__pycache__/expr.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/computation/__pycache__/expressions.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/computation/__pycache__/expressions.cpython-312.pyc index 594c28c1..be5bc206 100644 Binary files a/venv/Lib/site-packages/pandas/core/computation/__pycache__/expressions.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/computation/__pycache__/expressions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/computation/__pycache__/ops.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/computation/__pycache__/ops.cpython-312.pyc index 303dae86..0658d78d 100644 Binary files a/venv/Lib/site-packages/pandas/core/computation/__pycache__/ops.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/computation/__pycache__/ops.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/computation/__pycache__/parsing.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/computation/__pycache__/parsing.cpython-312.pyc index ff92db90..b2826db8 100644 Binary files a/venv/Lib/site-packages/pandas/core/computation/__pycache__/parsing.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/computation/__pycache__/parsing.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/computation/__pycache__/pytables.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/computation/__pycache__/pytables.cpython-312.pyc index 683d84c5..1d68f6d1 100644 Binary files a/venv/Lib/site-packages/pandas/core/computation/__pycache__/pytables.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/computation/__pycache__/pytables.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/computation/__pycache__/scope.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/computation/__pycache__/scope.cpython-312.pyc index ab217f79..47d76506 100644 Binary files a/venv/Lib/site-packages/pandas/core/computation/__pycache__/scope.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/computation/__pycache__/scope.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/__init__.cpython-312.pyc index e278d9b2..caf258c6 100644 Binary files a/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/api.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/api.cpython-312.pyc index 0856d5c9..e43f2aea 100644 Binary files a/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/api.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/api.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/astype.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/astype.cpython-312.pyc index dbecd22d..6edd60e6 100644 Binary files a/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/astype.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/astype.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/base.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/base.cpython-312.pyc index 3b2402d8..2c39c5fc 100644 Binary files a/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/base.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/cast.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/cast.cpython-312.pyc index 1fa3a47a..5b258cdc 100644 Binary files a/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/cast.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/cast.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/common.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/common.cpython-312.pyc index 2db8d8a4..98c854be 100644 Binary files a/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/common.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/common.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/concat.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/concat.cpython-312.pyc index c2546cbd..93bcca9a 100644 Binary files a/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/concat.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/concat.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/dtypes.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/dtypes.cpython-312.pyc index 58efefa0..f098bc48 100644 Binary files a/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/dtypes.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/dtypes.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/generic.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/generic.cpython-312.pyc index 912fd2df..cab15dec 100644 Binary files a/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/generic.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/generic.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/inference.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/inference.cpython-312.pyc index 6730c8eb..16fd8c20 100644 Binary files a/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/inference.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/inference.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/missing.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/missing.cpython-312.pyc index 65f27917..d5a7ea22 100644 Binary files a/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/missing.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/dtypes/__pycache__/missing.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/groupby/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/groupby/__pycache__/__init__.cpython-312.pyc index 358e2cad..5fd6c066 100644 Binary files a/venv/Lib/site-packages/pandas/core/groupby/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/groupby/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/groupby/__pycache__/base.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/groupby/__pycache__/base.cpython-312.pyc index c5ad7ac2..6a4fe4d6 100644 Binary files a/venv/Lib/site-packages/pandas/core/groupby/__pycache__/base.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/groupby/__pycache__/base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/groupby/__pycache__/categorical.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/groupby/__pycache__/categorical.cpython-312.pyc index 1e1f5581..5e3fac8c 100644 Binary files a/venv/Lib/site-packages/pandas/core/groupby/__pycache__/categorical.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/groupby/__pycache__/categorical.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/groupby/__pycache__/generic.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/groupby/__pycache__/generic.cpython-312.pyc index 1a29dd1c..1e7379d0 100644 Binary files a/venv/Lib/site-packages/pandas/core/groupby/__pycache__/generic.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/groupby/__pycache__/generic.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/groupby/__pycache__/groupby.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/groupby/__pycache__/groupby.cpython-312.pyc index 58c8553e..963fa740 100644 Binary files a/venv/Lib/site-packages/pandas/core/groupby/__pycache__/groupby.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/groupby/__pycache__/groupby.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/groupby/__pycache__/grouper.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/groupby/__pycache__/grouper.cpython-312.pyc index f7376c36..1e809922 100644 Binary files a/venv/Lib/site-packages/pandas/core/groupby/__pycache__/grouper.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/groupby/__pycache__/grouper.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/groupby/__pycache__/indexing.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/groupby/__pycache__/indexing.cpython-312.pyc index 1f829801..fb7fed08 100644 Binary files a/venv/Lib/site-packages/pandas/core/groupby/__pycache__/indexing.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/groupby/__pycache__/indexing.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/groupby/__pycache__/numba_.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/groupby/__pycache__/numba_.cpython-312.pyc index 50492c43..48166e13 100644 Binary files a/venv/Lib/site-packages/pandas/core/groupby/__pycache__/numba_.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/groupby/__pycache__/numba_.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/groupby/__pycache__/ops.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/groupby/__pycache__/ops.cpython-312.pyc index 6bfbd689..0b88147c 100644 Binary files a/venv/Lib/site-packages/pandas/core/groupby/__pycache__/ops.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/groupby/__pycache__/ops.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/indexers/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/indexers/__pycache__/__init__.cpython-312.pyc index a6fb9822..31a31cad 100644 Binary files a/venv/Lib/site-packages/pandas/core/indexers/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/indexers/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/indexers/__pycache__/objects.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/indexers/__pycache__/objects.cpython-312.pyc index 90330122..1d9c61bf 100644 Binary files a/venv/Lib/site-packages/pandas/core/indexers/__pycache__/objects.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/indexers/__pycache__/objects.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/indexers/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/indexers/__pycache__/utils.cpython-312.pyc index b3eab9bd..87214b46 100644 Binary files a/venv/Lib/site-packages/pandas/core/indexers/__pycache__/utils.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/indexers/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/__init__.cpython-312.pyc index 9f52d382..82720d5e 100644 Binary files a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/accessors.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/accessors.cpython-312.pyc index 030afecc..23f79d4a 100644 Binary files a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/accessors.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/accessors.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/api.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/api.cpython-312.pyc index 4ed4cd62..bf342b0e 100644 Binary files a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/api.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/api.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/base.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/base.cpython-312.pyc index f7ab6746..16cca797 100644 Binary files a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/base.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/category.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/category.cpython-312.pyc index 87ff1904..216d7137 100644 Binary files a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/category.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/category.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/datetimelike.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/datetimelike.cpython-312.pyc index b8bd7c57..bfd94d9a 100644 Binary files a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/datetimelike.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/datetimelike.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/datetimes.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/datetimes.cpython-312.pyc index f35db196..42087762 100644 Binary files a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/datetimes.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/datetimes.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/extension.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/extension.cpython-312.pyc index 343ca883..e2938ea5 100644 Binary files a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/extension.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/extension.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/frozen.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/frozen.cpython-312.pyc index 2892b719..82034ed4 100644 Binary files a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/frozen.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/frozen.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/interval.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/interval.cpython-312.pyc index a093df15..da9ba8e0 100644 Binary files a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/interval.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/interval.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/multi.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/multi.cpython-312.pyc index 3d91243b..c3aeffca 100644 Binary files a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/multi.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/multi.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/period.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/period.cpython-312.pyc index 8bc02ab9..6d132d89 100644 Binary files a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/period.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/period.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/range.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/range.cpython-312.pyc index c18a6bd7..75d7058c 100644 Binary files a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/range.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/range.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/timedeltas.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/timedeltas.cpython-312.pyc index 4a709652..e04f527d 100644 Binary files a/venv/Lib/site-packages/pandas/core/indexes/__pycache__/timedeltas.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/indexes/__pycache__/timedeltas.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/interchange/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/interchange/__pycache__/__init__.cpython-312.pyc index ac2fd652..bae90436 100644 Binary files a/venv/Lib/site-packages/pandas/core/interchange/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/interchange/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/interchange/__pycache__/dataframe_protocol.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/interchange/__pycache__/dataframe_protocol.cpython-312.pyc index e766330a..38a4360a 100644 Binary files a/venv/Lib/site-packages/pandas/core/interchange/__pycache__/dataframe_protocol.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/interchange/__pycache__/dataframe_protocol.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/interchange/__pycache__/from_dataframe.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/interchange/__pycache__/from_dataframe.cpython-312.pyc index 6b884afb..881e8287 100644 Binary files a/venv/Lib/site-packages/pandas/core/interchange/__pycache__/from_dataframe.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/interchange/__pycache__/from_dataframe.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/interchange/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/interchange/__pycache__/utils.cpython-312.pyc index 779f5f09..27200a27 100644 Binary files a/venv/Lib/site-packages/pandas/core/interchange/__pycache__/utils.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/interchange/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/internals/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/internals/__pycache__/__init__.cpython-312.pyc index 2243121f..93a675cd 100644 Binary files a/venv/Lib/site-packages/pandas/core/internals/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/internals/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/internals/__pycache__/api.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/internals/__pycache__/api.cpython-312.pyc index 58bbff8b..29e07254 100644 Binary files a/venv/Lib/site-packages/pandas/core/internals/__pycache__/api.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/internals/__pycache__/api.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/internals/__pycache__/array_manager.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/internals/__pycache__/array_manager.cpython-312.pyc index 2abaf2be..c1be93ff 100644 Binary files a/venv/Lib/site-packages/pandas/core/internals/__pycache__/array_manager.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/internals/__pycache__/array_manager.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/internals/__pycache__/base.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/internals/__pycache__/base.cpython-312.pyc index ad9f19d9..ec9fd953 100644 Binary files a/venv/Lib/site-packages/pandas/core/internals/__pycache__/base.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/internals/__pycache__/base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/internals/__pycache__/blocks.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/internals/__pycache__/blocks.cpython-312.pyc index e3e36b56..c0896fd0 100644 Binary files a/venv/Lib/site-packages/pandas/core/internals/__pycache__/blocks.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/internals/__pycache__/blocks.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/internals/__pycache__/concat.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/internals/__pycache__/concat.cpython-312.pyc index 6efefd29..df9fca0c 100644 Binary files a/venv/Lib/site-packages/pandas/core/internals/__pycache__/concat.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/internals/__pycache__/concat.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/internals/__pycache__/construction.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/internals/__pycache__/construction.cpython-312.pyc index b04c7f0a..429acbcc 100644 Binary files a/venv/Lib/site-packages/pandas/core/internals/__pycache__/construction.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/internals/__pycache__/construction.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/internals/__pycache__/managers.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/internals/__pycache__/managers.cpython-312.pyc index 23acb8f9..a5991fa0 100644 Binary files a/venv/Lib/site-packages/pandas/core/internals/__pycache__/managers.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/internals/__pycache__/managers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/internals/__pycache__/ops.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/internals/__pycache__/ops.cpython-312.pyc index c96397f5..80bdfaeb 100644 Binary files a/venv/Lib/site-packages/pandas/core/internals/__pycache__/ops.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/internals/__pycache__/ops.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/methods/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/methods/__pycache__/__init__.cpython-312.pyc index 0fde03d1..ac68b041 100644 Binary files a/venv/Lib/site-packages/pandas/core/methods/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/methods/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/methods/__pycache__/describe.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/methods/__pycache__/describe.cpython-312.pyc index b4e3b8dc..aa26245b 100644 Binary files a/venv/Lib/site-packages/pandas/core/methods/__pycache__/describe.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/methods/__pycache__/describe.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/methods/__pycache__/selectn.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/methods/__pycache__/selectn.cpython-312.pyc index f3ddf5ab..0dc170d9 100644 Binary files a/venv/Lib/site-packages/pandas/core/methods/__pycache__/selectn.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/methods/__pycache__/selectn.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/ops/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/ops/__pycache__/__init__.cpython-312.pyc index 86661c23..51f073bd 100644 Binary files a/venv/Lib/site-packages/pandas/core/ops/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/ops/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/ops/__pycache__/array_ops.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/ops/__pycache__/array_ops.cpython-312.pyc index 7e969939..cfab908c 100644 Binary files a/venv/Lib/site-packages/pandas/core/ops/__pycache__/array_ops.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/ops/__pycache__/array_ops.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/ops/__pycache__/common.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/ops/__pycache__/common.cpython-312.pyc index 773b2b9f..7fffc7f8 100644 Binary files a/venv/Lib/site-packages/pandas/core/ops/__pycache__/common.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/ops/__pycache__/common.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/ops/__pycache__/dispatch.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/ops/__pycache__/dispatch.cpython-312.pyc index 4b910adc..053f1d80 100644 Binary files a/venv/Lib/site-packages/pandas/core/ops/__pycache__/dispatch.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/ops/__pycache__/dispatch.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/ops/__pycache__/docstrings.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/ops/__pycache__/docstrings.cpython-312.pyc index 24f7586b..a4b31e0c 100644 Binary files a/venv/Lib/site-packages/pandas/core/ops/__pycache__/docstrings.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/ops/__pycache__/docstrings.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/ops/__pycache__/invalid.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/ops/__pycache__/invalid.cpython-312.pyc index 36502667..7b06fb00 100644 Binary files a/venv/Lib/site-packages/pandas/core/ops/__pycache__/invalid.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/ops/__pycache__/invalid.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/ops/__pycache__/mask_ops.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/ops/__pycache__/mask_ops.cpython-312.pyc index 8b8467ac..bb0a9eb0 100644 Binary files a/venv/Lib/site-packages/pandas/core/ops/__pycache__/mask_ops.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/ops/__pycache__/mask_ops.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/ops/__pycache__/missing.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/ops/__pycache__/missing.cpython-312.pyc index 8e2f9f73..17fbc045 100644 Binary files a/venv/Lib/site-packages/pandas/core/ops/__pycache__/missing.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/ops/__pycache__/missing.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/reshape/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/reshape/__pycache__/__init__.cpython-312.pyc index 9f6099a1..91481a5c 100644 Binary files a/venv/Lib/site-packages/pandas/core/reshape/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/reshape/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/reshape/__pycache__/api.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/reshape/__pycache__/api.cpython-312.pyc index 20567de3..41cd07dd 100644 Binary files a/venv/Lib/site-packages/pandas/core/reshape/__pycache__/api.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/reshape/__pycache__/api.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/reshape/__pycache__/concat.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/reshape/__pycache__/concat.cpython-312.pyc index 9ef1af23..467610ab 100644 Binary files a/venv/Lib/site-packages/pandas/core/reshape/__pycache__/concat.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/reshape/__pycache__/concat.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/reshape/__pycache__/encoding.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/reshape/__pycache__/encoding.cpython-312.pyc index f5654d85..62d30740 100644 Binary files a/venv/Lib/site-packages/pandas/core/reshape/__pycache__/encoding.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/reshape/__pycache__/encoding.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/reshape/__pycache__/melt.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/reshape/__pycache__/melt.cpython-312.pyc index 9e5f4328..814aafd4 100644 Binary files a/venv/Lib/site-packages/pandas/core/reshape/__pycache__/melt.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/reshape/__pycache__/melt.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/reshape/__pycache__/merge.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/reshape/__pycache__/merge.cpython-312.pyc index a6989aad..1a85ba40 100644 Binary files a/venv/Lib/site-packages/pandas/core/reshape/__pycache__/merge.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/reshape/__pycache__/merge.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/reshape/__pycache__/pivot.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/reshape/__pycache__/pivot.cpython-312.pyc index 68f72b52..bad8fc04 100644 Binary files a/venv/Lib/site-packages/pandas/core/reshape/__pycache__/pivot.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/reshape/__pycache__/pivot.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/reshape/__pycache__/tile.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/reshape/__pycache__/tile.cpython-312.pyc index 669c8848..54742770 100644 Binary files a/venv/Lib/site-packages/pandas/core/reshape/__pycache__/tile.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/reshape/__pycache__/tile.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/reshape/__pycache__/util.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/reshape/__pycache__/util.cpython-312.pyc index 4e306d6c..5609ae0e 100644 Binary files a/venv/Lib/site-packages/pandas/core/reshape/__pycache__/util.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/reshape/__pycache__/util.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/strings/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/strings/__pycache__/__init__.cpython-312.pyc index 37b50a6e..e900aded 100644 Binary files a/venv/Lib/site-packages/pandas/core/strings/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/strings/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/strings/__pycache__/accessor.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/strings/__pycache__/accessor.cpython-312.pyc index 55d480d8..a60a7b8b 100644 Binary files a/venv/Lib/site-packages/pandas/core/strings/__pycache__/accessor.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/strings/__pycache__/accessor.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/strings/__pycache__/base.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/strings/__pycache__/base.cpython-312.pyc index 0eaf0bf7..4ba5d056 100644 Binary files a/venv/Lib/site-packages/pandas/core/strings/__pycache__/base.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/strings/__pycache__/base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/strings/__pycache__/object_array.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/strings/__pycache__/object_array.cpython-312.pyc index 9e7e79d1..2cf7f049 100644 Binary files a/venv/Lib/site-packages/pandas/core/strings/__pycache__/object_array.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/strings/__pycache__/object_array.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/tools/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/tools/__pycache__/__init__.cpython-312.pyc index 9ee37f59..69802113 100644 Binary files a/venv/Lib/site-packages/pandas/core/tools/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/tools/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/tools/__pycache__/datetimes.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/tools/__pycache__/datetimes.cpython-312.pyc index d74ff9cd..eaaf2db1 100644 Binary files a/venv/Lib/site-packages/pandas/core/tools/__pycache__/datetimes.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/tools/__pycache__/datetimes.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/tools/__pycache__/numeric.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/tools/__pycache__/numeric.cpython-312.pyc index df323f6f..1c5308d3 100644 Binary files a/venv/Lib/site-packages/pandas/core/tools/__pycache__/numeric.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/tools/__pycache__/numeric.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/tools/__pycache__/timedeltas.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/tools/__pycache__/timedeltas.cpython-312.pyc index b32166e1..0159c292 100644 Binary files a/venv/Lib/site-packages/pandas/core/tools/__pycache__/timedeltas.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/tools/__pycache__/timedeltas.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/tools/__pycache__/times.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/tools/__pycache__/times.cpython-312.pyc index 043c9d1d..f1d39080 100644 Binary files a/venv/Lib/site-packages/pandas/core/tools/__pycache__/times.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/tools/__pycache__/times.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/util/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/util/__pycache__/__init__.cpython-312.pyc index 42998350..6c93b3a1 100644 Binary files a/venv/Lib/site-packages/pandas/core/util/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/util/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/util/__pycache__/hashing.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/util/__pycache__/hashing.cpython-312.pyc index fec3827f..248baf7a 100644 Binary files a/venv/Lib/site-packages/pandas/core/util/__pycache__/hashing.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/util/__pycache__/hashing.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/util/__pycache__/numba_.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/util/__pycache__/numba_.cpython-312.pyc index 7cdb5454..abf1f82c 100644 Binary files a/venv/Lib/site-packages/pandas/core/util/__pycache__/numba_.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/util/__pycache__/numba_.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/window/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/window/__pycache__/__init__.cpython-312.pyc index ed0c54fe..c17a882c 100644 Binary files a/venv/Lib/site-packages/pandas/core/window/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/window/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/window/__pycache__/common.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/window/__pycache__/common.cpython-312.pyc index 4ef6327e..15d4623f 100644 Binary files a/venv/Lib/site-packages/pandas/core/window/__pycache__/common.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/window/__pycache__/common.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/window/__pycache__/doc.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/window/__pycache__/doc.cpython-312.pyc index fc38b720..7b088ca9 100644 Binary files a/venv/Lib/site-packages/pandas/core/window/__pycache__/doc.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/window/__pycache__/doc.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/window/__pycache__/ewm.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/window/__pycache__/ewm.cpython-312.pyc index 508cc8fb..1ea52add 100644 Binary files a/venv/Lib/site-packages/pandas/core/window/__pycache__/ewm.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/window/__pycache__/ewm.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/window/__pycache__/expanding.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/window/__pycache__/expanding.cpython-312.pyc index f2c55a1a..58f99f5d 100644 Binary files a/venv/Lib/site-packages/pandas/core/window/__pycache__/expanding.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/window/__pycache__/expanding.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/window/__pycache__/numba_.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/window/__pycache__/numba_.cpython-312.pyc index 692313f1..1d5b52f0 100644 Binary files a/venv/Lib/site-packages/pandas/core/window/__pycache__/numba_.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/window/__pycache__/numba_.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/window/__pycache__/online.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/window/__pycache__/online.cpython-312.pyc index ee8eec5e..5e001fa7 100644 Binary files a/venv/Lib/site-packages/pandas/core/window/__pycache__/online.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/window/__pycache__/online.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/core/window/__pycache__/rolling.cpython-312.pyc b/venv/Lib/site-packages/pandas/core/window/__pycache__/rolling.cpython-312.pyc index 487ee373..18c37a75 100644 Binary files a/venv/Lib/site-packages/pandas/core/window/__pycache__/rolling.cpython-312.pyc and b/venv/Lib/site-packages/pandas/core/window/__pycache__/rolling.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/errors/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/errors/__pycache__/__init__.cpython-312.pyc index 638e9fbd..af8a30e8 100644 Binary files a/venv/Lib/site-packages/pandas/errors/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/errors/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/__pycache__/__init__.cpython-312.pyc index dd650c36..755df84c 100644 Binary files a/venv/Lib/site-packages/pandas/io/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/__pycache__/_util.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/__pycache__/_util.cpython-312.pyc index 0dd42a53..f14906c0 100644 Binary files a/venv/Lib/site-packages/pandas/io/__pycache__/_util.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/__pycache__/_util.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/__pycache__/api.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/__pycache__/api.cpython-312.pyc index d239f589..afe72bc2 100644 Binary files a/venv/Lib/site-packages/pandas/io/__pycache__/api.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/__pycache__/api.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/__pycache__/clipboards.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/__pycache__/clipboards.cpython-312.pyc index 59a191ed..760570ab 100644 Binary files a/venv/Lib/site-packages/pandas/io/__pycache__/clipboards.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/__pycache__/clipboards.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/__pycache__/common.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/__pycache__/common.cpython-312.pyc index b477ef14..43152163 100644 Binary files a/venv/Lib/site-packages/pandas/io/__pycache__/common.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/__pycache__/common.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/__pycache__/feather_format.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/__pycache__/feather_format.cpython-312.pyc index 6ec7044a..c9231490 100644 Binary files a/venv/Lib/site-packages/pandas/io/__pycache__/feather_format.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/__pycache__/feather_format.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/__pycache__/gbq.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/__pycache__/gbq.cpython-312.pyc index 66dcfb3b..1c3f23d7 100644 Binary files a/venv/Lib/site-packages/pandas/io/__pycache__/gbq.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/__pycache__/gbq.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/__pycache__/html.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/__pycache__/html.cpython-312.pyc index 5ed21849..2d67485f 100644 Binary files a/venv/Lib/site-packages/pandas/io/__pycache__/html.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/__pycache__/html.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/__pycache__/orc.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/__pycache__/orc.cpython-312.pyc index ada3aa2c..b8f869dc 100644 Binary files a/venv/Lib/site-packages/pandas/io/__pycache__/orc.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/__pycache__/orc.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/__pycache__/parquet.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/__pycache__/parquet.cpython-312.pyc index aad08346..1e9a33a8 100644 Binary files a/venv/Lib/site-packages/pandas/io/__pycache__/parquet.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/__pycache__/parquet.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/__pycache__/pickle.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/__pycache__/pickle.cpython-312.pyc index 90f7d91d..d0efb488 100644 Binary files a/venv/Lib/site-packages/pandas/io/__pycache__/pickle.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/__pycache__/pickle.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/__pycache__/pytables.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/__pycache__/pytables.cpython-312.pyc index c4b5151d..cec7fd4b 100644 Binary files a/venv/Lib/site-packages/pandas/io/__pycache__/pytables.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/__pycache__/pytables.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/__pycache__/spss.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/__pycache__/spss.cpython-312.pyc index b7069001..6cc69756 100644 Binary files a/venv/Lib/site-packages/pandas/io/__pycache__/spss.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/__pycache__/spss.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/__pycache__/sql.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/__pycache__/sql.cpython-312.pyc index c0e93c46..74dda29c 100644 Binary files a/venv/Lib/site-packages/pandas/io/__pycache__/sql.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/__pycache__/sql.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/__pycache__/stata.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/__pycache__/stata.cpython-312.pyc index 516e237f..12417b90 100644 Binary files a/venv/Lib/site-packages/pandas/io/__pycache__/stata.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/__pycache__/stata.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/__pycache__/xml.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/__pycache__/xml.cpython-312.pyc index 4c33c8be..594703cc 100644 Binary files a/venv/Lib/site-packages/pandas/io/__pycache__/xml.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/__pycache__/xml.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/excel/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/excel/__pycache__/__init__.cpython-312.pyc index 738c37a7..5c4a016a 100644 Binary files a/venv/Lib/site-packages/pandas/io/excel/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/excel/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/excel/__pycache__/_base.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/excel/__pycache__/_base.cpython-312.pyc index ecb70079..2ee0d3ec 100644 Binary files a/venv/Lib/site-packages/pandas/io/excel/__pycache__/_base.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/excel/__pycache__/_base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/excel/__pycache__/_calamine.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/excel/__pycache__/_calamine.cpython-312.pyc index bf07f69c..578ec6dd 100644 Binary files a/venv/Lib/site-packages/pandas/io/excel/__pycache__/_calamine.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/excel/__pycache__/_calamine.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/excel/__pycache__/_odfreader.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/excel/__pycache__/_odfreader.cpython-312.pyc index fdc872cc..46b6736a 100644 Binary files a/venv/Lib/site-packages/pandas/io/excel/__pycache__/_odfreader.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/excel/__pycache__/_odfreader.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/excel/__pycache__/_odswriter.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/excel/__pycache__/_odswriter.cpython-312.pyc index 4a30de80..dba2bb51 100644 Binary files a/venv/Lib/site-packages/pandas/io/excel/__pycache__/_odswriter.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/excel/__pycache__/_odswriter.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/excel/__pycache__/_openpyxl.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/excel/__pycache__/_openpyxl.cpython-312.pyc index da9cb5ad..d973fb10 100644 Binary files a/venv/Lib/site-packages/pandas/io/excel/__pycache__/_openpyxl.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/excel/__pycache__/_openpyxl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/excel/__pycache__/_pyxlsb.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/excel/__pycache__/_pyxlsb.cpython-312.pyc index 8aeb3655..a981901b 100644 Binary files a/venv/Lib/site-packages/pandas/io/excel/__pycache__/_pyxlsb.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/excel/__pycache__/_pyxlsb.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/excel/__pycache__/_util.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/excel/__pycache__/_util.cpython-312.pyc index 99d376e4..fbface06 100644 Binary files a/venv/Lib/site-packages/pandas/io/excel/__pycache__/_util.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/excel/__pycache__/_util.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/excel/__pycache__/_xlrd.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/excel/__pycache__/_xlrd.cpython-312.pyc index fab443ad..0531334d 100644 Binary files a/venv/Lib/site-packages/pandas/io/excel/__pycache__/_xlrd.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/excel/__pycache__/_xlrd.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/excel/__pycache__/_xlsxwriter.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/excel/__pycache__/_xlsxwriter.cpython-312.pyc index 80b5c571..f7eef104 100644 Binary files a/venv/Lib/site-packages/pandas/io/excel/__pycache__/_xlsxwriter.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/excel/__pycache__/_xlsxwriter.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/formats/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/formats/__pycache__/__init__.cpython-312.pyc index d8a50d8d..e999c8fb 100644 Binary files a/venv/Lib/site-packages/pandas/io/formats/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/formats/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/formats/__pycache__/console.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/formats/__pycache__/console.cpython-312.pyc index 8dfd8a8f..09bacd1f 100644 Binary files a/venv/Lib/site-packages/pandas/io/formats/__pycache__/console.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/formats/__pycache__/console.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/formats/__pycache__/csvs.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/formats/__pycache__/csvs.cpython-312.pyc index d4749c35..b6cfd6f6 100644 Binary files a/venv/Lib/site-packages/pandas/io/formats/__pycache__/csvs.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/formats/__pycache__/csvs.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/formats/__pycache__/format.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/formats/__pycache__/format.cpython-312.pyc index 889eaadc..03af0a76 100644 Binary files a/venv/Lib/site-packages/pandas/io/formats/__pycache__/format.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/formats/__pycache__/format.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/formats/__pycache__/info.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/formats/__pycache__/info.cpython-312.pyc index 8015f342..ce5c1e5f 100644 Binary files a/venv/Lib/site-packages/pandas/io/formats/__pycache__/info.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/formats/__pycache__/info.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/formats/__pycache__/printing.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/formats/__pycache__/printing.cpython-312.pyc index f92190bc..5526ef32 100644 Binary files a/venv/Lib/site-packages/pandas/io/formats/__pycache__/printing.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/formats/__pycache__/printing.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/json/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/json/__pycache__/__init__.cpython-312.pyc index 759ac9ff..6b3f3711 100644 Binary files a/venv/Lib/site-packages/pandas/io/json/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/json/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/json/__pycache__/_json.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/json/__pycache__/_json.cpython-312.pyc index ce32e60a..25021d34 100644 Binary files a/venv/Lib/site-packages/pandas/io/json/__pycache__/_json.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/json/__pycache__/_json.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/json/__pycache__/_normalize.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/json/__pycache__/_normalize.cpython-312.pyc index 393fe07e..3967631e 100644 Binary files a/venv/Lib/site-packages/pandas/io/json/__pycache__/_normalize.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/json/__pycache__/_normalize.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/json/__pycache__/_table_schema.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/json/__pycache__/_table_schema.cpython-312.pyc index b69dac40..b450c459 100644 Binary files a/venv/Lib/site-packages/pandas/io/json/__pycache__/_table_schema.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/json/__pycache__/_table_schema.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/parsers/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/parsers/__pycache__/__init__.cpython-312.pyc index c04a3cb7..5aa20b03 100644 Binary files a/venv/Lib/site-packages/pandas/io/parsers/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/parsers/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/parsers/__pycache__/arrow_parser_wrapper.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/parsers/__pycache__/arrow_parser_wrapper.cpython-312.pyc index bc73a46b..f36034a8 100644 Binary files a/venv/Lib/site-packages/pandas/io/parsers/__pycache__/arrow_parser_wrapper.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/parsers/__pycache__/arrow_parser_wrapper.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/parsers/__pycache__/base_parser.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/parsers/__pycache__/base_parser.cpython-312.pyc index 2ce296b1..f4c4d1d6 100644 Binary files a/venv/Lib/site-packages/pandas/io/parsers/__pycache__/base_parser.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/parsers/__pycache__/base_parser.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/parsers/__pycache__/c_parser_wrapper.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/parsers/__pycache__/c_parser_wrapper.cpython-312.pyc index 9328e5f2..8b4a153c 100644 Binary files a/venv/Lib/site-packages/pandas/io/parsers/__pycache__/c_parser_wrapper.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/parsers/__pycache__/c_parser_wrapper.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/parsers/__pycache__/python_parser.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/parsers/__pycache__/python_parser.cpython-312.pyc index a7862d6c..dd24f632 100644 Binary files a/venv/Lib/site-packages/pandas/io/parsers/__pycache__/python_parser.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/parsers/__pycache__/python_parser.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/parsers/__pycache__/readers.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/parsers/__pycache__/readers.cpython-312.pyc index d5162538..a246c764 100644 Binary files a/venv/Lib/site-packages/pandas/io/parsers/__pycache__/readers.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/parsers/__pycache__/readers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/sas/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/sas/__pycache__/__init__.cpython-312.pyc index e899a0cc..e562bb3a 100644 Binary files a/venv/Lib/site-packages/pandas/io/sas/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/sas/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/io/sas/__pycache__/sasreader.cpython-312.pyc b/venv/Lib/site-packages/pandas/io/sas/__pycache__/sasreader.cpython-312.pyc index 975bc1a1..a957637b 100644 Binary files a/venv/Lib/site-packages/pandas/io/sas/__pycache__/sasreader.cpython-312.pyc and b/venv/Lib/site-packages/pandas/io/sas/__pycache__/sasreader.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/plotting/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/plotting/__pycache__/__init__.cpython-312.pyc index 69254932..d4eea7e0 100644 Binary files a/venv/Lib/site-packages/pandas/plotting/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/plotting/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/plotting/__pycache__/_core.cpython-312.pyc b/venv/Lib/site-packages/pandas/plotting/__pycache__/_core.cpython-312.pyc index e071cd94..b1be9191 100644 Binary files a/venv/Lib/site-packages/pandas/plotting/__pycache__/_core.cpython-312.pyc and b/venv/Lib/site-packages/pandas/plotting/__pycache__/_core.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/plotting/__pycache__/_misc.cpython-312.pyc b/venv/Lib/site-packages/pandas/plotting/__pycache__/_misc.cpython-312.pyc index b152a16d..3f2e4f8f 100644 Binary files a/venv/Lib/site-packages/pandas/plotting/__pycache__/_misc.cpython-312.pyc and b/venv/Lib/site-packages/pandas/plotting/__pycache__/_misc.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/tseries/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/tseries/__pycache__/__init__.cpython-312.pyc index 12f89ff2..bad0800c 100644 Binary files a/venv/Lib/site-packages/pandas/tseries/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/tseries/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/tseries/__pycache__/api.cpython-312.pyc b/venv/Lib/site-packages/pandas/tseries/__pycache__/api.cpython-312.pyc index 6b617315..93984ef2 100644 Binary files a/venv/Lib/site-packages/pandas/tseries/__pycache__/api.cpython-312.pyc and b/venv/Lib/site-packages/pandas/tseries/__pycache__/api.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/tseries/__pycache__/frequencies.cpython-312.pyc b/venv/Lib/site-packages/pandas/tseries/__pycache__/frequencies.cpython-312.pyc index de803f43..dcf149d3 100644 Binary files a/venv/Lib/site-packages/pandas/tseries/__pycache__/frequencies.cpython-312.pyc and b/venv/Lib/site-packages/pandas/tseries/__pycache__/frequencies.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/tseries/__pycache__/offsets.cpython-312.pyc b/venv/Lib/site-packages/pandas/tseries/__pycache__/offsets.cpython-312.pyc index c6035486..aab43ac7 100644 Binary files a/venv/Lib/site-packages/pandas/tseries/__pycache__/offsets.cpython-312.pyc and b/venv/Lib/site-packages/pandas/tseries/__pycache__/offsets.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/util/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/util/__pycache__/__init__.cpython-312.pyc index 4e168e49..ad504c00 100644 Binary files a/venv/Lib/site-packages/pandas/util/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/util/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/util/__pycache__/_decorators.cpython-312.pyc b/venv/Lib/site-packages/pandas/util/__pycache__/_decorators.cpython-312.pyc index 404240d4..a2433122 100644 Binary files a/venv/Lib/site-packages/pandas/util/__pycache__/_decorators.cpython-312.pyc and b/venv/Lib/site-packages/pandas/util/__pycache__/_decorators.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/util/__pycache__/_exceptions.cpython-312.pyc b/venv/Lib/site-packages/pandas/util/__pycache__/_exceptions.cpython-312.pyc index 6ca00f99..47e22be9 100644 Binary files a/venv/Lib/site-packages/pandas/util/__pycache__/_exceptions.cpython-312.pyc and b/venv/Lib/site-packages/pandas/util/__pycache__/_exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/util/__pycache__/_print_versions.cpython-312.pyc b/venv/Lib/site-packages/pandas/util/__pycache__/_print_versions.cpython-312.pyc index beb393e1..777b0cbb 100644 Binary files a/venv/Lib/site-packages/pandas/util/__pycache__/_print_versions.cpython-312.pyc and b/venv/Lib/site-packages/pandas/util/__pycache__/_print_versions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/util/__pycache__/_tester.cpython-312.pyc b/venv/Lib/site-packages/pandas/util/__pycache__/_tester.cpython-312.pyc index 5cd4f72e..0281e66d 100644 Binary files a/venv/Lib/site-packages/pandas/util/__pycache__/_tester.cpython-312.pyc and b/venv/Lib/site-packages/pandas/util/__pycache__/_tester.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/util/__pycache__/_validators.cpython-312.pyc b/venv/Lib/site-packages/pandas/util/__pycache__/_validators.cpython-312.pyc index 4cd998b2..4c316bb4 100644 Binary files a/venv/Lib/site-packages/pandas/util/__pycache__/_validators.cpython-312.pyc and b/venv/Lib/site-packages/pandas/util/__pycache__/_validators.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pandas/util/version/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pandas/util/version/__pycache__/__init__.cpython-312.pyc index 66b99c2c..43bb7889 100644 Binary files a/venv/Lib/site-packages/pandas/util/version/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pandas/util/version/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/__pycache__/__init__.cpython-312.pyc index c623f8d3..fe8fe004 100644 Binary files a/venv/Lib/site-packages/pip/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/__pycache__/__init__.cpython-312.pyc index 251d8a03..819661c5 100644 Binary files a/venv/Lib/site-packages/pip/_internal/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/__pycache__/build_env.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/__pycache__/build_env.cpython-312.pyc index d2e5bc6e..2618cf63 100644 Binary files a/venv/Lib/site-packages/pip/_internal/__pycache__/build_env.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/__pycache__/build_env.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/__pycache__/cache.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/__pycache__/cache.cpython-312.pyc index ee375d3b..1a078920 100644 Binary files a/venv/Lib/site-packages/pip/_internal/__pycache__/cache.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/__pycache__/cache.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/__pycache__/configuration.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/__pycache__/configuration.cpython-312.pyc index 7297d567..ae64dd3a 100644 Binary files a/venv/Lib/site-packages/pip/_internal/__pycache__/configuration.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/__pycache__/configuration.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/__pycache__/exceptions.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/__pycache__/exceptions.cpython-312.pyc index de0bdba1..998a22ae 100644 Binary files a/venv/Lib/site-packages/pip/_internal/__pycache__/exceptions.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/__pycache__/exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/__pycache__/pyproject.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/__pycache__/pyproject.cpython-312.pyc index 988daa52..3848e33c 100644 Binary files a/venv/Lib/site-packages/pip/_internal/__pycache__/pyproject.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/__pycache__/pyproject.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/__pycache__/self_outdated_check.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/__pycache__/self_outdated_check.cpython-312.pyc index 873b03fe..5e681f5a 100644 Binary files a/venv/Lib/site-packages/pip/_internal/__pycache__/self_outdated_check.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/__pycache__/self_outdated_check.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/__pycache__/wheel_builder.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/__pycache__/wheel_builder.cpython-312.pyc index bdafee07..16054d15 100644 Binary files a/venv/Lib/site-packages/pip/_internal/__pycache__/wheel_builder.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/__pycache__/wheel_builder.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/cli/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/cli/__pycache__/__init__.cpython-312.pyc index 4979f017..5ad7aa59 100644 Binary files a/venv/Lib/site-packages/pip/_internal/cli/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/cli/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/cli/__pycache__/autocompletion.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/cli/__pycache__/autocompletion.cpython-312.pyc index 08bb3507..4ecc7fb2 100644 Binary files a/venv/Lib/site-packages/pip/_internal/cli/__pycache__/autocompletion.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/cli/__pycache__/autocompletion.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/cli/__pycache__/base_command.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/cli/__pycache__/base_command.cpython-312.pyc index 1613ca04..bfaa01c8 100644 Binary files a/venv/Lib/site-packages/pip/_internal/cli/__pycache__/base_command.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/cli/__pycache__/base_command.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/cli/__pycache__/cmdoptions.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/cli/__pycache__/cmdoptions.cpython-312.pyc index f11cac48..02ba0532 100644 Binary files a/venv/Lib/site-packages/pip/_internal/cli/__pycache__/cmdoptions.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/cli/__pycache__/cmdoptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/cli/__pycache__/command_context.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/cli/__pycache__/command_context.cpython-312.pyc index 03d18899..c7c06ea1 100644 Binary files a/venv/Lib/site-packages/pip/_internal/cli/__pycache__/command_context.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/cli/__pycache__/command_context.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/cli/__pycache__/main.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/cli/__pycache__/main.cpython-312.pyc index efe5c7c7..aa0854e8 100644 Binary files a/venv/Lib/site-packages/pip/_internal/cli/__pycache__/main.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/cli/__pycache__/main.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/cli/__pycache__/main_parser.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/cli/__pycache__/main_parser.cpython-312.pyc index fce18ea7..409520db 100644 Binary files a/venv/Lib/site-packages/pip/_internal/cli/__pycache__/main_parser.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/cli/__pycache__/main_parser.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/cli/__pycache__/parser.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/cli/__pycache__/parser.cpython-312.pyc index a8ff6488..06be0eb0 100644 Binary files a/venv/Lib/site-packages/pip/_internal/cli/__pycache__/parser.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/cli/__pycache__/parser.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/cli/__pycache__/progress_bars.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/cli/__pycache__/progress_bars.cpython-312.pyc index 650966c0..356d0fff 100644 Binary files a/venv/Lib/site-packages/pip/_internal/cli/__pycache__/progress_bars.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/cli/__pycache__/progress_bars.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/cli/__pycache__/req_command.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/cli/__pycache__/req_command.cpython-312.pyc index c6967013..4281f84c 100644 Binary files a/venv/Lib/site-packages/pip/_internal/cli/__pycache__/req_command.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/cli/__pycache__/req_command.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/cli/__pycache__/spinners.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/cli/__pycache__/spinners.cpython-312.pyc index ba240a44..6a515f92 100644 Binary files a/venv/Lib/site-packages/pip/_internal/cli/__pycache__/spinners.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/cli/__pycache__/spinners.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/cli/__pycache__/status_codes.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/cli/__pycache__/status_codes.cpython-312.pyc index 9b0205cb..fa0abf74 100644 Binary files a/venv/Lib/site-packages/pip/_internal/cli/__pycache__/status_codes.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/cli/__pycache__/status_codes.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/commands/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/commands/__pycache__/__init__.cpython-312.pyc index 91d203d4..2f4f4b00 100644 Binary files a/venv/Lib/site-packages/pip/_internal/commands/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/commands/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/commands/__pycache__/install.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/commands/__pycache__/install.cpython-312.pyc index d84f4ce6..78afbea6 100644 Binary files a/venv/Lib/site-packages/pip/_internal/commands/__pycache__/install.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/commands/__pycache__/install.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/commands/__pycache__/uninstall.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/commands/__pycache__/uninstall.cpython-312.pyc index 987a5974..47d5ac96 100644 Binary files a/venv/Lib/site-packages/pip/_internal/commands/__pycache__/uninstall.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/commands/__pycache__/uninstall.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/distributions/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/distributions/__pycache__/__init__.cpython-312.pyc index 32497d8d..c6976399 100644 Binary files a/venv/Lib/site-packages/pip/_internal/distributions/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/distributions/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/distributions/__pycache__/base.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/distributions/__pycache__/base.cpython-312.pyc index 8e0f564a..ad6af117 100644 Binary files a/venv/Lib/site-packages/pip/_internal/distributions/__pycache__/base.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/distributions/__pycache__/base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/distributions/__pycache__/installed.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/distributions/__pycache__/installed.cpython-312.pyc index e4949acc..71ee4cd8 100644 Binary files a/venv/Lib/site-packages/pip/_internal/distributions/__pycache__/installed.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/distributions/__pycache__/installed.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/distributions/__pycache__/sdist.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/distributions/__pycache__/sdist.cpython-312.pyc index 017dce8d..a6596232 100644 Binary files a/venv/Lib/site-packages/pip/_internal/distributions/__pycache__/sdist.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/distributions/__pycache__/sdist.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/distributions/__pycache__/wheel.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/distributions/__pycache__/wheel.cpython-312.pyc index 0dcd876d..dcd568f5 100644 Binary files a/venv/Lib/site-packages/pip/_internal/distributions/__pycache__/wheel.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/distributions/__pycache__/wheel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/index/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/index/__pycache__/__init__.cpython-312.pyc index f6575a7e..63868825 100644 Binary files a/venv/Lib/site-packages/pip/_internal/index/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/index/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/index/__pycache__/collector.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/index/__pycache__/collector.cpython-312.pyc index bb58f087..2d4b5c3b 100644 Binary files a/venv/Lib/site-packages/pip/_internal/index/__pycache__/collector.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/index/__pycache__/collector.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/index/__pycache__/package_finder.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/index/__pycache__/package_finder.cpython-312.pyc index eac6e063..d7a866fe 100644 Binary files a/venv/Lib/site-packages/pip/_internal/index/__pycache__/package_finder.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/index/__pycache__/package_finder.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/index/__pycache__/sources.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/index/__pycache__/sources.cpython-312.pyc index 7b678ee2..8412079d 100644 Binary files a/venv/Lib/site-packages/pip/_internal/index/__pycache__/sources.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/index/__pycache__/sources.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/locations/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/locations/__pycache__/__init__.cpython-312.pyc index 2807f4ea..fa49a444 100644 Binary files a/venv/Lib/site-packages/pip/_internal/locations/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/locations/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/locations/__pycache__/_sysconfig.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/locations/__pycache__/_sysconfig.cpython-312.pyc index 2b6d12bd..b40fb780 100644 Binary files a/venv/Lib/site-packages/pip/_internal/locations/__pycache__/_sysconfig.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/locations/__pycache__/_sysconfig.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/locations/__pycache__/base.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/locations/__pycache__/base.cpython-312.pyc index efd9dbd3..84d3c6aa 100644 Binary files a/venv/Lib/site-packages/pip/_internal/locations/__pycache__/base.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/locations/__pycache__/base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/metadata/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/metadata/__pycache__/__init__.cpython-312.pyc index cbec41af..29fb874d 100644 Binary files a/venv/Lib/site-packages/pip/_internal/metadata/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/metadata/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/metadata/__pycache__/_json.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/metadata/__pycache__/_json.cpython-312.pyc index 3af3de0f..d7aa5815 100644 Binary files a/venv/Lib/site-packages/pip/_internal/metadata/__pycache__/_json.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/metadata/__pycache__/_json.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/metadata/__pycache__/base.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/metadata/__pycache__/base.cpython-312.pyc index 86950b7b..2fa19c45 100644 Binary files a/venv/Lib/site-packages/pip/_internal/metadata/__pycache__/base.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/metadata/__pycache__/base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/metadata/__pycache__/pkg_resources.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/metadata/__pycache__/pkg_resources.cpython-312.pyc index 852734f5..6ee9629c 100644 Binary files a/venv/Lib/site-packages/pip/_internal/metadata/__pycache__/pkg_resources.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/metadata/__pycache__/pkg_resources.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/metadata/importlib/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/metadata/importlib/__pycache__/__init__.cpython-312.pyc index 393b9ce4..be47b42e 100644 Binary files a/venv/Lib/site-packages/pip/_internal/metadata/importlib/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/metadata/importlib/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/metadata/importlib/__pycache__/_compat.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/metadata/importlib/__pycache__/_compat.cpython-312.pyc index 2b3f3156..b26c4372 100644 Binary files a/venv/Lib/site-packages/pip/_internal/metadata/importlib/__pycache__/_compat.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/metadata/importlib/__pycache__/_compat.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/metadata/importlib/__pycache__/_dists.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/metadata/importlib/__pycache__/_dists.cpython-312.pyc index e7b3c543..385e0532 100644 Binary files a/venv/Lib/site-packages/pip/_internal/metadata/importlib/__pycache__/_dists.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/metadata/importlib/__pycache__/_dists.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/metadata/importlib/__pycache__/_envs.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/metadata/importlib/__pycache__/_envs.cpython-312.pyc index 84afb51e..c8212515 100644 Binary files a/venv/Lib/site-packages/pip/_internal/metadata/importlib/__pycache__/_envs.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/metadata/importlib/__pycache__/_envs.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/models/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/models/__pycache__/__init__.cpython-312.pyc index 8d196e48..1b02d8b3 100644 Binary files a/venv/Lib/site-packages/pip/_internal/models/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/models/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/models/__pycache__/candidate.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/models/__pycache__/candidate.cpython-312.pyc index fadc0010..1d37ff17 100644 Binary files a/venv/Lib/site-packages/pip/_internal/models/__pycache__/candidate.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/models/__pycache__/candidate.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/models/__pycache__/direct_url.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/models/__pycache__/direct_url.cpython-312.pyc index 98dc38b0..44f50623 100644 Binary files a/venv/Lib/site-packages/pip/_internal/models/__pycache__/direct_url.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/models/__pycache__/direct_url.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/models/__pycache__/format_control.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/models/__pycache__/format_control.cpython-312.pyc index 7c96a2e9..99ed746c 100644 Binary files a/venv/Lib/site-packages/pip/_internal/models/__pycache__/format_control.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/models/__pycache__/format_control.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/models/__pycache__/index.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/models/__pycache__/index.cpython-312.pyc index b483a1d9..0a06f4cb 100644 Binary files a/venv/Lib/site-packages/pip/_internal/models/__pycache__/index.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/models/__pycache__/index.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/models/__pycache__/installation_report.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/models/__pycache__/installation_report.cpython-312.pyc index a7f682cb..754a1d06 100644 Binary files a/venv/Lib/site-packages/pip/_internal/models/__pycache__/installation_report.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/models/__pycache__/installation_report.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/models/__pycache__/link.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/models/__pycache__/link.cpython-312.pyc index 803d8a77..42f32211 100644 Binary files a/venv/Lib/site-packages/pip/_internal/models/__pycache__/link.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/models/__pycache__/link.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/models/__pycache__/scheme.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/models/__pycache__/scheme.cpython-312.pyc index 53ff205a..d13870fa 100644 Binary files a/venv/Lib/site-packages/pip/_internal/models/__pycache__/scheme.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/models/__pycache__/scheme.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/models/__pycache__/search_scope.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/models/__pycache__/search_scope.cpython-312.pyc index 56f666e3..598440ee 100644 Binary files a/venv/Lib/site-packages/pip/_internal/models/__pycache__/search_scope.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/models/__pycache__/search_scope.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/models/__pycache__/selection_prefs.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/models/__pycache__/selection_prefs.cpython-312.pyc index 66731265..71f75120 100644 Binary files a/venv/Lib/site-packages/pip/_internal/models/__pycache__/selection_prefs.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/models/__pycache__/selection_prefs.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/models/__pycache__/target_python.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/models/__pycache__/target_python.cpython-312.pyc index f6ac4e7f..3cb635c5 100644 Binary files a/venv/Lib/site-packages/pip/_internal/models/__pycache__/target_python.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/models/__pycache__/target_python.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/models/__pycache__/wheel.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/models/__pycache__/wheel.cpython-312.pyc index 3e486237..ec359919 100644 Binary files a/venv/Lib/site-packages/pip/_internal/models/__pycache__/wheel.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/models/__pycache__/wheel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/network/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/network/__pycache__/__init__.cpython-312.pyc index 02963e50..1386ae25 100644 Binary files a/venv/Lib/site-packages/pip/_internal/network/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/network/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/network/__pycache__/auth.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/network/__pycache__/auth.cpython-312.pyc index c3661311..17bf668b 100644 Binary files a/venv/Lib/site-packages/pip/_internal/network/__pycache__/auth.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/network/__pycache__/auth.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/network/__pycache__/cache.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/network/__pycache__/cache.cpython-312.pyc index 91cc5729..be4f38ba 100644 Binary files a/venv/Lib/site-packages/pip/_internal/network/__pycache__/cache.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/network/__pycache__/cache.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/network/__pycache__/download.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/network/__pycache__/download.cpython-312.pyc index 0a47edf4..fa8e45fb 100644 Binary files a/venv/Lib/site-packages/pip/_internal/network/__pycache__/download.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/network/__pycache__/download.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/network/__pycache__/lazy_wheel.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/network/__pycache__/lazy_wheel.cpython-312.pyc index e350bf67..49164d2f 100644 Binary files a/venv/Lib/site-packages/pip/_internal/network/__pycache__/lazy_wheel.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/network/__pycache__/lazy_wheel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/network/__pycache__/session.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/network/__pycache__/session.cpython-312.pyc index ee5ac4cc..ee9052f2 100644 Binary files a/venv/Lib/site-packages/pip/_internal/network/__pycache__/session.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/network/__pycache__/session.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/network/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/network/__pycache__/utils.cpython-312.pyc index a0f78baf..c672d8e9 100644 Binary files a/venv/Lib/site-packages/pip/_internal/network/__pycache__/utils.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/network/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/operations/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/operations/__pycache__/__init__.cpython-312.pyc index 0f81fc2d..57e758f4 100644 Binary files a/venv/Lib/site-packages/pip/_internal/operations/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/operations/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/operations/__pycache__/check.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/operations/__pycache__/check.cpython-312.pyc index b68d8cc0..249d6ed2 100644 Binary files a/venv/Lib/site-packages/pip/_internal/operations/__pycache__/check.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/operations/__pycache__/check.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/operations/__pycache__/prepare.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/operations/__pycache__/prepare.cpython-312.pyc index cc707f80..07efaba6 100644 Binary files a/venv/Lib/site-packages/pip/_internal/operations/__pycache__/prepare.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/operations/__pycache__/prepare.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/__init__.cpython-312.pyc index 4c911b01..e2dddc63 100644 Binary files a/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/build_tracker.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/build_tracker.cpython-312.pyc index c1e9b2cb..ed4f98e1 100644 Binary files a/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/build_tracker.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/build_tracker.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/metadata.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/metadata.cpython-312.pyc index 1eb5ae37..871443d9 100644 Binary files a/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/metadata.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/metadata.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/metadata_editable.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/metadata_editable.cpython-312.pyc index 191ca44a..edc7896e 100644 Binary files a/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/metadata_editable.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/metadata_editable.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/metadata_legacy.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/metadata_legacy.cpython-312.pyc index 49449e86..acb3bead 100644 Binary files a/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/metadata_legacy.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/metadata_legacy.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/wheel.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/wheel.cpython-312.pyc index 7789bb3b..7baba89a 100644 Binary files a/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/wheel.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/wheel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/wheel_editable.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/wheel_editable.cpython-312.pyc index 820a1871..fbffa562 100644 Binary files a/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/wheel_editable.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/wheel_editable.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/wheel_legacy.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/wheel_legacy.cpython-312.pyc index b030e3b9..cc1f31d6 100644 Binary files a/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/wheel_legacy.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/wheel_legacy.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/operations/install/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/operations/install/__pycache__/__init__.cpython-312.pyc index c71b282f..bfe68902 100644 Binary files a/venv/Lib/site-packages/pip/_internal/operations/install/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/operations/install/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/operations/install/__pycache__/editable_legacy.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/operations/install/__pycache__/editable_legacy.cpython-312.pyc index 0ee9811c..ee82a7e5 100644 Binary files a/venv/Lib/site-packages/pip/_internal/operations/install/__pycache__/editable_legacy.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/operations/install/__pycache__/editable_legacy.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/operations/install/__pycache__/wheel.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/operations/install/__pycache__/wheel.cpython-312.pyc index e641a125..f45f71be 100644 Binary files a/venv/Lib/site-packages/pip/_internal/operations/install/__pycache__/wheel.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/operations/install/__pycache__/wheel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/req/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/req/__pycache__/__init__.cpython-312.pyc index 5dee07df..3e26e539 100644 Binary files a/venv/Lib/site-packages/pip/_internal/req/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/req/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/req/__pycache__/constructors.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/req/__pycache__/constructors.cpython-312.pyc index 90562fb4..7433b11f 100644 Binary files a/venv/Lib/site-packages/pip/_internal/req/__pycache__/constructors.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/req/__pycache__/constructors.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/req/__pycache__/req_file.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/req/__pycache__/req_file.cpython-312.pyc index fd8cc038..5e6dfee7 100644 Binary files a/venv/Lib/site-packages/pip/_internal/req/__pycache__/req_file.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/req/__pycache__/req_file.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/req/__pycache__/req_install.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/req/__pycache__/req_install.cpython-312.pyc index 0c637f22..33c50af0 100644 Binary files a/venv/Lib/site-packages/pip/_internal/req/__pycache__/req_install.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/req/__pycache__/req_install.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/req/__pycache__/req_set.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/req/__pycache__/req_set.cpython-312.pyc index 60fa5d5b..8e023fbc 100644 Binary files a/venv/Lib/site-packages/pip/_internal/req/__pycache__/req_set.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/req/__pycache__/req_set.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/req/__pycache__/req_uninstall.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/req/__pycache__/req_uninstall.cpython-312.pyc index bf06e8b2..863f7ea3 100644 Binary files a/venv/Lib/site-packages/pip/_internal/req/__pycache__/req_uninstall.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/req/__pycache__/req_uninstall.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/resolution/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/resolution/__pycache__/__init__.cpython-312.pyc index 9340045c..d62708a9 100644 Binary files a/venv/Lib/site-packages/pip/_internal/resolution/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/resolution/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/resolution/__pycache__/base.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/resolution/__pycache__/base.cpython-312.pyc index 509ec0f5..99c469e5 100644 Binary files a/venv/Lib/site-packages/pip/_internal/resolution/__pycache__/base.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/resolution/__pycache__/base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/__init__.cpython-312.pyc index 39785517..469d5f98 100644 Binary files a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/base.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/base.cpython-312.pyc index 921811fa..9af71ff2 100644 Binary files a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/base.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/candidates.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/candidates.cpython-312.pyc index 36bf898d..395c70cf 100644 Binary files a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/candidates.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/candidates.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/factory.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/factory.cpython-312.pyc index 11f3ad0a..7e4d1735 100644 Binary files a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/factory.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/factory.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/found_candidates.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/found_candidates.cpython-312.pyc index c06c45d4..d67ba561 100644 Binary files a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/found_candidates.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/found_candidates.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/provider.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/provider.cpython-312.pyc index f44b0621..f5106dcf 100644 Binary files a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/provider.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/provider.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/reporter.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/reporter.cpython-312.pyc index 88449bdb..8c14044c 100644 Binary files a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/reporter.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/reporter.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/requirements.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/requirements.cpython-312.pyc index 2a99cbc1..7eedc6ca 100644 Binary files a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/requirements.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/requirements.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/resolver.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/resolver.cpython-312.pyc index b5ff8973..b3dc8802 100644 Binary files a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/resolver.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/resolver.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/__init__.cpython-312.pyc index 16a8d73d..bb12f0f2 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/_jaraco_text.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/_jaraco_text.cpython-312.pyc index cb188e11..865a4a4a 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/_jaraco_text.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/_jaraco_text.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/_log.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/_log.cpython-312.pyc index 854e0457..d5179584 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/_log.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/_log.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/appdirs.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/appdirs.cpython-312.pyc index bbddfb3d..28ecebbe 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/appdirs.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/appdirs.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/compat.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/compat.cpython-312.pyc index 158d3bcb..9003310e 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/compat.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/compat.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/compatibility_tags.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/compatibility_tags.cpython-312.pyc index 64b6bbd8..8862f4a2 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/compatibility_tags.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/compatibility_tags.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/deprecation.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/deprecation.cpython-312.pyc index 72afd8a1..f56ee82f 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/deprecation.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/deprecation.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/direct_url_helpers.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/direct_url_helpers.cpython-312.pyc index 72a93a35..be5f791c 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/direct_url_helpers.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/direct_url_helpers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/egg_link.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/egg_link.cpython-312.pyc index 355573d7..afda5be3 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/egg_link.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/egg_link.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/encoding.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/encoding.cpython-312.pyc index 2304fbfd..1133df0f 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/encoding.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/encoding.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/entrypoints.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/entrypoints.cpython-312.pyc index dd751fd1..f68ca162 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/entrypoints.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/entrypoints.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/filesystem.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/filesystem.cpython-312.pyc index d406f35a..7ae6b469 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/filesystem.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/filesystem.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/filetypes.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/filetypes.cpython-312.pyc index cc0a56a0..def56fbc 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/filetypes.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/filetypes.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/glibc.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/glibc.cpython-312.pyc index cb2b4a83..48a89869 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/glibc.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/glibc.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/hashes.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/hashes.cpython-312.pyc index 33d7e907..89c3a269 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/hashes.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/hashes.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/logging.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/logging.cpython-312.pyc index 9817053d..5737a696 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/logging.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/logging.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/misc.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/misc.cpython-312.pyc index 7d5fd2b3..a02072f8 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/misc.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/misc.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/models.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/models.cpython-312.pyc index e656677f..bd61e903 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/models.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/models.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/packaging.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/packaging.cpython-312.pyc index 5b88cc71..58c3ae13 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/packaging.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/packaging.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/setuptools_build.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/setuptools_build.cpython-312.pyc index 738a1b7d..33bd9556 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/setuptools_build.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/setuptools_build.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/subprocess.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/subprocess.cpython-312.pyc index daa00a5e..fd9e1857 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/subprocess.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/subprocess.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/temp_dir.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/temp_dir.cpython-312.pyc index 8d40b61b..b01cd063 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/temp_dir.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/temp_dir.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/unpacking.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/unpacking.cpython-312.pyc index 0020fae3..147eb2be 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/unpacking.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/unpacking.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/urls.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/urls.cpython-312.pyc index c0613f7d..930b4e02 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/urls.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/urls.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/virtualenv.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/virtualenv.cpython-312.pyc index ac20d867..dd455203 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/virtualenv.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/virtualenv.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/wheel.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/wheel.cpython-312.pyc index c08fc4c7..7c6e432b 100644 Binary files a/venv/Lib/site-packages/pip/_internal/utils/__pycache__/wheel.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/utils/__pycache__/wheel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/__init__.cpython-312.pyc index 188cf467..b824b25b 100644 Binary files a/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/bazaar.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/bazaar.cpython-312.pyc index e31835f6..a47c30d6 100644 Binary files a/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/bazaar.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/bazaar.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/git.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/git.cpython-312.pyc index 2c361f2d..1e37227c 100644 Binary files a/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/git.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/git.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/mercurial.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/mercurial.cpython-312.pyc index a49fea32..d50a8e63 100644 Binary files a/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/mercurial.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/mercurial.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/subversion.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/subversion.cpython-312.pyc index 29692d36..0ab5a0af 100644 Binary files a/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/subversion.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/subversion.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/versioncontrol.cpython-312.pyc b/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/versioncontrol.cpython-312.pyc index 06304203..057378c1 100644 Binary files a/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/versioncontrol.cpython-312.pyc and b/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/versioncontrol.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/__pycache__/__init__.cpython-312.pyc index b3cf8879..2331b57a 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/__init__.cpython-312.pyc index d3542b06..021ef74d 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/adapter.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/adapter.cpython-312.pyc index 03dbb4d8..266da169 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/adapter.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/adapter.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/cache.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/cache.cpython-312.pyc index 2a6ab4ac..1f4b2b99 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/cache.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/cache.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/controller.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/controller.cpython-312.pyc index aa86b016..aac5977d 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/controller.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/controller.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/filewrapper.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/filewrapper.cpython-312.pyc index 0636572d..4ce4b18d 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/filewrapper.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/filewrapper.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/serialize.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/serialize.cpython-312.pyc index eb351adb..79149042 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/serialize.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/serialize.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/wrapper.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/wrapper.cpython-312.pyc index 45324f7e..7c699900 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/wrapper.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/wrapper.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/__pycache__/__init__.cpython-312.pyc index 0c2a0a74..854c4d93 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/__pycache__/file_cache.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/__pycache__/file_cache.cpython-312.pyc index 33f7c426..ef18370b 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/__pycache__/file_cache.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/__pycache__/file_cache.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/__pycache__/redis_cache.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/__pycache__/redis_cache.cpython-312.pyc index 90abd28e..9a101792 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/__pycache__/redis_cache.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/__pycache__/redis_cache.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/certifi/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/certifi/__pycache__/__init__.cpython-312.pyc index d5c72291..6c6ec82c 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/certifi/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/certifi/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/certifi/__pycache__/core.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/certifi/__pycache__/core.cpython-312.pyc index e8d465ab..2f3b47f2 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/certifi/__pycache__/core.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/certifi/__pycache__/core.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/__init__.cpython-312.pyc index 995265b0..2281cd2e 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/big5freq.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/big5freq.cpython-312.pyc index 4da57e9f..b0903ab3 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/big5freq.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/big5freq.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/big5prober.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/big5prober.cpython-312.pyc index 09a1088c..6f7bf522 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/big5prober.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/big5prober.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/chardistribution.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/chardistribution.cpython-312.pyc index 07037225..09a20a7b 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/chardistribution.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/chardistribution.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/charsetgroupprober.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/charsetgroupprober.cpython-312.pyc index b8d98e4c..8a582062 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/charsetgroupprober.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/charsetgroupprober.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/charsetprober.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/charsetprober.cpython-312.pyc index 5b8bb873..947b1ec3 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/charsetprober.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/charsetprober.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/codingstatemachine.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/codingstatemachine.cpython-312.pyc index 0ce5a118..591ea1b8 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/codingstatemachine.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/codingstatemachine.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/codingstatemachinedict.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/codingstatemachinedict.cpython-312.pyc index 2dc13c4f..ddc518dd 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/codingstatemachinedict.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/codingstatemachinedict.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/cp949prober.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/cp949prober.cpython-312.pyc index e24b811b..abcbec51 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/cp949prober.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/cp949prober.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/enums.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/enums.cpython-312.pyc index a37e1478..fdabf5bd 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/enums.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/enums.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/escprober.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/escprober.cpython-312.pyc index 75cf25a5..db679a61 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/escprober.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/escprober.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/escsm.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/escsm.cpython-312.pyc index 92dc1d78..b52d010f 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/escsm.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/escsm.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/eucjpprober.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/eucjpprober.cpython-312.pyc index c893cc11..e4942ee6 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/eucjpprober.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/eucjpprober.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/euckrfreq.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/euckrfreq.cpython-312.pyc index fdc487a8..d2d1f80a 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/euckrfreq.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/euckrfreq.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/euckrprober.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/euckrprober.cpython-312.pyc index d16e79b6..b39f0dc4 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/euckrprober.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/euckrprober.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/euctwfreq.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/euctwfreq.cpython-312.pyc index 86704d87..3bbc18b7 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/euctwfreq.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/euctwfreq.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/euctwprober.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/euctwprober.cpython-312.pyc index b53f6f72..879bf753 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/euctwprober.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/euctwprober.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/gb2312freq.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/gb2312freq.cpython-312.pyc index 046524a7..cd08ea41 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/gb2312freq.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/gb2312freq.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/gb2312prober.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/gb2312prober.cpython-312.pyc index 91cae7b5..5c9e3c79 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/gb2312prober.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/gb2312prober.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/hebrewprober.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/hebrewprober.cpython-312.pyc index 2c758c3e..c4f78da2 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/hebrewprober.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/hebrewprober.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/jisfreq.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/jisfreq.cpython-312.pyc index 17881b6d..e8616838 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/jisfreq.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/jisfreq.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/johabfreq.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/johabfreq.cpython-312.pyc index ad7b6dea..796a8d73 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/johabfreq.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/johabfreq.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/johabprober.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/johabprober.cpython-312.pyc index fec4e5e0..a42b208b 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/johabprober.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/johabprober.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/jpcntx.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/jpcntx.cpython-312.pyc index 4a819880..2b85dd93 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/jpcntx.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/jpcntx.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/langbulgarianmodel.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/langbulgarianmodel.cpython-312.pyc index 04b3d128..b364acb1 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/langbulgarianmodel.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/langbulgarianmodel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/langgreekmodel.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/langgreekmodel.cpython-312.pyc index 76e61b01..9148238c 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/langgreekmodel.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/langgreekmodel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/langhebrewmodel.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/langhebrewmodel.cpython-312.pyc index 2987ddb8..ffe520b6 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/langhebrewmodel.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/langhebrewmodel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/langrussianmodel.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/langrussianmodel.cpython-312.pyc index 7916ea11..753ecd1d 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/langrussianmodel.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/langrussianmodel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/langthaimodel.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/langthaimodel.cpython-312.pyc index 9da30a28..54c133ab 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/langthaimodel.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/langthaimodel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/langturkishmodel.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/langturkishmodel.cpython-312.pyc index fabb6282..e69620d0 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/langturkishmodel.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/langturkishmodel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/latin1prober.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/latin1prober.cpython-312.pyc index 3a733a83..7e540bd7 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/latin1prober.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/latin1prober.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/macromanprober.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/macromanprober.cpython-312.pyc index 6ea0bd7a..18443ff7 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/macromanprober.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/macromanprober.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/mbcharsetprober.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/mbcharsetprober.cpython-312.pyc index 66417240..49310c55 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/mbcharsetprober.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/mbcharsetprober.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/mbcsgroupprober.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/mbcsgroupprober.cpython-312.pyc index 3c2dd662..62604084 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/mbcsgroupprober.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/mbcsgroupprober.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/mbcssm.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/mbcssm.cpython-312.pyc index 78f98717..28d7c53c 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/mbcssm.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/mbcssm.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/resultdict.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/resultdict.cpython-312.pyc index d5790a40..1650747b 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/resultdict.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/resultdict.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/sbcharsetprober.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/sbcharsetprober.cpython-312.pyc index e8e7da13..c18dea9a 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/sbcharsetprober.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/sbcharsetprober.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/sbcsgroupprober.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/sbcsgroupprober.cpython-312.pyc index 13fe3854..084cbe34 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/sbcsgroupprober.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/sbcsgroupprober.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/sjisprober.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/sjisprober.cpython-312.pyc index c0517346..ef794c07 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/sjisprober.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/sjisprober.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/universaldetector.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/universaldetector.cpython-312.pyc index d27e487e..a059c49e 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/universaldetector.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/universaldetector.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/utf1632prober.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/utf1632prober.cpython-312.pyc index 3b375047..96e81d83 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/utf1632prober.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/utf1632prober.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/utf8prober.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/utf8prober.cpython-312.pyc index 8f8c45ca..0d190b1d 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/utf8prober.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/utf8prober.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/version.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/version.cpython-312.pyc index 57ee74b6..0eac4622 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/version.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/chardet/__pycache__/version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/distlib/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/distlib/__pycache__/__init__.cpython-312.pyc index 2bbc6440..0428877e 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/distlib/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/distlib/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/distlib/__pycache__/compat.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/distlib/__pycache__/compat.cpython-312.pyc index 4942b8f9..db2557a1 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/distlib/__pycache__/compat.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/distlib/__pycache__/compat.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/distlib/__pycache__/resources.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/distlib/__pycache__/resources.cpython-312.pyc index fb11a47f..b341d829 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/distlib/__pycache__/resources.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/distlib/__pycache__/resources.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/distlib/__pycache__/scripts.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/distlib/__pycache__/scripts.cpython-312.pyc index f48d9298..12f86120 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/distlib/__pycache__/scripts.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/distlib/__pycache__/scripts.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/distlib/__pycache__/util.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/distlib/__pycache__/util.cpython-312.pyc index cd3bf9df..8fbfbdc2 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/distlib/__pycache__/util.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/distlib/__pycache__/util.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/idna/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/idna/__pycache__/__init__.cpython-312.pyc index fac1f9e7..ed35ca81 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/idna/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/idna/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/idna/__pycache__/core.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/idna/__pycache__/core.cpython-312.pyc index 414c0435..6ed413fe 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/idna/__pycache__/core.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/idna/__pycache__/core.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/idna/__pycache__/idnadata.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/idna/__pycache__/idnadata.cpython-312.pyc index 1f6b15c1..8679d8a0 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/idna/__pycache__/idnadata.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/idna/__pycache__/idnadata.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/idna/__pycache__/intranges.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/idna/__pycache__/intranges.cpython-312.pyc index 52d1e179..90277b30 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/idna/__pycache__/intranges.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/idna/__pycache__/intranges.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/idna/__pycache__/package_data.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/idna/__pycache__/package_data.cpython-312.pyc index 5983873e..a2383dad 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/idna/__pycache__/package_data.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/idna/__pycache__/package_data.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/msgpack/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/msgpack/__pycache__/__init__.cpython-312.pyc index 7df01261..6c28f73b 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/msgpack/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/msgpack/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/msgpack/__pycache__/exceptions.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/msgpack/__pycache__/exceptions.cpython-312.pyc index 7c663142..13ce9deb 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/msgpack/__pycache__/exceptions.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/msgpack/__pycache__/exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/msgpack/__pycache__/ext.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/msgpack/__pycache__/ext.cpython-312.pyc index 59e0c476..c06f8392 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/msgpack/__pycache__/ext.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/msgpack/__pycache__/ext.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/msgpack/__pycache__/fallback.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/msgpack/__pycache__/fallback.cpython-312.pyc index 2aa95cdf..38480a8c 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/msgpack/__pycache__/fallback.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/msgpack/__pycache__/fallback.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/__about__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/__about__.cpython-312.pyc index f0fa7193..13ade599 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/__about__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/__about__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/__init__.cpython-312.pyc index 21117c31..8e89cc24 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/_manylinux.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/_manylinux.cpython-312.pyc index 4a28938a..a5a190e0 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/_manylinux.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/_manylinux.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/_musllinux.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/_musllinux.cpython-312.pyc index 2b1754a1..6047529d 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/_musllinux.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/_musllinux.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/_structures.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/_structures.cpython-312.pyc index f3524b24..a0825c1e 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/_structures.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/_structures.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/markers.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/markers.cpython-312.pyc index 40efded5..cf553f95 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/markers.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/markers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/requirements.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/requirements.cpython-312.pyc index bf56f14d..c83e7680 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/requirements.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/requirements.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/specifiers.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/specifiers.cpython-312.pyc index 953275bd..4d25f812 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/specifiers.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/specifiers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/tags.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/tags.cpython-312.pyc index 15082962..28e01c97 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/tags.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/tags.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/utils.cpython-312.pyc index e37283f5..5a231d5a 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/utils.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/version.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/version.cpython-312.pyc index 7457256e..ab567930 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/version.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pkg_resources/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pkg_resources/__pycache__/__init__.cpython-312.pyc index 7a1f37b8..a20d570f 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pkg_resources/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pkg_resources/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/platformdirs/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/platformdirs/__pycache__/__init__.cpython-312.pyc index 41385f53..346a13a0 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/platformdirs/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/platformdirs/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/platformdirs/__pycache__/api.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/platformdirs/__pycache__/api.cpython-312.pyc index 82633b6d..8550f9a8 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/platformdirs/__pycache__/api.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/platformdirs/__pycache__/api.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/platformdirs/__pycache__/version.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/platformdirs/__pycache__/version.cpython-312.pyc index df6939f9..9e8c9479 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/platformdirs/__pycache__/version.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/platformdirs/__pycache__/version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/platformdirs/__pycache__/windows.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/platformdirs/__pycache__/windows.cpython-312.pyc index a379486b..804810ed 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/platformdirs/__pycache__/windows.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/platformdirs/__pycache__/windows.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/__init__.cpython-312.pyc index 8198fd78..c290dc17 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/filter.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/filter.cpython-312.pyc index 5ed50f7f..0e86ae85 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/filter.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/filter.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/lexer.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/lexer.cpython-312.pyc index 00a362f8..256a28e9 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/lexer.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/lexer.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/modeline.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/modeline.cpython-312.pyc index 0053fdd1..3498b31b 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/modeline.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/modeline.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/plugin.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/plugin.cpython-312.pyc index a6ed523f..70d7f3a5 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/plugin.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/plugin.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/regexopt.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/regexopt.cpython-312.pyc index 98e4dd50..6586ae90 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/regexopt.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/regexopt.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/style.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/style.cpython-312.pyc index 55fc9240..18e60564 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/style.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/style.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/token.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/token.cpython-312.pyc index a5990aca..75cd51b3 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/token.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/token.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/util.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/util.cpython-312.pyc index 067816c3..e2196b61 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/util.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pygments/__pycache__/util.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/filters/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pygments/filters/__pycache__/__init__.cpython-312.pyc index 067f41fb..875acd78 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pygments/filters/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pygments/filters/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/lexers/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pygments/lexers/__pycache__/__init__.cpython-312.pyc index 90c22cea..da626db5 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pygments/lexers/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pygments/lexers/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/lexers/__pycache__/_mapping.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pygments/lexers/__pycache__/_mapping.cpython-312.pyc index b4dee3e3..3726a00a 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pygments/lexers/__pycache__/_mapping.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pygments/lexers/__pycache__/_mapping.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/styles/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pygments/styles/__pycache__/__init__.cpython-312.pyc index eac17df1..edf55396 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pygments/styles/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pygments/styles/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/__init__.cpython-312.pyc index 63b40751..46d3996a 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/actions.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/actions.cpython-312.pyc index 83289e8a..c449925b 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/actions.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/actions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/common.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/common.cpython-312.pyc index 8eb64312..ded4108f 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/common.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/common.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/core.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/core.cpython-312.pyc index 99cfb4cf..275dbc3b 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/core.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/core.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/exceptions.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/exceptions.cpython-312.pyc index f77b49c2..9943f1f5 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/exceptions.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/helpers.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/helpers.cpython-312.pyc index 2b0f1aba..f5c75845 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/helpers.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/helpers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/results.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/results.cpython-312.pyc index 4cfb4694..fc851c00 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/results.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/results.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/testing.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/testing.cpython-312.pyc index ff64f9a8..d7b81f59 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/testing.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/testing.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/unicode.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/unicode.cpython-312.pyc index 904b2ab1..e00d401f 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/unicode.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/unicode.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/util.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/util.cpython-312.pyc index 5ac93d96..7590e796 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/util.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pyparsing/__pycache__/util.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/__pycache__/__init__.cpython-312.pyc index 4d3d95c6..f327d1b8 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/__pycache__/_impl.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/__pycache__/_impl.cpython-312.pyc index 11576a1a..8474a4b3 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/__pycache__/_impl.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/__pycache__/_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/_in_process/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/_in_process/__pycache__/__init__.cpython-312.pyc index e0368b6a..c2c509ea 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/_in_process/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/_in_process/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/__init__.cpython-312.pyc index 7bef8a5a..225dbe85 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/__version__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/__version__.cpython-312.pyc index e1765af6..7c339da7 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/__version__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/__version__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/_internal_utils.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/_internal_utils.cpython-312.pyc index 447c72fd..18b82da7 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/_internal_utils.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/_internal_utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/adapters.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/adapters.cpython-312.pyc index 764b1995..6f0c6773 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/adapters.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/adapters.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/api.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/api.cpython-312.pyc index d605a378..b94e3225 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/api.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/api.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/auth.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/auth.cpython-312.pyc index 90d231ec..7f342ae4 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/auth.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/auth.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/certs.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/certs.cpython-312.pyc index 07436947..6a3ac934 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/certs.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/certs.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/compat.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/compat.cpython-312.pyc index e3f145e6..9644e002 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/compat.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/compat.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/cookies.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/cookies.cpython-312.pyc index 4625e775..e2f184b8 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/cookies.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/cookies.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/exceptions.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/exceptions.cpython-312.pyc index 39b439c6..66c78bf1 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/exceptions.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/hooks.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/hooks.cpython-312.pyc index 91009dd3..47ceb7a1 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/hooks.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/hooks.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/models.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/models.cpython-312.pyc index 1fdf73a8..06d33d57 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/models.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/models.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/packages.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/packages.cpython-312.pyc index 9a57304d..710fe043 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/packages.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/packages.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/sessions.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/sessions.cpython-312.pyc index b19edf91..2dea436d 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/sessions.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/sessions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/status_codes.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/status_codes.cpython-312.pyc index 47bfd2da..f282d47b 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/status_codes.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/status_codes.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/structures.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/structures.cpython-312.pyc index 0d59b21b..0f6dfd3f 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/structures.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/structures.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/utils.cpython-312.pyc index 93ed0925..662319a3 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/utils.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/resolvelib/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/resolvelib/__pycache__/__init__.cpython-312.pyc index 94809391..cbdd18cd 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/resolvelib/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/resolvelib/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/resolvelib/__pycache__/providers.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/resolvelib/__pycache__/providers.cpython-312.pyc index 330b8c98..d004d8f3 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/resolvelib/__pycache__/providers.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/resolvelib/__pycache__/providers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/resolvelib/__pycache__/reporters.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/resolvelib/__pycache__/reporters.cpython-312.pyc index 1b81b1a9..116003eb 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/resolvelib/__pycache__/reporters.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/resolvelib/__pycache__/reporters.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/resolvelib/__pycache__/resolvers.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/resolvelib/__pycache__/resolvers.cpython-312.pyc index 4da81279..1cdc0cda 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/resolvelib/__pycache__/resolvers.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/resolvelib/__pycache__/resolvers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/resolvelib/__pycache__/structs.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/resolvelib/__pycache__/structs.cpython-312.pyc index 39dbd446..d923fec2 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/resolvelib/__pycache__/structs.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/resolvelib/__pycache__/structs.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/resolvelib/compat/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/resolvelib/compat/__pycache__/__init__.cpython-312.pyc index 1ce74bd5..ef6efb84 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/resolvelib/compat/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/resolvelib/compat/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/resolvelib/compat/__pycache__/collections_abc.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/resolvelib/compat/__pycache__/collections_abc.cpython-312.pyc index 59f4fdb8..ea5e99f2 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/resolvelib/compat/__pycache__/collections_abc.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/resolvelib/compat/__pycache__/collections_abc.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/__init__.cpython-312.pyc index e8cebc0b..9cdcabb8 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_cell_widths.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_cell_widths.cpython-312.pyc index ea3a2813..7ddaebba 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_cell_widths.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_cell_widths.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_emoji_codes.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_emoji_codes.cpython-312.pyc index f28a1266..a8a716ec 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_emoji_codes.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_emoji_codes.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_emoji_replace.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_emoji_replace.cpython-312.pyc index 22a8f1a5..e7ddbce7 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_emoji_replace.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_emoji_replace.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_export_format.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_export_format.cpython-312.pyc index d72463e2..26465e07 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_export_format.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_export_format.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_extension.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_extension.cpython-312.pyc index 11d381a1..a8385e61 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_extension.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_extension.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_fileno.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_fileno.cpython-312.pyc index b597d7d3..a4816278 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_fileno.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_fileno.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_log_render.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_log_render.cpython-312.pyc index d7ed20cd..660ba9ab 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_log_render.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_log_render.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_loop.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_loop.cpython-312.pyc index b65ed52b..3bfa08ec 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_loop.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_loop.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_null_file.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_null_file.cpython-312.pyc index 0661c4c9..7170a103 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_null_file.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_null_file.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_palettes.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_palettes.cpython-312.pyc index 2894abc1..f335e8be 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_palettes.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_palettes.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_pick.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_pick.cpython-312.pyc index ccf0be6f..7749f0df 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_pick.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_pick.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_ratio.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_ratio.cpython-312.pyc index 3b4ba937..6414958e 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_ratio.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_ratio.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_spinners.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_spinners.cpython-312.pyc index db8971b9..e069a015 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_spinners.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_spinners.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_win32_console.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_win32_console.cpython-312.pyc index 953dcbcf..fdb2ad75 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_win32_console.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_win32_console.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_windows.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_windows.cpython-312.pyc index de7486ff..051488e3 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_windows.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_windows.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_wrap.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_wrap.cpython-312.pyc index edc9e8f8..30542381 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_wrap.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/_wrap.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/abc.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/abc.cpython-312.pyc index 765a25e4..de963460 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/abc.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/abc.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/align.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/align.cpython-312.pyc index cf8ddca2..862e352b 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/align.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/align.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/ansi.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/ansi.cpython-312.pyc index 47daac77..29c7fd59 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/ansi.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/ansi.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/box.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/box.cpython-312.pyc index 71a93ed4..27e8ba87 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/box.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/box.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/cells.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/cells.cpython-312.pyc index 875a71a7..6ac56aae 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/cells.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/cells.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/color.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/color.cpython-312.pyc index 8f5c63b5..9a911b15 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/color.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/color.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/color_triplet.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/color_triplet.cpython-312.pyc index 9edbafc9..7a1e6b3c 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/color_triplet.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/color_triplet.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/columns.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/columns.cpython-312.pyc index 2a3d6ece..4fe2eae2 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/columns.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/columns.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/console.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/console.cpython-312.pyc index cf133d82..d7e7beab 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/console.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/console.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/constrain.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/constrain.cpython-312.pyc index 228ff3d6..3435603b 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/constrain.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/constrain.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/containers.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/containers.cpython-312.pyc index 42f84ea1..d896819b 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/containers.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/containers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/control.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/control.cpython-312.pyc index 4b4e30cd..91bcd917 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/control.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/control.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/default_styles.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/default_styles.cpython-312.pyc index 06b25d8c..befc4a5c 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/default_styles.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/default_styles.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/emoji.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/emoji.cpython-312.pyc index 1ee9b2dc..f03190d4 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/emoji.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/emoji.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/errors.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/errors.cpython-312.pyc index f181643d..338a2d53 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/errors.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/errors.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/file_proxy.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/file_proxy.cpython-312.pyc index c7e45f91..d68bd246 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/file_proxy.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/file_proxy.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/filesize.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/filesize.cpython-312.pyc index d33b63bd..c8b1f53f 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/filesize.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/filesize.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/highlighter.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/highlighter.cpython-312.pyc index 8a51f085..2d3912d9 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/highlighter.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/highlighter.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/jupyter.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/jupyter.cpython-312.pyc index 9d7792d5..e3c2fedd 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/jupyter.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/jupyter.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/live.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/live.cpython-312.pyc index 06de1008..3e471672 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/live.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/live.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/live_render.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/live_render.cpython-312.pyc index 4685ec6d..3409a656 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/live_render.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/live_render.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/logging.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/logging.cpython-312.pyc index 59fdfa2c..cc94450e 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/logging.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/logging.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/markup.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/markup.cpython-312.pyc index e9c413bb..0cf6cc61 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/markup.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/markup.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/measure.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/measure.cpython-312.pyc index 3d77a1b0..4502cc71 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/measure.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/measure.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/padding.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/padding.cpython-312.pyc index 05e78636..96f2d060 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/padding.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/padding.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/pager.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/pager.cpython-312.pyc index 57f4d730..c2ddd206 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/pager.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/pager.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/palette.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/palette.cpython-312.pyc index 8a0d86b8..f103c895 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/palette.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/palette.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/panel.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/panel.cpython-312.pyc index 829892e4..4302c0a9 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/panel.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/panel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/pretty.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/pretty.cpython-312.pyc index 0d4d75a6..fee83623 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/pretty.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/pretty.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/progress.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/progress.cpython-312.pyc index c6048ac3..c5de1054 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/progress.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/progress.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/progress_bar.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/progress_bar.cpython-312.pyc index 75df968c..93343326 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/progress_bar.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/progress_bar.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/protocol.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/protocol.cpython-312.pyc index ad0d4f18..9ef168dd 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/protocol.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/protocol.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/region.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/region.cpython-312.pyc index bc23d20c..b652ba2d 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/region.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/region.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/repr.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/repr.cpython-312.pyc index d74f7d1a..6c4cfb68 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/repr.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/repr.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/scope.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/scope.cpython-312.pyc index e0e2ed92..391b751a 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/scope.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/scope.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/screen.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/screen.cpython-312.pyc index c1acdca7..a030386c 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/screen.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/screen.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/segment.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/segment.cpython-312.pyc index 015ca5f1..77276716 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/segment.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/segment.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/spinner.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/spinner.cpython-312.pyc index 51857cc9..a793d5e2 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/spinner.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/spinner.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/style.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/style.cpython-312.pyc index 984ee64f..c6af8c36 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/style.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/style.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/styled.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/styled.cpython-312.pyc index 52ebaed0..19e5b1af 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/styled.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/styled.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/syntax.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/syntax.cpython-312.pyc index 3f26c47d..f60eb79f 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/syntax.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/syntax.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/table.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/table.cpython-312.pyc index 8909955d..5920fc29 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/table.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/table.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/terminal_theme.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/terminal_theme.cpython-312.pyc index cabfb9fa..0ab68ef4 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/terminal_theme.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/terminal_theme.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/text.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/text.cpython-312.pyc index 24adf1a1..f41386a0 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/text.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/text.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/theme.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/theme.cpython-312.pyc index a63465a3..2f096c61 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/theme.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/theme.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/themes.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/themes.cpython-312.pyc index fec19f32..f0e8c184 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/themes.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/themes.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/traceback.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/traceback.cpython-312.pyc index 8c9bb2c9..8981318c 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/traceback.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/rich/__pycache__/traceback.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/__init__.cpython-312.pyc index a1d4b6a2..2df0bc4a 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/_asyncio.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/_asyncio.cpython-312.pyc index 91617b10..6f1f4218 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/_asyncio.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/_asyncio.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/_utils.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/_utils.cpython-312.pyc index 082833be..b96b75ed 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/_utils.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/_utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/after.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/after.cpython-312.pyc index bec05142..61daca72 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/after.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/after.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/before.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/before.cpython-312.pyc index e5e77fa8..93ba5eac 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/before.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/before.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/before_sleep.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/before_sleep.cpython-312.pyc index 4fec6e9a..a2d41581 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/before_sleep.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/before_sleep.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/nap.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/nap.cpython-312.pyc index d2c0264a..2d7aef24 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/nap.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/nap.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/retry.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/retry.cpython-312.pyc index 4ce517ca..84d8b226 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/retry.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/retry.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/stop.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/stop.cpython-312.pyc index 1ad48ecb..cbc2d44b 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/stop.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/stop.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/wait.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/wait.cpython-312.pyc index af610544..d78f402d 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/wait.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/tenacity/__pycache__/wait.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/tomli/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/tomli/__pycache__/__init__.cpython-312.pyc index da10f9e9..6c9e4260 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/tomli/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/tomli/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/tomli/__pycache__/_parser.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/tomli/__pycache__/_parser.cpython-312.pyc index 5bd14221..e8d7af4a 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/tomli/__pycache__/_parser.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/tomli/__pycache__/_parser.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/tomli/__pycache__/_re.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/tomli/__pycache__/_re.cpython-312.pyc index 6fede51b..2545bdd9 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/tomli/__pycache__/_re.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/tomli/__pycache__/_re.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/tomli/__pycache__/_types.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/tomli/__pycache__/_types.cpython-312.pyc index 30625709..9d28e419 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/tomli/__pycache__/_types.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/tomli/__pycache__/_types.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/__init__.cpython-312.pyc index 93af891e..8f41d195 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/_collections.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/_collections.cpython-312.pyc index bcdae9cd..3ec63465 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/_collections.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/_collections.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/_version.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/_version.cpython-312.pyc index f3365a51..f685d279 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/_version.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/_version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/connection.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/connection.cpython-312.pyc index 2f395b35..2fe7cbb9 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/connection.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/connection.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/connectionpool.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/connectionpool.cpython-312.pyc index ba963a35..afd86166 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/connectionpool.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/connectionpool.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/exceptions.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/exceptions.cpython-312.pyc index e247d4a3..329138f5 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/exceptions.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/fields.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/fields.cpython-312.pyc index a7cfce79..76c410bd 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/fields.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/fields.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/filepost.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/filepost.cpython-312.pyc index 6d8ea601..70d20dbf 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/filepost.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/filepost.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/poolmanager.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/poolmanager.cpython-312.pyc index acfccda4..aba900dd 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/poolmanager.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/poolmanager.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/request.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/request.cpython-312.pyc index 5b6eb6ed..2e594410 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/request.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/request.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/response.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/response.cpython-312.pyc index 9dda6be7..d14274e1 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/response.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/contrib/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/contrib/__pycache__/__init__.cpython-312.pyc index 0bc67ff1..94262649 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/contrib/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/contrib/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/contrib/__pycache__/_appengine_environ.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/contrib/__pycache__/_appengine_environ.cpython-312.pyc index 8fdc60f8..ab8db992 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/contrib/__pycache__/_appengine_environ.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/contrib/__pycache__/_appengine_environ.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/contrib/__pycache__/socks.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/contrib/__pycache__/socks.cpython-312.pyc index eb525373..3892026e 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/contrib/__pycache__/socks.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/contrib/__pycache__/socks.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/packages/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/packages/__pycache__/__init__.cpython-312.pyc index b7f2b5f7..3ac063cf 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/packages/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/packages/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/packages/__pycache__/six.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/packages/__pycache__/six.cpython-312.pyc index b439a1fb..56fab104 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/packages/__pycache__/six.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/packages/__pycache__/six.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/__init__.cpython-312.pyc index e9e25478..f4566259 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/connection.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/connection.cpython-312.pyc index fd484857..7b51edbb 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/connection.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/connection.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/proxy.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/proxy.cpython-312.pyc index d075c782..ec09782f 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/proxy.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/proxy.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/queue.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/queue.cpython-312.pyc index b4aae558..a341b999 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/queue.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/queue.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/request.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/request.cpython-312.pyc index 32eae843..64ce982e 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/request.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/request.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/response.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/response.cpython-312.pyc index a165ebe4..c68462aa 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/response.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/retry.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/retry.cpython-312.pyc index 6d4bc4bc..2ffc7d17 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/retry.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/retry.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/ssl_.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/ssl_.cpython-312.pyc index b1f4b7ef..cc743104 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/ssl_.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/ssl_.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/ssl_match_hostname.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/ssl_match_hostname.cpython-312.pyc index f4793e59..27d7fd28 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/ssl_match_hostname.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/ssl_match_hostname.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/ssltransport.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/ssltransport.cpython-312.pyc index a3d5897c..55bd3a6c 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/ssltransport.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/ssltransport.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/timeout.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/timeout.cpython-312.pyc index bd87c6a0..194ce71a 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/timeout.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/timeout.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/url.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/url.cpython-312.pyc index 243804b4..38928a41 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/url.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/url.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/wait.cpython-312.pyc b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/wait.cpython-312.pyc index 0b8a5a0c..f6f0698d 100644 Binary files a/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/wait.cpython-312.pyc and b/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/wait.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/propcache/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/propcache/__pycache__/__init__.cpython-312.pyc index 0a3224e4..9a804495 100644 Binary files a/venv/Lib/site-packages/propcache/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/propcache/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/propcache/__pycache__/_helpers.cpython-312.pyc b/venv/Lib/site-packages/propcache/__pycache__/_helpers.cpython-312.pyc index 7009d40e..adeab1ae 100644 Binary files a/venv/Lib/site-packages/propcache/__pycache__/_helpers.cpython-312.pyc and b/venv/Lib/site-packages/propcache/__pycache__/_helpers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/propcache/__pycache__/api.cpython-312.pyc b/venv/Lib/site-packages/propcache/__pycache__/api.cpython-312.pyc index 65aad137..cfbaaa9a 100644 Binary files a/venv/Lib/site-packages/propcache/__pycache__/api.cpython-312.pyc and b/venv/Lib/site-packages/propcache/__pycache__/api.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/psutil/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/psutil/__pycache__/__init__.cpython-312.pyc index 7b3a8564..c4b49992 100644 Binary files a/venv/Lib/site-packages/psutil/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/psutil/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/psutil/__pycache__/_common.cpython-312.pyc b/venv/Lib/site-packages/psutil/__pycache__/_common.cpython-312.pyc index d8b09eda..35a07e63 100644 Binary files a/venv/Lib/site-packages/psutil/__pycache__/_common.cpython-312.pyc and b/venv/Lib/site-packages/psutil/__pycache__/_common.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/psutil/__pycache__/_pswindows.cpython-312.pyc b/venv/Lib/site-packages/psutil/__pycache__/_pswindows.cpython-312.pyc index 058555a2..4285edc0 100644 Binary files a/venv/Lib/site-packages/psutil/__pycache__/_pswindows.cpython-312.pyc and b/venv/Lib/site-packages/psutil/__pycache__/_pswindows.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pydantic/__pycache__/__init__.cpython-312.pyc index 9ce57b55..a3b953ff 100644 Binary files a/venv/Lib/site-packages/pydantic/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/__pycache__/_migration.cpython-312.pyc b/venv/Lib/site-packages/pydantic/__pycache__/_migration.cpython-312.pyc index 856fba43..e2cc4584 100644 Binary files a/venv/Lib/site-packages/pydantic/__pycache__/_migration.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/__pycache__/_migration.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/__pycache__/aliases.cpython-312.pyc b/venv/Lib/site-packages/pydantic/__pycache__/aliases.cpython-312.pyc index 243c3135..9ffaf82a 100644 Binary files a/venv/Lib/site-packages/pydantic/__pycache__/aliases.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/__pycache__/aliases.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/__pycache__/annotated_handlers.cpython-312.pyc b/venv/Lib/site-packages/pydantic/__pycache__/annotated_handlers.cpython-312.pyc index 41e77389..003e9051 100644 Binary files a/venv/Lib/site-packages/pydantic/__pycache__/annotated_handlers.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/__pycache__/annotated_handlers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/__pycache__/color.cpython-312.pyc b/venv/Lib/site-packages/pydantic/__pycache__/color.cpython-312.pyc index 218c346a..785e1119 100644 Binary files a/venv/Lib/site-packages/pydantic/__pycache__/color.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/__pycache__/color.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/__pycache__/config.cpython-312.pyc b/venv/Lib/site-packages/pydantic/__pycache__/config.cpython-312.pyc index ae3ef31f..784c17f4 100644 Binary files a/venv/Lib/site-packages/pydantic/__pycache__/config.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/__pycache__/config.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/__pycache__/errors.cpython-312.pyc b/venv/Lib/site-packages/pydantic/__pycache__/errors.cpython-312.pyc index 897ef888..53ecf96c 100644 Binary files a/venv/Lib/site-packages/pydantic/__pycache__/errors.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/__pycache__/errors.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/__pycache__/fields.cpython-312.pyc b/venv/Lib/site-packages/pydantic/__pycache__/fields.cpython-312.pyc index e06466cf..fe6cce4f 100644 Binary files a/venv/Lib/site-packages/pydantic/__pycache__/fields.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/__pycache__/fields.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/__pycache__/functional_validators.cpython-312.pyc b/venv/Lib/site-packages/pydantic/__pycache__/functional_validators.cpython-312.pyc index 271ead41..492c28ea 100644 Binary files a/venv/Lib/site-packages/pydantic/__pycache__/functional_validators.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/__pycache__/functional_validators.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/__pycache__/json_schema.cpython-312.pyc b/venv/Lib/site-packages/pydantic/__pycache__/json_schema.cpython-312.pyc index 0d9dc2a0..b5c8ef9d 100644 Binary files a/venv/Lib/site-packages/pydantic/__pycache__/json_schema.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/__pycache__/json_schema.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/__pycache__/main.cpython-312.pyc b/venv/Lib/site-packages/pydantic/__pycache__/main.cpython-312.pyc index 5f793465..df3b0bc5 100644 Binary files a/venv/Lib/site-packages/pydantic/__pycache__/main.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/__pycache__/main.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/__pycache__/networks.cpython-312.pyc b/venv/Lib/site-packages/pydantic/__pycache__/networks.cpython-312.pyc index 301248de..76e8cd53 100644 Binary files a/venv/Lib/site-packages/pydantic/__pycache__/networks.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/__pycache__/networks.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/__pycache__/type_adapter.cpython-312.pyc b/venv/Lib/site-packages/pydantic/__pycache__/type_adapter.cpython-312.pyc index 182f0a63..dffcdda2 100644 Binary files a/venv/Lib/site-packages/pydantic/__pycache__/type_adapter.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/__pycache__/type_adapter.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/__pycache__/types.cpython-312.pyc b/venv/Lib/site-packages/pydantic/__pycache__/types.cpython-312.pyc index 19e09cdc..731e8d90 100644 Binary files a/venv/Lib/site-packages/pydantic/__pycache__/types.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/__pycache__/types.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/__pycache__/version.cpython-312.pyc b/venv/Lib/site-packages/pydantic/__pycache__/version.cpython-312.pyc index 8b2a087e..04d50b48 100644 Binary files a/venv/Lib/site-packages/pydantic/__pycache__/version.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/__pycache__/version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/__pycache__/warnings.cpython-312.pyc b/venv/Lib/site-packages/pydantic/__pycache__/warnings.cpython-312.pyc index bf868df5..1621d240 100644 Binary files a/venv/Lib/site-packages/pydantic/__pycache__/warnings.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/__pycache__/warnings.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/__init__.cpython-312.pyc index 5535d22f..768b308d 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_config.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_config.cpython-312.pyc index 75146acd..edb03e2f 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_config.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_config.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_core_metadata.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_core_metadata.cpython-312.pyc index 5b29545f..bfdd2ed1 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_core_metadata.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_core_metadata.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_core_utils.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_core_utils.cpython-312.pyc index ecf45100..d05bf21e 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_core_utils.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_core_utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_decorators.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_decorators.cpython-312.pyc index 9046da8a..13513e02 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_decorators.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_decorators.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_discriminated_union.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_discriminated_union.cpython-312.pyc index dc6fd8af..4f285061 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_discriminated_union.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_discriminated_union.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_docs_extraction.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_docs_extraction.cpython-312.pyc index bbd704a1..28d6af81 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_docs_extraction.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_docs_extraction.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_fields.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_fields.cpython-312.pyc index 57dfeb3f..15e13e30 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_fields.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_fields.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_forward_ref.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_forward_ref.cpython-312.pyc index a7615355..2d8d9017 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_forward_ref.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_forward_ref.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_generate_schema.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_generate_schema.cpython-312.pyc index c44e8bdc..6eaf2904 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_generate_schema.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_generate_schema.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_generics.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_generics.cpython-312.pyc index 1b80872b..5ad18f53 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_generics.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_generics.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_import_utils.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_import_utils.cpython-312.pyc index 091482d9..d691d634 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_import_utils.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_import_utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_internal_dataclass.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_internal_dataclass.cpython-312.pyc index 2f56fc20..8161e75e 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_internal_dataclass.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_internal_dataclass.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_known_annotated_metadata.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_known_annotated_metadata.cpython-312.pyc index 192ade22..6819e94a 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_known_annotated_metadata.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_known_annotated_metadata.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_mock_val_ser.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_mock_val_ser.cpython-312.pyc index df068429..678f825d 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_mock_val_ser.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_mock_val_ser.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_model_construction.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_model_construction.cpython-312.pyc index 63152d85..a37475c0 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_model_construction.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_model_construction.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_namespace_utils.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_namespace_utils.cpython-312.pyc index 68649c4d..c641be8c 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_namespace_utils.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_namespace_utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_repr.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_repr.cpython-312.pyc index e15c5dac..52578662 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_repr.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_repr.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_schema_gather.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_schema_gather.cpython-312.pyc index 441fb6f0..fa4128c9 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_schema_gather.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_schema_gather.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_schema_generation_shared.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_schema_generation_shared.cpython-312.pyc index 9aad74a8..6124353b 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_schema_generation_shared.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_schema_generation_shared.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_serializers.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_serializers.cpython-312.pyc index 9454fdd9..25b8ec1a 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_serializers.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_serializers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_signature.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_signature.cpython-312.pyc index 6bcbdd5c..41ca88ab 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_signature.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_signature.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_typing_extra.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_typing_extra.cpython-312.pyc index 6073ecda..da7db70f 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_typing_extra.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_typing_extra.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_utils.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_utils.cpython-312.pyc index d61cb418..b817891c 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_utils.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_validators.cpython-312.pyc b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_validators.cpython-312.pyc index c51fb6ca..ead553b8 100644 Binary files a/venv/Lib/site-packages/pydantic/_internal/__pycache__/_validators.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/_internal/__pycache__/_validators.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/plugin/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pydantic/plugin/__pycache__/__init__.cpython-312.pyc index 9caff606..a177608f 100644 Binary files a/venv/Lib/site-packages/pydantic/plugin/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/plugin/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/plugin/__pycache__/_loader.cpython-312.pyc b/venv/Lib/site-packages/pydantic/plugin/__pycache__/_loader.cpython-312.pyc index 26c4527c..7e5e9ea3 100644 Binary files a/venv/Lib/site-packages/pydantic/plugin/__pycache__/_loader.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/plugin/__pycache__/_loader.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/plugin/__pycache__/_schema_validator.cpython-312.pyc b/venv/Lib/site-packages/pydantic/plugin/__pycache__/_schema_validator.cpython-312.pyc index c321f9ce..5480ef9a 100644 Binary files a/venv/Lib/site-packages/pydantic/plugin/__pycache__/_schema_validator.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/plugin/__pycache__/_schema_validator.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pydantic/v1/__pycache__/__init__.cpython-312.pyc index 1039d7f0..a23fd38e 100644 Binary files a/venv/Lib/site-packages/pydantic/v1/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/v1/__pycache__/annotated_types.cpython-312.pyc b/venv/Lib/site-packages/pydantic/v1/__pycache__/annotated_types.cpython-312.pyc index d2254939..539a077c 100644 Binary files a/venv/Lib/site-packages/pydantic/v1/__pycache__/annotated_types.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/v1/__pycache__/annotated_types.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/v1/__pycache__/class_validators.cpython-312.pyc b/venv/Lib/site-packages/pydantic/v1/__pycache__/class_validators.cpython-312.pyc index 8dca342a..b57ef862 100644 Binary files a/venv/Lib/site-packages/pydantic/v1/__pycache__/class_validators.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/v1/__pycache__/class_validators.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/v1/__pycache__/color.cpython-312.pyc b/venv/Lib/site-packages/pydantic/v1/__pycache__/color.cpython-312.pyc index 8afa2579..455290a2 100644 Binary files a/venv/Lib/site-packages/pydantic/v1/__pycache__/color.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/v1/__pycache__/color.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/v1/__pycache__/config.cpython-312.pyc b/venv/Lib/site-packages/pydantic/v1/__pycache__/config.cpython-312.pyc index 58475973..3a0d0bac 100644 Binary files a/venv/Lib/site-packages/pydantic/v1/__pycache__/config.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/v1/__pycache__/config.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/v1/__pycache__/dataclasses.cpython-312.pyc b/venv/Lib/site-packages/pydantic/v1/__pycache__/dataclasses.cpython-312.pyc index 0807aa96..bafdd998 100644 Binary files a/venv/Lib/site-packages/pydantic/v1/__pycache__/dataclasses.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/v1/__pycache__/dataclasses.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/v1/__pycache__/datetime_parse.cpython-312.pyc b/venv/Lib/site-packages/pydantic/v1/__pycache__/datetime_parse.cpython-312.pyc index fbeb377d..118b15fb 100644 Binary files a/venv/Lib/site-packages/pydantic/v1/__pycache__/datetime_parse.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/v1/__pycache__/datetime_parse.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/v1/__pycache__/decorator.cpython-312.pyc b/venv/Lib/site-packages/pydantic/v1/__pycache__/decorator.cpython-312.pyc index 965ee3e3..0c411edf 100644 Binary files a/venv/Lib/site-packages/pydantic/v1/__pycache__/decorator.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/v1/__pycache__/decorator.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/v1/__pycache__/env_settings.cpython-312.pyc b/venv/Lib/site-packages/pydantic/v1/__pycache__/env_settings.cpython-312.pyc index 8a0b8044..2c909ca0 100644 Binary files a/venv/Lib/site-packages/pydantic/v1/__pycache__/env_settings.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/v1/__pycache__/env_settings.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/v1/__pycache__/error_wrappers.cpython-312.pyc b/venv/Lib/site-packages/pydantic/v1/__pycache__/error_wrappers.cpython-312.pyc index c327c738..a0e129cf 100644 Binary files a/venv/Lib/site-packages/pydantic/v1/__pycache__/error_wrappers.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/v1/__pycache__/error_wrappers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/v1/__pycache__/errors.cpython-312.pyc b/venv/Lib/site-packages/pydantic/v1/__pycache__/errors.cpython-312.pyc index 480b857a..bb8f876f 100644 Binary files a/venv/Lib/site-packages/pydantic/v1/__pycache__/errors.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/v1/__pycache__/errors.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/v1/__pycache__/fields.cpython-312.pyc b/venv/Lib/site-packages/pydantic/v1/__pycache__/fields.cpython-312.pyc index 74201142..f1b20ff0 100644 Binary files a/venv/Lib/site-packages/pydantic/v1/__pycache__/fields.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/v1/__pycache__/fields.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/v1/__pycache__/json.cpython-312.pyc b/venv/Lib/site-packages/pydantic/v1/__pycache__/json.cpython-312.pyc index 65e0aa16..8013e273 100644 Binary files a/venv/Lib/site-packages/pydantic/v1/__pycache__/json.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/v1/__pycache__/json.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/v1/__pycache__/main.cpython-312.pyc b/venv/Lib/site-packages/pydantic/v1/__pycache__/main.cpython-312.pyc index fe06031c..2c0f7891 100644 Binary files a/venv/Lib/site-packages/pydantic/v1/__pycache__/main.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/v1/__pycache__/main.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/v1/__pycache__/networks.cpython-312.pyc b/venv/Lib/site-packages/pydantic/v1/__pycache__/networks.cpython-312.pyc index ad01acc3..9a07f105 100644 Binary files a/venv/Lib/site-packages/pydantic/v1/__pycache__/networks.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/v1/__pycache__/networks.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/v1/__pycache__/parse.cpython-312.pyc b/venv/Lib/site-packages/pydantic/v1/__pycache__/parse.cpython-312.pyc index b4b1d494..f1852130 100644 Binary files a/venv/Lib/site-packages/pydantic/v1/__pycache__/parse.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/v1/__pycache__/parse.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/v1/__pycache__/schema.cpython-312.pyc b/venv/Lib/site-packages/pydantic/v1/__pycache__/schema.cpython-312.pyc index cf0342fc..a3ba9987 100644 Binary files a/venv/Lib/site-packages/pydantic/v1/__pycache__/schema.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/v1/__pycache__/schema.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/v1/__pycache__/tools.cpython-312.pyc b/venv/Lib/site-packages/pydantic/v1/__pycache__/tools.cpython-312.pyc index e072cba3..c5b86d4b 100644 Binary files a/venv/Lib/site-packages/pydantic/v1/__pycache__/tools.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/v1/__pycache__/tools.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/v1/__pycache__/types.cpython-312.pyc b/venv/Lib/site-packages/pydantic/v1/__pycache__/types.cpython-312.pyc index 88b48a63..59314259 100644 Binary files a/venv/Lib/site-packages/pydantic/v1/__pycache__/types.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/v1/__pycache__/types.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/v1/__pycache__/typing.cpython-312.pyc b/venv/Lib/site-packages/pydantic/v1/__pycache__/typing.cpython-312.pyc index 1ee77a5b..56713392 100644 Binary files a/venv/Lib/site-packages/pydantic/v1/__pycache__/typing.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/v1/__pycache__/typing.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/v1/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/pydantic/v1/__pycache__/utils.cpython-312.pyc index 5f0ae56b..8b6ce9ef 100644 Binary files a/venv/Lib/site-packages/pydantic/v1/__pycache__/utils.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/v1/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/v1/__pycache__/validators.cpython-312.pyc b/venv/Lib/site-packages/pydantic/v1/__pycache__/validators.cpython-312.pyc index dcc37200..f3cf3cc9 100644 Binary files a/venv/Lib/site-packages/pydantic/v1/__pycache__/validators.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/v1/__pycache__/validators.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic/v1/__pycache__/version.cpython-312.pyc b/venv/Lib/site-packages/pydantic/v1/__pycache__/version.cpython-312.pyc index 6baf351d..0fa53f04 100644 Binary files a/venv/Lib/site-packages/pydantic/v1/__pycache__/version.cpython-312.pyc and b/venv/Lib/site-packages/pydantic/v1/__pycache__/version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic_core/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pydantic_core/__pycache__/__init__.cpython-312.pyc index 86a12996..41916df6 100644 Binary files a/venv/Lib/site-packages/pydantic_core/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pydantic_core/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pydantic_core/__pycache__/core_schema.cpython-312.pyc b/venv/Lib/site-packages/pydantic_core/__pycache__/core_schema.cpython-312.pyc index 0e6e520a..91b41308 100644 Binary files a/venv/Lib/site-packages/pydantic_core/__pycache__/core_schema.cpython-312.pyc and b/venv/Lib/site-packages/pydantic_core/__pycache__/core_schema.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/python_multipart-0.0.20.dist-info/INSTALLER b/venv/Lib/site-packages/python_multipart-0.0.20.dist-info/INSTALLER new file mode 100644 index 00000000..a1b589e3 --- /dev/null +++ b/venv/Lib/site-packages/python_multipart-0.0.20.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/Lib/site-packages/python_multipart-0.0.20.dist-info/METADATA b/venv/Lib/site-packages/python_multipart-0.0.20.dist-info/METADATA new file mode 100644 index 00000000..155ce8b6 --- /dev/null +++ b/venv/Lib/site-packages/python_multipart-0.0.20.dist-info/METADATA @@ -0,0 +1,40 @@ +Metadata-Version: 2.4 +Name: python-multipart +Version: 0.0.20 +Summary: A streaming multipart parser for Python +Project-URL: Homepage, https://github.com/Kludex/python-multipart +Project-URL: Documentation, https://kludex.github.io/python-multipart/ +Project-URL: Changelog, https://github.com/Kludex/python-multipart/blob/master/CHANGELOG.md +Project-URL: Source, https://github.com/Kludex/python-multipart +Author-email: Andrew Dunham , Marcelo Trylesinski +License-Expression: Apache-2.0 +License-File: LICENSE.txt +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Web Environment +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.8 +Description-Content-Type: text/markdown + +# [Python-Multipart](https://kludex.github.io/python-multipart/) + +[![Package version](https://badge.fury.io/py/python-multipart.svg)](https://pypi.python.org/pypi/python-multipart) +[![Supported Python Version](https://img.shields.io/pypi/pyversions/python-multipart.svg?color=%2334D058)](https://pypi.org/project/python-multipart) + +--- + +`python-multipart` is an Apache2-licensed streaming multipart parser for Python. +Test coverage is currently 100%. + +## Why? + +Because streaming uploads are awesome for large files. diff --git a/venv/Lib/site-packages/python_multipart-0.0.20.dist-info/RECORD b/venv/Lib/site-packages/python_multipart-0.0.20.dist-info/RECORD new file mode 100644 index 00000000..f80836d0 --- /dev/null +++ b/venv/Lib/site-packages/python_multipart-0.0.20.dist-info/RECORD @@ -0,0 +1,23 @@ +multipart/__init__.py,sha256=_ttxOAFnTN4jeac-_8NeXpaXYYo0PPEIp8Ogo4YFNHE,935 +multipart/__pycache__/__init__.cpython-312.pyc,, +multipart/__pycache__/decoders.cpython-312.pyc,, +multipart/__pycache__/exceptions.cpython-312.pyc,, +multipart/__pycache__/multipart.cpython-312.pyc,, +multipart/decoders.py,sha256=XvkAwTU9UFPiXkc0hkvovHf0W6H3vK-2ieWlhav02hQ,40 +multipart/exceptions.py,sha256=6D_X-seiOmMAlIeiGlPGUs8-vpcvIGJeQycFMDb1f7A,42 +multipart/multipart.py,sha256=8fDH14j_VMbrch_58wlzi63XNARGv80kOZAyN72aG7A,41 +python_multipart-0.0.20.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +python_multipart-0.0.20.dist-info/METADATA,sha256=h2GtPOVShbVkpBUrjp5KE3t6eiJJhd0_WCaCXrb5TgU,1817 +python_multipart-0.0.20.dist-info/RECORD,, +python_multipart-0.0.20.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +python_multipart-0.0.20.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +python_multipart-0.0.20.dist-info/licenses/LICENSE.txt,sha256=qOgzF2zWF9rwC51tOfoVyo7evG0WQwec0vSJPAwom-I,556 +python_multipart/__init__.py,sha256=Nlw6Yrc__qXnCZLo17OzbJR2w2mwiSFk69IG4Wl35EU,512 +python_multipart/__pycache__/__init__.cpython-312.pyc,, +python_multipart/__pycache__/decoders.cpython-312.pyc,, +python_multipart/__pycache__/exceptions.cpython-312.pyc,, +python_multipart/__pycache__/multipart.cpython-312.pyc,, +python_multipart/decoders.py,sha256=JM43FMNn_EKP0MI2ZkuZHhNa0MOASoIR0U5TvdG585k,6669 +python_multipart/exceptions.py,sha256=a9buSOv_eiHZoukEJhdWX9LJYSJ6t7XOK3ZEaWoQZlk,992 +python_multipart/multipart.py,sha256=pk3o3eB3KXbNxzOBxbEjCdz-1ESEZIMXVIfl12grG-o,76427 +python_multipart/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/venv/Lib/site-packages/python_multipart-0.0.20.dist-info/REQUESTED b/venv/Lib/site-packages/python_multipart-0.0.20.dist-info/REQUESTED new file mode 100644 index 00000000..e69de29b diff --git a/venv/Lib/site-packages/python_multipart-0.0.20.dist-info/WHEEL b/venv/Lib/site-packages/python_multipart-0.0.20.dist-info/WHEEL new file mode 100644 index 00000000..12228d41 --- /dev/null +++ b/venv/Lib/site-packages/python_multipart-0.0.20.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/venv/Lib/site-packages/python_multipart-0.0.20.dist-info/licenses/LICENSE.txt b/venv/Lib/site-packages/python_multipart-0.0.20.dist-info/licenses/LICENSE.txt new file mode 100644 index 00000000..303a1bf5 --- /dev/null +++ b/venv/Lib/site-packages/python_multipart-0.0.20.dist-info/licenses/LICENSE.txt @@ -0,0 +1,14 @@ +Copyright 2012, Andrew Dunham + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + diff --git a/venv/Lib/site-packages/python_multipart/__init__.py b/venv/Lib/site-packages/python_multipart/__init__.py new file mode 100644 index 00000000..e4265264 --- /dev/null +++ b/venv/Lib/site-packages/python_multipart/__init__.py @@ -0,0 +1,25 @@ +# This is the canonical package information. +__author__ = "Andrew Dunham" +__license__ = "Apache" +__copyright__ = "Copyright (c) 2012-2013, Andrew Dunham" +__version__ = "0.0.20" + +from .multipart import ( + BaseParser, + FormParser, + MultipartParser, + OctetStreamParser, + QuerystringParser, + create_form_parser, + parse_form, +) + +__all__ = ( + "BaseParser", + "FormParser", + "MultipartParser", + "OctetStreamParser", + "QuerystringParser", + "create_form_parser", + "parse_form", +) diff --git a/venv/Lib/site-packages/python_multipart/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/python_multipart/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..f4d55911 Binary files /dev/null and b/venv/Lib/site-packages/python_multipart/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/python_multipart/__pycache__/decoders.cpython-312.pyc b/venv/Lib/site-packages/python_multipart/__pycache__/decoders.cpython-312.pyc new file mode 100644 index 00000000..fbfc62eb Binary files /dev/null and b/venv/Lib/site-packages/python_multipart/__pycache__/decoders.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/python_multipart/__pycache__/exceptions.cpython-312.pyc b/venv/Lib/site-packages/python_multipart/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 00000000..b6a4f75b Binary files /dev/null and b/venv/Lib/site-packages/python_multipart/__pycache__/exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/python_multipart/__pycache__/multipart.cpython-312.pyc b/venv/Lib/site-packages/python_multipart/__pycache__/multipart.cpython-312.pyc new file mode 100644 index 00000000..d53857a5 Binary files /dev/null and b/venv/Lib/site-packages/python_multipart/__pycache__/multipart.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/python_multipart/decoders.py b/venv/Lib/site-packages/python_multipart/decoders.py new file mode 100644 index 00000000..82b56a1e --- /dev/null +++ b/venv/Lib/site-packages/python_multipart/decoders.py @@ -0,0 +1,185 @@ +import base64 +import binascii +from typing import TYPE_CHECKING + +from .exceptions import DecodeError + +if TYPE_CHECKING: # pragma: no cover + from typing import Protocol, TypeVar + + _T_contra = TypeVar("_T_contra", contravariant=True) + + class SupportsWrite(Protocol[_T_contra]): + def write(self, __b: _T_contra) -> object: ... + + # No way to specify optional methods. See + # https://github.com/python/typing/issues/601 + # close() [Optional] + # finalize() [Optional] + + +class Base64Decoder: + """This object provides an interface to decode a stream of Base64 data. It + is instantiated with an "underlying object", and whenever a write() + operation is performed, it will decode the incoming data as Base64, and + call write() on the underlying object. This is primarily used for decoding + form data encoded as Base64, but can be used for other purposes:: + + from python_multipart.decoders import Base64Decoder + fd = open("notb64.txt", "wb") + decoder = Base64Decoder(fd) + try: + decoder.write("Zm9vYmFy") # "foobar" in Base64 + decoder.finalize() + finally: + decoder.close() + + # The contents of "notb64.txt" should be "foobar". + + This object will also pass all finalize() and close() calls to the + underlying object, if the underlying object supports them. + + Note that this class maintains a cache of base64 chunks, so that a write of + arbitrary size can be performed. You must call :meth:`finalize` on this + object after all writes are completed to ensure that all data is flushed + to the underlying object. + + :param underlying: the underlying object to pass writes to + """ + + def __init__(self, underlying: "SupportsWrite[bytes]") -> None: + self.cache = bytearray() + self.underlying = underlying + + def write(self, data: bytes) -> int: + """Takes any input data provided, decodes it as base64, and passes it + on to the underlying object. If the data provided is invalid base64 + data, then this method will raise + a :class:`python_multipart.exceptions.DecodeError` + + :param data: base64 data to decode + """ + + # Prepend any cache info to our data. + if len(self.cache) > 0: + data = self.cache + data + + # Slice off a string that's a multiple of 4. + decode_len = (len(data) // 4) * 4 + val = data[:decode_len] + + # Decode and write, if we have any. + if len(val) > 0: + try: + decoded = base64.b64decode(val) + except binascii.Error: + raise DecodeError("There was an error raised while decoding base64-encoded data.") + + self.underlying.write(decoded) + + # Get the remaining bytes and save in our cache. + remaining_len = len(data) % 4 + if remaining_len > 0: + self.cache[:] = data[-remaining_len:] + else: + self.cache[:] = b"" + + # Return the length of the data to indicate no error. + return len(data) + + def close(self) -> None: + """Close this decoder. If the underlying object has a `close()` + method, this function will call it. + """ + if hasattr(self.underlying, "close"): + self.underlying.close() + + def finalize(self) -> None: + """Finalize this object. This should be called when no more data + should be written to the stream. This function can raise a + :class:`python_multipart.exceptions.DecodeError` if there is some remaining + data in the cache. + + If the underlying object has a `finalize()` method, this function will + call it. + """ + if len(self.cache) > 0: + raise DecodeError( + "There are %d bytes remaining in the Base64Decoder cache when finalize() is called" % len(self.cache) + ) + + if hasattr(self.underlying, "finalize"): + self.underlying.finalize() + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(underlying={self.underlying!r})" + + +class QuotedPrintableDecoder: + """This object provides an interface to decode a stream of quoted-printable + data. It is instantiated with an "underlying object", in the same manner + as the :class:`python_multipart.decoders.Base64Decoder` class. This class behaves + in exactly the same way, including maintaining a cache of quoted-printable + chunks. + + :param underlying: the underlying object to pass writes to + """ + + def __init__(self, underlying: "SupportsWrite[bytes]") -> None: + self.cache = b"" + self.underlying = underlying + + def write(self, data: bytes) -> int: + """Takes any input data provided, decodes it as quoted-printable, and + passes it on to the underlying object. + + :param data: quoted-printable data to decode + """ + # Prepend any cache info to our data. + if len(self.cache) > 0: + data = self.cache + data + + # If the last 2 characters have an '=' sign in it, then we won't be + # able to decode the encoded value and we'll need to save it for the + # next decoding step. + if data[-2:].find(b"=") != -1: + enc, rest = data[:-2], data[-2:] + else: + enc = data + rest = b"" + + # Encode and write, if we have data. + if len(enc) > 0: + self.underlying.write(binascii.a2b_qp(enc)) + + # Save remaining in cache. + self.cache = rest + return len(data) + + def close(self) -> None: + """Close this decoder. If the underlying object has a `close()` + method, this function will call it. + """ + if hasattr(self.underlying, "close"): + self.underlying.close() + + def finalize(self) -> None: + """Finalize this object. This should be called when no more data + should be written to the stream. This function will not raise any + exceptions, but it may write more data to the underlying object if + there is data remaining in the cache. + + If the underlying object has a `finalize()` method, this function will + call it. + """ + # If we have a cache, write and then remove it. + if len(self.cache) > 0: # pragma: no cover + self.underlying.write(binascii.a2b_qp(self.cache)) + self.cache = b"" + + # Finalize our underlying stream. + if hasattr(self.underlying, "finalize"): + self.underlying.finalize() + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(underlying={self.underlying!r})" diff --git a/venv/Lib/site-packages/python_multipart/exceptions.py b/venv/Lib/site-packages/python_multipart/exceptions.py new file mode 100644 index 00000000..cc3671f5 --- /dev/null +++ b/venv/Lib/site-packages/python_multipart/exceptions.py @@ -0,0 +1,34 @@ +class FormParserError(ValueError): + """Base error class for our form parser.""" + + +class ParseError(FormParserError): + """This exception (or a subclass) is raised when there is an error while + parsing something. + """ + + #: This is the offset in the input data chunk (*NOT* the overall stream) in + #: which the parse error occurred. It will be -1 if not specified. + offset = -1 + + +class MultipartParseError(ParseError): + """This is a specific error that is raised when the MultipartParser detects + an error while parsing. + """ + + +class QuerystringParseError(ParseError): + """This is a specific error that is raised when the QuerystringParser + detects an error while parsing. + """ + + +class DecodeError(ParseError): + """This exception is raised when there is a decoding error - for example + with the Base64Decoder or QuotedPrintableDecoder. + """ + + +class FileError(FormParserError, OSError): + """Exception class for problems with the File class.""" diff --git a/venv/Lib/site-packages/python_multipart/multipart.py b/venv/Lib/site-packages/python_multipart/multipart.py new file mode 100644 index 00000000..f26a815a --- /dev/null +++ b/venv/Lib/site-packages/python_multipart/multipart.py @@ -0,0 +1,1873 @@ +from __future__ import annotations + +import logging +import os +import shutil +import sys +import tempfile +from email.message import Message +from enum import IntEnum +from io import BufferedRandom, BytesIO +from numbers import Number +from typing import TYPE_CHECKING, cast + +from .decoders import Base64Decoder, QuotedPrintableDecoder +from .exceptions import FileError, FormParserError, MultipartParseError, QuerystringParseError + +if TYPE_CHECKING: # pragma: no cover + from typing import Any, Callable, Literal, Protocol, TypedDict + + from typing_extensions import TypeAlias + + class SupportsRead(Protocol): + def read(self, __n: int) -> bytes: ... + + class QuerystringCallbacks(TypedDict, total=False): + on_field_start: Callable[[], None] + on_field_name: Callable[[bytes, int, int], None] + on_field_data: Callable[[bytes, int, int], None] + on_field_end: Callable[[], None] + on_end: Callable[[], None] + + class OctetStreamCallbacks(TypedDict, total=False): + on_start: Callable[[], None] + on_data: Callable[[bytes, int, int], None] + on_end: Callable[[], None] + + class MultipartCallbacks(TypedDict, total=False): + on_part_begin: Callable[[], None] + on_part_data: Callable[[bytes, int, int], None] + on_part_end: Callable[[], None] + on_header_begin: Callable[[], None] + on_header_field: Callable[[bytes, int, int], None] + on_header_value: Callable[[bytes, int, int], None] + on_header_end: Callable[[], None] + on_headers_finished: Callable[[], None] + on_end: Callable[[], None] + + class FormParserConfig(TypedDict): + UPLOAD_DIR: str | None + UPLOAD_KEEP_FILENAME: bool + UPLOAD_KEEP_EXTENSIONS: bool + UPLOAD_ERROR_ON_BAD_CTE: bool + MAX_MEMORY_FILE_SIZE: int + MAX_BODY_SIZE: float + + class FileConfig(TypedDict, total=False): + UPLOAD_DIR: str | bytes | None + UPLOAD_DELETE_TMP: bool + UPLOAD_KEEP_FILENAME: bool + UPLOAD_KEEP_EXTENSIONS: bool + MAX_MEMORY_FILE_SIZE: int + + class _FormProtocol(Protocol): + def write(self, data: bytes) -> int: ... + + def finalize(self) -> None: ... + + def close(self) -> None: ... + + class FieldProtocol(_FormProtocol, Protocol): + def __init__(self, name: bytes | None) -> None: ... + + def set_none(self) -> None: ... + + class FileProtocol(_FormProtocol, Protocol): + def __init__(self, file_name: bytes | None, field_name: bytes | None, config: FileConfig) -> None: ... + + OnFieldCallback = Callable[[FieldProtocol], None] + OnFileCallback = Callable[[FileProtocol], None] + + CallbackName: TypeAlias = Literal[ + "start", + "data", + "end", + "field_start", + "field_name", + "field_data", + "field_end", + "part_begin", + "part_data", + "part_end", + "header_begin", + "header_field", + "header_value", + "header_end", + "headers_finished", + ] + +# Unique missing object. +_missing = object() + + +class QuerystringState(IntEnum): + """Querystring parser states. + + These are used to keep track of the state of the parser, and are used to determine + what to do when new data is encountered. + """ + + BEFORE_FIELD = 0 + FIELD_NAME = 1 + FIELD_DATA = 2 + + +class MultipartState(IntEnum): + """Multipart parser states. + + These are used to keep track of the state of the parser, and are used to determine + what to do when new data is encountered. + """ + + START = 0 + START_BOUNDARY = 1 + HEADER_FIELD_START = 2 + HEADER_FIELD = 3 + HEADER_VALUE_START = 4 + HEADER_VALUE = 5 + HEADER_VALUE_ALMOST_DONE = 6 + HEADERS_ALMOST_DONE = 7 + PART_DATA_START = 8 + PART_DATA = 9 + PART_DATA_END = 10 + END_BOUNDARY = 11 + END = 12 + + +# Flags for the multipart parser. +FLAG_PART_BOUNDARY = 1 +FLAG_LAST_BOUNDARY = 2 + +# Get constants. Since iterating over a str on Python 2 gives you a 1-length +# string, but iterating over a bytes object on Python 3 gives you an integer, +# we need to save these constants. +CR = b"\r"[0] +LF = b"\n"[0] +COLON = b":"[0] +SPACE = b" "[0] +HYPHEN = b"-"[0] +AMPERSAND = b"&"[0] +SEMICOLON = b";"[0] +LOWER_A = b"a"[0] +LOWER_Z = b"z"[0] +NULL = b"\x00"[0] + +# fmt: off +# Mask for ASCII characters that can be http tokens. +# Per RFC7230 - 3.2.6, this is all alpha-numeric characters +# and these: !#$%&'*+-.^_`|~ +TOKEN_CHARS_SET = frozenset( + b"ABCDEFGHIJKLMNOPQRSTUVWXYZ" + b"abcdefghijklmnopqrstuvwxyz" + b"0123456789" + b"!#$%&'*+-.^_`|~") +# fmt: on + + +def parse_options_header(value: str | bytes | None) -> tuple[bytes, dict[bytes, bytes]]: + """Parses a Content-Type header into a value in the following format: (content_type, {parameters}).""" + # Uses email.message.Message to parse the header as described in PEP 594. + # Ref: https://peps.python.org/pep-0594/#cgi + if not value: + return (b"", {}) + + # If we are passed bytes, we assume that it conforms to WSGI, encoding in latin-1. + if isinstance(value, bytes): # pragma: no cover + value = value.decode("latin-1") + + # For types + assert isinstance(value, str), "Value should be a string by now" + + # If we have no options, return the string as-is. + if ";" not in value: + return (value.lower().strip().encode("latin-1"), {}) + + # Split at the first semicolon, to get our value and then options. + # ctype, rest = value.split(b';', 1) + message = Message() + message["content-type"] = value + params = message.get_params() + # If there were no parameters, this would have already returned above + assert params, "At least the content type value should be present" + ctype = params.pop(0)[0].encode("latin-1") + options: dict[bytes, bytes] = {} + for param in params: + key, value = param + # If the value returned from get_params() is a 3-tuple, the last + # element corresponds to the value. + # See: https://docs.python.org/3/library/email.compat32-message.html + if isinstance(value, tuple): + value = value[-1] + # If the value is a filename, we need to fix a bug on IE6 that sends + # the full file path instead of the filename. + if key == "filename": + if value[1:3] == ":\\" or value[:2] == "\\\\": + value = value.split("\\")[-1] + options[key.encode("latin-1")] = value.encode("latin-1") + return ctype, options + + +class Field: + """A Field object represents a (parsed) form field. It represents a single + field with a corresponding name and value. + + The name that a :class:`Field` will be instantiated with is the same name + that would be found in the following HTML:: + + + + This class defines two methods, :meth:`on_data` and :meth:`on_end`, that + will be called when data is written to the Field, and when the Field is + finalized, respectively. + + Args: + name: The name of the form field. + """ + + def __init__(self, name: bytes | None) -> None: + self._name = name + self._value: list[bytes] = [] + + # We cache the joined version of _value for speed. + self._cache = _missing + + @classmethod + def from_value(cls, name: bytes, value: bytes | None) -> Field: + """Create an instance of a :class:`Field`, and set the corresponding + value - either None or an actual value. This method will also + finalize the Field itself. + + Args: + name: the name of the form field. + value: the value of the form field - either a bytestring or None. + + Returns: + A new instance of a [`Field`][python_multipart.Field]. + """ + + f = cls(name) + if value is None: + f.set_none() + else: + f.write(value) + f.finalize() + return f + + def write(self, data: bytes) -> int: + """Write some data into the form field. + + Args: + data: The data to write to the field. + + Returns: + The number of bytes written. + """ + return self.on_data(data) + + def on_data(self, data: bytes) -> int: + """This method is a callback that will be called whenever data is + written to the Field. + + Args: + data: The data to write to the field. + + Returns: + The number of bytes written. + """ + self._value.append(data) + self._cache = _missing + return len(data) + + def on_end(self) -> None: + """This method is called whenever the Field is finalized.""" + if self._cache is _missing: + self._cache = b"".join(self._value) + + def finalize(self) -> None: + """Finalize the form field.""" + self.on_end() + + def close(self) -> None: + """Close the Field object. This will free any underlying cache.""" + # Free our value array. + if self._cache is _missing: + self._cache = b"".join(self._value) + + del self._value + + def set_none(self) -> None: + """Some fields in a querystring can possibly have a value of None - for + example, the string "foo&bar=&baz=asdf" will have a field with the + name "foo" and value None, one with name "bar" and value "", and one + with name "baz" and value "asdf". Since the write() interface doesn't + support writing None, this function will set the field value to None. + """ + self._cache = None + + @property + def field_name(self) -> bytes | None: + """This property returns the name of the field.""" + return self._name + + @property + def value(self) -> bytes | None: + """This property returns the value of the form field.""" + if self._cache is _missing: + self._cache = b"".join(self._value) + + assert isinstance(self._cache, bytes) or self._cache is None + return self._cache + + def __eq__(self, other: object) -> bool: + if isinstance(other, Field): + return self.field_name == other.field_name and self.value == other.value + else: + return NotImplemented + + def __repr__(self) -> str: + if self.value is not None and len(self.value) > 97: + # We get the repr, and then insert three dots before the final + # quote. + v = repr(self.value[:97])[:-1] + "...'" + else: + v = repr(self.value) + + return "{}(field_name={!r}, value={})".format(self.__class__.__name__, self.field_name, v) + + +class File: + """This class represents an uploaded file. It handles writing file data to + either an in-memory file or a temporary file on-disk, if the optional + threshold is passed. + + There are some options that can be passed to the File to change behavior + of the class. Valid options are as follows: + + | Name | Type | Default | Description | + |-----------------------|-------|---------|-------------| + | UPLOAD_DIR | `str` | None | The directory to store uploaded files in. If this is None, a temporary file will be created in the system's standard location. | + | UPLOAD_DELETE_TMP | `bool`| True | Delete automatically created TMP file | + | UPLOAD_KEEP_FILENAME | `bool`| False | Whether or not to keep the filename of the uploaded file. If True, then the filename will be converted to a safe representation (e.g. by removing any invalid path segments), and then saved with the same name). Otherwise, a temporary name will be used. | + | UPLOAD_KEEP_EXTENSIONS| `bool`| False | Whether or not to keep the uploaded file's extension. If False, the file will be saved with the default temporary extension (usually ".tmp"). Otherwise, the file's extension will be maintained. Note that this will properly combine with the UPLOAD_KEEP_FILENAME setting. | + | MAX_MEMORY_FILE_SIZE | `int` | 1 MiB | The maximum number of bytes of a File to keep in memory. By default, the contents of a File are kept into memory until a certain limit is reached, after which the contents of the File are written to a temporary file. This behavior can be disabled by setting this value to an appropriately large value (or, for example, infinity, such as `float('inf')`. | + + Args: + file_name: The name of the file that this [`File`][python_multipart.File] represents. + field_name: The name of the form field that this file was uploaded with. This can be None, if, for example, + the file was uploaded with Content-Type application/octet-stream. + config: The configuration for this File. See above for valid configuration keys and their corresponding values. + """ # noqa: E501 + + def __init__(self, file_name: bytes | None, field_name: bytes | None = None, config: FileConfig = {}) -> None: + # Save configuration, set other variables default. + self.logger = logging.getLogger(__name__) + self._config = config + self._in_memory = True + self._bytes_written = 0 + self._fileobj: BytesIO | BufferedRandom = BytesIO() + + # Save the provided field/file name. + self._field_name = field_name + self._file_name = file_name + + # Our actual file name is None by default, since, depending on our + # config, we may not actually use the provided name. + self._actual_file_name: bytes | None = None + + # Split the extension from the filename. + if file_name is not None: + base, ext = os.path.splitext(file_name) + self._file_base = base + self._ext = ext + + @property + def field_name(self) -> bytes | None: + """The form field associated with this file. May be None if there isn't + one, for example when we have an application/octet-stream upload. + """ + return self._field_name + + @property + def file_name(self) -> bytes | None: + """The file name given in the upload request.""" + return self._file_name + + @property + def actual_file_name(self) -> bytes | None: + """The file name that this file is saved as. Will be None if it's not + currently saved on disk. + """ + return self._actual_file_name + + @property + def file_object(self) -> BytesIO | BufferedRandom: + """The file object that we're currently writing to. Note that this + will either be an instance of a :class:`io.BytesIO`, or a regular file + object. + """ + return self._fileobj + + @property + def size(self) -> int: + """The total size of this file, counted as the number of bytes that + currently have been written to the file. + """ + return self._bytes_written + + @property + def in_memory(self) -> bool: + """A boolean representing whether or not this file object is currently + stored in-memory or on-disk. + """ + return self._in_memory + + def flush_to_disk(self) -> None: + """If the file is already on-disk, do nothing. Otherwise, copy from + the in-memory buffer to a disk file, and then reassign our internal + file object to this new disk file. + + Note that if you attempt to flush a file that is already on-disk, a + warning will be logged to this module's logger. + """ + if not self._in_memory: + self.logger.warning("Trying to flush to disk when we're not in memory") + return + + # Go back to the start of our file. + self._fileobj.seek(0) + + # Open a new file. + new_file = self._get_disk_file() + + # Copy the file objects. + shutil.copyfileobj(self._fileobj, new_file) + + # Seek to the new position in our new file. + new_file.seek(self._bytes_written) + + # Reassign the fileobject. + old_fileobj = self._fileobj + self._fileobj = new_file + + # We're no longer in memory. + self._in_memory = False + + # Close the old file object. + old_fileobj.close() + + def _get_disk_file(self) -> BufferedRandom: + """This function is responsible for getting a file object on-disk for us.""" + self.logger.info("Opening a file on disk") + + file_dir = self._config.get("UPLOAD_DIR") + keep_filename = self._config.get("UPLOAD_KEEP_FILENAME", False) + keep_extensions = self._config.get("UPLOAD_KEEP_EXTENSIONS", False) + delete_tmp = self._config.get("UPLOAD_DELETE_TMP", True) + tmp_file: None | BufferedRandom = None + + # If we have a directory and are to keep the filename... + if file_dir is not None and keep_filename: + self.logger.info("Saving with filename in: %r", file_dir) + + # Build our filename. + # TODO: what happens if we don't have a filename? + fname = self._file_base + self._ext if keep_extensions else self._file_base + + path = os.path.join(file_dir, fname) # type: ignore[arg-type] + try: + self.logger.info("Opening file: %r", path) + tmp_file = open(path, "w+b") + except OSError: + tmp_file = None + + self.logger.exception("Error opening temporary file") + raise FileError("Error opening temporary file: %r" % path) + else: + # Build options array. + # Note that on Python 3, tempfile doesn't support byte names. We + # encode our paths using the default filesystem encoding. + suffix = self._ext.decode(sys.getfilesystemencoding()) if keep_extensions else None + + if file_dir is None: + dir = None + elif isinstance(file_dir, bytes): + dir = file_dir.decode(sys.getfilesystemencoding()) + else: + dir = file_dir # pragma: no cover + + # Create a temporary (named) file with the appropriate settings. + self.logger.info( + "Creating a temporary file with options: %r", {"suffix": suffix, "delete": delete_tmp, "dir": dir} + ) + try: + tmp_file = cast(BufferedRandom, tempfile.NamedTemporaryFile(suffix=suffix, delete=delete_tmp, dir=dir)) + except OSError: + self.logger.exception("Error creating named temporary file") + raise FileError("Error creating named temporary file") + + assert tmp_file is not None + # Encode filename as bytes. + if isinstance(tmp_file.name, str): + fname = tmp_file.name.encode(sys.getfilesystemencoding()) + else: + fname = cast(bytes, tmp_file.name) # pragma: no cover + + self._actual_file_name = fname + return tmp_file + + def write(self, data: bytes) -> int: + """Write some data to the File. + + :param data: a bytestring + """ + return self.on_data(data) + + def on_data(self, data: bytes) -> int: + """This method is a callback that will be called whenever data is + written to the File. + + Args: + data: The data to write to the file. + + Returns: + The number of bytes written. + """ + bwritten = self._fileobj.write(data) + + # If the bytes written isn't the same as the length, just return. + if bwritten != len(data): + self.logger.warning("bwritten != len(data) (%d != %d)", bwritten, len(data)) + return bwritten + + # Keep track of how many bytes we've written. + self._bytes_written += bwritten + + # If we're in-memory and are over our limit, we create a file. + max_memory_file_size = self._config.get("MAX_MEMORY_FILE_SIZE") + if self._in_memory and max_memory_file_size is not None and (self._bytes_written > max_memory_file_size): + self.logger.info("Flushing to disk") + self.flush_to_disk() + + # Return the number of bytes written. + return bwritten + + def on_end(self) -> None: + """This method is called whenever the Field is finalized.""" + # Flush the underlying file object + self._fileobj.flush() + + def finalize(self) -> None: + """Finalize the form file. This will not close the underlying file, + but simply signal that we are finished writing to the File. + """ + self.on_end() + + def close(self) -> None: + """Close the File object. This will actually close the underlying + file object (whether it's a :class:`io.BytesIO` or an actual file + object). + """ + self._fileobj.close() + + def __repr__(self) -> str: + return "{}(file_name={!r}, field_name={!r})".format(self.__class__.__name__, self.file_name, self.field_name) + + +class BaseParser: + """This class is the base class for all parsers. It contains the logic for + calling and adding callbacks. + + A callback can be one of two different forms. "Notification callbacks" are + callbacks that are called when something happens - for example, when a new + part of a multipart message is encountered by the parser. "Data callbacks" + are called when we get some sort of data - for example, part of the body of + a multipart chunk. Notification callbacks are called with no parameters, + whereas data callbacks are called with three, as follows:: + + data_callback(data, start, end) + + The "data" parameter is a bytestring (i.e. "foo" on Python 2, or b"foo" on + Python 3). "start" and "end" are integer indexes into the "data" string + that represent the data of interest. Thus, in a data callback, the slice + `data[start:end]` represents the data that the callback is "interested in". + The callback is not passed a copy of the data, since copying severely hurts + performance. + """ + + def __init__(self) -> None: + self.logger = logging.getLogger(__name__) + self.callbacks: QuerystringCallbacks | OctetStreamCallbacks | MultipartCallbacks = {} + + def callback( + self, name: CallbackName, data: bytes | None = None, start: int | None = None, end: int | None = None + ) -> None: + """This function calls a provided callback with some data. If the + callback is not set, will do nothing. + + Args: + name: The name of the callback to call (as a string). + data: Data to pass to the callback. If None, then it is assumed that the callback is a notification + callback, and no parameters are given. + end: An integer that is passed to the data callback. + start: An integer that is passed to the data callback. + """ + on_name = "on_" + name + func = self.callbacks.get(on_name) + if func is None: + return + func = cast("Callable[..., Any]", func) + # Depending on whether we're given a buffer... + if data is not None: + # Don't do anything if we have start == end. + if start is not None and start == end: + return + + self.logger.debug("Calling %s with data[%d:%d]", on_name, start, end) + func(data, start, end) + else: + self.logger.debug("Calling %s with no data", on_name) + func() + + def set_callback(self, name: CallbackName, new_func: Callable[..., Any] | None) -> None: + """Update the function for a callback. Removes from the callbacks dict + if new_func is None. + + :param name: The name of the callback to call (as a string). + + :param new_func: The new function for the callback. If None, then the + callback will be removed (with no error if it does not + exist). + """ + if new_func is None: + self.callbacks.pop("on_" + name, None) # type: ignore[misc] + else: + self.callbacks["on_" + name] = new_func # type: ignore[literal-required] + + def close(self) -> None: + pass # pragma: no cover + + def finalize(self) -> None: + pass # pragma: no cover + + def __repr__(self) -> str: + return "%s()" % self.__class__.__name__ + + +class OctetStreamParser(BaseParser): + """This parser parses an octet-stream request body and calls callbacks when + incoming data is received. Callbacks are as follows: + + | Callback Name | Parameters | Description | + |----------------|-----------------|-----------------------------------------------------| + | on_start | None | Called when the first data is parsed. | + | on_data | data, start, end| Called for each data chunk that is parsed. | + | on_end | None | Called when the parser is finished parsing all data.| + + Args: + callbacks: A dictionary of callbacks. See the documentation for [`BaseParser`][python_multipart.BaseParser]. + max_size: The maximum size of body to parse. Defaults to infinity - i.e. unbounded. + """ + + def __init__(self, callbacks: OctetStreamCallbacks = {}, max_size: float = float("inf")): + super().__init__() + self.callbacks = callbacks + self._started = False + + if not isinstance(max_size, Number) or max_size < 1: + raise ValueError("max_size must be a positive number, not %r" % max_size) + self.max_size: int | float = max_size + self._current_size = 0 + + def write(self, data: bytes) -> int: + """Write some data to the parser, which will perform size verification, + and then pass the data to the underlying callback. + + Args: + data: The data to write to the parser. + + Returns: + The number of bytes written. + """ + if not self._started: + self.callback("start") + self._started = True + + # Truncate data length. + data_len = len(data) + if (self._current_size + data_len) > self.max_size: + # We truncate the length of data that we are to process. + new_size = int(self.max_size - self._current_size) + self.logger.warning( + "Current size is %d (max %d), so truncating data length from %d to %d", + self._current_size, + self.max_size, + data_len, + new_size, + ) + data_len = new_size + + # Increment size, then callback, in case there's an exception. + self._current_size += data_len + self.callback("data", data, 0, data_len) + return data_len + + def finalize(self) -> None: + """Finalize this parser, which signals to that we are finished parsing, + and sends the on_end callback. + """ + self.callback("end") + + def __repr__(self) -> str: + return "%s()" % self.__class__.__name__ + + +class QuerystringParser(BaseParser): + """This is a streaming querystring parser. It will consume data, and call + the callbacks given when it has data. + + | Callback Name | Parameters | Description | + |----------------|-----------------|-----------------------------------------------------| + | on_field_start | None | Called when a new field is encountered. | + | on_field_name | data, start, end| Called when a portion of a field's name is encountered. | + | on_field_data | data, start, end| Called when a portion of a field's data is encountered. | + | on_field_end | None | Called when the end of a field is encountered. | + | on_end | None | Called when the parser is finished parsing all data.| + + Args: + callbacks: A dictionary of callbacks. See the documentation for [`BaseParser`][python_multipart.BaseParser]. + strict_parsing: Whether or not to parse the body strictly. Defaults to False. If this is set to True, then the + behavior of the parser changes as the following: if a field has a value with an equal sign + (e.g. "foo=bar", or "foo="), it is always included. If a field has no equals sign (e.g. "...&name&..."), + it will be treated as an error if 'strict_parsing' is True, otherwise included. If an error is encountered, + then a [`QuerystringParseError`][python_multipart.exceptions.QuerystringParseError] will be raised. + max_size: The maximum size of body to parse. Defaults to infinity - i.e. unbounded. + """ # noqa: E501 + + state: QuerystringState + + def __init__( + self, callbacks: QuerystringCallbacks = {}, strict_parsing: bool = False, max_size: float = float("inf") + ) -> None: + super().__init__() + self.state = QuerystringState.BEFORE_FIELD + self._found_sep = False + + self.callbacks = callbacks + + # Max-size stuff + if not isinstance(max_size, Number) or max_size < 1: + raise ValueError("max_size must be a positive number, not %r" % max_size) + self.max_size: int | float = max_size + self._current_size = 0 + + # Should parsing be strict? + self.strict_parsing = strict_parsing + + def write(self, data: bytes) -> int: + """Write some data to the parser, which will perform size verification, + parse into either a field name or value, and then pass the + corresponding data to the underlying callback. If an error is + encountered while parsing, a QuerystringParseError will be raised. The + "offset" attribute of the raised exception will be set to the offset in + the input data chunk (NOT the overall stream) that caused the error. + + Args: + data: The data to write to the parser. + + Returns: + The number of bytes written. + """ + # Handle sizing. + data_len = len(data) + if (self._current_size + data_len) > self.max_size: + # We truncate the length of data that we are to process. + new_size = int(self.max_size - self._current_size) + self.logger.warning( + "Current size is %d (max %d), so truncating data length from %d to %d", + self._current_size, + self.max_size, + data_len, + new_size, + ) + data_len = new_size + + l = 0 + try: + l = self._internal_write(data, data_len) + finally: + self._current_size += l + + return l + + def _internal_write(self, data: bytes, length: int) -> int: + state = self.state + strict_parsing = self.strict_parsing + found_sep = self._found_sep + + i = 0 + while i < length: + ch = data[i] + + # Depending on our state... + if state == QuerystringState.BEFORE_FIELD: + # If the 'found_sep' flag is set, we've already encountered + # and skipped a single separator. If so, we check our strict + # parsing flag and decide what to do. Otherwise, we haven't + # yet reached a separator, and thus, if we do, we need to skip + # it as it will be the boundary between fields that's supposed + # to be there. + if ch == AMPERSAND or ch == SEMICOLON: + if found_sep: + # If we're parsing strictly, we disallow blank chunks. + if strict_parsing: + e = QuerystringParseError("Skipping duplicate ampersand/semicolon at %d" % i) + e.offset = i + raise e + else: + self.logger.debug("Skipping duplicate ampersand/semicolon at %d", i) + else: + # This case is when we're skipping the (first) + # separator between fields, so we just set our flag + # and continue on. + found_sep = True + else: + # Emit a field-start event, and go to that state. Also, + # reset the "found_sep" flag, for the next time we get to + # this state. + self.callback("field_start") + i -= 1 + state = QuerystringState.FIELD_NAME + found_sep = False + + elif state == QuerystringState.FIELD_NAME: + # Try and find a separator - we ensure that, if we do, we only + # look for the equal sign before it. + sep_pos = data.find(b"&", i) + if sep_pos == -1: + sep_pos = data.find(b";", i) + + # See if we can find an equals sign in the remaining data. If + # so, we can immediately emit the field name and jump to the + # data state. + if sep_pos != -1: + equals_pos = data.find(b"=", i, sep_pos) + else: + equals_pos = data.find(b"=", i) + + if equals_pos != -1: + # Emit this name. + self.callback("field_name", data, i, equals_pos) + + # Jump i to this position. Note that it will then have 1 + # added to it below, which means the next iteration of this + # loop will inspect the character after the equals sign. + i = equals_pos + state = QuerystringState.FIELD_DATA + else: + # No equals sign found. + if not strict_parsing: + # See also comments in the QuerystringState.FIELD_DATA case below. + # If we found the separator, we emit the name and just + # end - there's no data callback at all (not even with + # a blank value). + if sep_pos != -1: + self.callback("field_name", data, i, sep_pos) + self.callback("field_end") + + i = sep_pos - 1 + state = QuerystringState.BEFORE_FIELD + else: + # Otherwise, no separator in this block, so the + # rest of this chunk must be a name. + self.callback("field_name", data, i, length) + i = length + + else: + # We're parsing strictly. If we find a separator, + # this is an error - we require an equals sign. + if sep_pos != -1: + e = QuerystringParseError( + "When strict_parsing is True, we require an " + "equals sign in all field chunks. Did not " + "find one in the chunk that starts at %d" % (i,) + ) + e.offset = i + raise e + + # No separator in the rest of this chunk, so it's just + # a field name. + self.callback("field_name", data, i, length) + i = length + + elif state == QuerystringState.FIELD_DATA: + # Try finding either an ampersand or a semicolon after this + # position. + sep_pos = data.find(b"&", i) + if sep_pos == -1: + sep_pos = data.find(b";", i) + + # If we found it, callback this bit as data and then go back + # to expecting to find a field. + if sep_pos != -1: + self.callback("field_data", data, i, sep_pos) + self.callback("field_end") + + # Note that we go to the separator, which brings us to the + # "before field" state. This allows us to properly emit + # "field_start" events only when we actually have data for + # a field of some sort. + i = sep_pos - 1 + state = QuerystringState.BEFORE_FIELD + + # Otherwise, emit the rest as data and finish. + else: + self.callback("field_data", data, i, length) + i = length + + else: # pragma: no cover (error case) + msg = "Reached an unknown state %d at %d" % (state, i) + self.logger.warning(msg) + e = QuerystringParseError(msg) + e.offset = i + raise e + + i += 1 + + self.state = state + self._found_sep = found_sep + return len(data) + + def finalize(self) -> None: + """Finalize this parser, which signals to that we are finished parsing, + if we're still in the middle of a field, an on_field_end callback, and + then the on_end callback. + """ + # If we're currently in the middle of a field, we finish it. + if self.state == QuerystringState.FIELD_DATA: + self.callback("field_end") + self.callback("end") + + def __repr__(self) -> str: + return "{}(strict_parsing={!r}, max_size={!r})".format( + self.__class__.__name__, self.strict_parsing, self.max_size + ) + + +class MultipartParser(BaseParser): + """This class is a streaming multipart/form-data parser. + + | Callback Name | Parameters | Description | + |--------------------|-----------------|-------------| + | on_part_begin | None | Called when a new part of the multipart message is encountered. | + | on_part_data | data, start, end| Called when a portion of a part's data is encountered. | + | on_part_end | None | Called when the end of a part is reached. | + | on_header_begin | None | Called when we've found a new header in a part of a multipart message | + | on_header_field | data, start, end| Called each time an additional portion of a header is read (i.e. the part of the header that is before the colon; the "Foo" in "Foo: Bar"). | + | on_header_value | data, start, end| Called when we get data for a header. | + | on_header_end | None | Called when the current header is finished - i.e. we've reached the newline at the end of the header. | + | on_headers_finished| None | Called when all headers are finished, and before the part data starts. | + | on_end | None | Called when the parser is finished parsing all data. | + + Args: + boundary: The multipart boundary. This is required, and must match what is given in the HTTP request - usually in the Content-Type header. + callbacks: A dictionary of callbacks. See the documentation for [`BaseParser`][python_multipart.BaseParser]. + max_size: The maximum size of body to parse. Defaults to infinity - i.e. unbounded. + """ # noqa: E501 + + def __init__( + self, boundary: bytes | str, callbacks: MultipartCallbacks = {}, max_size: float = float("inf") + ) -> None: + # Initialize parser state. + super().__init__() + self.state = MultipartState.START + self.index = self.flags = 0 + + self.callbacks = callbacks + + if not isinstance(max_size, Number) or max_size < 1: + raise ValueError("max_size must be a positive number, not %r" % max_size) + self.max_size = max_size + self._current_size = 0 + + # Setup marks. These are used to track the state of data received. + self.marks: dict[str, int] = {} + + # Save our boundary. + if isinstance(boundary, str): # pragma: no cover + boundary = boundary.encode("latin-1") + self.boundary = b"\r\n--" + boundary + + def write(self, data: bytes) -> int: + """Write some data to the parser, which will perform size verification, + and then parse the data into the appropriate location (e.g. header, + data, etc.), and pass this on to the underlying callback. If an error + is encountered, a MultipartParseError will be raised. The "offset" + attribute on the raised exception will be set to the offset of the byte + in the input chunk that caused the error. + + Args: + data: The data to write to the parser. + + Returns: + The number of bytes written. + """ + # Handle sizing. + data_len = len(data) + if (self._current_size + data_len) > self.max_size: + # We truncate the length of data that we are to process. + new_size = int(self.max_size - self._current_size) + self.logger.warning( + "Current size is %d (max %d), so truncating data length from %d to %d", + self._current_size, + self.max_size, + data_len, + new_size, + ) + data_len = new_size + + l = 0 + try: + l = self._internal_write(data, data_len) + finally: + self._current_size += l + + return l + + def _internal_write(self, data: bytes, length: int) -> int: + # Get values from locals. + boundary = self.boundary + + # Get our state, flags and index. These are persisted between calls to + # this function. + state = self.state + index = self.index + flags = self.flags + + # Our index defaults to 0. + i = 0 + + # Set a mark. + def set_mark(name: str) -> None: + self.marks[name] = i + + # Remove a mark. + def delete_mark(name: str, reset: bool = False) -> None: + self.marks.pop(name, None) + + # Helper function that makes calling a callback with data easier. The + # 'remaining' parameter will callback from the marked value until the + # end of the buffer, and reset the mark, instead of deleting it. This + # is used at the end of the function to call our callbacks with any + # remaining data in this chunk. + def data_callback(name: CallbackName, end_i: int, remaining: bool = False) -> None: + marked_index = self.marks.get(name) + if marked_index is None: + return + + # Otherwise, we call it from the mark to the current byte we're + # processing. + if end_i <= marked_index: + # There is no additional data to send. + pass + elif marked_index >= 0: + # We are emitting data from the local buffer. + self.callback(name, data, marked_index, end_i) + else: + # Some of the data comes from a partial boundary match. + # and requires look-behind. + # We need to use self.flags (and not flags) because we care about + # the state when we entered the loop. + lookbehind_len = -marked_index + if lookbehind_len <= len(boundary): + self.callback(name, boundary, 0, lookbehind_len) + elif self.flags & FLAG_PART_BOUNDARY: + lookback = boundary + b"\r\n" + self.callback(name, lookback, 0, lookbehind_len) + elif self.flags & FLAG_LAST_BOUNDARY: + lookback = boundary + b"--\r\n" + self.callback(name, lookback, 0, lookbehind_len) + else: # pragma: no cover (error case) + self.logger.warning("Look-back buffer error") + + if end_i > 0: + self.callback(name, data, 0, end_i) + # If we're getting remaining data, we have got all the data we + # can be certain is not a boundary, leaving only a partial boundary match. + if remaining: + self.marks[name] = end_i - length + else: + self.marks.pop(name, None) + + # For each byte... + while i < length: + c = data[i] + + if state == MultipartState.START: + # Skip leading newlines + if c == CR or c == LF: + i += 1 + continue + + # index is used as in index into our boundary. Set to 0. + index = 0 + + # Move to the next state, but decrement i so that we re-process + # this character. + state = MultipartState.START_BOUNDARY + i -= 1 + + elif state == MultipartState.START_BOUNDARY: + # Check to ensure that the last 2 characters in our boundary + # are CRLF. + if index == len(boundary) - 2: + if c == HYPHEN: + # Potential empty message. + state = MultipartState.END_BOUNDARY + elif c != CR: + # Error! + msg = "Did not find CR at end of boundary (%d)" % (i,) + self.logger.warning(msg) + e = MultipartParseError(msg) + e.offset = i + raise e + + index += 1 + + elif index == len(boundary) - 2 + 1: + if c != LF: + msg = "Did not find LF at end of boundary (%d)" % (i,) + self.logger.warning(msg) + e = MultipartParseError(msg) + e.offset = i + raise e + + # The index is now used for indexing into our boundary. + index = 0 + + # Callback for the start of a part. + self.callback("part_begin") + + # Move to the next character and state. + state = MultipartState.HEADER_FIELD_START + + else: + # Check to ensure our boundary matches + if c != boundary[index + 2]: + msg = "Expected boundary character %r, got %r at index %d" % (boundary[index + 2], c, index + 2) + self.logger.warning(msg) + e = MultipartParseError(msg) + e.offset = i + raise e + + # Increment index into boundary and continue. + index += 1 + + elif state == MultipartState.HEADER_FIELD_START: + # Mark the start of a header field here, reset the index, and + # continue parsing our header field. + index = 0 + + # Set a mark of our header field. + set_mark("header_field") + + # Notify that we're starting a header if the next character is + # not a CR; a CR at the beginning of the header will cause us + # to stop parsing headers in the MultipartState.HEADER_FIELD state, + # below. + if c != CR: + self.callback("header_begin") + + # Move to parsing header fields. + state = MultipartState.HEADER_FIELD + i -= 1 + + elif state == MultipartState.HEADER_FIELD: + # If we've reached a CR at the beginning of a header, it means + # that we've reached the second of 2 newlines, and so there are + # no more headers to parse. + if c == CR and index == 0: + delete_mark("header_field") + state = MultipartState.HEADERS_ALMOST_DONE + i += 1 + continue + + # Increment our index in the header. + index += 1 + + # If we've reached a colon, we're done with this header. + if c == COLON: + # A 0-length header is an error. + if index == 1: + msg = "Found 0-length header at %d" % (i,) + self.logger.warning(msg) + e = MultipartParseError(msg) + e.offset = i + raise e + + # Call our callback with the header field. + data_callback("header_field", i) + + # Move to parsing the header value. + state = MultipartState.HEADER_VALUE_START + + elif c not in TOKEN_CHARS_SET: + msg = "Found invalid character %r in header at %d" % (c, i) + self.logger.warning(msg) + e = MultipartParseError(msg) + e.offset = i + raise e + + elif state == MultipartState.HEADER_VALUE_START: + # Skip leading spaces. + if c == SPACE: + i += 1 + continue + + # Mark the start of the header value. + set_mark("header_value") + + # Move to the header-value state, reprocessing this character. + state = MultipartState.HEADER_VALUE + i -= 1 + + elif state == MultipartState.HEADER_VALUE: + # If we've got a CR, we're nearly done our headers. Otherwise, + # we do nothing and just move past this character. + if c == CR: + data_callback("header_value", i) + self.callback("header_end") + state = MultipartState.HEADER_VALUE_ALMOST_DONE + + elif state == MultipartState.HEADER_VALUE_ALMOST_DONE: + # The last character should be a LF. If not, it's an error. + if c != LF: + msg = "Did not find LF character at end of header " "(found %r)" % (c,) + self.logger.warning(msg) + e = MultipartParseError(msg) + e.offset = i + raise e + + # Move back to the start of another header. Note that if that + # state detects ANOTHER newline, it'll trigger the end of our + # headers. + state = MultipartState.HEADER_FIELD_START + + elif state == MultipartState.HEADERS_ALMOST_DONE: + # We're almost done our headers. This is reached when we parse + # a CR at the beginning of a header, so our next character + # should be a LF, or it's an error. + if c != LF: + msg = f"Did not find LF at end of headers (found {c!r})" + self.logger.warning(msg) + e = MultipartParseError(msg) + e.offset = i + raise e + + self.callback("headers_finished") + state = MultipartState.PART_DATA_START + + elif state == MultipartState.PART_DATA_START: + # Mark the start of our part data. + set_mark("part_data") + + # Start processing part data, including this character. + state = MultipartState.PART_DATA + i -= 1 + + elif state == MultipartState.PART_DATA: + # We're processing our part data right now. During this, we + # need to efficiently search for our boundary, since any data + # on any number of lines can be a part of the current data. + + # Save the current value of our index. We use this in case we + # find part of a boundary, but it doesn't match fully. + prev_index = index + + # Set up variables. + boundary_length = len(boundary) + data_length = length + + # If our index is 0, we're starting a new part, so start our + # search. + if index == 0: + # The most common case is likely to be that the whole + # boundary is present in the buffer. + # Calling `find` is much faster than iterating here. + i0 = data.find(boundary, i, data_length) + if i0 >= 0: + # We matched the whole boundary string. + index = boundary_length - 1 + i = i0 + boundary_length - 1 + else: + # No match found for whole string. + # There may be a partial boundary at the end of the + # data, which the find will not match. + # Since the length should to be searched is limited to + # the boundary length, just perform a naive search. + i = max(i, data_length - boundary_length) + + # Search forward until we either hit the end of our buffer, + # or reach a potential start of the boundary. + while i < data_length - 1 and data[i] != boundary[0]: + i += 1 + + c = data[i] + + # Now, we have a couple of cases here. If our index is before + # the end of the boundary... + if index < boundary_length: + # If the character matches... + if boundary[index] == c: + # The current character matches, so continue! + index += 1 + else: + index = 0 + + # Our index is equal to the length of our boundary! + elif index == boundary_length: + # First we increment it. + index += 1 + + # Now, if we've reached a newline, we need to set this as + # the potential end of our boundary. + if c == CR: + flags |= FLAG_PART_BOUNDARY + + # Otherwise, if this is a hyphen, we might be at the last + # of all boundaries. + elif c == HYPHEN: + flags |= FLAG_LAST_BOUNDARY + + # Otherwise, we reset our index, since this isn't either a + # newline or a hyphen. + else: + index = 0 + + # Our index is right after the part boundary, which should be + # a LF. + elif index == boundary_length + 1: + # If we're at a part boundary (i.e. we've seen a CR + # character already)... + if flags & FLAG_PART_BOUNDARY: + # We need a LF character next. + if c == LF: + # Unset the part boundary flag. + flags &= ~FLAG_PART_BOUNDARY + + # We have identified a boundary, callback for any data before it. + data_callback("part_data", i - index) + # Callback indicating that we've reached the end of + # a part, and are starting a new one. + self.callback("part_end") + self.callback("part_begin") + + # Move to parsing new headers. + index = 0 + state = MultipartState.HEADER_FIELD_START + i += 1 + continue + + # We didn't find an LF character, so no match. Reset + # our index and clear our flag. + index = 0 + flags &= ~FLAG_PART_BOUNDARY + + # Otherwise, if we're at the last boundary (i.e. we've + # seen a hyphen already)... + elif flags & FLAG_LAST_BOUNDARY: + # We need a second hyphen here. + if c == HYPHEN: + # We have identified a boundary, callback for any data before it. + data_callback("part_data", i - index) + # Callback to end the current part, and then the + # message. + self.callback("part_end") + self.callback("end") + state = MultipartState.END + else: + # No match, so reset index. + index = 0 + + # Otherwise, our index is 0. If the previous index is not, it + # means we reset something, and we need to take the data we + # thought was part of our boundary and send it along as actual + # data. + if index == 0 and prev_index > 0: + # Overwrite our previous index. + prev_index = 0 + + # Re-consider the current character, since this could be + # the start of the boundary itself. + i -= 1 + + elif state == MultipartState.END_BOUNDARY: + if index == len(boundary) - 2 + 1: + if c != HYPHEN: + msg = "Did not find - at end of boundary (%d)" % (i,) + self.logger.warning(msg) + e = MultipartParseError(msg) + e.offset = i + raise e + index += 1 + self.callback("end") + state = MultipartState.END + + elif state == MultipartState.END: + # Don't do anything if chunk ends with CRLF. + if c == CR and i + 1 < length and data[i + 1] == LF: + i += 2 + continue + # Skip data after the last boundary. + self.logger.warning("Skipping data after last boundary") + i = length + break + + else: # pragma: no cover (error case) + # We got into a strange state somehow! Just stop processing. + msg = "Reached an unknown state %d at %d" % (state, i) + self.logger.warning(msg) + e = MultipartParseError(msg) + e.offset = i + raise e + + # Move to the next byte. + i += 1 + + # We call our callbacks with any remaining data. Note that we pass + # the 'remaining' flag, which sets the mark back to 0 instead of + # deleting it, if it's found. This is because, if the mark is found + # at this point, we assume that there's data for one of these things + # that has been parsed, but not yet emitted. And, as such, it implies + # that we haven't yet reached the end of this 'thing'. So, by setting + # the mark to 0, we cause any data callbacks that take place in future + # calls to this function to start from the beginning of that buffer. + data_callback("header_field", length, True) + data_callback("header_value", length, True) + data_callback("part_data", length - index, True) + + # Save values to locals. + self.state = state + self.index = index + self.flags = flags + + # Return our data length to indicate no errors, and that we processed + # all of it. + return length + + def finalize(self) -> None: + """Finalize this parser, which signals to that we are finished parsing. + + Note: It does not currently, but in the future, it will verify that we + are in the final state of the parser (i.e. the end of the multipart + message is well-formed), and, if not, throw an error. + """ + # TODO: verify that we're in the state MultipartState.END, otherwise throw an + # error or otherwise state that we're not finished parsing. + pass + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(boundary={self.boundary!r})" + + +class FormParser: + """This class is the all-in-one form parser. Given all the information + necessary to parse a form, it will instantiate the correct parser, create + the proper :class:`Field` and :class:`File` classes to store the data that + is parsed, and call the two given callbacks with each field and file as + they become available. + + Args: + content_type: The Content-Type of the incoming request. This is used to select the appropriate parser. + on_field: The callback to call when a field has been parsed and is ready for usage. See above for parameters. + on_file: The callback to call when a file has been parsed and is ready for usage. See above for parameters. + on_end: An optional callback to call when all fields and files in a request has been parsed. Can be None. + boundary: If the request is a multipart/form-data request, this should be the boundary of the request, as given + in the Content-Type header, as a bytestring. + file_name: If the request is of type application/octet-stream, then the body of the request will not contain any + information about the uploaded file. In such cases, you can provide the file name of the uploaded file + manually. + FileClass: The class to use for uploaded files. Defaults to :class:`File`, but you can provide your own class + if you wish to customize behaviour. The class will be instantiated as FileClass(file_name, field_name), and + it must provide the following functions:: + - file_instance.write(data) + - file_instance.finalize() + - file_instance.close() + FieldClass: The class to use for uploaded fields. Defaults to :class:`Field`, but you can provide your own + class if you wish to customize behaviour. The class will be instantiated as FieldClass(field_name), and it + must provide the following functions:: + - field_instance.write(data) + - field_instance.finalize() + - field_instance.close() + - field_instance.set_none() + config: Configuration to use for this FormParser. The default values are taken from the DEFAULT_CONFIG value, + and then any keys present in this dictionary will overwrite the default values. + """ + + #: This is the default configuration for our form parser. + #: Note: all file sizes should be in bytes. + DEFAULT_CONFIG: FormParserConfig = { + "MAX_BODY_SIZE": float("inf"), + "MAX_MEMORY_FILE_SIZE": 1 * 1024 * 1024, + "UPLOAD_DIR": None, + "UPLOAD_KEEP_FILENAME": False, + "UPLOAD_KEEP_EXTENSIONS": False, + # Error on invalid Content-Transfer-Encoding? + "UPLOAD_ERROR_ON_BAD_CTE": False, + } + + def __init__( + self, + content_type: str, + on_field: OnFieldCallback | None, + on_file: OnFileCallback | None, + on_end: Callable[[], None] | None = None, + boundary: bytes | str | None = None, + file_name: bytes | None = None, + FileClass: type[FileProtocol] = File, + FieldClass: type[FieldProtocol] = Field, + config: dict[Any, Any] = {}, + ) -> None: + self.logger = logging.getLogger(__name__) + + # Save variables. + self.content_type = content_type + self.boundary = boundary + self.bytes_received = 0 + self.parser = None + + # Save callbacks. + self.on_field = on_field + self.on_file = on_file + self.on_end = on_end + + # Save classes. + self.FileClass = File + self.FieldClass = Field + + # Set configuration options. + self.config: FormParserConfig = self.DEFAULT_CONFIG.copy() + self.config.update(config) # type: ignore[typeddict-item] + + parser: OctetStreamParser | MultipartParser | QuerystringParser | None = None + + # Depending on the Content-Type, we instantiate the correct parser. + if content_type == "application/octet-stream": + file: FileProtocol = None # type: ignore + + def on_start() -> None: + nonlocal file + file = FileClass(file_name, None, config=cast("FileConfig", self.config)) + + def on_data(data: bytes, start: int, end: int) -> None: + nonlocal file + file.write(data[start:end]) + + def _on_end() -> None: + nonlocal file + # Finalize the file itself. + file.finalize() + + # Call our callback. + if on_file: + on_file(file) + + # Call the on-end callback. + if self.on_end is not None: + self.on_end() + + # Instantiate an octet-stream parser + parser = OctetStreamParser( + callbacks={"on_start": on_start, "on_data": on_data, "on_end": _on_end}, + max_size=self.config["MAX_BODY_SIZE"], + ) + + elif content_type == "application/x-www-form-urlencoded" or content_type == "application/x-url-encoded": + name_buffer: list[bytes] = [] + + f: FieldProtocol | None = None + + def on_field_start() -> None: + pass + + def on_field_name(data: bytes, start: int, end: int) -> None: + name_buffer.append(data[start:end]) + + def on_field_data(data: bytes, start: int, end: int) -> None: + nonlocal f + if f is None: + f = FieldClass(b"".join(name_buffer)) + del name_buffer[:] + f.write(data[start:end]) + + def on_field_end() -> None: + nonlocal f + # Finalize and call callback. + if f is None: + # If we get here, it's because there was no field data. + # We create a field, set it to None, and then continue. + f = FieldClass(b"".join(name_buffer)) + del name_buffer[:] + f.set_none() + + f.finalize() + if on_field: + on_field(f) + f = None + + def _on_end() -> None: + if self.on_end is not None: + self.on_end() + + # Instantiate parser. + parser = QuerystringParser( + callbacks={ + "on_field_start": on_field_start, + "on_field_name": on_field_name, + "on_field_data": on_field_data, + "on_field_end": on_field_end, + "on_end": _on_end, + }, + max_size=self.config["MAX_BODY_SIZE"], + ) + + elif content_type == "multipart/form-data": + if boundary is None: + self.logger.error("No boundary given") + raise FormParserError("No boundary given") + + header_name: list[bytes] = [] + header_value: list[bytes] = [] + headers: dict[bytes, bytes] = {} + + f_multi: FileProtocol | FieldProtocol | None = None + writer = None + is_file = False + + def on_part_begin() -> None: + # Reset headers in case this isn't the first part. + nonlocal headers + headers = {} + + def on_part_data(data: bytes, start: int, end: int) -> None: + nonlocal writer + assert writer is not None + writer.write(data[start:end]) + # TODO: check for error here. + + def on_part_end() -> None: + nonlocal f_multi, is_file + assert f_multi is not None + f_multi.finalize() + if is_file: + if on_file: + on_file(f_multi) + else: + if on_field: + on_field(cast("FieldProtocol", f_multi)) + + def on_header_field(data: bytes, start: int, end: int) -> None: + header_name.append(data[start:end]) + + def on_header_value(data: bytes, start: int, end: int) -> None: + header_value.append(data[start:end]) + + def on_header_end() -> None: + headers[b"".join(header_name)] = b"".join(header_value) + del header_name[:] + del header_value[:] + + def on_headers_finished() -> None: + nonlocal is_file, f_multi, writer + # Reset the 'is file' flag. + is_file = False + + # Parse the content-disposition header. + # TODO: handle mixed case + content_disp = headers.get(b"Content-Disposition") + disp, options = parse_options_header(content_disp) + + # Get the field and filename. + field_name = options.get(b"name") + file_name = options.get(b"filename") + # TODO: check for errors + + # Create the proper class. + if file_name is None: + f_multi = FieldClass(field_name) + else: + f_multi = FileClass(file_name, field_name, config=cast("FileConfig", self.config)) + is_file = True + + # Parse the given Content-Transfer-Encoding to determine what + # we need to do with the incoming data. + # TODO: check that we properly handle 8bit / 7bit encoding. + transfer_encoding = headers.get(b"Content-Transfer-Encoding", b"7bit") + + if transfer_encoding in (b"binary", b"8bit", b"7bit"): + writer = f_multi + + elif transfer_encoding == b"base64": + writer = Base64Decoder(f_multi) + + elif transfer_encoding == b"quoted-printable": + writer = QuotedPrintableDecoder(f_multi) + + else: + self.logger.warning("Unknown Content-Transfer-Encoding: %r", transfer_encoding) + if self.config["UPLOAD_ERROR_ON_BAD_CTE"]: + raise FormParserError('Unknown Content-Transfer-Encoding "{!r}"'.format(transfer_encoding)) + else: + # If we aren't erroring, then we just treat this as an + # unencoded Content-Transfer-Encoding. + writer = f_multi + + def _on_end() -> None: + nonlocal writer + if writer is not None: + writer.finalize() + if self.on_end is not None: + self.on_end() + + # Instantiate a multipart parser. + parser = MultipartParser( + boundary, + callbacks={ + "on_part_begin": on_part_begin, + "on_part_data": on_part_data, + "on_part_end": on_part_end, + "on_header_field": on_header_field, + "on_header_value": on_header_value, + "on_header_end": on_header_end, + "on_headers_finished": on_headers_finished, + "on_end": _on_end, + }, + max_size=self.config["MAX_BODY_SIZE"], + ) + + else: + self.logger.warning("Unknown Content-Type: %r", content_type) + raise FormParserError("Unknown Content-Type: {}".format(content_type)) + + self.parser = parser + + def write(self, data: bytes) -> int: + """Write some data. The parser will forward this to the appropriate + underlying parser. + + Args: + data: The data to write. + + Returns: + The number of bytes processed. + """ + self.bytes_received += len(data) + # TODO: check the parser's return value for errors? + assert self.parser is not None + return self.parser.write(data) + + def finalize(self) -> None: + """Finalize the parser.""" + if self.parser is not None and hasattr(self.parser, "finalize"): + self.parser.finalize() + + def close(self) -> None: + """Close the parser.""" + if self.parser is not None and hasattr(self.parser, "close"): + self.parser.close() + + def __repr__(self) -> str: + return "{}(content_type={!r}, parser={!r})".format(self.__class__.__name__, self.content_type, self.parser) + + +def create_form_parser( + headers: dict[str, bytes], + on_field: OnFieldCallback | None, + on_file: OnFileCallback | None, + trust_x_headers: bool = False, + config: dict[Any, Any] = {}, +) -> FormParser: + """This function is a helper function to aid in creating a FormParser + instances. Given a dictionary-like headers object, it will determine + the correct information needed, instantiate a FormParser with the + appropriate values and given callbacks, and then return the corresponding + parser. + + Args: + headers: A dictionary-like object of HTTP headers. The only required header is Content-Type. + on_field: Callback to call with each parsed field. + on_file: Callback to call with each parsed file. + trust_x_headers: Whether or not to trust information received from certain X-Headers - for example, the file + name from X-File-Name. + config: Configuration variables to pass to the FormParser. + """ + content_type: str | bytes | None = headers.get("Content-Type") + if content_type is None: + logging.getLogger(__name__).warning("No Content-Type header given") + raise ValueError("No Content-Type header given!") + + # Boundaries are optional (the FormParser will raise if one is needed + # but not given). + content_type, params = parse_options_header(content_type) + boundary = params.get(b"boundary") + + # We need content_type to be a string, not a bytes object. + content_type = content_type.decode("latin-1") + + # File names are optional. + file_name = headers.get("X-File-Name") + + # Instantiate a form parser. + form_parser = FormParser(content_type, on_field, on_file, boundary=boundary, file_name=file_name, config=config) + + # Return our parser. + return form_parser + + +def parse_form( + headers: dict[str, bytes], + input_stream: SupportsRead, + on_field: OnFieldCallback | None, + on_file: OnFileCallback | None, + chunk_size: int = 1048576, +) -> None: + """This function is useful if you just want to parse a request body, + without too much work. Pass it a dictionary-like object of the request's + headers, and a file-like object for the input stream, along with two + callbacks that will get called whenever a field or file is parsed. + + Args: + headers: A dictionary-like object of HTTP headers. The only required header is Content-Type. + input_stream: A file-like object that represents the request body. The read() method must return bytestrings. + on_field: Callback to call with each parsed field. + on_file: Callback to call with each parsed file. + chunk_size: The maximum size to read from the input stream and write to the parser at one time. + Defaults to 1 MiB. + """ + # Create our form parser. + parser = create_form_parser(headers, on_field, on_file) + + # Read chunks of 1MiB and write to the parser, but never read more than + # the given Content-Length, if any. + content_length: int | float | bytes | None = headers.get("Content-Length") + if content_length is not None: + content_length = int(content_length) + else: + content_length = float("inf") + bytes_read = 0 + + while True: + # Read only up to the Content-Length given. + max_readable = int(min(content_length - bytes_read, chunk_size)) + buff = input_stream.read(max_readable) + + # Write to the parser and update our length. + parser.write(buff) + bytes_read += len(buff) + + # If we get a buffer that's smaller than the size requested, or if we + # have read up to our content length, we're done. + if len(buff) != max_readable or bytes_read == content_length: + break + + # Tell our parser that we're done writing data. + parser.finalize() diff --git a/venv/Lib/site-packages/python_multipart/py.typed b/venv/Lib/site-packages/python_multipart/py.typed new file mode 100644 index 00000000..e69de29b diff --git a/venv/Lib/site-packages/pytz/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/pytz/__pycache__/__init__.cpython-312.pyc index 9719bb9b..1b14e32a 100644 Binary files a/venv/Lib/site-packages/pytz/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/pytz/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pytz/__pycache__/exceptions.cpython-312.pyc b/venv/Lib/site-packages/pytz/__pycache__/exceptions.cpython-312.pyc index 8d294773..e1463e86 100644 Binary files a/venv/Lib/site-packages/pytz/__pycache__/exceptions.cpython-312.pyc and b/venv/Lib/site-packages/pytz/__pycache__/exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pytz/__pycache__/lazy.cpython-312.pyc b/venv/Lib/site-packages/pytz/__pycache__/lazy.cpython-312.pyc index 89efa8fb..330f5aeb 100644 Binary files a/venv/Lib/site-packages/pytz/__pycache__/lazy.cpython-312.pyc and b/venv/Lib/site-packages/pytz/__pycache__/lazy.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pytz/__pycache__/tzfile.cpython-312.pyc b/venv/Lib/site-packages/pytz/__pycache__/tzfile.cpython-312.pyc index cce75675..21693205 100644 Binary files a/venv/Lib/site-packages/pytz/__pycache__/tzfile.cpython-312.pyc and b/venv/Lib/site-packages/pytz/__pycache__/tzfile.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/pytz/__pycache__/tzinfo.cpython-312.pyc b/venv/Lib/site-packages/pytz/__pycache__/tzinfo.cpython-312.pyc index bc5d9920..62abe62a 100644 Binary files a/venv/Lib/site-packages/pytz/__pycache__/tzinfo.cpython-312.pyc and b/venv/Lib/site-packages/pytz/__pycache__/tzinfo.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/requests-2.32.4.dist-info/INSTALLER b/venv/Lib/site-packages/requests-2.32.4.dist-info/INSTALLER new file mode 100644 index 00000000..a1b589e3 --- /dev/null +++ b/venv/Lib/site-packages/requests-2.32.4.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/Lib/site-packages/requests-2.32.4.dist-info/METADATA b/venv/Lib/site-packages/requests-2.32.4.dist-info/METADATA new file mode 100644 index 00000000..837ff4da --- /dev/null +++ b/venv/Lib/site-packages/requests-2.32.4.dist-info/METADATA @@ -0,0 +1,133 @@ +Metadata-Version: 2.4 +Name: requests +Version: 2.32.4 +Summary: Python HTTP for Humans. +Home-page: https://requests.readthedocs.io +Author: Kenneth Reitz +Author-email: me@kennethreitz.org +License: Apache-2.0 +Project-URL: Documentation, https://requests.readthedocs.io +Project-URL: Source, https://github.com/psf/requests +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Web Environment +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Natural Language :: English +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Internet :: WWW/HTTP +Classifier: Topic :: Software Development :: Libraries +Requires-Python: >=3.8 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: charset_normalizer<4,>=2 +Requires-Dist: idna<4,>=2.5 +Requires-Dist: urllib3<3,>=1.21.1 +Requires-Dist: certifi>=2017.4.17 +Provides-Extra: security +Provides-Extra: socks +Requires-Dist: PySocks!=1.5.7,>=1.5.6; extra == "socks" +Provides-Extra: use-chardet-on-py3 +Requires-Dist: chardet<6,>=3.0.2; extra == "use-chardet-on-py3" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: project-url +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + +# Requests + +**Requests** is a simple, yet elegant, HTTP library. + +```python +>>> import requests +>>> r = requests.get('https://httpbin.org/basic-auth/user/pass', auth=('user', 'pass')) +>>> r.status_code +200 +>>> r.headers['content-type'] +'application/json; charset=utf8' +>>> r.encoding +'utf-8' +>>> r.text +'{"authenticated": true, ...' +>>> r.json() +{'authenticated': True, ...} +``` + +Requests allows you to send HTTP/1.1 requests extremely easily. There’s no need to manually add query strings to your URLs, or to form-encode your `PUT` & `POST` data — but nowadays, just use the `json` method! + +Requests is one of the most downloaded Python packages today, pulling in around `30M downloads / week`— according to GitHub, Requests is currently [depended upon](https://github.com/psf/requests/network/dependents?package_id=UGFja2FnZS01NzA4OTExNg%3D%3D) by `1,000,000+` repositories. You may certainly put your trust in this code. + +[![Downloads](https://static.pepy.tech/badge/requests/month)](https://pepy.tech/project/requests) +[![Supported Versions](https://img.shields.io/pypi/pyversions/requests.svg)](https://pypi.org/project/requests) +[![Contributors](https://img.shields.io/github/contributors/psf/requests.svg)](https://github.com/psf/requests/graphs/contributors) + +## Installing Requests and Supported Versions + +Requests is available on PyPI: + +```console +$ python -m pip install requests +``` + +Requests officially supports Python 3.8+. + +## Supported Features & Best–Practices + +Requests is ready for the demands of building robust and reliable HTTP–speaking applications, for the needs of today. + +- Keep-Alive & Connection Pooling +- International Domains and URLs +- Sessions with Cookie Persistence +- Browser-style TLS/SSL Verification +- Basic & Digest Authentication +- Familiar `dict`–like Cookies +- Automatic Content Decompression and Decoding +- Multi-part File Uploads +- SOCKS Proxy Support +- Connection Timeouts +- Streaming Downloads +- Automatic honoring of `.netrc` +- Chunked HTTP Requests + +## API Reference and User Guide available on [Read the Docs](https://requests.readthedocs.io) + +[![Read the Docs](https://raw.githubusercontent.com/psf/requests/main/ext/ss.png)](https://requests.readthedocs.io) + +## Cloning the repository + +When cloning the Requests repository, you may need to add the `-c +fetch.fsck.badTimezone=ignore` flag to avoid an error about a bad commit (see +[this issue](https://github.com/psf/requests/issues/2690) for more background): + +```shell +git clone -c fetch.fsck.badTimezone=ignore https://github.com/psf/requests.git +``` + +You can also apply this setting to your global Git config: + +```shell +git config --global fetch.fsck.badTimezone ignore +``` + +--- + +[![Kenneth Reitz](https://raw.githubusercontent.com/psf/requests/main/ext/kr.png)](https://kennethreitz.org) [![Python Software Foundation](https://raw.githubusercontent.com/psf/requests/main/ext/psf.png)](https://www.python.org/psf) diff --git a/venv/Lib/site-packages/requests-2.32.4.dist-info/RECORD b/venv/Lib/site-packages/requests-2.32.4.dist-info/RECORD new file mode 100644 index 00000000..fdad7f40 --- /dev/null +++ b/venv/Lib/site-packages/requests-2.32.4.dist-info/RECORD @@ -0,0 +1,42 @@ +requests-2.32.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +requests-2.32.4.dist-info/METADATA,sha256=3S42LvNNoL2EP2IjC1VCXoElnGrTTVWwPgImVB4FYF4,4934 +requests-2.32.4.dist-info/RECORD,, +requests-2.32.4.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +requests-2.32.4.dist-info/licenses/LICENSE,sha256=CeipvOyAZxBGUsFoaFqwkx54aPnIKEtm9a5u2uXxEws,10142 +requests-2.32.4.dist-info/top_level.txt,sha256=fMSVmHfb5rbGOo6xv-O_tUX6j-WyixssE-SnwcDRxNQ,9 +requests/__init__.py,sha256=4xaAERmPDIBPsa2PsjpU9r06yooK-2mZKHTZAhWRWts,5072 +requests/__pycache__/__init__.cpython-312.pyc,, +requests/__pycache__/__version__.cpython-312.pyc,, +requests/__pycache__/_internal_utils.cpython-312.pyc,, +requests/__pycache__/adapters.cpython-312.pyc,, +requests/__pycache__/api.cpython-312.pyc,, +requests/__pycache__/auth.cpython-312.pyc,, +requests/__pycache__/certs.cpython-312.pyc,, +requests/__pycache__/compat.cpython-312.pyc,, +requests/__pycache__/cookies.cpython-312.pyc,, +requests/__pycache__/exceptions.cpython-312.pyc,, +requests/__pycache__/help.cpython-312.pyc,, +requests/__pycache__/hooks.cpython-312.pyc,, +requests/__pycache__/models.cpython-312.pyc,, +requests/__pycache__/packages.cpython-312.pyc,, +requests/__pycache__/sessions.cpython-312.pyc,, +requests/__pycache__/status_codes.cpython-312.pyc,, +requests/__pycache__/structures.cpython-312.pyc,, +requests/__pycache__/utils.cpython-312.pyc,, +requests/__version__.py,sha256=FDq681Y3EvBjdDp5UqplMZ28uTTYlM_Jib0sAV-NpXc,435 +requests/_internal_utils.py,sha256=nMQymr4hs32TqVo5AbCrmcJEhvPUh7xXlluyqwslLiQ,1495 +requests/adapters.py,sha256=KIcecscqam6reOCXRl4DwP4jX8Jcl8sd57ft17KR2cQ,27451 +requests/api.py,sha256=_Zb9Oa7tzVIizTKwFrPjDEY9ejtm_OnSRERnADxGsQs,6449 +requests/auth.py,sha256=kF75tqnLctZ9Mf_hm9TZIj4cQWnN5uxRz8oWsx5wmR0,10186 +requests/certs.py,sha256=Z9Sb410Anv6jUFTyss0jFFhU6xst8ctELqfy8Ev23gw,429 +requests/compat.py,sha256=J7sIjR6XoDGp5JTVzOxkK5fSoUVUa_Pjc7iRZhAWGmI,2142 +requests/cookies.py,sha256=bNi-iqEj4NPZ00-ob-rHvzkvObzN3lEpgw3g6paS3Xw,18590 +requests/exceptions.py,sha256=jJPS1UWATs86ShVUaLorTiJb1SaGuoNEWgICJep-VkY,4260 +requests/help.py,sha256=gPX5d_H7Xd88aDABejhqGgl9B1VFRTt5BmiYvL3PzIQ,3875 +requests/hooks.py,sha256=CiuysiHA39V5UfcCBXFIx83IrDpuwfN9RcTUgv28ftQ,733 +requests/models.py,sha256=MjZdZ4k7tnw-1nz5PKShjmPmqyk0L6DciwnFngb_Vk4,35510 +requests/packages.py,sha256=_g0gZ681UyAlKHRjH6kanbaoxx2eAb6qzcXiODyTIoc,904 +requests/sessions.py,sha256=ykTI8UWGSltOfH07HKollH7kTBGw4WhiBVaQGmckTw4,30495 +requests/status_codes.py,sha256=iJUAeA25baTdw-6PfD0eF4qhpINDJRJI-yaMqxs4LEI,4322 +requests/structures.py,sha256=-IbmhVz06S-5aPSZuUthZ6-6D9XOjRuTXHOabY041XM,2912 +requests/utils.py,sha256=WqU86rZ3wvhC-tQjWcjtH_HEKZwWB3iWCZV6SW5DEdQ,33213 diff --git a/venv/Lib/site-packages/deepgram_sdk-4.2.0.dist-info/WHEEL b/venv/Lib/site-packages/requests-2.32.4.dist-info/WHEEL similarity index 100% rename from venv/Lib/site-packages/deepgram_sdk-4.2.0.dist-info/WHEEL rename to venv/Lib/site-packages/requests-2.32.4.dist-info/WHEEL diff --git a/venv/Lib/site-packages/requests-2.32.4.dist-info/licenses/LICENSE b/venv/Lib/site-packages/requests-2.32.4.dist-info/licenses/LICENSE new file mode 100644 index 00000000..67db8588 --- /dev/null +++ b/venv/Lib/site-packages/requests-2.32.4.dist-info/licenses/LICENSE @@ -0,0 +1,175 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. diff --git a/venv/Lib/site-packages/requests-2.32.4.dist-info/top_level.txt b/venv/Lib/site-packages/requests-2.32.4.dist-info/top_level.txt new file mode 100644 index 00000000..f2293605 --- /dev/null +++ b/venv/Lib/site-packages/requests-2.32.4.dist-info/top_level.txt @@ -0,0 +1 @@ +requests diff --git a/venv/Lib/site-packages/requests/__init__.py b/venv/Lib/site-packages/requests/__init__.py new file mode 100644 index 00000000..051cda13 --- /dev/null +++ b/venv/Lib/site-packages/requests/__init__.py @@ -0,0 +1,184 @@ +# __ +# /__) _ _ _ _ _/ _ +# / ( (- (/ (/ (- _) / _) +# / + +""" +Requests HTTP Library +~~~~~~~~~~~~~~~~~~~~~ + +Requests is an HTTP library, written in Python, for human beings. +Basic GET usage: + + >>> import requests + >>> r = requests.get('https://www.python.org') + >>> r.status_code + 200 + >>> b'Python is a programming language' in r.content + True + +... or POST: + + >>> payload = dict(key1='value1', key2='value2') + >>> r = requests.post('https://httpbin.org/post', data=payload) + >>> print(r.text) + { + ... + "form": { + "key1": "value1", + "key2": "value2" + }, + ... + } + +The other HTTP methods are supported - see `requests.api`. Full documentation +is at . + +:copyright: (c) 2017 by Kenneth Reitz. +:license: Apache 2.0, see LICENSE for more details. +""" + +import warnings + +import urllib3 + +from .exceptions import RequestsDependencyWarning + +try: + from charset_normalizer import __version__ as charset_normalizer_version +except ImportError: + charset_normalizer_version = None + +try: + from chardet import __version__ as chardet_version +except ImportError: + chardet_version = None + + +def check_compatibility(urllib3_version, chardet_version, charset_normalizer_version): + urllib3_version = urllib3_version.split(".") + assert urllib3_version != ["dev"] # Verify urllib3 isn't installed from git. + + # Sometimes, urllib3 only reports its version as 16.1. + if len(urllib3_version) == 2: + urllib3_version.append("0") + + # Check urllib3 for compatibility. + major, minor, patch = urllib3_version # noqa: F811 + major, minor, patch = int(major), int(minor), int(patch) + # urllib3 >= 1.21.1 + assert major >= 1 + if major == 1: + assert minor >= 21 + + # Check charset_normalizer for compatibility. + if chardet_version: + major, minor, patch = chardet_version.split(".")[:3] + major, minor, patch = int(major), int(minor), int(patch) + # chardet_version >= 3.0.2, < 6.0.0 + assert (3, 0, 2) <= (major, minor, patch) < (6, 0, 0) + elif charset_normalizer_version: + major, minor, patch = charset_normalizer_version.split(".")[:3] + major, minor, patch = int(major), int(minor), int(patch) + # charset_normalizer >= 2.0.0 < 4.0.0 + assert (2, 0, 0) <= (major, minor, patch) < (4, 0, 0) + else: + warnings.warn( + "Unable to find acceptable character detection dependency " + "(chardet or charset_normalizer).", + RequestsDependencyWarning, + ) + + +def _check_cryptography(cryptography_version): + # cryptography < 1.3.4 + try: + cryptography_version = list(map(int, cryptography_version.split("."))) + except ValueError: + return + + if cryptography_version < [1, 3, 4]: + warning = "Old version of cryptography ({}) may cause slowdown.".format( + cryptography_version + ) + warnings.warn(warning, RequestsDependencyWarning) + + +# Check imported dependencies for compatibility. +try: + check_compatibility( + urllib3.__version__, chardet_version, charset_normalizer_version + ) +except (AssertionError, ValueError): + warnings.warn( + "urllib3 ({}) or chardet ({})/charset_normalizer ({}) doesn't match a supported " + "version!".format( + urllib3.__version__, chardet_version, charset_normalizer_version + ), + RequestsDependencyWarning, + ) + +# Attempt to enable urllib3's fallback for SNI support +# if the standard library doesn't support SNI or the +# 'ssl' library isn't available. +try: + try: + import ssl + except ImportError: + ssl = None + + if not getattr(ssl, "HAS_SNI", False): + from urllib3.contrib import pyopenssl + + pyopenssl.inject_into_urllib3() + + # Check cryptography version + from cryptography import __version__ as cryptography_version + + _check_cryptography(cryptography_version) +except ImportError: + pass + +# urllib3's DependencyWarnings should be silenced. +from urllib3.exceptions import DependencyWarning + +warnings.simplefilter("ignore", DependencyWarning) + +# Set default logging handler to avoid "No handler found" warnings. +import logging +from logging import NullHandler + +from . import packages, utils +from .__version__ import ( + __author__, + __author_email__, + __build__, + __cake__, + __copyright__, + __description__, + __license__, + __title__, + __url__, + __version__, +) +from .api import delete, get, head, options, patch, post, put, request +from .exceptions import ( + ConnectionError, + ConnectTimeout, + FileModeWarning, + HTTPError, + JSONDecodeError, + ReadTimeout, + RequestException, + Timeout, + TooManyRedirects, + URLRequired, +) +from .models import PreparedRequest, Request, Response +from .sessions import Session, session +from .status_codes import codes + +logging.getLogger(__name__).addHandler(NullHandler()) + +# FileModeWarnings go off per the default. +warnings.simplefilter("default", FileModeWarning, append=True) diff --git a/venv/Lib/site-packages/requests/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/requests/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..8cb4ab36 Binary files /dev/null and b/venv/Lib/site-packages/requests/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/requests/__pycache__/__version__.cpython-312.pyc b/venv/Lib/site-packages/requests/__pycache__/__version__.cpython-312.pyc new file mode 100644 index 00000000..585128cb Binary files /dev/null and b/venv/Lib/site-packages/requests/__pycache__/__version__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/requests/__pycache__/_internal_utils.cpython-312.pyc b/venv/Lib/site-packages/requests/__pycache__/_internal_utils.cpython-312.pyc new file mode 100644 index 00000000..20ceec26 Binary files /dev/null and b/venv/Lib/site-packages/requests/__pycache__/_internal_utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/requests/__pycache__/adapters.cpython-312.pyc b/venv/Lib/site-packages/requests/__pycache__/adapters.cpython-312.pyc new file mode 100644 index 00000000..0064b68b Binary files /dev/null and b/venv/Lib/site-packages/requests/__pycache__/adapters.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/requests/__pycache__/api.cpython-312.pyc b/venv/Lib/site-packages/requests/__pycache__/api.cpython-312.pyc new file mode 100644 index 00000000..197220d7 Binary files /dev/null and b/venv/Lib/site-packages/requests/__pycache__/api.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/requests/__pycache__/auth.cpython-312.pyc b/venv/Lib/site-packages/requests/__pycache__/auth.cpython-312.pyc new file mode 100644 index 00000000..30b3af4f Binary files /dev/null and b/venv/Lib/site-packages/requests/__pycache__/auth.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/requests/__pycache__/certs.cpython-312.pyc b/venv/Lib/site-packages/requests/__pycache__/certs.cpython-312.pyc new file mode 100644 index 00000000..4cc6f6ee Binary files /dev/null and b/venv/Lib/site-packages/requests/__pycache__/certs.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/requests/__pycache__/compat.cpython-312.pyc b/venv/Lib/site-packages/requests/__pycache__/compat.cpython-312.pyc new file mode 100644 index 00000000..32f99174 Binary files /dev/null and b/venv/Lib/site-packages/requests/__pycache__/compat.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/requests/__pycache__/cookies.cpython-312.pyc b/venv/Lib/site-packages/requests/__pycache__/cookies.cpython-312.pyc new file mode 100644 index 00000000..bb60dc0e Binary files /dev/null and b/venv/Lib/site-packages/requests/__pycache__/cookies.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/requests/__pycache__/exceptions.cpython-312.pyc b/venv/Lib/site-packages/requests/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 00000000..7a6dddfb Binary files /dev/null and b/venv/Lib/site-packages/requests/__pycache__/exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/requests/__pycache__/help.cpython-312.pyc b/venv/Lib/site-packages/requests/__pycache__/help.cpython-312.pyc new file mode 100644 index 00000000..9b9c3a05 Binary files /dev/null and b/venv/Lib/site-packages/requests/__pycache__/help.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/requests/__pycache__/hooks.cpython-312.pyc b/venv/Lib/site-packages/requests/__pycache__/hooks.cpython-312.pyc new file mode 100644 index 00000000..406cc7b9 Binary files /dev/null and b/venv/Lib/site-packages/requests/__pycache__/hooks.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/requests/__pycache__/models.cpython-312.pyc b/venv/Lib/site-packages/requests/__pycache__/models.cpython-312.pyc new file mode 100644 index 00000000..9fbfcc75 Binary files /dev/null and b/venv/Lib/site-packages/requests/__pycache__/models.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/requests/__pycache__/packages.cpython-312.pyc b/venv/Lib/site-packages/requests/__pycache__/packages.cpython-312.pyc new file mode 100644 index 00000000..fe908128 Binary files /dev/null and b/venv/Lib/site-packages/requests/__pycache__/packages.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/requests/__pycache__/sessions.cpython-312.pyc b/venv/Lib/site-packages/requests/__pycache__/sessions.cpython-312.pyc new file mode 100644 index 00000000..d718b171 Binary files /dev/null and b/venv/Lib/site-packages/requests/__pycache__/sessions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/requests/__pycache__/status_codes.cpython-312.pyc b/venv/Lib/site-packages/requests/__pycache__/status_codes.cpython-312.pyc new file mode 100644 index 00000000..6c1d7995 Binary files /dev/null and b/venv/Lib/site-packages/requests/__pycache__/status_codes.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/requests/__pycache__/structures.cpython-312.pyc b/venv/Lib/site-packages/requests/__pycache__/structures.cpython-312.pyc new file mode 100644 index 00000000..e79495e3 Binary files /dev/null and b/venv/Lib/site-packages/requests/__pycache__/structures.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/requests/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/requests/__pycache__/utils.cpython-312.pyc new file mode 100644 index 00000000..0fba5b61 Binary files /dev/null and b/venv/Lib/site-packages/requests/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/requests/__version__.py b/venv/Lib/site-packages/requests/__version__.py new file mode 100644 index 00000000..3128a464 --- /dev/null +++ b/venv/Lib/site-packages/requests/__version__.py @@ -0,0 +1,14 @@ +# .-. .-. .-. . . .-. .-. .-. .-. +# |( |- |.| | | |- `-. | `-. +# ' ' `-' `-`.`-' `-' `-' ' `-' + +__title__ = "requests" +__description__ = "Python HTTP for Humans." +__url__ = "https://requests.readthedocs.io" +__version__ = "2.32.4" +__build__ = 0x023204 +__author__ = "Kenneth Reitz" +__author_email__ = "me@kennethreitz.org" +__license__ = "Apache-2.0" +__copyright__ = "Copyright Kenneth Reitz" +__cake__ = "\u2728 \U0001f370 \u2728" diff --git a/venv/Lib/site-packages/requests/_internal_utils.py b/venv/Lib/site-packages/requests/_internal_utils.py new file mode 100644 index 00000000..f2cf635e --- /dev/null +++ b/venv/Lib/site-packages/requests/_internal_utils.py @@ -0,0 +1,50 @@ +""" +requests._internal_utils +~~~~~~~~~~~~~~ + +Provides utility functions that are consumed internally by Requests +which depend on extremely few external helpers (such as compat) +""" +import re + +from .compat import builtin_str + +_VALID_HEADER_NAME_RE_BYTE = re.compile(rb"^[^:\s][^:\r\n]*$") +_VALID_HEADER_NAME_RE_STR = re.compile(r"^[^:\s][^:\r\n]*$") +_VALID_HEADER_VALUE_RE_BYTE = re.compile(rb"^\S[^\r\n]*$|^$") +_VALID_HEADER_VALUE_RE_STR = re.compile(r"^\S[^\r\n]*$|^$") + +_HEADER_VALIDATORS_STR = (_VALID_HEADER_NAME_RE_STR, _VALID_HEADER_VALUE_RE_STR) +_HEADER_VALIDATORS_BYTE = (_VALID_HEADER_NAME_RE_BYTE, _VALID_HEADER_VALUE_RE_BYTE) +HEADER_VALIDATORS = { + bytes: _HEADER_VALIDATORS_BYTE, + str: _HEADER_VALIDATORS_STR, +} + + +def to_native_string(string, encoding="ascii"): + """Given a string object, regardless of type, returns a representation of + that string in the native string type, encoding and decoding where + necessary. This assumes ASCII unless told otherwise. + """ + if isinstance(string, builtin_str): + out = string + else: + out = string.decode(encoding) + + return out + + +def unicode_is_ascii(u_string): + """Determine if unicode string only contains ASCII characters. + + :param str u_string: unicode string to check. Must be unicode + and not Python 2 `str`. + :rtype: bool + """ + assert isinstance(u_string, str) + try: + u_string.encode("ascii") + return True + except UnicodeEncodeError: + return False diff --git a/venv/Lib/site-packages/requests/adapters.py b/venv/Lib/site-packages/requests/adapters.py new file mode 100644 index 00000000..9a58b160 --- /dev/null +++ b/venv/Lib/site-packages/requests/adapters.py @@ -0,0 +1,719 @@ +""" +requests.adapters +~~~~~~~~~~~~~~~~~ + +This module contains the transport adapters that Requests uses to define +and maintain connections. +""" + +import os.path +import socket # noqa: F401 +import typing +import warnings + +from urllib3.exceptions import ClosedPoolError, ConnectTimeoutError +from urllib3.exceptions import HTTPError as _HTTPError +from urllib3.exceptions import InvalidHeader as _InvalidHeader +from urllib3.exceptions import ( + LocationValueError, + MaxRetryError, + NewConnectionError, + ProtocolError, +) +from urllib3.exceptions import ProxyError as _ProxyError +from urllib3.exceptions import ReadTimeoutError, ResponseError +from urllib3.exceptions import SSLError as _SSLError +from urllib3.poolmanager import PoolManager, proxy_from_url +from urllib3.util import Timeout as TimeoutSauce +from urllib3.util import parse_url +from urllib3.util.retry import Retry +from urllib3.util.ssl_ import create_urllib3_context + +from .auth import _basic_auth_str +from .compat import basestring, urlparse +from .cookies import extract_cookies_to_jar +from .exceptions import ( + ConnectionError, + ConnectTimeout, + InvalidHeader, + InvalidProxyURL, + InvalidSchema, + InvalidURL, + ProxyError, + ReadTimeout, + RetryError, + SSLError, +) +from .models import Response +from .structures import CaseInsensitiveDict +from .utils import ( + DEFAULT_CA_BUNDLE_PATH, + extract_zipped_paths, + get_auth_from_url, + get_encoding_from_headers, + prepend_scheme_if_needed, + select_proxy, + urldefragauth, +) + +try: + from urllib3.contrib.socks import SOCKSProxyManager +except ImportError: + + def SOCKSProxyManager(*args, **kwargs): + raise InvalidSchema("Missing dependencies for SOCKS support.") + + +if typing.TYPE_CHECKING: + from .models import PreparedRequest + + +DEFAULT_POOLBLOCK = False +DEFAULT_POOLSIZE = 10 +DEFAULT_RETRIES = 0 +DEFAULT_POOL_TIMEOUT = None + + +try: + import ssl # noqa: F401 + + _preloaded_ssl_context = create_urllib3_context() + _preloaded_ssl_context.load_verify_locations( + extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH) + ) +except ImportError: + # Bypass default SSLContext creation when Python + # interpreter isn't built with the ssl module. + _preloaded_ssl_context = None + + +def _urllib3_request_context( + request: "PreparedRequest", + verify: "bool | str | None", + client_cert: "typing.Tuple[str, str] | str | None", + poolmanager: "PoolManager", +) -> "(typing.Dict[str, typing.Any], typing.Dict[str, typing.Any])": + host_params = {} + pool_kwargs = {} + parsed_request_url = urlparse(request.url) + scheme = parsed_request_url.scheme.lower() + port = parsed_request_url.port + + # Determine if we have and should use our default SSLContext + # to optimize performance on standard requests. + poolmanager_kwargs = getattr(poolmanager, "connection_pool_kw", {}) + has_poolmanager_ssl_context = poolmanager_kwargs.get("ssl_context") + should_use_default_ssl_context = ( + _preloaded_ssl_context is not None and not has_poolmanager_ssl_context + ) + + cert_reqs = "CERT_REQUIRED" + if verify is False: + cert_reqs = "CERT_NONE" + elif verify is True and should_use_default_ssl_context: + pool_kwargs["ssl_context"] = _preloaded_ssl_context + elif isinstance(verify, str): + if not os.path.isdir(verify): + pool_kwargs["ca_certs"] = verify + else: + pool_kwargs["ca_cert_dir"] = verify + pool_kwargs["cert_reqs"] = cert_reqs + if client_cert is not None: + if isinstance(client_cert, tuple) and len(client_cert) == 2: + pool_kwargs["cert_file"] = client_cert[0] + pool_kwargs["key_file"] = client_cert[1] + else: + # According to our docs, we allow users to specify just the client + # cert path + pool_kwargs["cert_file"] = client_cert + host_params = { + "scheme": scheme, + "host": parsed_request_url.hostname, + "port": port, + } + return host_params, pool_kwargs + + +class BaseAdapter: + """The Base Transport Adapter""" + + def __init__(self): + super().__init__() + + def send( + self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None + ): + """Sends PreparedRequest object. Returns Response object. + + :param request: The :class:`PreparedRequest ` being sent. + :param stream: (optional) Whether to stream the request content. + :param timeout: (optional) How long to wait for the server to send + data before giving up, as a float, or a :ref:`(connect timeout, + read timeout) ` tuple. + :type timeout: float or tuple + :param verify: (optional) Either a boolean, in which case it controls whether we verify + the server's TLS certificate, or a string, in which case it must be a path + to a CA bundle to use + :param cert: (optional) Any user-provided SSL certificate to be trusted. + :param proxies: (optional) The proxies dictionary to apply to the request. + """ + raise NotImplementedError + + def close(self): + """Cleans up adapter specific items.""" + raise NotImplementedError + + +class HTTPAdapter(BaseAdapter): + """The built-in HTTP Adapter for urllib3. + + Provides a general-case interface for Requests sessions to contact HTTP and + HTTPS urls by implementing the Transport Adapter interface. This class will + usually be created by the :class:`Session ` class under the + covers. + + :param pool_connections: The number of urllib3 connection pools to cache. + :param pool_maxsize: The maximum number of connections to save in the pool. + :param max_retries: The maximum number of retries each connection + should attempt. Note, this applies only to failed DNS lookups, socket + connections and connection timeouts, never to requests where data has + made it to the server. By default, Requests does not retry failed + connections. If you need granular control over the conditions under + which we retry a request, import urllib3's ``Retry`` class and pass + that instead. + :param pool_block: Whether the connection pool should block for connections. + + Usage:: + + >>> import requests + >>> s = requests.Session() + >>> a = requests.adapters.HTTPAdapter(max_retries=3) + >>> s.mount('http://', a) + """ + + __attrs__ = [ + "max_retries", + "config", + "_pool_connections", + "_pool_maxsize", + "_pool_block", + ] + + def __init__( + self, + pool_connections=DEFAULT_POOLSIZE, + pool_maxsize=DEFAULT_POOLSIZE, + max_retries=DEFAULT_RETRIES, + pool_block=DEFAULT_POOLBLOCK, + ): + if max_retries == DEFAULT_RETRIES: + self.max_retries = Retry(0, read=False) + else: + self.max_retries = Retry.from_int(max_retries) + self.config = {} + self.proxy_manager = {} + + super().__init__() + + self._pool_connections = pool_connections + self._pool_maxsize = pool_maxsize + self._pool_block = pool_block + + self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block) + + def __getstate__(self): + return {attr: getattr(self, attr, None) for attr in self.__attrs__} + + def __setstate__(self, state): + # Can't handle by adding 'proxy_manager' to self.__attrs__ because + # self.poolmanager uses a lambda function, which isn't pickleable. + self.proxy_manager = {} + self.config = {} + + for attr, value in state.items(): + setattr(self, attr, value) + + self.init_poolmanager( + self._pool_connections, self._pool_maxsize, block=self._pool_block + ) + + def init_poolmanager( + self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs + ): + """Initializes a urllib3 PoolManager. + + This method should not be called from user code, and is only + exposed for use when subclassing the + :class:`HTTPAdapter `. + + :param connections: The number of urllib3 connection pools to cache. + :param maxsize: The maximum number of connections to save in the pool. + :param block: Block when no free connections are available. + :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager. + """ + # save these values for pickling + self._pool_connections = connections + self._pool_maxsize = maxsize + self._pool_block = block + + self.poolmanager = PoolManager( + num_pools=connections, + maxsize=maxsize, + block=block, + **pool_kwargs, + ) + + def proxy_manager_for(self, proxy, **proxy_kwargs): + """Return urllib3 ProxyManager for the given proxy. + + This method should not be called from user code, and is only + exposed for use when subclassing the + :class:`HTTPAdapter `. + + :param proxy: The proxy to return a urllib3 ProxyManager for. + :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager. + :returns: ProxyManager + :rtype: urllib3.ProxyManager + """ + if proxy in self.proxy_manager: + manager = self.proxy_manager[proxy] + elif proxy.lower().startswith("socks"): + username, password = get_auth_from_url(proxy) + manager = self.proxy_manager[proxy] = SOCKSProxyManager( + proxy, + username=username, + password=password, + num_pools=self._pool_connections, + maxsize=self._pool_maxsize, + block=self._pool_block, + **proxy_kwargs, + ) + else: + proxy_headers = self.proxy_headers(proxy) + manager = self.proxy_manager[proxy] = proxy_from_url( + proxy, + proxy_headers=proxy_headers, + num_pools=self._pool_connections, + maxsize=self._pool_maxsize, + block=self._pool_block, + **proxy_kwargs, + ) + + return manager + + def cert_verify(self, conn, url, verify, cert): + """Verify a SSL certificate. This method should not be called from user + code, and is only exposed for use when subclassing the + :class:`HTTPAdapter `. + + :param conn: The urllib3 connection object associated with the cert. + :param url: The requested URL. + :param verify: Either a boolean, in which case it controls whether we verify + the server's TLS certificate, or a string, in which case it must be a path + to a CA bundle to use + :param cert: The SSL certificate to verify. + """ + if url.lower().startswith("https") and verify: + conn.cert_reqs = "CERT_REQUIRED" + + # Only load the CA certificates if 'verify' is a string indicating the CA bundle to use. + # Otherwise, if verify is a boolean, we don't load anything since + # the connection will be using a context with the default certificates already loaded, + # and this avoids a call to the slow load_verify_locations() + if verify is not True: + # `verify` must be a str with a path then + cert_loc = verify + + if not os.path.exists(cert_loc): + raise OSError( + f"Could not find a suitable TLS CA certificate bundle, " + f"invalid path: {cert_loc}" + ) + + if not os.path.isdir(cert_loc): + conn.ca_certs = cert_loc + else: + conn.ca_cert_dir = cert_loc + else: + conn.cert_reqs = "CERT_NONE" + conn.ca_certs = None + conn.ca_cert_dir = None + + if cert: + if not isinstance(cert, basestring): + conn.cert_file = cert[0] + conn.key_file = cert[1] + else: + conn.cert_file = cert + conn.key_file = None + if conn.cert_file and not os.path.exists(conn.cert_file): + raise OSError( + f"Could not find the TLS certificate file, " + f"invalid path: {conn.cert_file}" + ) + if conn.key_file and not os.path.exists(conn.key_file): + raise OSError( + f"Could not find the TLS key file, invalid path: {conn.key_file}" + ) + + def build_response(self, req, resp): + """Builds a :class:`Response ` object from a urllib3 + response. This should not be called from user code, and is only exposed + for use when subclassing the + :class:`HTTPAdapter ` + + :param req: The :class:`PreparedRequest ` used to generate the response. + :param resp: The urllib3 response object. + :rtype: requests.Response + """ + response = Response() + + # Fallback to None if there's no status_code, for whatever reason. + response.status_code = getattr(resp, "status", None) + + # Make headers case-insensitive. + response.headers = CaseInsensitiveDict(getattr(resp, "headers", {})) + + # Set encoding. + response.encoding = get_encoding_from_headers(response.headers) + response.raw = resp + response.reason = response.raw.reason + + if isinstance(req.url, bytes): + response.url = req.url.decode("utf-8") + else: + response.url = req.url + + # Add new cookies from the server. + extract_cookies_to_jar(response.cookies, req, resp) + + # Give the Response some context. + response.request = req + response.connection = self + + return response + + def build_connection_pool_key_attributes(self, request, verify, cert=None): + """Build the PoolKey attributes used by urllib3 to return a connection. + + This looks at the PreparedRequest, the user-specified verify value, + and the value of the cert parameter to determine what PoolKey values + to use to select a connection from a given urllib3 Connection Pool. + + The SSL related pool key arguments are not consistently set. As of + this writing, use the following to determine what keys may be in that + dictionary: + + * If ``verify`` is ``True``, ``"ssl_context"`` will be set and will be the + default Requests SSL Context + * If ``verify`` is ``False``, ``"ssl_context"`` will not be set but + ``"cert_reqs"`` will be set + * If ``verify`` is a string, (i.e., it is a user-specified trust bundle) + ``"ca_certs"`` will be set if the string is not a directory recognized + by :py:func:`os.path.isdir`, otherwise ``"ca_certs_dir"`` will be + set. + * If ``"cert"`` is specified, ``"cert_file"`` will always be set. If + ``"cert"`` is a tuple with a second item, ``"key_file"`` will also + be present + + To override these settings, one may subclass this class, call this + method and use the above logic to change parameters as desired. For + example, if one wishes to use a custom :py:class:`ssl.SSLContext` one + must both set ``"ssl_context"`` and based on what else they require, + alter the other keys to ensure the desired behaviour. + + :param request: + The PreparedReqest being sent over the connection. + :type request: + :class:`~requests.models.PreparedRequest` + :param verify: + Either a boolean, in which case it controls whether + we verify the server's TLS certificate, or a string, in which case it + must be a path to a CA bundle to use. + :param cert: + (optional) Any user-provided SSL certificate for client + authentication (a.k.a., mTLS). This may be a string (i.e., just + the path to a file which holds both certificate and key) or a + tuple of length 2 with the certificate file path and key file + path. + :returns: + A tuple of two dictionaries. The first is the "host parameters" + portion of the Pool Key including scheme, hostname, and port. The + second is a dictionary of SSLContext related parameters. + """ + return _urllib3_request_context(request, verify, cert, self.poolmanager) + + def get_connection_with_tls_context(self, request, verify, proxies=None, cert=None): + """Returns a urllib3 connection for the given request and TLS settings. + This should not be called from user code, and is only exposed for use + when subclassing the :class:`HTTPAdapter `. + + :param request: + The :class:`PreparedRequest ` object to be sent + over the connection. + :param verify: + Either a boolean, in which case it controls whether we verify the + server's TLS certificate, or a string, in which case it must be a + path to a CA bundle to use. + :param proxies: + (optional) The proxies dictionary to apply to the request. + :param cert: + (optional) Any user-provided SSL certificate to be used for client + authentication (a.k.a., mTLS). + :rtype: + urllib3.ConnectionPool + """ + proxy = select_proxy(request.url, proxies) + try: + host_params, pool_kwargs = self.build_connection_pool_key_attributes( + request, + verify, + cert, + ) + except ValueError as e: + raise InvalidURL(e, request=request) + if proxy: + proxy = prepend_scheme_if_needed(proxy, "http") + proxy_url = parse_url(proxy) + if not proxy_url.host: + raise InvalidProxyURL( + "Please check proxy URL. It is malformed " + "and could be missing the host." + ) + proxy_manager = self.proxy_manager_for(proxy) + conn = proxy_manager.connection_from_host( + **host_params, pool_kwargs=pool_kwargs + ) + else: + # Only scheme should be lower case + conn = self.poolmanager.connection_from_host( + **host_params, pool_kwargs=pool_kwargs + ) + + return conn + + def get_connection(self, url, proxies=None): + """DEPRECATED: Users should move to `get_connection_with_tls_context` + for all subclasses of HTTPAdapter using Requests>=2.32.2. + + Returns a urllib3 connection for the given URL. This should not be + called from user code, and is only exposed for use when subclassing the + :class:`HTTPAdapter `. + + :param url: The URL to connect to. + :param proxies: (optional) A Requests-style dictionary of proxies used on this request. + :rtype: urllib3.ConnectionPool + """ + warnings.warn( + ( + "`get_connection` has been deprecated in favor of " + "`get_connection_with_tls_context`. Custom HTTPAdapter subclasses " + "will need to migrate for Requests>=2.32.2. Please see " + "https://github.com/psf/requests/pull/6710 for more details." + ), + DeprecationWarning, + ) + proxy = select_proxy(url, proxies) + + if proxy: + proxy = prepend_scheme_if_needed(proxy, "http") + proxy_url = parse_url(proxy) + if not proxy_url.host: + raise InvalidProxyURL( + "Please check proxy URL. It is malformed " + "and could be missing the host." + ) + proxy_manager = self.proxy_manager_for(proxy) + conn = proxy_manager.connection_from_url(url) + else: + # Only scheme should be lower case + parsed = urlparse(url) + url = parsed.geturl() + conn = self.poolmanager.connection_from_url(url) + + return conn + + def close(self): + """Disposes of any internal state. + + Currently, this closes the PoolManager and any active ProxyManager, + which closes any pooled connections. + """ + self.poolmanager.clear() + for proxy in self.proxy_manager.values(): + proxy.clear() + + def request_url(self, request, proxies): + """Obtain the url to use when making the final request. + + If the message is being sent through a HTTP proxy, the full URL has to + be used. Otherwise, we should only use the path portion of the URL. + + This should not be called from user code, and is only exposed for use + when subclassing the + :class:`HTTPAdapter `. + + :param request: The :class:`PreparedRequest ` being sent. + :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs. + :rtype: str + """ + proxy = select_proxy(request.url, proxies) + scheme = urlparse(request.url).scheme + + is_proxied_http_request = proxy and scheme != "https" + using_socks_proxy = False + if proxy: + proxy_scheme = urlparse(proxy).scheme.lower() + using_socks_proxy = proxy_scheme.startswith("socks") + + url = request.path_url + if url.startswith("//"): # Don't confuse urllib3 + url = f"/{url.lstrip('/')}" + + if is_proxied_http_request and not using_socks_proxy: + url = urldefragauth(request.url) + + return url + + def add_headers(self, request, **kwargs): + """Add any headers needed by the connection. As of v2.0 this does + nothing by default, but is left for overriding by users that subclass + the :class:`HTTPAdapter `. + + This should not be called from user code, and is only exposed for use + when subclassing the + :class:`HTTPAdapter `. + + :param request: The :class:`PreparedRequest ` to add headers to. + :param kwargs: The keyword arguments from the call to send(). + """ + pass + + def proxy_headers(self, proxy): + """Returns a dictionary of the headers to add to any request sent + through a proxy. This works with urllib3 magic to ensure that they are + correctly sent to the proxy, rather than in a tunnelled request if + CONNECT is being used. + + This should not be called from user code, and is only exposed for use + when subclassing the + :class:`HTTPAdapter `. + + :param proxy: The url of the proxy being used for this request. + :rtype: dict + """ + headers = {} + username, password = get_auth_from_url(proxy) + + if username: + headers["Proxy-Authorization"] = _basic_auth_str(username, password) + + return headers + + def send( + self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None + ): + """Sends PreparedRequest object. Returns Response object. + + :param request: The :class:`PreparedRequest ` being sent. + :param stream: (optional) Whether to stream the request content. + :param timeout: (optional) How long to wait for the server to send + data before giving up, as a float, or a :ref:`(connect timeout, + read timeout) ` tuple. + :type timeout: float or tuple or urllib3 Timeout object + :param verify: (optional) Either a boolean, in which case it controls whether + we verify the server's TLS certificate, or a string, in which case it + must be a path to a CA bundle to use + :param cert: (optional) Any user-provided SSL certificate to be trusted. + :param proxies: (optional) The proxies dictionary to apply to the request. + :rtype: requests.Response + """ + + try: + conn = self.get_connection_with_tls_context( + request, verify, proxies=proxies, cert=cert + ) + except LocationValueError as e: + raise InvalidURL(e, request=request) + + self.cert_verify(conn, request.url, verify, cert) + url = self.request_url(request, proxies) + self.add_headers( + request, + stream=stream, + timeout=timeout, + verify=verify, + cert=cert, + proxies=proxies, + ) + + chunked = not (request.body is None or "Content-Length" in request.headers) + + if isinstance(timeout, tuple): + try: + connect, read = timeout + timeout = TimeoutSauce(connect=connect, read=read) + except ValueError: + raise ValueError( + f"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, " + f"or a single float to set both timeouts to the same value." + ) + elif isinstance(timeout, TimeoutSauce): + pass + else: + timeout = TimeoutSauce(connect=timeout, read=timeout) + + try: + resp = conn.urlopen( + method=request.method, + url=url, + body=request.body, + headers=request.headers, + redirect=False, + assert_same_host=False, + preload_content=False, + decode_content=False, + retries=self.max_retries, + timeout=timeout, + chunked=chunked, + ) + + except (ProtocolError, OSError) as err: + raise ConnectionError(err, request=request) + + except MaxRetryError as e: + if isinstance(e.reason, ConnectTimeoutError): + # TODO: Remove this in 3.0.0: see #2811 + if not isinstance(e.reason, NewConnectionError): + raise ConnectTimeout(e, request=request) + + if isinstance(e.reason, ResponseError): + raise RetryError(e, request=request) + + if isinstance(e.reason, _ProxyError): + raise ProxyError(e, request=request) + + if isinstance(e.reason, _SSLError): + # This branch is for urllib3 v1.22 and later. + raise SSLError(e, request=request) + + raise ConnectionError(e, request=request) + + except ClosedPoolError as e: + raise ConnectionError(e, request=request) + + except _ProxyError as e: + raise ProxyError(e) + + except (_SSLError, _HTTPError) as e: + if isinstance(e, _SSLError): + # This branch is for urllib3 versions earlier than v1.22 + raise SSLError(e, request=request) + elif isinstance(e, ReadTimeoutError): + raise ReadTimeout(e, request=request) + elif isinstance(e, _InvalidHeader): + raise InvalidHeader(e, request=request) + else: + raise + + return self.build_response(request, resp) diff --git a/venv/Lib/site-packages/requests/api.py b/venv/Lib/site-packages/requests/api.py new file mode 100644 index 00000000..59607445 --- /dev/null +++ b/venv/Lib/site-packages/requests/api.py @@ -0,0 +1,157 @@ +""" +requests.api +~~~~~~~~~~~~ + +This module implements the Requests API. + +:copyright: (c) 2012 by Kenneth Reitz. +:license: Apache2, see LICENSE for more details. +""" + +from . import sessions + + +def request(method, url, **kwargs): + """Constructs and sends a :class:`Request `. + + :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``. + :param url: URL for the new :class:`Request` object. + :param params: (optional) Dictionary, list of tuples or bytes to send + in the query string for the :class:`Request`. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`. + :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. + :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. + :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload. + ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')`` + or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content_type'`` is a string + defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers + to add for the file. + :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth. + :param timeout: (optional) How many seconds to wait for the server to send data + before giving up, as a float, or a :ref:`(connect timeout, read + timeout) ` tuple. + :type timeout: float or tuple + :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``. + :type allow_redirects: bool + :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy. + :param verify: (optional) Either a boolean, in which case it controls whether we verify + the server's TLS certificate, or a string, in which case it must be a path + to a CA bundle to use. Defaults to ``True``. + :param stream: (optional) if ``False``, the response content will be immediately downloaded. + :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. + :return: :class:`Response ` object + :rtype: requests.Response + + Usage:: + + >>> import requests + >>> req = requests.request('GET', 'https://httpbin.org/get') + >>> req + + """ + + # By using the 'with' statement we are sure the session is closed, thus we + # avoid leaving sockets open which can trigger a ResourceWarning in some + # cases, and look like a memory leak in others. + with sessions.Session() as session: + return session.request(method=method, url=url, **kwargs) + + +def get(url, params=None, **kwargs): + r"""Sends a GET request. + + :param url: URL for the new :class:`Request` object. + :param params: (optional) Dictionary, list of tuples or bytes to send + in the query string for the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :return: :class:`Response ` object + :rtype: requests.Response + """ + + return request("get", url, params=params, **kwargs) + + +def options(url, **kwargs): + r"""Sends an OPTIONS request. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :return: :class:`Response ` object + :rtype: requests.Response + """ + + return request("options", url, **kwargs) + + +def head(url, **kwargs): + r"""Sends a HEAD request. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. If + `allow_redirects` is not provided, it will be set to `False` (as + opposed to the default :meth:`request` behavior). + :return: :class:`Response ` object + :rtype: requests.Response + """ + + kwargs.setdefault("allow_redirects", False) + return request("head", url, **kwargs) + + +def post(url, data=None, json=None, **kwargs): + r"""Sends a POST request. + + :param url: URL for the new :class:`Request` object. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :return: :class:`Response ` object + :rtype: requests.Response + """ + + return request("post", url, data=data, json=json, **kwargs) + + +def put(url, data=None, **kwargs): + r"""Sends a PUT request. + + :param url: URL for the new :class:`Request` object. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :return: :class:`Response ` object + :rtype: requests.Response + """ + + return request("put", url, data=data, **kwargs) + + +def patch(url, data=None, **kwargs): + r"""Sends a PATCH request. + + :param url: URL for the new :class:`Request` object. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :return: :class:`Response ` object + :rtype: requests.Response + """ + + return request("patch", url, data=data, **kwargs) + + +def delete(url, **kwargs): + r"""Sends a DELETE request. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :return: :class:`Response ` object + :rtype: requests.Response + """ + + return request("delete", url, **kwargs) diff --git a/venv/Lib/site-packages/requests/auth.py b/venv/Lib/site-packages/requests/auth.py new file mode 100644 index 00000000..4a7ce6dc --- /dev/null +++ b/venv/Lib/site-packages/requests/auth.py @@ -0,0 +1,314 @@ +""" +requests.auth +~~~~~~~~~~~~~ + +This module contains the authentication handlers for Requests. +""" + +import hashlib +import os +import re +import threading +import time +import warnings +from base64 import b64encode + +from ._internal_utils import to_native_string +from .compat import basestring, str, urlparse +from .cookies import extract_cookies_to_jar +from .utils import parse_dict_header + +CONTENT_TYPE_FORM_URLENCODED = "application/x-www-form-urlencoded" +CONTENT_TYPE_MULTI_PART = "multipart/form-data" + + +def _basic_auth_str(username, password): + """Returns a Basic Auth string.""" + + # "I want us to put a big-ol' comment on top of it that + # says that this behaviour is dumb but we need to preserve + # it because people are relying on it." + # - Lukasa + # + # These are here solely to maintain backwards compatibility + # for things like ints. This will be removed in 3.0.0. + if not isinstance(username, basestring): + warnings.warn( + "Non-string usernames will no longer be supported in Requests " + "3.0.0. Please convert the object you've passed in ({!r}) to " + "a string or bytes object in the near future to avoid " + "problems.".format(username), + category=DeprecationWarning, + ) + username = str(username) + + if not isinstance(password, basestring): + warnings.warn( + "Non-string passwords will no longer be supported in Requests " + "3.0.0. Please convert the object you've passed in ({!r}) to " + "a string or bytes object in the near future to avoid " + "problems.".format(type(password)), + category=DeprecationWarning, + ) + password = str(password) + # -- End Removal -- + + if isinstance(username, str): + username = username.encode("latin1") + + if isinstance(password, str): + password = password.encode("latin1") + + authstr = "Basic " + to_native_string( + b64encode(b":".join((username, password))).strip() + ) + + return authstr + + +class AuthBase: + """Base class that all auth implementations derive from""" + + def __call__(self, r): + raise NotImplementedError("Auth hooks must be callable.") + + +class HTTPBasicAuth(AuthBase): + """Attaches HTTP Basic Authentication to the given Request object.""" + + def __init__(self, username, password): + self.username = username + self.password = password + + def __eq__(self, other): + return all( + [ + self.username == getattr(other, "username", None), + self.password == getattr(other, "password", None), + ] + ) + + def __ne__(self, other): + return not self == other + + def __call__(self, r): + r.headers["Authorization"] = _basic_auth_str(self.username, self.password) + return r + + +class HTTPProxyAuth(HTTPBasicAuth): + """Attaches HTTP Proxy Authentication to a given Request object.""" + + def __call__(self, r): + r.headers["Proxy-Authorization"] = _basic_auth_str(self.username, self.password) + return r + + +class HTTPDigestAuth(AuthBase): + """Attaches HTTP Digest Authentication to the given Request object.""" + + def __init__(self, username, password): + self.username = username + self.password = password + # Keep state in per-thread local storage + self._thread_local = threading.local() + + def init_per_thread_state(self): + # Ensure state is initialized just once per-thread + if not hasattr(self._thread_local, "init"): + self._thread_local.init = True + self._thread_local.last_nonce = "" + self._thread_local.nonce_count = 0 + self._thread_local.chal = {} + self._thread_local.pos = None + self._thread_local.num_401_calls = None + + def build_digest_header(self, method, url): + """ + :rtype: str + """ + + realm = self._thread_local.chal["realm"] + nonce = self._thread_local.chal["nonce"] + qop = self._thread_local.chal.get("qop") + algorithm = self._thread_local.chal.get("algorithm") + opaque = self._thread_local.chal.get("opaque") + hash_utf8 = None + + if algorithm is None: + _algorithm = "MD5" + else: + _algorithm = algorithm.upper() + # lambdas assume digest modules are imported at the top level + if _algorithm == "MD5" or _algorithm == "MD5-SESS": + + def md5_utf8(x): + if isinstance(x, str): + x = x.encode("utf-8") + return hashlib.md5(x).hexdigest() + + hash_utf8 = md5_utf8 + elif _algorithm == "SHA": + + def sha_utf8(x): + if isinstance(x, str): + x = x.encode("utf-8") + return hashlib.sha1(x).hexdigest() + + hash_utf8 = sha_utf8 + elif _algorithm == "SHA-256": + + def sha256_utf8(x): + if isinstance(x, str): + x = x.encode("utf-8") + return hashlib.sha256(x).hexdigest() + + hash_utf8 = sha256_utf8 + elif _algorithm == "SHA-512": + + def sha512_utf8(x): + if isinstance(x, str): + x = x.encode("utf-8") + return hashlib.sha512(x).hexdigest() + + hash_utf8 = sha512_utf8 + + KD = lambda s, d: hash_utf8(f"{s}:{d}") # noqa:E731 + + if hash_utf8 is None: + return None + + # XXX not implemented yet + entdig = None + p_parsed = urlparse(url) + #: path is request-uri defined in RFC 2616 which should not be empty + path = p_parsed.path or "/" + if p_parsed.query: + path += f"?{p_parsed.query}" + + A1 = f"{self.username}:{realm}:{self.password}" + A2 = f"{method}:{path}" + + HA1 = hash_utf8(A1) + HA2 = hash_utf8(A2) + + if nonce == self._thread_local.last_nonce: + self._thread_local.nonce_count += 1 + else: + self._thread_local.nonce_count = 1 + ncvalue = f"{self._thread_local.nonce_count:08x}" + s = str(self._thread_local.nonce_count).encode("utf-8") + s += nonce.encode("utf-8") + s += time.ctime().encode("utf-8") + s += os.urandom(8) + + cnonce = hashlib.sha1(s).hexdigest()[:16] + if _algorithm == "MD5-SESS": + HA1 = hash_utf8(f"{HA1}:{nonce}:{cnonce}") + + if not qop: + respdig = KD(HA1, f"{nonce}:{HA2}") + elif qop == "auth" or "auth" in qop.split(","): + noncebit = f"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}" + respdig = KD(HA1, noncebit) + else: + # XXX handle auth-int. + return None + + self._thread_local.last_nonce = nonce + + # XXX should the partial digests be encoded too? + base = ( + f'username="{self.username}", realm="{realm}", nonce="{nonce}", ' + f'uri="{path}", response="{respdig}"' + ) + if opaque: + base += f', opaque="{opaque}"' + if algorithm: + base += f', algorithm="{algorithm}"' + if entdig: + base += f', digest="{entdig}"' + if qop: + base += f', qop="auth", nc={ncvalue}, cnonce="{cnonce}"' + + return f"Digest {base}" + + def handle_redirect(self, r, **kwargs): + """Reset num_401_calls counter on redirects.""" + if r.is_redirect: + self._thread_local.num_401_calls = 1 + + def handle_401(self, r, **kwargs): + """ + Takes the given response and tries digest-auth, if needed. + + :rtype: requests.Response + """ + + # If response is not 4xx, do not auth + # See https://github.com/psf/requests/issues/3772 + if not 400 <= r.status_code < 500: + self._thread_local.num_401_calls = 1 + return r + + if self._thread_local.pos is not None: + # Rewind the file position indicator of the body to where + # it was to resend the request. + r.request.body.seek(self._thread_local.pos) + s_auth = r.headers.get("www-authenticate", "") + + if "digest" in s_auth.lower() and self._thread_local.num_401_calls < 2: + self._thread_local.num_401_calls += 1 + pat = re.compile(r"digest ", flags=re.IGNORECASE) + self._thread_local.chal = parse_dict_header(pat.sub("", s_auth, count=1)) + + # Consume content and release the original connection + # to allow our new request to reuse the same one. + r.content + r.close() + prep = r.request.copy() + extract_cookies_to_jar(prep._cookies, r.request, r.raw) + prep.prepare_cookies(prep._cookies) + + prep.headers["Authorization"] = self.build_digest_header( + prep.method, prep.url + ) + _r = r.connection.send(prep, **kwargs) + _r.history.append(r) + _r.request = prep + + return _r + + self._thread_local.num_401_calls = 1 + return r + + def __call__(self, r): + # Initialize per-thread state, if needed + self.init_per_thread_state() + # If we have a saved nonce, skip the 401 + if self._thread_local.last_nonce: + r.headers["Authorization"] = self.build_digest_header(r.method, r.url) + try: + self._thread_local.pos = r.body.tell() + except AttributeError: + # In the case of HTTPDigestAuth being reused and the body of + # the previous request was a file-like object, pos has the + # file position of the previous body. Ensure it's set to + # None. + self._thread_local.pos = None + r.register_hook("response", self.handle_401) + r.register_hook("response", self.handle_redirect) + self._thread_local.num_401_calls = 1 + + return r + + def __eq__(self, other): + return all( + [ + self.username == getattr(other, "username", None), + self.password == getattr(other, "password", None), + ] + ) + + def __ne__(self, other): + return not self == other diff --git a/venv/Lib/site-packages/requests/certs.py b/venv/Lib/site-packages/requests/certs.py new file mode 100644 index 00000000..be422c3e --- /dev/null +++ b/venv/Lib/site-packages/requests/certs.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python + +""" +requests.certs +~~~~~~~~~~~~~~ + +This module returns the preferred default CA certificate bundle. There is +only one — the one from the certifi package. + +If you are packaging Requests, e.g., for a Linux distribution or a managed +environment, you can change the definition of where() to return a separately +packaged CA bundle. +""" +from certifi import where + +if __name__ == "__main__": + print(where()) diff --git a/venv/Lib/site-packages/requests/compat.py b/venv/Lib/site-packages/requests/compat.py new file mode 100644 index 00000000..7f9d7543 --- /dev/null +++ b/venv/Lib/site-packages/requests/compat.py @@ -0,0 +1,106 @@ +""" +requests.compat +~~~~~~~~~~~~~~~ + +This module previously handled import compatibility issues +between Python 2 and Python 3. It remains for backwards +compatibility until the next major version. +""" + +import importlib +import sys + +# ------- +# urllib3 +# ------- +from urllib3 import __version__ as urllib3_version + +# Detect which major version of urllib3 is being used. +try: + is_urllib3_1 = int(urllib3_version.split(".")[0]) == 1 +except (TypeError, AttributeError): + # If we can't discern a version, prefer old functionality. + is_urllib3_1 = True + +# ------------------- +# Character Detection +# ------------------- + + +def _resolve_char_detection(): + """Find supported character detection libraries.""" + chardet = None + for lib in ("chardet", "charset_normalizer"): + if chardet is None: + try: + chardet = importlib.import_module(lib) + except ImportError: + pass + return chardet + + +chardet = _resolve_char_detection() + +# ------- +# Pythons +# ------- + +# Syntax sugar. +_ver = sys.version_info + +#: Python 2.x? +is_py2 = _ver[0] == 2 + +#: Python 3.x? +is_py3 = _ver[0] == 3 + +# json/simplejson module import resolution +has_simplejson = False +try: + import simplejson as json + + has_simplejson = True +except ImportError: + import json + +if has_simplejson: + from simplejson import JSONDecodeError +else: + from json import JSONDecodeError + +# Keep OrderedDict for backwards compatibility. +from collections import OrderedDict +from collections.abc import Callable, Mapping, MutableMapping +from http import cookiejar as cookielib +from http.cookies import Morsel +from io import StringIO + +# -------------- +# Legacy Imports +# -------------- +from urllib.parse import ( + quote, + quote_plus, + unquote, + unquote_plus, + urldefrag, + urlencode, + urljoin, + urlparse, + urlsplit, + urlunparse, +) +from urllib.request import ( + getproxies, + getproxies_environment, + parse_http_list, + proxy_bypass, + proxy_bypass_environment, +) + +builtin_str = str +str = str +bytes = bytes +basestring = (str, bytes) +numeric_types = (int, float) +integer_types = (int,) diff --git a/venv/Lib/site-packages/requests/cookies.py b/venv/Lib/site-packages/requests/cookies.py new file mode 100644 index 00000000..f69d0cda --- /dev/null +++ b/venv/Lib/site-packages/requests/cookies.py @@ -0,0 +1,561 @@ +""" +requests.cookies +~~~~~~~~~~~~~~~~ + +Compatibility code to be able to use `http.cookiejar.CookieJar` with requests. + +requests.utils imports from here, so be careful with imports. +""" + +import calendar +import copy +import time + +from ._internal_utils import to_native_string +from .compat import Morsel, MutableMapping, cookielib, urlparse, urlunparse + +try: + import threading +except ImportError: + import dummy_threading as threading + + +class MockRequest: + """Wraps a `requests.Request` to mimic a `urllib2.Request`. + + The code in `http.cookiejar.CookieJar` expects this interface in order to correctly + manage cookie policies, i.e., determine whether a cookie can be set, given the + domains of the request and the cookie. + + The original request object is read-only. The client is responsible for collecting + the new headers via `get_new_headers()` and interpreting them appropriately. You + probably want `get_cookie_header`, defined below. + """ + + def __init__(self, request): + self._r = request + self._new_headers = {} + self.type = urlparse(self._r.url).scheme + + def get_type(self): + return self.type + + def get_host(self): + return urlparse(self._r.url).netloc + + def get_origin_req_host(self): + return self.get_host() + + def get_full_url(self): + # Only return the response's URL if the user hadn't set the Host + # header + if not self._r.headers.get("Host"): + return self._r.url + # If they did set it, retrieve it and reconstruct the expected domain + host = to_native_string(self._r.headers["Host"], encoding="utf-8") + parsed = urlparse(self._r.url) + # Reconstruct the URL as we expect it + return urlunparse( + [ + parsed.scheme, + host, + parsed.path, + parsed.params, + parsed.query, + parsed.fragment, + ] + ) + + def is_unverifiable(self): + return True + + def has_header(self, name): + return name in self._r.headers or name in self._new_headers + + def get_header(self, name, default=None): + return self._r.headers.get(name, self._new_headers.get(name, default)) + + def add_header(self, key, val): + """cookiejar has no legitimate use for this method; add it back if you find one.""" + raise NotImplementedError( + "Cookie headers should be added with add_unredirected_header()" + ) + + def add_unredirected_header(self, name, value): + self._new_headers[name] = value + + def get_new_headers(self): + return self._new_headers + + @property + def unverifiable(self): + return self.is_unverifiable() + + @property + def origin_req_host(self): + return self.get_origin_req_host() + + @property + def host(self): + return self.get_host() + + +class MockResponse: + """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`. + + ...what? Basically, expose the parsed HTTP headers from the server response + the way `http.cookiejar` expects to see them. + """ + + def __init__(self, headers): + """Make a MockResponse for `cookiejar` to read. + + :param headers: a httplib.HTTPMessage or analogous carrying the headers + """ + self._headers = headers + + def info(self): + return self._headers + + def getheaders(self, name): + self._headers.getheaders(name) + + +def extract_cookies_to_jar(jar, request, response): + """Extract the cookies from the response into a CookieJar. + + :param jar: http.cookiejar.CookieJar (not necessarily a RequestsCookieJar) + :param request: our own requests.Request object + :param response: urllib3.HTTPResponse object + """ + if not (hasattr(response, "_original_response") and response._original_response): + return + # the _original_response field is the wrapped httplib.HTTPResponse object, + req = MockRequest(request) + # pull out the HTTPMessage with the headers and put it in the mock: + res = MockResponse(response._original_response.msg) + jar.extract_cookies(res, req) + + +def get_cookie_header(jar, request): + """ + Produce an appropriate Cookie header string to be sent with `request`, or None. + + :rtype: str + """ + r = MockRequest(request) + jar.add_cookie_header(r) + return r.get_new_headers().get("Cookie") + + +def remove_cookie_by_name(cookiejar, name, domain=None, path=None): + """Unsets a cookie by name, by default over all domains and paths. + + Wraps CookieJar.clear(), is O(n). + """ + clearables = [] + for cookie in cookiejar: + if cookie.name != name: + continue + if domain is not None and domain != cookie.domain: + continue + if path is not None and path != cookie.path: + continue + clearables.append((cookie.domain, cookie.path, cookie.name)) + + for domain, path, name in clearables: + cookiejar.clear(domain, path, name) + + +class CookieConflictError(RuntimeError): + """There are two cookies that meet the criteria specified in the cookie jar. + Use .get and .set and include domain and path args in order to be more specific. + """ + + +class RequestsCookieJar(cookielib.CookieJar, MutableMapping): + """Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict + interface. + + This is the CookieJar we create by default for requests and sessions that + don't specify one, since some clients may expect response.cookies and + session.cookies to support dict operations. + + Requests does not use the dict interface internally; it's just for + compatibility with external client code. All requests code should work + out of the box with externally provided instances of ``CookieJar``, e.g. + ``LWPCookieJar`` and ``FileCookieJar``. + + Unlike a regular CookieJar, this class is pickleable. + + .. warning:: dictionary operations that are normally O(1) may be O(n). + """ + + def get(self, name, default=None, domain=None, path=None): + """Dict-like get() that also supports optional domain and path args in + order to resolve naming collisions from using one cookie jar over + multiple domains. + + .. warning:: operation is O(n), not O(1). + """ + try: + return self._find_no_duplicates(name, domain, path) + except KeyError: + return default + + def set(self, name, value, **kwargs): + """Dict-like set() that also supports optional domain and path args in + order to resolve naming collisions from using one cookie jar over + multiple domains. + """ + # support client code that unsets cookies by assignment of a None value: + if value is None: + remove_cookie_by_name( + self, name, domain=kwargs.get("domain"), path=kwargs.get("path") + ) + return + + if isinstance(value, Morsel): + c = morsel_to_cookie(value) + else: + c = create_cookie(name, value, **kwargs) + self.set_cookie(c) + return c + + def iterkeys(self): + """Dict-like iterkeys() that returns an iterator of names of cookies + from the jar. + + .. seealso:: itervalues() and iteritems(). + """ + for cookie in iter(self): + yield cookie.name + + def keys(self): + """Dict-like keys() that returns a list of names of cookies from the + jar. + + .. seealso:: values() and items(). + """ + return list(self.iterkeys()) + + def itervalues(self): + """Dict-like itervalues() that returns an iterator of values of cookies + from the jar. + + .. seealso:: iterkeys() and iteritems(). + """ + for cookie in iter(self): + yield cookie.value + + def values(self): + """Dict-like values() that returns a list of values of cookies from the + jar. + + .. seealso:: keys() and items(). + """ + return list(self.itervalues()) + + def iteritems(self): + """Dict-like iteritems() that returns an iterator of name-value tuples + from the jar. + + .. seealso:: iterkeys() and itervalues(). + """ + for cookie in iter(self): + yield cookie.name, cookie.value + + def items(self): + """Dict-like items() that returns a list of name-value tuples from the + jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a + vanilla python dict of key value pairs. + + .. seealso:: keys() and values(). + """ + return list(self.iteritems()) + + def list_domains(self): + """Utility method to list all the domains in the jar.""" + domains = [] + for cookie in iter(self): + if cookie.domain not in domains: + domains.append(cookie.domain) + return domains + + def list_paths(self): + """Utility method to list all the paths in the jar.""" + paths = [] + for cookie in iter(self): + if cookie.path not in paths: + paths.append(cookie.path) + return paths + + def multiple_domains(self): + """Returns True if there are multiple domains in the jar. + Returns False otherwise. + + :rtype: bool + """ + domains = [] + for cookie in iter(self): + if cookie.domain is not None and cookie.domain in domains: + return True + domains.append(cookie.domain) + return False # there is only one domain in jar + + def get_dict(self, domain=None, path=None): + """Takes as an argument an optional domain and path and returns a plain + old Python dict of name-value pairs of cookies that meet the + requirements. + + :rtype: dict + """ + dictionary = {} + for cookie in iter(self): + if (domain is None or cookie.domain == domain) and ( + path is None or cookie.path == path + ): + dictionary[cookie.name] = cookie.value + return dictionary + + def __contains__(self, name): + try: + return super().__contains__(name) + except CookieConflictError: + return True + + def __getitem__(self, name): + """Dict-like __getitem__() for compatibility with client code. Throws + exception if there are more than one cookie with name. In that case, + use the more explicit get() method instead. + + .. warning:: operation is O(n), not O(1). + """ + return self._find_no_duplicates(name) + + def __setitem__(self, name, value): + """Dict-like __setitem__ for compatibility with client code. Throws + exception if there is already a cookie of that name in the jar. In that + case, use the more explicit set() method instead. + """ + self.set(name, value) + + def __delitem__(self, name): + """Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s + ``remove_cookie_by_name()``. + """ + remove_cookie_by_name(self, name) + + def set_cookie(self, cookie, *args, **kwargs): + if ( + hasattr(cookie.value, "startswith") + and cookie.value.startswith('"') + and cookie.value.endswith('"') + ): + cookie.value = cookie.value.replace('\\"', "") + return super().set_cookie(cookie, *args, **kwargs) + + def update(self, other): + """Updates this jar with cookies from another CookieJar or dict-like""" + if isinstance(other, cookielib.CookieJar): + for cookie in other: + self.set_cookie(copy.copy(cookie)) + else: + super().update(other) + + def _find(self, name, domain=None, path=None): + """Requests uses this method internally to get cookie values. + + If there are conflicting cookies, _find arbitrarily chooses one. + See _find_no_duplicates if you want an exception thrown if there are + conflicting cookies. + + :param name: a string containing name of cookie + :param domain: (optional) string containing domain of cookie + :param path: (optional) string containing path of cookie + :return: cookie.value + """ + for cookie in iter(self): + if cookie.name == name: + if domain is None or cookie.domain == domain: + if path is None or cookie.path == path: + return cookie.value + + raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}") + + def _find_no_duplicates(self, name, domain=None, path=None): + """Both ``__get_item__`` and ``get`` call this function: it's never + used elsewhere in Requests. + + :param name: a string containing name of cookie + :param domain: (optional) string containing domain of cookie + :param path: (optional) string containing path of cookie + :raises KeyError: if cookie is not found + :raises CookieConflictError: if there are multiple cookies + that match name and optionally domain and path + :return: cookie.value + """ + toReturn = None + for cookie in iter(self): + if cookie.name == name: + if domain is None or cookie.domain == domain: + if path is None or cookie.path == path: + if toReturn is not None: + # if there are multiple cookies that meet passed in criteria + raise CookieConflictError( + f"There are multiple cookies with name, {name!r}" + ) + # we will eventually return this as long as no cookie conflict + toReturn = cookie.value + + if toReturn: + return toReturn + raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}") + + def __getstate__(self): + """Unlike a normal CookieJar, this class is pickleable.""" + state = self.__dict__.copy() + # remove the unpickleable RLock object + state.pop("_cookies_lock") + return state + + def __setstate__(self, state): + """Unlike a normal CookieJar, this class is pickleable.""" + self.__dict__.update(state) + if "_cookies_lock" not in self.__dict__: + self._cookies_lock = threading.RLock() + + def copy(self): + """Return a copy of this RequestsCookieJar.""" + new_cj = RequestsCookieJar() + new_cj.set_policy(self.get_policy()) + new_cj.update(self) + return new_cj + + def get_policy(self): + """Return the CookiePolicy instance used.""" + return self._policy + + +def _copy_cookie_jar(jar): + if jar is None: + return None + + if hasattr(jar, "copy"): + # We're dealing with an instance of RequestsCookieJar + return jar.copy() + # We're dealing with a generic CookieJar instance + new_jar = copy.copy(jar) + new_jar.clear() + for cookie in jar: + new_jar.set_cookie(copy.copy(cookie)) + return new_jar + + +def create_cookie(name, value, **kwargs): + """Make a cookie from underspecified parameters. + + By default, the pair of `name` and `value` will be set for the domain '' + and sent on every request (this is sometimes called a "supercookie"). + """ + result = { + "version": 0, + "name": name, + "value": value, + "port": None, + "domain": "", + "path": "/", + "secure": False, + "expires": None, + "discard": True, + "comment": None, + "comment_url": None, + "rest": {"HttpOnly": None}, + "rfc2109": False, + } + + badargs = set(kwargs) - set(result) + if badargs: + raise TypeError( + f"create_cookie() got unexpected keyword arguments: {list(badargs)}" + ) + + result.update(kwargs) + result["port_specified"] = bool(result["port"]) + result["domain_specified"] = bool(result["domain"]) + result["domain_initial_dot"] = result["domain"].startswith(".") + result["path_specified"] = bool(result["path"]) + + return cookielib.Cookie(**result) + + +def morsel_to_cookie(morsel): + """Convert a Morsel object into a Cookie containing the one k/v pair.""" + + expires = None + if morsel["max-age"]: + try: + expires = int(time.time() + int(morsel["max-age"])) + except ValueError: + raise TypeError(f"max-age: {morsel['max-age']} must be integer") + elif morsel["expires"]: + time_template = "%a, %d-%b-%Y %H:%M:%S GMT" + expires = calendar.timegm(time.strptime(morsel["expires"], time_template)) + return create_cookie( + comment=morsel["comment"], + comment_url=bool(morsel["comment"]), + discard=False, + domain=morsel["domain"], + expires=expires, + name=morsel.key, + path=morsel["path"], + port=None, + rest={"HttpOnly": morsel["httponly"]}, + rfc2109=False, + secure=bool(morsel["secure"]), + value=morsel.value, + version=morsel["version"] or 0, + ) + + +def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True): + """Returns a CookieJar from a key/value dictionary. + + :param cookie_dict: Dict of key/values to insert into CookieJar. + :param cookiejar: (optional) A cookiejar to add the cookies to. + :param overwrite: (optional) If False, will not replace cookies + already in the jar with new ones. + :rtype: CookieJar + """ + if cookiejar is None: + cookiejar = RequestsCookieJar() + + if cookie_dict is not None: + names_from_jar = [cookie.name for cookie in cookiejar] + for name in cookie_dict: + if overwrite or (name not in names_from_jar): + cookiejar.set_cookie(create_cookie(name, cookie_dict[name])) + + return cookiejar + + +def merge_cookies(cookiejar, cookies): + """Add cookies to cookiejar and returns a merged CookieJar. + + :param cookiejar: CookieJar object to add the cookies to. + :param cookies: Dictionary or CookieJar object to be added. + :rtype: CookieJar + """ + if not isinstance(cookiejar, cookielib.CookieJar): + raise ValueError("You can only merge into CookieJar") + + if isinstance(cookies, dict): + cookiejar = cookiejar_from_dict(cookies, cookiejar=cookiejar, overwrite=False) + elif isinstance(cookies, cookielib.CookieJar): + try: + cookiejar.update(cookies) + except AttributeError: + for cookie_in_jar in cookies: + cookiejar.set_cookie(cookie_in_jar) + + return cookiejar diff --git a/venv/Lib/site-packages/requests/exceptions.py b/venv/Lib/site-packages/requests/exceptions.py new file mode 100644 index 00000000..83986b48 --- /dev/null +++ b/venv/Lib/site-packages/requests/exceptions.py @@ -0,0 +1,151 @@ +""" +requests.exceptions +~~~~~~~~~~~~~~~~~~~ + +This module contains the set of Requests' exceptions. +""" +from urllib3.exceptions import HTTPError as BaseHTTPError + +from .compat import JSONDecodeError as CompatJSONDecodeError + + +class RequestException(IOError): + """There was an ambiguous exception that occurred while handling your + request. + """ + + def __init__(self, *args, **kwargs): + """Initialize RequestException with `request` and `response` objects.""" + response = kwargs.pop("response", None) + self.response = response + self.request = kwargs.pop("request", None) + if response is not None and not self.request and hasattr(response, "request"): + self.request = self.response.request + super().__init__(*args, **kwargs) + + +class InvalidJSONError(RequestException): + """A JSON error occurred.""" + + +class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError): + """Couldn't decode the text into json""" + + def __init__(self, *args, **kwargs): + """ + Construct the JSONDecodeError instance first with all + args. Then use it's args to construct the IOError so that + the json specific args aren't used as IOError specific args + and the error message from JSONDecodeError is preserved. + """ + CompatJSONDecodeError.__init__(self, *args) + InvalidJSONError.__init__(self, *self.args, **kwargs) + + def __reduce__(self): + """ + The __reduce__ method called when pickling the object must + be the one from the JSONDecodeError (be it json/simplejson) + as it expects all the arguments for instantiation, not just + one like the IOError, and the MRO would by default call the + __reduce__ method from the IOError due to the inheritance order. + """ + return CompatJSONDecodeError.__reduce__(self) + + +class HTTPError(RequestException): + """An HTTP error occurred.""" + + +class ConnectionError(RequestException): + """A Connection error occurred.""" + + +class ProxyError(ConnectionError): + """A proxy error occurred.""" + + +class SSLError(ConnectionError): + """An SSL error occurred.""" + + +class Timeout(RequestException): + """The request timed out. + + Catching this error will catch both + :exc:`~requests.exceptions.ConnectTimeout` and + :exc:`~requests.exceptions.ReadTimeout` errors. + """ + + +class ConnectTimeout(ConnectionError, Timeout): + """The request timed out while trying to connect to the remote server. + + Requests that produced this error are safe to retry. + """ + + +class ReadTimeout(Timeout): + """The server did not send any data in the allotted amount of time.""" + + +class URLRequired(RequestException): + """A valid URL is required to make a request.""" + + +class TooManyRedirects(RequestException): + """Too many redirects.""" + + +class MissingSchema(RequestException, ValueError): + """The URL scheme (e.g. http or https) is missing.""" + + +class InvalidSchema(RequestException, ValueError): + """The URL scheme provided is either invalid or unsupported.""" + + +class InvalidURL(RequestException, ValueError): + """The URL provided was somehow invalid.""" + + +class InvalidHeader(RequestException, ValueError): + """The header value provided was somehow invalid.""" + + +class InvalidProxyURL(InvalidURL): + """The proxy URL provided is invalid.""" + + +class ChunkedEncodingError(RequestException): + """The server declared chunked encoding but sent an invalid chunk.""" + + +class ContentDecodingError(RequestException, BaseHTTPError): + """Failed to decode response content.""" + + +class StreamConsumedError(RequestException, TypeError): + """The content for this response was already consumed.""" + + +class RetryError(RequestException): + """Custom retries logic failed""" + + +class UnrewindableBodyError(RequestException): + """Requests encountered an error when trying to rewind a body.""" + + +# Warnings + + +class RequestsWarning(Warning): + """Base warning for Requests.""" + + +class FileModeWarning(RequestsWarning, DeprecationWarning): + """A file was opened in text mode, but Requests determined its binary length.""" + + +class RequestsDependencyWarning(RequestsWarning): + """An imported dependency doesn't match the expected version range.""" diff --git a/venv/Lib/site-packages/requests/help.py b/venv/Lib/site-packages/requests/help.py new file mode 100644 index 00000000..8fbcd656 --- /dev/null +++ b/venv/Lib/site-packages/requests/help.py @@ -0,0 +1,134 @@ +"""Module containing bug report helper(s).""" + +import json +import platform +import ssl +import sys + +import idna +import urllib3 + +from . import __version__ as requests_version + +try: + import charset_normalizer +except ImportError: + charset_normalizer = None + +try: + import chardet +except ImportError: + chardet = None + +try: + from urllib3.contrib import pyopenssl +except ImportError: + pyopenssl = None + OpenSSL = None + cryptography = None +else: + import cryptography + import OpenSSL + + +def _implementation(): + """Return a dict with the Python implementation and version. + + Provide both the name and the version of the Python implementation + currently running. For example, on CPython 3.10.3 it will return + {'name': 'CPython', 'version': '3.10.3'}. + + This function works best on CPython and PyPy: in particular, it probably + doesn't work for Jython or IronPython. Future investigation should be done + to work out the correct shape of the code for those platforms. + """ + implementation = platform.python_implementation() + + if implementation == "CPython": + implementation_version = platform.python_version() + elif implementation == "PyPy": + implementation_version = "{}.{}.{}".format( + sys.pypy_version_info.major, + sys.pypy_version_info.minor, + sys.pypy_version_info.micro, + ) + if sys.pypy_version_info.releaselevel != "final": + implementation_version = "".join( + [implementation_version, sys.pypy_version_info.releaselevel] + ) + elif implementation == "Jython": + implementation_version = platform.python_version() # Complete Guess + elif implementation == "IronPython": + implementation_version = platform.python_version() # Complete Guess + else: + implementation_version = "Unknown" + + return {"name": implementation, "version": implementation_version} + + +def info(): + """Generate information for a bug report.""" + try: + platform_info = { + "system": platform.system(), + "release": platform.release(), + } + except OSError: + platform_info = { + "system": "Unknown", + "release": "Unknown", + } + + implementation_info = _implementation() + urllib3_info = {"version": urllib3.__version__} + charset_normalizer_info = {"version": None} + chardet_info = {"version": None} + if charset_normalizer: + charset_normalizer_info = {"version": charset_normalizer.__version__} + if chardet: + chardet_info = {"version": chardet.__version__} + + pyopenssl_info = { + "version": None, + "openssl_version": "", + } + if OpenSSL: + pyopenssl_info = { + "version": OpenSSL.__version__, + "openssl_version": f"{OpenSSL.SSL.OPENSSL_VERSION_NUMBER:x}", + } + cryptography_info = { + "version": getattr(cryptography, "__version__", ""), + } + idna_info = { + "version": getattr(idna, "__version__", ""), + } + + system_ssl = ssl.OPENSSL_VERSION_NUMBER + system_ssl_info = {"version": f"{system_ssl:x}" if system_ssl is not None else ""} + + return { + "platform": platform_info, + "implementation": implementation_info, + "system_ssl": system_ssl_info, + "using_pyopenssl": pyopenssl is not None, + "using_charset_normalizer": chardet is None, + "pyOpenSSL": pyopenssl_info, + "urllib3": urllib3_info, + "chardet": chardet_info, + "charset_normalizer": charset_normalizer_info, + "cryptography": cryptography_info, + "idna": idna_info, + "requests": { + "version": requests_version, + }, + } + + +def main(): + """Pretty-print the bug information as JSON.""" + print(json.dumps(info(), sort_keys=True, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/venv/Lib/site-packages/requests/hooks.py b/venv/Lib/site-packages/requests/hooks.py new file mode 100644 index 00000000..d181ba2e --- /dev/null +++ b/venv/Lib/site-packages/requests/hooks.py @@ -0,0 +1,33 @@ +""" +requests.hooks +~~~~~~~~~~~~~~ + +This module provides the capabilities for the Requests hooks system. + +Available hooks: + +``response``: + The response generated from a Request. +""" +HOOKS = ["response"] + + +def default_hooks(): + return {event: [] for event in HOOKS} + + +# TODO: response is the only one + + +def dispatch_hook(key, hooks, hook_data, **kwargs): + """Dispatches a hook dictionary on a given piece of data.""" + hooks = hooks or {} + hooks = hooks.get(key) + if hooks: + if hasattr(hooks, "__call__"): + hooks = [hooks] + for hook in hooks: + _hook_data = hook(hook_data, **kwargs) + if _hook_data is not None: + hook_data = _hook_data + return hook_data diff --git a/venv/Lib/site-packages/requests/models.py b/venv/Lib/site-packages/requests/models.py new file mode 100644 index 00000000..c4b25fa0 --- /dev/null +++ b/venv/Lib/site-packages/requests/models.py @@ -0,0 +1,1039 @@ +""" +requests.models +~~~~~~~~~~~~~~~ + +This module contains the primary objects that power Requests. +""" + +import datetime + +# Import encoding now, to avoid implicit import later. +# Implicit import within threads may cause LookupError when standard library is in a ZIP, +# such as in Embedded Python. See https://github.com/psf/requests/issues/3578. +import encodings.idna # noqa: F401 +from io import UnsupportedOperation + +from urllib3.exceptions import ( + DecodeError, + LocationParseError, + ProtocolError, + ReadTimeoutError, + SSLError, +) +from urllib3.fields import RequestField +from urllib3.filepost import encode_multipart_formdata +from urllib3.util import parse_url + +from ._internal_utils import to_native_string, unicode_is_ascii +from .auth import HTTPBasicAuth +from .compat import ( + Callable, + JSONDecodeError, + Mapping, + basestring, + builtin_str, + chardet, + cookielib, +) +from .compat import json as complexjson +from .compat import urlencode, urlsplit, urlunparse +from .cookies import _copy_cookie_jar, cookiejar_from_dict, get_cookie_header +from .exceptions import ( + ChunkedEncodingError, + ConnectionError, + ContentDecodingError, + HTTPError, + InvalidJSONError, + InvalidURL, +) +from .exceptions import JSONDecodeError as RequestsJSONDecodeError +from .exceptions import MissingSchema +from .exceptions import SSLError as RequestsSSLError +from .exceptions import StreamConsumedError +from .hooks import default_hooks +from .status_codes import codes +from .structures import CaseInsensitiveDict +from .utils import ( + check_header_validity, + get_auth_from_url, + guess_filename, + guess_json_utf, + iter_slices, + parse_header_links, + requote_uri, + stream_decode_response_unicode, + super_len, + to_key_val_list, +) + +#: The set of HTTP status codes that indicate an automatically +#: processable redirect. +REDIRECT_STATI = ( + codes.moved, # 301 + codes.found, # 302 + codes.other, # 303 + codes.temporary_redirect, # 307 + codes.permanent_redirect, # 308 +) + +DEFAULT_REDIRECT_LIMIT = 30 +CONTENT_CHUNK_SIZE = 10 * 1024 +ITER_CHUNK_SIZE = 512 + + +class RequestEncodingMixin: + @property + def path_url(self): + """Build the path URL to use.""" + + url = [] + + p = urlsplit(self.url) + + path = p.path + if not path: + path = "/" + + url.append(path) + + query = p.query + if query: + url.append("?") + url.append(query) + + return "".join(url) + + @staticmethod + def _encode_params(data): + """Encode parameters in a piece of data. + + Will successfully encode parameters when passed as a dict or a list of + 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary + if parameters are supplied as a dict. + """ + + if isinstance(data, (str, bytes)): + return data + elif hasattr(data, "read"): + return data + elif hasattr(data, "__iter__"): + result = [] + for k, vs in to_key_val_list(data): + if isinstance(vs, basestring) or not hasattr(vs, "__iter__"): + vs = [vs] + for v in vs: + if v is not None: + result.append( + ( + k.encode("utf-8") if isinstance(k, str) else k, + v.encode("utf-8") if isinstance(v, str) else v, + ) + ) + return urlencode(result, doseq=True) + else: + return data + + @staticmethod + def _encode_files(files, data): + """Build the body for a multipart/form-data request. + + Will successfully encode files when passed as a dict or a list of + tuples. Order is retained if data is a list of tuples but arbitrary + if parameters are supplied as a dict. + The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) + or 4-tuples (filename, fileobj, contentype, custom_headers). + """ + if not files: + raise ValueError("Files must be provided.") + elif isinstance(data, basestring): + raise ValueError("Data must not be a string.") + + new_fields = [] + fields = to_key_val_list(data or {}) + files = to_key_val_list(files or {}) + + for field, val in fields: + if isinstance(val, basestring) or not hasattr(val, "__iter__"): + val = [val] + for v in val: + if v is not None: + # Don't call str() on bytestrings: in Py3 it all goes wrong. + if not isinstance(v, bytes): + v = str(v) + + new_fields.append( + ( + field.decode("utf-8") + if isinstance(field, bytes) + else field, + v.encode("utf-8") if isinstance(v, str) else v, + ) + ) + + for k, v in files: + # support for explicit filename + ft = None + fh = None + if isinstance(v, (tuple, list)): + if len(v) == 2: + fn, fp = v + elif len(v) == 3: + fn, fp, ft = v + else: + fn, fp, ft, fh = v + else: + fn = guess_filename(v) or k + fp = v + + if isinstance(fp, (str, bytes, bytearray)): + fdata = fp + elif hasattr(fp, "read"): + fdata = fp.read() + elif fp is None: + continue + else: + fdata = fp + + rf = RequestField(name=k, data=fdata, filename=fn, headers=fh) + rf.make_multipart(content_type=ft) + new_fields.append(rf) + + body, content_type = encode_multipart_formdata(new_fields) + + return body, content_type + + +class RequestHooksMixin: + def register_hook(self, event, hook): + """Properly register a hook.""" + + if event not in self.hooks: + raise ValueError(f'Unsupported event specified, with event name "{event}"') + + if isinstance(hook, Callable): + self.hooks[event].append(hook) + elif hasattr(hook, "__iter__"): + self.hooks[event].extend(h for h in hook if isinstance(h, Callable)) + + def deregister_hook(self, event, hook): + """Deregister a previously registered hook. + Returns True if the hook existed, False if not. + """ + + try: + self.hooks[event].remove(hook) + return True + except ValueError: + return False + + +class Request(RequestHooksMixin): + """A user-created :class:`Request ` object. + + Used to prepare a :class:`PreparedRequest `, which is sent to the server. + + :param method: HTTP method to use. + :param url: URL to send. + :param headers: dictionary of headers to send. + :param files: dictionary of {filename: fileobject} files to multipart upload. + :param data: the body to attach to the request. If a dictionary or + list of tuples ``[(key, value)]`` is provided, form-encoding will + take place. + :param json: json for the body to attach to the request (if files or data is not specified). + :param params: URL parameters to append to the URL. If a dictionary or + list of tuples ``[(key, value)]`` is provided, form-encoding will + take place. + :param auth: Auth handler or (user, pass) tuple. + :param cookies: dictionary or CookieJar of cookies to attach to this request. + :param hooks: dictionary of callback hooks, for internal usage. + + Usage:: + + >>> import requests + >>> req = requests.Request('GET', 'https://httpbin.org/get') + >>> req.prepare() + + """ + + def __init__( + self, + method=None, + url=None, + headers=None, + files=None, + data=None, + params=None, + auth=None, + cookies=None, + hooks=None, + json=None, + ): + # Default empty dicts for dict params. + data = [] if data is None else data + files = [] if files is None else files + headers = {} if headers is None else headers + params = {} if params is None else params + hooks = {} if hooks is None else hooks + + self.hooks = default_hooks() + for k, v in list(hooks.items()): + self.register_hook(event=k, hook=v) + + self.method = method + self.url = url + self.headers = headers + self.files = files + self.data = data + self.json = json + self.params = params + self.auth = auth + self.cookies = cookies + + def __repr__(self): + return f"" + + def prepare(self): + """Constructs a :class:`PreparedRequest ` for transmission and returns it.""" + p = PreparedRequest() + p.prepare( + method=self.method, + url=self.url, + headers=self.headers, + files=self.files, + data=self.data, + json=self.json, + params=self.params, + auth=self.auth, + cookies=self.cookies, + hooks=self.hooks, + ) + return p + + +class PreparedRequest(RequestEncodingMixin, RequestHooksMixin): + """The fully mutable :class:`PreparedRequest ` object, + containing the exact bytes that will be sent to the server. + + Instances are generated from a :class:`Request ` object, and + should not be instantiated manually; doing so may produce undesirable + effects. + + Usage:: + + >>> import requests + >>> req = requests.Request('GET', 'https://httpbin.org/get') + >>> r = req.prepare() + >>> r + + + >>> s = requests.Session() + >>> s.send(r) + + """ + + def __init__(self): + #: HTTP verb to send to the server. + self.method = None + #: HTTP URL to send the request to. + self.url = None + #: dictionary of HTTP headers. + self.headers = None + # The `CookieJar` used to create the Cookie header will be stored here + # after prepare_cookies is called + self._cookies = None + #: request body to send to the server. + self.body = None + #: dictionary of callback hooks, for internal usage. + self.hooks = default_hooks() + #: integer denoting starting position of a readable file-like body. + self._body_position = None + + def prepare( + self, + method=None, + url=None, + headers=None, + files=None, + data=None, + params=None, + auth=None, + cookies=None, + hooks=None, + json=None, + ): + """Prepares the entire request with the given parameters.""" + + self.prepare_method(method) + self.prepare_url(url, params) + self.prepare_headers(headers) + self.prepare_cookies(cookies) + self.prepare_body(data, files, json) + self.prepare_auth(auth, url) + + # Note that prepare_auth must be last to enable authentication schemes + # such as OAuth to work on a fully prepared request. + + # This MUST go after prepare_auth. Authenticators could add a hook + self.prepare_hooks(hooks) + + def __repr__(self): + return f"" + + def copy(self): + p = PreparedRequest() + p.method = self.method + p.url = self.url + p.headers = self.headers.copy() if self.headers is not None else None + p._cookies = _copy_cookie_jar(self._cookies) + p.body = self.body + p.hooks = self.hooks + p._body_position = self._body_position + return p + + def prepare_method(self, method): + """Prepares the given HTTP method.""" + self.method = method + if self.method is not None: + self.method = to_native_string(self.method.upper()) + + @staticmethod + def _get_idna_encoded_host(host): + import idna + + try: + host = idna.encode(host, uts46=True).decode("utf-8") + except idna.IDNAError: + raise UnicodeError + return host + + def prepare_url(self, url, params): + """Prepares the given HTTP URL.""" + #: Accept objects that have string representations. + #: We're unable to blindly call unicode/str functions + #: as this will include the bytestring indicator (b'') + #: on python 3.x. + #: https://github.com/psf/requests/pull/2238 + if isinstance(url, bytes): + url = url.decode("utf8") + else: + url = str(url) + + # Remove leading whitespaces from url + url = url.lstrip() + + # Don't do any URL preparation for non-HTTP schemes like `mailto`, + # `data` etc to work around exceptions from `url_parse`, which + # handles RFC 3986 only. + if ":" in url and not url.lower().startswith("http"): + self.url = url + return + + # Support for unicode domain names and paths. + try: + scheme, auth, host, port, path, query, fragment = parse_url(url) + except LocationParseError as e: + raise InvalidURL(*e.args) + + if not scheme: + raise MissingSchema( + f"Invalid URL {url!r}: No scheme supplied. " + f"Perhaps you meant https://{url}?" + ) + + if not host: + raise InvalidURL(f"Invalid URL {url!r}: No host supplied") + + # In general, we want to try IDNA encoding the hostname if the string contains + # non-ASCII characters. This allows users to automatically get the correct IDNA + # behaviour. For strings containing only ASCII characters, we need to also verify + # it doesn't start with a wildcard (*), before allowing the unencoded hostname. + if not unicode_is_ascii(host): + try: + host = self._get_idna_encoded_host(host) + except UnicodeError: + raise InvalidURL("URL has an invalid label.") + elif host.startswith(("*", ".")): + raise InvalidURL("URL has an invalid label.") + + # Carefully reconstruct the network location + netloc = auth or "" + if netloc: + netloc += "@" + netloc += host + if port: + netloc += f":{port}" + + # Bare domains aren't valid URLs. + if not path: + path = "/" + + if isinstance(params, (str, bytes)): + params = to_native_string(params) + + enc_params = self._encode_params(params) + if enc_params: + if query: + query = f"{query}&{enc_params}" + else: + query = enc_params + + url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment])) + self.url = url + + def prepare_headers(self, headers): + """Prepares the given HTTP headers.""" + + self.headers = CaseInsensitiveDict() + if headers: + for header in headers.items(): + # Raise exception on invalid header value. + check_header_validity(header) + name, value = header + self.headers[to_native_string(name)] = value + + def prepare_body(self, data, files, json=None): + """Prepares the given HTTP body data.""" + + # Check if file, fo, generator, iterator. + # If not, run through normal process. + + # Nottin' on you. + body = None + content_type = None + + if not data and json is not None: + # urllib3 requires a bytes-like body. Python 2's json.dumps + # provides this natively, but Python 3 gives a Unicode string. + content_type = "application/json" + + try: + body = complexjson.dumps(json, allow_nan=False) + except ValueError as ve: + raise InvalidJSONError(ve, request=self) + + if not isinstance(body, bytes): + body = body.encode("utf-8") + + is_stream = all( + [ + hasattr(data, "__iter__"), + not isinstance(data, (basestring, list, tuple, Mapping)), + ] + ) + + if is_stream: + try: + length = super_len(data) + except (TypeError, AttributeError, UnsupportedOperation): + length = None + + body = data + + if getattr(body, "tell", None) is not None: + # Record the current file position before reading. + # This will allow us to rewind a file in the event + # of a redirect. + try: + self._body_position = body.tell() + except OSError: + # This differentiates from None, allowing us to catch + # a failed `tell()` later when trying to rewind the body + self._body_position = object() + + if files: + raise NotImplementedError( + "Streamed bodies and files are mutually exclusive." + ) + + if length: + self.headers["Content-Length"] = builtin_str(length) + else: + self.headers["Transfer-Encoding"] = "chunked" + else: + # Multi-part file uploads. + if files: + (body, content_type) = self._encode_files(files, data) + else: + if data: + body = self._encode_params(data) + if isinstance(data, basestring) or hasattr(data, "read"): + content_type = None + else: + content_type = "application/x-www-form-urlencoded" + + self.prepare_content_length(body) + + # Add content-type if it wasn't explicitly provided. + if content_type and ("content-type" not in self.headers): + self.headers["Content-Type"] = content_type + + self.body = body + + def prepare_content_length(self, body): + """Prepare Content-Length header based on request method and body""" + if body is not None: + length = super_len(body) + if length: + # If length exists, set it. Otherwise, we fallback + # to Transfer-Encoding: chunked. + self.headers["Content-Length"] = builtin_str(length) + elif ( + self.method not in ("GET", "HEAD") + and self.headers.get("Content-Length") is None + ): + # Set Content-Length to 0 for methods that can have a body + # but don't provide one. (i.e. not GET or HEAD) + self.headers["Content-Length"] = "0" + + def prepare_auth(self, auth, url=""): + """Prepares the given HTTP auth data.""" + + # If no Auth is explicitly provided, extract it from the URL first. + if auth is None: + url_auth = get_auth_from_url(self.url) + auth = url_auth if any(url_auth) else None + + if auth: + if isinstance(auth, tuple) and len(auth) == 2: + # special-case basic HTTP auth + auth = HTTPBasicAuth(*auth) + + # Allow auth to make its changes. + r = auth(self) + + # Update self to reflect the auth changes. + self.__dict__.update(r.__dict__) + + # Recompute Content-Length + self.prepare_content_length(self.body) + + def prepare_cookies(self, cookies): + """Prepares the given HTTP cookie data. + + This function eventually generates a ``Cookie`` header from the + given cookies using cookielib. Due to cookielib's design, the header + will not be regenerated if it already exists, meaning this function + can only be called once for the life of the + :class:`PreparedRequest ` object. Any subsequent calls + to ``prepare_cookies`` will have no actual effect, unless the "Cookie" + header is removed beforehand. + """ + if isinstance(cookies, cookielib.CookieJar): + self._cookies = cookies + else: + self._cookies = cookiejar_from_dict(cookies) + + cookie_header = get_cookie_header(self._cookies, self) + if cookie_header is not None: + self.headers["Cookie"] = cookie_header + + def prepare_hooks(self, hooks): + """Prepares the given hooks.""" + # hooks can be passed as None to the prepare method and to this + # method. To prevent iterating over None, simply use an empty list + # if hooks is False-y + hooks = hooks or [] + for event in hooks: + self.register_hook(event, hooks[event]) + + +class Response: + """The :class:`Response ` object, which contains a + server's response to an HTTP request. + """ + + __attrs__ = [ + "_content", + "status_code", + "headers", + "url", + "history", + "encoding", + "reason", + "cookies", + "elapsed", + "request", + ] + + def __init__(self): + self._content = False + self._content_consumed = False + self._next = None + + #: Integer Code of responded HTTP Status, e.g. 404 or 200. + self.status_code = None + + #: Case-insensitive Dictionary of Response Headers. + #: For example, ``headers['content-encoding']`` will return the + #: value of a ``'Content-Encoding'`` response header. + self.headers = CaseInsensitiveDict() + + #: File-like object representation of response (for advanced usage). + #: Use of ``raw`` requires that ``stream=True`` be set on the request. + #: This requirement does not apply for use internally to Requests. + self.raw = None + + #: Final URL location of Response. + self.url = None + + #: Encoding to decode with when accessing r.text. + self.encoding = None + + #: A list of :class:`Response ` objects from + #: the history of the Request. Any redirect responses will end + #: up here. The list is sorted from the oldest to the most recent request. + self.history = [] + + #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK". + self.reason = None + + #: A CookieJar of Cookies the server sent back. + self.cookies = cookiejar_from_dict({}) + + #: The amount of time elapsed between sending the request + #: and the arrival of the response (as a timedelta). + #: This property specifically measures the time taken between sending + #: the first byte of the request and finishing parsing the headers. It + #: is therefore unaffected by consuming the response content or the + #: value of the ``stream`` keyword argument. + self.elapsed = datetime.timedelta(0) + + #: The :class:`PreparedRequest ` object to which this + #: is a response. + self.request = None + + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + def __getstate__(self): + # Consume everything; accessing the content attribute makes + # sure the content has been fully read. + if not self._content_consumed: + self.content + + return {attr: getattr(self, attr, None) for attr in self.__attrs__} + + def __setstate__(self, state): + for name, value in state.items(): + setattr(self, name, value) + + # pickled objects do not have .raw + setattr(self, "_content_consumed", True) + setattr(self, "raw", None) + + def __repr__(self): + return f"" + + def __bool__(self): + """Returns True if :attr:`status_code` is less than 400. + + This attribute checks if the status code of the response is between + 400 and 600 to see if there was a client error or a server error. If + the status code, is between 200 and 400, this will return True. This + is **not** a check to see if the response code is ``200 OK``. + """ + return self.ok + + def __nonzero__(self): + """Returns True if :attr:`status_code` is less than 400. + + This attribute checks if the status code of the response is between + 400 and 600 to see if there was a client error or a server error. If + the status code, is between 200 and 400, this will return True. This + is **not** a check to see if the response code is ``200 OK``. + """ + return self.ok + + def __iter__(self): + """Allows you to use a response as an iterator.""" + return self.iter_content(128) + + @property + def ok(self): + """Returns True if :attr:`status_code` is less than 400, False if not. + + This attribute checks if the status code of the response is between + 400 and 600 to see if there was a client error or a server error. If + the status code is between 200 and 400, this will return True. This + is **not** a check to see if the response code is ``200 OK``. + """ + try: + self.raise_for_status() + except HTTPError: + return False + return True + + @property + def is_redirect(self): + """True if this Response is a well-formed HTTP redirect that could have + been processed automatically (by :meth:`Session.resolve_redirects`). + """ + return "location" in self.headers and self.status_code in REDIRECT_STATI + + @property + def is_permanent_redirect(self): + """True if this Response one of the permanent versions of redirect.""" + return "location" in self.headers and self.status_code in ( + codes.moved_permanently, + codes.permanent_redirect, + ) + + @property + def next(self): + """Returns a PreparedRequest for the next request in a redirect chain, if there is one.""" + return self._next + + @property + def apparent_encoding(self): + """The apparent encoding, provided by the charset_normalizer or chardet libraries.""" + if chardet is not None: + return chardet.detect(self.content)["encoding"] + else: + # If no character detection library is available, we'll fall back + # to a standard Python utf-8 str. + return "utf-8" + + def iter_content(self, chunk_size=1, decode_unicode=False): + """Iterates over the response data. When stream=True is set on the + request, this avoids reading the content at once into memory for + large responses. The chunk size is the number of bytes it should + read into memory. This is not necessarily the length of each item + returned as decoding can take place. + + chunk_size must be of type int or None. A value of None will + function differently depending on the value of `stream`. + stream=True will read data as it arrives in whatever size the + chunks are received. If stream=False, data is returned as + a single chunk. + + If decode_unicode is True, content will be decoded using the best + available encoding based on the response. + """ + + def generate(): + # Special case for urllib3. + if hasattr(self.raw, "stream"): + try: + yield from self.raw.stream(chunk_size, decode_content=True) + except ProtocolError as e: + raise ChunkedEncodingError(e) + except DecodeError as e: + raise ContentDecodingError(e) + except ReadTimeoutError as e: + raise ConnectionError(e) + except SSLError as e: + raise RequestsSSLError(e) + else: + # Standard file-like object. + while True: + chunk = self.raw.read(chunk_size) + if not chunk: + break + yield chunk + + self._content_consumed = True + + if self._content_consumed and isinstance(self._content, bool): + raise StreamConsumedError() + elif chunk_size is not None and not isinstance(chunk_size, int): + raise TypeError( + f"chunk_size must be an int, it is instead a {type(chunk_size)}." + ) + # simulate reading small chunks of the content + reused_chunks = iter_slices(self._content, chunk_size) + + stream_chunks = generate() + + chunks = reused_chunks if self._content_consumed else stream_chunks + + if decode_unicode: + chunks = stream_decode_response_unicode(chunks, self) + + return chunks + + def iter_lines( + self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None + ): + """Iterates over the response data, one line at a time. When + stream=True is set on the request, this avoids reading the + content at once into memory for large responses. + + .. note:: This method is not reentrant safe. + """ + + pending = None + + for chunk in self.iter_content( + chunk_size=chunk_size, decode_unicode=decode_unicode + ): + if pending is not None: + chunk = pending + chunk + + if delimiter: + lines = chunk.split(delimiter) + else: + lines = chunk.splitlines() + + if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]: + pending = lines.pop() + else: + pending = None + + yield from lines + + if pending is not None: + yield pending + + @property + def content(self): + """Content of the response, in bytes.""" + + if self._content is False: + # Read the contents. + if self._content_consumed: + raise RuntimeError("The content for this response was already consumed") + + if self.status_code == 0 or self.raw is None: + self._content = None + else: + self._content = b"".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b"" + + self._content_consumed = True + # don't need to release the connection; that's been handled by urllib3 + # since we exhausted the data. + return self._content + + @property + def text(self): + """Content of the response, in unicode. + + If Response.encoding is None, encoding will be guessed using + ``charset_normalizer`` or ``chardet``. + + The encoding of the response content is determined based solely on HTTP + headers, following RFC 2616 to the letter. If you can take advantage of + non-HTTP knowledge to make a better guess at the encoding, you should + set ``r.encoding`` appropriately before accessing this property. + """ + + # Try charset from content-type + content = None + encoding = self.encoding + + if not self.content: + return "" + + # Fallback to auto-detected encoding. + if self.encoding is None: + encoding = self.apparent_encoding + + # Decode unicode from given encoding. + try: + content = str(self.content, encoding, errors="replace") + except (LookupError, TypeError): + # A LookupError is raised if the encoding was not found which could + # indicate a misspelling or similar mistake. + # + # A TypeError can be raised if encoding is None + # + # So we try blindly encoding. + content = str(self.content, errors="replace") + + return content + + def json(self, **kwargs): + r"""Decodes the JSON response body (if any) as a Python object. + + This may return a dictionary, list, etc. depending on what is in the response. + + :param \*\*kwargs: Optional arguments that ``json.loads`` takes. + :raises requests.exceptions.JSONDecodeError: If the response body does not + contain valid json. + """ + + if not self.encoding and self.content and len(self.content) > 3: + # No encoding set. JSON RFC 4627 section 3 states we should expect + # UTF-8, -16 or -32. Detect which one to use; If the detection or + # decoding fails, fall back to `self.text` (using charset_normalizer to make + # a best guess). + encoding = guess_json_utf(self.content) + if encoding is not None: + try: + return complexjson.loads(self.content.decode(encoding), **kwargs) + except UnicodeDecodeError: + # Wrong UTF codec detected; usually because it's not UTF-8 + # but some other 8-bit codec. This is an RFC violation, + # and the server didn't bother to tell us what codec *was* + # used. + pass + except JSONDecodeError as e: + raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) + + try: + return complexjson.loads(self.text, **kwargs) + except JSONDecodeError as e: + # Catch JSON-related errors and raise as requests.JSONDecodeError + # This aliases json.JSONDecodeError and simplejson.JSONDecodeError + raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) + + @property + def links(self): + """Returns the parsed header links of the response, if any.""" + + header = self.headers.get("link") + + resolved_links = {} + + if header: + links = parse_header_links(header) + + for link in links: + key = link.get("rel") or link.get("url") + resolved_links[key] = link + + return resolved_links + + def raise_for_status(self): + """Raises :class:`HTTPError`, if one occurred.""" + + http_error_msg = "" + if isinstance(self.reason, bytes): + # We attempt to decode utf-8 first because some servers + # choose to localize their reason strings. If the string + # isn't utf-8, we fall back to iso-8859-1 for all other + # encodings. (See PR #3538) + try: + reason = self.reason.decode("utf-8") + except UnicodeDecodeError: + reason = self.reason.decode("iso-8859-1") + else: + reason = self.reason + + if 400 <= self.status_code < 500: + http_error_msg = ( + f"{self.status_code} Client Error: {reason} for url: {self.url}" + ) + + elif 500 <= self.status_code < 600: + http_error_msg = ( + f"{self.status_code} Server Error: {reason} for url: {self.url}" + ) + + if http_error_msg: + raise HTTPError(http_error_msg, response=self) + + def close(self): + """Releases the connection back to the pool. Once this method has been + called the underlying ``raw`` object must not be accessed again. + + *Note: Should not normally need to be called explicitly.* + """ + if not self._content_consumed: + self.raw.close() + + release_conn = getattr(self.raw, "release_conn", None) + if release_conn is not None: + release_conn() diff --git a/venv/Lib/site-packages/requests/packages.py b/venv/Lib/site-packages/requests/packages.py new file mode 100644 index 00000000..5ab3d8e2 --- /dev/null +++ b/venv/Lib/site-packages/requests/packages.py @@ -0,0 +1,23 @@ +import sys + +from .compat import chardet + +# This code exists for backwards compatibility reasons. +# I don't like it either. Just look the other way. :) + +for package in ("urllib3", "idna"): + locals()[package] = __import__(package) + # This traversal is apparently necessary such that the identities are + # preserved (requests.packages.urllib3.* is urllib3.*) + for mod in list(sys.modules): + if mod == package or mod.startswith(f"{package}."): + sys.modules[f"requests.packages.{mod}"] = sys.modules[mod] + +if chardet is not None: + target = chardet.__name__ + for mod in list(sys.modules): + if mod == target or mod.startswith(f"{target}."): + imported_mod = sys.modules[mod] + sys.modules[f"requests.packages.{mod}"] = imported_mod + mod = mod.replace(target, "chardet") + sys.modules[f"requests.packages.{mod}"] = imported_mod diff --git a/venv/Lib/site-packages/requests/sessions.py b/venv/Lib/site-packages/requests/sessions.py new file mode 100644 index 00000000..b387bc36 --- /dev/null +++ b/venv/Lib/site-packages/requests/sessions.py @@ -0,0 +1,831 @@ +""" +requests.sessions +~~~~~~~~~~~~~~~~~ + +This module provides a Session object to manage and persist settings across +requests (cookies, auth, proxies). +""" +import os +import sys +import time +from collections import OrderedDict +from datetime import timedelta + +from ._internal_utils import to_native_string +from .adapters import HTTPAdapter +from .auth import _basic_auth_str +from .compat import Mapping, cookielib, urljoin, urlparse +from .cookies import ( + RequestsCookieJar, + cookiejar_from_dict, + extract_cookies_to_jar, + merge_cookies, +) +from .exceptions import ( + ChunkedEncodingError, + ContentDecodingError, + InvalidSchema, + TooManyRedirects, +) +from .hooks import default_hooks, dispatch_hook + +# formerly defined here, reexposed here for backward compatibility +from .models import ( # noqa: F401 + DEFAULT_REDIRECT_LIMIT, + REDIRECT_STATI, + PreparedRequest, + Request, +) +from .status_codes import codes +from .structures import CaseInsensitiveDict +from .utils import ( # noqa: F401 + DEFAULT_PORTS, + default_headers, + get_auth_from_url, + get_environ_proxies, + get_netrc_auth, + requote_uri, + resolve_proxies, + rewind_body, + should_bypass_proxies, + to_key_val_list, +) + +# Preferred clock, based on which one is more accurate on a given system. +if sys.platform == "win32": + preferred_clock = time.perf_counter +else: + preferred_clock = time.time + + +def merge_setting(request_setting, session_setting, dict_class=OrderedDict): + """Determines appropriate setting for a given request, taking into account + the explicit setting on that request, and the setting in the session. If a + setting is a dictionary, they will be merged together using `dict_class` + """ + + if session_setting is None: + return request_setting + + if request_setting is None: + return session_setting + + # Bypass if not a dictionary (e.g. verify) + if not ( + isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping) + ): + return request_setting + + merged_setting = dict_class(to_key_val_list(session_setting)) + merged_setting.update(to_key_val_list(request_setting)) + + # Remove keys that are set to None. Extract keys first to avoid altering + # the dictionary during iteration. + none_keys = [k for (k, v) in merged_setting.items() if v is None] + for key in none_keys: + del merged_setting[key] + + return merged_setting + + +def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict): + """Properly merges both requests and session hooks. + + This is necessary because when request_hooks == {'response': []}, the + merge breaks Session hooks entirely. + """ + if session_hooks is None or session_hooks.get("response") == []: + return request_hooks + + if request_hooks is None or request_hooks.get("response") == []: + return session_hooks + + return merge_setting(request_hooks, session_hooks, dict_class) + + +class SessionRedirectMixin: + def get_redirect_target(self, resp): + """Receives a Response. Returns a redirect URI or ``None``""" + # Due to the nature of how requests processes redirects this method will + # be called at least once upon the original response and at least twice + # on each subsequent redirect response (if any). + # If a custom mixin is used to handle this logic, it may be advantageous + # to cache the redirect location onto the response object as a private + # attribute. + if resp.is_redirect: + location = resp.headers["location"] + # Currently the underlying http module on py3 decode headers + # in latin1, but empirical evidence suggests that latin1 is very + # rarely used with non-ASCII characters in HTTP headers. + # It is more likely to get UTF8 header rather than latin1. + # This causes incorrect handling of UTF8 encoded location headers. + # To solve this, we re-encode the location in latin1. + location = location.encode("latin1") + return to_native_string(location, "utf8") + return None + + def should_strip_auth(self, old_url, new_url): + """Decide whether Authorization header should be removed when redirecting""" + old_parsed = urlparse(old_url) + new_parsed = urlparse(new_url) + if old_parsed.hostname != new_parsed.hostname: + return True + # Special case: allow http -> https redirect when using the standard + # ports. This isn't specified by RFC 7235, but is kept to avoid + # breaking backwards compatibility with older versions of requests + # that allowed any redirects on the same host. + if ( + old_parsed.scheme == "http" + and old_parsed.port in (80, None) + and new_parsed.scheme == "https" + and new_parsed.port in (443, None) + ): + return False + + # Handle default port usage corresponding to scheme. + changed_port = old_parsed.port != new_parsed.port + changed_scheme = old_parsed.scheme != new_parsed.scheme + default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None) + if ( + not changed_scheme + and old_parsed.port in default_port + and new_parsed.port in default_port + ): + return False + + # Standard case: root URI must match + return changed_port or changed_scheme + + def resolve_redirects( + self, + resp, + req, + stream=False, + timeout=None, + verify=True, + cert=None, + proxies=None, + yield_requests=False, + **adapter_kwargs, + ): + """Receives a Response. Returns a generator of Responses or Requests.""" + + hist = [] # keep track of history + + url = self.get_redirect_target(resp) + previous_fragment = urlparse(req.url).fragment + while url: + prepared_request = req.copy() + + # Update history and keep track of redirects. + # resp.history must ignore the original request in this loop + hist.append(resp) + resp.history = hist[1:] + + try: + resp.content # Consume socket so it can be released + except (ChunkedEncodingError, ContentDecodingError, RuntimeError): + resp.raw.read(decode_content=False) + + if len(resp.history) >= self.max_redirects: + raise TooManyRedirects( + f"Exceeded {self.max_redirects} redirects.", response=resp + ) + + # Release the connection back into the pool. + resp.close() + + # Handle redirection without scheme (see: RFC 1808 Section 4) + if url.startswith("//"): + parsed_rurl = urlparse(resp.url) + url = ":".join([to_native_string(parsed_rurl.scheme), url]) + + # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2) + parsed = urlparse(url) + if parsed.fragment == "" and previous_fragment: + parsed = parsed._replace(fragment=previous_fragment) + elif parsed.fragment: + previous_fragment = parsed.fragment + url = parsed.geturl() + + # Facilitate relative 'location' headers, as allowed by RFC 7231. + # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') + # Compliant with RFC3986, we percent encode the url. + if not parsed.netloc: + url = urljoin(resp.url, requote_uri(url)) + else: + url = requote_uri(url) + + prepared_request.url = to_native_string(url) + + self.rebuild_method(prepared_request, resp) + + # https://github.com/psf/requests/issues/1084 + if resp.status_code not in ( + codes.temporary_redirect, + codes.permanent_redirect, + ): + # https://github.com/psf/requests/issues/3490 + purged_headers = ("Content-Length", "Content-Type", "Transfer-Encoding") + for header in purged_headers: + prepared_request.headers.pop(header, None) + prepared_request.body = None + + headers = prepared_request.headers + headers.pop("Cookie", None) + + # Extract any cookies sent on the response to the cookiejar + # in the new request. Because we've mutated our copied prepared + # request, use the old one that we haven't yet touched. + extract_cookies_to_jar(prepared_request._cookies, req, resp.raw) + merge_cookies(prepared_request._cookies, self.cookies) + prepared_request.prepare_cookies(prepared_request._cookies) + + # Rebuild auth and proxy information. + proxies = self.rebuild_proxies(prepared_request, proxies) + self.rebuild_auth(prepared_request, resp) + + # A failed tell() sets `_body_position` to `object()`. This non-None + # value ensures `rewindable` will be True, allowing us to raise an + # UnrewindableBodyError, instead of hanging the connection. + rewindable = prepared_request._body_position is not None and ( + "Content-Length" in headers or "Transfer-Encoding" in headers + ) + + # Attempt to rewind consumed file-like object. + if rewindable: + rewind_body(prepared_request) + + # Override the original request. + req = prepared_request + + if yield_requests: + yield req + else: + resp = self.send( + req, + stream=stream, + timeout=timeout, + verify=verify, + cert=cert, + proxies=proxies, + allow_redirects=False, + **adapter_kwargs, + ) + + extract_cookies_to_jar(self.cookies, prepared_request, resp.raw) + + # extract redirect url, if any, for the next loop + url = self.get_redirect_target(resp) + yield resp + + def rebuild_auth(self, prepared_request, response): + """When being redirected we may want to strip authentication from the + request to avoid leaking credentials. This method intelligently removes + and reapplies authentication where possible to avoid credential loss. + """ + headers = prepared_request.headers + url = prepared_request.url + + if "Authorization" in headers and self.should_strip_auth( + response.request.url, url + ): + # If we get redirected to a new host, we should strip out any + # authentication headers. + del headers["Authorization"] + + # .netrc might have more auth for us on our new host. + new_auth = get_netrc_auth(url) if self.trust_env else None + if new_auth is not None: + prepared_request.prepare_auth(new_auth) + + def rebuild_proxies(self, prepared_request, proxies): + """This method re-evaluates the proxy configuration by considering the + environment variables. If we are redirected to a URL covered by + NO_PROXY, we strip the proxy configuration. Otherwise, we set missing + proxy keys for this URL (in case they were stripped by a previous + redirect). + + This method also replaces the Proxy-Authorization header where + necessary. + + :rtype: dict + """ + headers = prepared_request.headers + scheme = urlparse(prepared_request.url).scheme + new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env) + + if "Proxy-Authorization" in headers: + del headers["Proxy-Authorization"] + + try: + username, password = get_auth_from_url(new_proxies[scheme]) + except KeyError: + username, password = None, None + + # urllib3 handles proxy authorization for us in the standard adapter. + # Avoid appending this to TLS tunneled requests where it may be leaked. + if not scheme.startswith("https") and username and password: + headers["Proxy-Authorization"] = _basic_auth_str(username, password) + + return new_proxies + + def rebuild_method(self, prepared_request, response): + """When being redirected we may want to change the method of the request + based on certain specs or browser behavior. + """ + method = prepared_request.method + + # https://tools.ietf.org/html/rfc7231#section-6.4.4 + if response.status_code == codes.see_other and method != "HEAD": + method = "GET" + + # Do what the browsers do, despite standards... + # First, turn 302s into GETs. + if response.status_code == codes.found and method != "HEAD": + method = "GET" + + # Second, if a POST is responded to with a 301, turn it into a GET. + # This bizarre behaviour is explained in Issue 1704. + if response.status_code == codes.moved and method == "POST": + method = "GET" + + prepared_request.method = method + + +class Session(SessionRedirectMixin): + """A Requests session. + + Provides cookie persistence, connection-pooling, and configuration. + + Basic Usage:: + + >>> import requests + >>> s = requests.Session() + >>> s.get('https://httpbin.org/get') + + + Or as a context manager:: + + >>> with requests.Session() as s: + ... s.get('https://httpbin.org/get') + + """ + + __attrs__ = [ + "headers", + "cookies", + "auth", + "proxies", + "hooks", + "params", + "verify", + "cert", + "adapters", + "stream", + "trust_env", + "max_redirects", + ] + + def __init__(self): + #: A case-insensitive dictionary of headers to be sent on each + #: :class:`Request ` sent from this + #: :class:`Session `. + self.headers = default_headers() + + #: Default Authentication tuple or object to attach to + #: :class:`Request `. + self.auth = None + + #: Dictionary mapping protocol or protocol and host to the URL of the proxy + #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to + #: be used on each :class:`Request `. + self.proxies = {} + + #: Event-handling hooks. + self.hooks = default_hooks() + + #: Dictionary of querystring data to attach to each + #: :class:`Request `. The dictionary values may be lists for + #: representing multivalued query parameters. + self.params = {} + + #: Stream response content default. + self.stream = False + + #: SSL Verification default. + #: Defaults to `True`, requiring requests to verify the TLS certificate at the + #: remote end. + #: If verify is set to `False`, requests will accept any TLS certificate + #: presented by the server, and will ignore hostname mismatches and/or + #: expired certificates, which will make your application vulnerable to + #: man-in-the-middle (MitM) attacks. + #: Only set this to `False` for testing. + self.verify = True + + #: SSL client certificate default, if String, path to ssl client + #: cert file (.pem). If Tuple, ('cert', 'key') pair. + self.cert = None + + #: Maximum number of redirects allowed. If the request exceeds this + #: limit, a :class:`TooManyRedirects` exception is raised. + #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is + #: 30. + self.max_redirects = DEFAULT_REDIRECT_LIMIT + + #: Trust environment settings for proxy configuration, default + #: authentication and similar. + self.trust_env = True + + #: A CookieJar containing all currently outstanding cookies set on this + #: session. By default it is a + #: :class:`RequestsCookieJar `, but + #: may be any other ``cookielib.CookieJar`` compatible object. + self.cookies = cookiejar_from_dict({}) + + # Default connection adapters. + self.adapters = OrderedDict() + self.mount("https://", HTTPAdapter()) + self.mount("http://", HTTPAdapter()) + + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + def prepare_request(self, request): + """Constructs a :class:`PreparedRequest ` for + transmission and returns it. The :class:`PreparedRequest` has settings + merged from the :class:`Request ` instance and those of the + :class:`Session`. + + :param request: :class:`Request` instance to prepare with this + session's settings. + :rtype: requests.PreparedRequest + """ + cookies = request.cookies or {} + + # Bootstrap CookieJar. + if not isinstance(cookies, cookielib.CookieJar): + cookies = cookiejar_from_dict(cookies) + + # Merge with session cookies + merged_cookies = merge_cookies( + merge_cookies(RequestsCookieJar(), self.cookies), cookies + ) + + # Set environment's basic authentication if not explicitly set. + auth = request.auth + if self.trust_env and not auth and not self.auth: + auth = get_netrc_auth(request.url) + + p = PreparedRequest() + p.prepare( + method=request.method.upper(), + url=request.url, + files=request.files, + data=request.data, + json=request.json, + headers=merge_setting( + request.headers, self.headers, dict_class=CaseInsensitiveDict + ), + params=merge_setting(request.params, self.params), + auth=merge_setting(auth, self.auth), + cookies=merged_cookies, + hooks=merge_hooks(request.hooks, self.hooks), + ) + return p + + def request( + self, + method, + url, + params=None, + data=None, + headers=None, + cookies=None, + files=None, + auth=None, + timeout=None, + allow_redirects=True, + proxies=None, + hooks=None, + stream=None, + verify=None, + cert=None, + json=None, + ): + """Constructs a :class:`Request `, prepares it and sends it. + Returns :class:`Response ` object. + + :param method: method for the new :class:`Request` object. + :param url: URL for the new :class:`Request` object. + :param params: (optional) Dictionary or bytes to be sent in the query + string for the :class:`Request`. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param json: (optional) json to send in the body of the + :class:`Request`. + :param headers: (optional) Dictionary of HTTP Headers to send with the + :class:`Request`. + :param cookies: (optional) Dict or CookieJar object to send with the + :class:`Request`. + :param files: (optional) Dictionary of ``'filename': file-like-objects`` + for multipart encoding upload. + :param auth: (optional) Auth tuple or callable to enable + Basic/Digest/Custom HTTP Auth. + :param timeout: (optional) How long to wait for the server to send + data before giving up, as a float, or a :ref:`(connect timeout, + read timeout) ` tuple. + :type timeout: float or tuple + :param allow_redirects: (optional) Set to True by default. + :type allow_redirects: bool + :param proxies: (optional) Dictionary mapping protocol or protocol and + hostname to the URL of the proxy. + :param hooks: (optional) Dictionary mapping hook name to one event or + list of events, event must be callable. + :param stream: (optional) whether to immediately download the response + content. Defaults to ``False``. + :param verify: (optional) Either a boolean, in which case it controls whether we verify + the server's TLS certificate, or a string, in which case it must be a path + to a CA bundle to use. Defaults to ``True``. When set to + ``False``, requests will accept any TLS certificate presented by + the server, and will ignore hostname mismatches and/or expired + certificates, which will make your application vulnerable to + man-in-the-middle (MitM) attacks. Setting verify to ``False`` + may be useful during local development or testing. + :param cert: (optional) if String, path to ssl client cert file (.pem). + If Tuple, ('cert', 'key') pair. + :rtype: requests.Response + """ + # Create the Request. + req = Request( + method=method.upper(), + url=url, + headers=headers, + files=files, + data=data or {}, + json=json, + params=params or {}, + auth=auth, + cookies=cookies, + hooks=hooks, + ) + prep = self.prepare_request(req) + + proxies = proxies or {} + + settings = self.merge_environment_settings( + prep.url, proxies, stream, verify, cert + ) + + # Send the request. + send_kwargs = { + "timeout": timeout, + "allow_redirects": allow_redirects, + } + send_kwargs.update(settings) + resp = self.send(prep, **send_kwargs) + + return resp + + def get(self, url, **kwargs): + r"""Sends a GET request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + kwargs.setdefault("allow_redirects", True) + return self.request("GET", url, **kwargs) + + def options(self, url, **kwargs): + r"""Sends a OPTIONS request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + kwargs.setdefault("allow_redirects", True) + return self.request("OPTIONS", url, **kwargs) + + def head(self, url, **kwargs): + r"""Sends a HEAD request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + kwargs.setdefault("allow_redirects", False) + return self.request("HEAD", url, **kwargs) + + def post(self, url, data=None, json=None, **kwargs): + r"""Sends a POST request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param json: (optional) json to send in the body of the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + return self.request("POST", url, data=data, json=json, **kwargs) + + def put(self, url, data=None, **kwargs): + r"""Sends a PUT request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + return self.request("PUT", url, data=data, **kwargs) + + def patch(self, url, data=None, **kwargs): + r"""Sends a PATCH request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + return self.request("PATCH", url, data=data, **kwargs) + + def delete(self, url, **kwargs): + r"""Sends a DELETE request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + return self.request("DELETE", url, **kwargs) + + def send(self, request, **kwargs): + """Send a given PreparedRequest. + + :rtype: requests.Response + """ + # Set defaults that the hooks can utilize to ensure they always have + # the correct parameters to reproduce the previous request. + kwargs.setdefault("stream", self.stream) + kwargs.setdefault("verify", self.verify) + kwargs.setdefault("cert", self.cert) + if "proxies" not in kwargs: + kwargs["proxies"] = resolve_proxies(request, self.proxies, self.trust_env) + + # It's possible that users might accidentally send a Request object. + # Guard against that specific failure case. + if isinstance(request, Request): + raise ValueError("You can only send PreparedRequests.") + + # Set up variables needed for resolve_redirects and dispatching of hooks + allow_redirects = kwargs.pop("allow_redirects", True) + stream = kwargs.get("stream") + hooks = request.hooks + + # Get the appropriate adapter to use + adapter = self.get_adapter(url=request.url) + + # Start time (approximately) of the request + start = preferred_clock() + + # Send the request + r = adapter.send(request, **kwargs) + + # Total elapsed time of the request (approximately) + elapsed = preferred_clock() - start + r.elapsed = timedelta(seconds=elapsed) + + # Response manipulation hooks + r = dispatch_hook("response", hooks, r, **kwargs) + + # Persist cookies + if r.history: + # If the hooks create history then we want those cookies too + for resp in r.history: + extract_cookies_to_jar(self.cookies, resp.request, resp.raw) + + extract_cookies_to_jar(self.cookies, request, r.raw) + + # Resolve redirects if allowed. + if allow_redirects: + # Redirect resolving generator. + gen = self.resolve_redirects(r, request, **kwargs) + history = [resp for resp in gen] + else: + history = [] + + # Shuffle things around if there's history. + if history: + # Insert the first (original) request at the start + history.insert(0, r) + # Get the last request made + r = history.pop() + r.history = history + + # If redirects aren't being followed, store the response on the Request for Response.next(). + if not allow_redirects: + try: + r._next = next( + self.resolve_redirects(r, request, yield_requests=True, **kwargs) + ) + except StopIteration: + pass + + if not stream: + r.content + + return r + + def merge_environment_settings(self, url, proxies, stream, verify, cert): + """ + Check the environment and merge it with some settings. + + :rtype: dict + """ + # Gather clues from the surrounding environment. + if self.trust_env: + # Set environment's proxies. + no_proxy = proxies.get("no_proxy") if proxies is not None else None + env_proxies = get_environ_proxies(url, no_proxy=no_proxy) + for k, v in env_proxies.items(): + proxies.setdefault(k, v) + + # Look for requests environment configuration + # and be compatible with cURL. + if verify is True or verify is None: + verify = ( + os.environ.get("REQUESTS_CA_BUNDLE") + or os.environ.get("CURL_CA_BUNDLE") + or verify + ) + + # Merge all the kwargs. + proxies = merge_setting(proxies, self.proxies) + stream = merge_setting(stream, self.stream) + verify = merge_setting(verify, self.verify) + cert = merge_setting(cert, self.cert) + + return {"proxies": proxies, "stream": stream, "verify": verify, "cert": cert} + + def get_adapter(self, url): + """ + Returns the appropriate connection adapter for the given URL. + + :rtype: requests.adapters.BaseAdapter + """ + for prefix, adapter in self.adapters.items(): + if url.lower().startswith(prefix.lower()): + return adapter + + # Nothing matches :-/ + raise InvalidSchema(f"No connection adapters were found for {url!r}") + + def close(self): + """Closes all adapters and as such the session""" + for v in self.adapters.values(): + v.close() + + def mount(self, prefix, adapter): + """Registers a connection adapter to a prefix. + + Adapters are sorted in descending order by prefix length. + """ + self.adapters[prefix] = adapter + keys_to_move = [k for k in self.adapters if len(k) < len(prefix)] + + for key in keys_to_move: + self.adapters[key] = self.adapters.pop(key) + + def __getstate__(self): + state = {attr: getattr(self, attr, None) for attr in self.__attrs__} + return state + + def __setstate__(self, state): + for attr, value in state.items(): + setattr(self, attr, value) + + +def session(): + """ + Returns a :class:`Session` for context-management. + + .. deprecated:: 1.0.0 + + This method has been deprecated since version 1.0.0 and is only kept for + backwards compatibility. New code should use :class:`~requests.sessions.Session` + to create a session. This may be removed at a future date. + + :rtype: Session + """ + return Session() diff --git a/venv/Lib/site-packages/requests/status_codes.py b/venv/Lib/site-packages/requests/status_codes.py new file mode 100644 index 00000000..c7945a2f --- /dev/null +++ b/venv/Lib/site-packages/requests/status_codes.py @@ -0,0 +1,128 @@ +r""" +The ``codes`` object defines a mapping from common names for HTTP statuses +to their numerical codes, accessible either as attributes or as dictionary +items. + +Example:: + + >>> import requests + >>> requests.codes['temporary_redirect'] + 307 + >>> requests.codes.teapot + 418 + >>> requests.codes['\o/'] + 200 + +Some codes have multiple names, and both upper- and lower-case versions of +the names are allowed. For example, ``codes.ok``, ``codes.OK``, and +``codes.okay`` all correspond to the HTTP status code 200. +""" + +from .structures import LookupDict + +_codes = { + # Informational. + 100: ("continue",), + 101: ("switching_protocols",), + 102: ("processing", "early-hints"), + 103: ("checkpoint",), + 122: ("uri_too_long", "request_uri_too_long"), + 200: ("ok", "okay", "all_ok", "all_okay", "all_good", "\\o/", "✓"), + 201: ("created",), + 202: ("accepted",), + 203: ("non_authoritative_info", "non_authoritative_information"), + 204: ("no_content",), + 205: ("reset_content", "reset"), + 206: ("partial_content", "partial"), + 207: ("multi_status", "multiple_status", "multi_stati", "multiple_stati"), + 208: ("already_reported",), + 226: ("im_used",), + # Redirection. + 300: ("multiple_choices",), + 301: ("moved_permanently", "moved", "\\o-"), + 302: ("found",), + 303: ("see_other", "other"), + 304: ("not_modified",), + 305: ("use_proxy",), + 306: ("switch_proxy",), + 307: ("temporary_redirect", "temporary_moved", "temporary"), + 308: ( + "permanent_redirect", + "resume_incomplete", + "resume", + ), # "resume" and "resume_incomplete" to be removed in 3.0 + # Client Error. + 400: ("bad_request", "bad"), + 401: ("unauthorized",), + 402: ("payment_required", "payment"), + 403: ("forbidden",), + 404: ("not_found", "-o-"), + 405: ("method_not_allowed", "not_allowed"), + 406: ("not_acceptable",), + 407: ("proxy_authentication_required", "proxy_auth", "proxy_authentication"), + 408: ("request_timeout", "timeout"), + 409: ("conflict",), + 410: ("gone",), + 411: ("length_required",), + 412: ("precondition_failed", "precondition"), + 413: ("request_entity_too_large", "content_too_large"), + 414: ("request_uri_too_large", "uri_too_long"), + 415: ("unsupported_media_type", "unsupported_media", "media_type"), + 416: ( + "requested_range_not_satisfiable", + "requested_range", + "range_not_satisfiable", + ), + 417: ("expectation_failed",), + 418: ("im_a_teapot", "teapot", "i_am_a_teapot"), + 421: ("misdirected_request",), + 422: ("unprocessable_entity", "unprocessable", "unprocessable_content"), + 423: ("locked",), + 424: ("failed_dependency", "dependency"), + 425: ("unordered_collection", "unordered", "too_early"), + 426: ("upgrade_required", "upgrade"), + 428: ("precondition_required", "precondition"), + 429: ("too_many_requests", "too_many"), + 431: ("header_fields_too_large", "fields_too_large"), + 444: ("no_response", "none"), + 449: ("retry_with", "retry"), + 450: ("blocked_by_windows_parental_controls", "parental_controls"), + 451: ("unavailable_for_legal_reasons", "legal_reasons"), + 499: ("client_closed_request",), + # Server Error. + 500: ("internal_server_error", "server_error", "/o\\", "✗"), + 501: ("not_implemented",), + 502: ("bad_gateway",), + 503: ("service_unavailable", "unavailable"), + 504: ("gateway_timeout",), + 505: ("http_version_not_supported", "http_version"), + 506: ("variant_also_negotiates",), + 507: ("insufficient_storage",), + 509: ("bandwidth_limit_exceeded", "bandwidth"), + 510: ("not_extended",), + 511: ("network_authentication_required", "network_auth", "network_authentication"), +} + +codes = LookupDict(name="status_codes") + + +def _init(): + for code, titles in _codes.items(): + for title in titles: + setattr(codes, title, code) + if not title.startswith(("\\", "/")): + setattr(codes, title.upper(), code) + + def doc(code): + names = ", ".join(f"``{n}``" for n in _codes[code]) + return "* %d: %s" % (code, names) + + global __doc__ + __doc__ = ( + __doc__ + "\n" + "\n".join(doc(code) for code in sorted(_codes)) + if __doc__ is not None + else None + ) + + +_init() diff --git a/venv/Lib/site-packages/requests/structures.py b/venv/Lib/site-packages/requests/structures.py new file mode 100644 index 00000000..188e13e4 --- /dev/null +++ b/venv/Lib/site-packages/requests/structures.py @@ -0,0 +1,99 @@ +""" +requests.structures +~~~~~~~~~~~~~~~~~~~ + +Data structures that power Requests. +""" + +from collections import OrderedDict + +from .compat import Mapping, MutableMapping + + +class CaseInsensitiveDict(MutableMapping): + """A case-insensitive ``dict``-like object. + + Implements all methods and operations of + ``MutableMapping`` as well as dict's ``copy``. Also + provides ``lower_items``. + + All keys are expected to be strings. The structure remembers the + case of the last key to be set, and ``iter(instance)``, + ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()`` + will contain case-sensitive keys. However, querying and contains + testing is case insensitive:: + + cid = CaseInsensitiveDict() + cid['Accept'] = 'application/json' + cid['aCCEPT'] == 'application/json' # True + list(cid) == ['Accept'] # True + + For example, ``headers['content-encoding']`` will return the + value of a ``'Content-Encoding'`` response header, regardless + of how the header name was originally stored. + + If the constructor, ``.update``, or equality comparison + operations are given keys that have equal ``.lower()``s, the + behavior is undefined. + """ + + def __init__(self, data=None, **kwargs): + self._store = OrderedDict() + if data is None: + data = {} + self.update(data, **kwargs) + + def __setitem__(self, key, value): + # Use the lowercased key for lookups, but store the actual + # key alongside the value. + self._store[key.lower()] = (key, value) + + def __getitem__(self, key): + return self._store[key.lower()][1] + + def __delitem__(self, key): + del self._store[key.lower()] + + def __iter__(self): + return (casedkey for casedkey, mappedvalue in self._store.values()) + + def __len__(self): + return len(self._store) + + def lower_items(self): + """Like iteritems(), but with all lowercase keys.""" + return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items()) + + def __eq__(self, other): + if isinstance(other, Mapping): + other = CaseInsensitiveDict(other) + else: + return NotImplemented + # Compare insensitively + return dict(self.lower_items()) == dict(other.lower_items()) + + # Copy is required + def copy(self): + return CaseInsensitiveDict(self._store.values()) + + def __repr__(self): + return str(dict(self.items())) + + +class LookupDict(dict): + """Dictionary lookup object.""" + + def __init__(self, name=None): + self.name = name + super().__init__() + + def __repr__(self): + return f"" + + def __getitem__(self, key): + # We allow fall-through here, so values default to None + + return self.__dict__.get(key, None) + + def get(self, key, default=None): + return self.__dict__.get(key, default) diff --git a/venv/Lib/site-packages/requests/utils.py b/venv/Lib/site-packages/requests/utils.py new file mode 100644 index 00000000..8ab55852 --- /dev/null +++ b/venv/Lib/site-packages/requests/utils.py @@ -0,0 +1,1086 @@ +""" +requests.utils +~~~~~~~~~~~~~~ + +This module provides utility functions that are used within Requests +that are also useful for external consumption. +""" + +import codecs +import contextlib +import io +import os +import re +import socket +import struct +import sys +import tempfile +import warnings +import zipfile +from collections import OrderedDict + +from urllib3.util import make_headers, parse_url + +from . import certs +from .__version__ import __version__ + +# to_native_string is unused here, but imported here for backwards compatibility +from ._internal_utils import ( # noqa: F401 + _HEADER_VALIDATORS_BYTE, + _HEADER_VALIDATORS_STR, + HEADER_VALIDATORS, + to_native_string, +) +from .compat import ( + Mapping, + basestring, + bytes, + getproxies, + getproxies_environment, + integer_types, + is_urllib3_1, +) +from .compat import parse_http_list as _parse_list_header +from .compat import ( + proxy_bypass, + proxy_bypass_environment, + quote, + str, + unquote, + urlparse, + urlunparse, +) +from .cookies import cookiejar_from_dict +from .exceptions import ( + FileModeWarning, + InvalidHeader, + InvalidURL, + UnrewindableBodyError, +) +from .structures import CaseInsensitiveDict + +NETRC_FILES = (".netrc", "_netrc") + +DEFAULT_CA_BUNDLE_PATH = certs.where() + +DEFAULT_PORTS = {"http": 80, "https": 443} + +# Ensure that ', ' is used to preserve previous delimiter behavior. +DEFAULT_ACCEPT_ENCODING = ", ".join( + re.split(r",\s*", make_headers(accept_encoding=True)["accept-encoding"]) +) + + +if sys.platform == "win32": + # provide a proxy_bypass version on Windows without DNS lookups + + def proxy_bypass_registry(host): + try: + import winreg + except ImportError: + return False + + try: + internetSettings = winreg.OpenKey( + winreg.HKEY_CURRENT_USER, + r"Software\Microsoft\Windows\CurrentVersion\Internet Settings", + ) + # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it + proxyEnable = int(winreg.QueryValueEx(internetSettings, "ProxyEnable")[0]) + # ProxyOverride is almost always a string + proxyOverride = winreg.QueryValueEx(internetSettings, "ProxyOverride")[0] + except (OSError, ValueError): + return False + if not proxyEnable or not proxyOverride: + return False + + # make a check value list from the registry entry: replace the + # '' string by the localhost entry and the corresponding + # canonical entry. + proxyOverride = proxyOverride.split(";") + # filter out empty strings to avoid re.match return true in the following code. + proxyOverride = filter(None, proxyOverride) + # now check if we match one of the registry values. + for test in proxyOverride: + if test == "": + if "." not in host: + return True + test = test.replace(".", r"\.") # mask dots + test = test.replace("*", r".*") # change glob sequence + test = test.replace("?", r".") # change glob char + if re.match(test, host, re.I): + return True + return False + + def proxy_bypass(host): # noqa + """Return True, if the host should be bypassed. + + Checks proxy settings gathered from the environment, if specified, + or the registry. + """ + if getproxies_environment(): + return proxy_bypass_environment(host) + else: + return proxy_bypass_registry(host) + + +def dict_to_sequence(d): + """Returns an internal sequence dictionary update.""" + + if hasattr(d, "items"): + d = d.items() + + return d + + +def super_len(o): + total_length = None + current_position = 0 + + if not is_urllib3_1 and isinstance(o, str): + # urllib3 2.x+ treats all strings as utf-8 instead + # of latin-1 (iso-8859-1) like http.client. + o = o.encode("utf-8") + + if hasattr(o, "__len__"): + total_length = len(o) + + elif hasattr(o, "len"): + total_length = o.len + + elif hasattr(o, "fileno"): + try: + fileno = o.fileno() + except (io.UnsupportedOperation, AttributeError): + # AttributeError is a surprising exception, seeing as how we've just checked + # that `hasattr(o, 'fileno')`. It happens for objects obtained via + # `Tarfile.extractfile()`, per issue 5229. + pass + else: + total_length = os.fstat(fileno).st_size + + # Having used fstat to determine the file length, we need to + # confirm that this file was opened up in binary mode. + if "b" not in o.mode: + warnings.warn( + ( + "Requests has determined the content-length for this " + "request using the binary size of the file: however, the " + "file has been opened in text mode (i.e. without the 'b' " + "flag in the mode). This may lead to an incorrect " + "content-length. In Requests 3.0, support will be removed " + "for files in text mode." + ), + FileModeWarning, + ) + + if hasattr(o, "tell"): + try: + current_position = o.tell() + except OSError: + # This can happen in some weird situations, such as when the file + # is actually a special file descriptor like stdin. In this + # instance, we don't know what the length is, so set it to zero and + # let requests chunk it instead. + if total_length is not None: + current_position = total_length + else: + if hasattr(o, "seek") and total_length is None: + # StringIO and BytesIO have seek but no usable fileno + try: + # seek to end of file + o.seek(0, 2) + total_length = o.tell() + + # seek back to current position to support + # partially read file-like objects + o.seek(current_position or 0) + except OSError: + total_length = 0 + + if total_length is None: + total_length = 0 + + return max(0, total_length - current_position) + + +def get_netrc_auth(url, raise_errors=False): + """Returns the Requests tuple auth for a given url from netrc.""" + + netrc_file = os.environ.get("NETRC") + if netrc_file is not None: + netrc_locations = (netrc_file,) + else: + netrc_locations = (f"~/{f}" for f in NETRC_FILES) + + try: + from netrc import NetrcParseError, netrc + + netrc_path = None + + for f in netrc_locations: + loc = os.path.expanduser(f) + if os.path.exists(loc): + netrc_path = loc + break + + # Abort early if there isn't one. + if netrc_path is None: + return + + ri = urlparse(url) + host = ri.hostname + + try: + _netrc = netrc(netrc_path).authenticators(host) + if _netrc: + # Return with login / password + login_i = 0 if _netrc[0] else 1 + return (_netrc[login_i], _netrc[2]) + except (NetrcParseError, OSError): + # If there was a parsing error or a permissions issue reading the file, + # we'll just skip netrc auth unless explicitly asked to raise errors. + if raise_errors: + raise + + # App Engine hackiness. + except (ImportError, AttributeError): + pass + + +def guess_filename(obj): + """Tries to guess the filename of the given object.""" + name = getattr(obj, "name", None) + if name and isinstance(name, basestring) and name[0] != "<" and name[-1] != ">": + return os.path.basename(name) + + +def extract_zipped_paths(path): + """Replace nonexistent paths that look like they refer to a member of a zip + archive with the location of an extracted copy of the target, or else + just return the provided path unchanged. + """ + if os.path.exists(path): + # this is already a valid path, no need to do anything further + return path + + # find the first valid part of the provided path and treat that as a zip archive + # assume the rest of the path is the name of a member in the archive + archive, member = os.path.split(path) + while archive and not os.path.exists(archive): + archive, prefix = os.path.split(archive) + if not prefix: + # If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split), + # we _can_ end up in an infinite loop on a rare corner case affecting a small number of users + break + member = "/".join([prefix, member]) + + if not zipfile.is_zipfile(archive): + return path + + zip_file = zipfile.ZipFile(archive) + if member not in zip_file.namelist(): + return path + + # we have a valid zip archive and a valid member of that archive + tmp = tempfile.gettempdir() + extracted_path = os.path.join(tmp, member.split("/")[-1]) + if not os.path.exists(extracted_path): + # use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition + with atomic_open(extracted_path) as file_handler: + file_handler.write(zip_file.read(member)) + return extracted_path + + +@contextlib.contextmanager +def atomic_open(filename): + """Write a file to the disk in an atomic fashion""" + tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename)) + try: + with os.fdopen(tmp_descriptor, "wb") as tmp_handler: + yield tmp_handler + os.replace(tmp_name, filename) + except BaseException: + os.remove(tmp_name) + raise + + +def from_key_val_list(value): + """Take an object and test to see if it can be represented as a + dictionary. Unless it can not be represented as such, return an + OrderedDict, e.g., + + :: + + >>> from_key_val_list([('key', 'val')]) + OrderedDict([('key', 'val')]) + >>> from_key_val_list('string') + Traceback (most recent call last): + ... + ValueError: cannot encode objects that are not 2-tuples + >>> from_key_val_list({'key': 'val'}) + OrderedDict([('key', 'val')]) + + :rtype: OrderedDict + """ + if value is None: + return None + + if isinstance(value, (str, bytes, bool, int)): + raise ValueError("cannot encode objects that are not 2-tuples") + + return OrderedDict(value) + + +def to_key_val_list(value): + """Take an object and test to see if it can be represented as a + dictionary. If it can be, return a list of tuples, e.g., + + :: + + >>> to_key_val_list([('key', 'val')]) + [('key', 'val')] + >>> to_key_val_list({'key': 'val'}) + [('key', 'val')] + >>> to_key_val_list('string') + Traceback (most recent call last): + ... + ValueError: cannot encode objects that are not 2-tuples + + :rtype: list + """ + if value is None: + return None + + if isinstance(value, (str, bytes, bool, int)): + raise ValueError("cannot encode objects that are not 2-tuples") + + if isinstance(value, Mapping): + value = value.items() + + return list(value) + + +# From mitsuhiko/werkzeug (used with permission). +def parse_list_header(value): + """Parse lists as described by RFC 2068 Section 2. + + In particular, parse comma-separated lists where the elements of + the list may include quoted-strings. A quoted-string could + contain a comma. A non-quoted string could have quotes in the + middle. Quotes are removed automatically after parsing. + + It basically works like :func:`parse_set_header` just that items + may appear multiple times and case sensitivity is preserved. + + The return value is a standard :class:`list`: + + >>> parse_list_header('token, "quoted value"') + ['token', 'quoted value'] + + To create a header from the :class:`list` again, use the + :func:`dump_header` function. + + :param value: a string with a list header. + :return: :class:`list` + :rtype: list + """ + result = [] + for item in _parse_list_header(value): + if item[:1] == item[-1:] == '"': + item = unquote_header_value(item[1:-1]) + result.append(item) + return result + + +# From mitsuhiko/werkzeug (used with permission). +def parse_dict_header(value): + """Parse lists of key, value pairs as described by RFC 2068 Section 2 and + convert them into a python dict: + + >>> d = parse_dict_header('foo="is a fish", bar="as well"') + >>> type(d) is dict + True + >>> sorted(d.items()) + [('bar', 'as well'), ('foo', 'is a fish')] + + If there is no value for a key it will be `None`: + + >>> parse_dict_header('key_without_value') + {'key_without_value': None} + + To create a header from the :class:`dict` again, use the + :func:`dump_header` function. + + :param value: a string with a dict header. + :return: :class:`dict` + :rtype: dict + """ + result = {} + for item in _parse_list_header(value): + if "=" not in item: + result[item] = None + continue + name, value = item.split("=", 1) + if value[:1] == value[-1:] == '"': + value = unquote_header_value(value[1:-1]) + result[name] = value + return result + + +# From mitsuhiko/werkzeug (used with permission). +def unquote_header_value(value, is_filename=False): + r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). + This does not use the real unquoting but what browsers are actually + using for quoting. + + :param value: the header value to unquote. + :rtype: str + """ + if value and value[0] == value[-1] == '"': + # this is not the real unquoting, but fixing this so that the + # RFC is met will result in bugs with internet explorer and + # probably some other browsers as well. IE for example is + # uploading files with "C:\foo\bar.txt" as filename + value = value[1:-1] + + # if this is a filename and the starting characters look like + # a UNC path, then just return the value without quotes. Using the + # replace sequence below on a UNC path has the effect of turning + # the leading double slash into a single slash and then + # _fix_ie_filename() doesn't work correctly. See #458. + if not is_filename or value[:2] != "\\\\": + return value.replace("\\\\", "\\").replace('\\"', '"') + return value + + +def dict_from_cookiejar(cj): + """Returns a key/value dictionary from a CookieJar. + + :param cj: CookieJar object to extract cookies from. + :rtype: dict + """ + + cookie_dict = {cookie.name: cookie.value for cookie in cj} + return cookie_dict + + +def add_dict_to_cookiejar(cj, cookie_dict): + """Returns a CookieJar from a key/value dictionary. + + :param cj: CookieJar to insert cookies into. + :param cookie_dict: Dict of key/values to insert into CookieJar. + :rtype: CookieJar + """ + + return cookiejar_from_dict(cookie_dict, cj) + + +def get_encodings_from_content(content): + """Returns encodings from given content string. + + :param content: bytestring to extract encodings from. + """ + warnings.warn( + ( + "In requests 3.0, get_encodings_from_content will be removed. For " + "more information, please see the discussion on issue #2266. (This" + " warning should only appear once.)" + ), + DeprecationWarning, + ) + + charset_re = re.compile(r']', flags=re.I) + pragma_re = re.compile(r']', flags=re.I) + xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]') + + return ( + charset_re.findall(content) + + pragma_re.findall(content) + + xml_re.findall(content) + ) + + +def _parse_content_type_header(header): + """Returns content type and parameters from given header + + :param header: string + :return: tuple containing content type and dictionary of + parameters + """ + + tokens = header.split(";") + content_type, params = tokens[0].strip(), tokens[1:] + params_dict = {} + items_to_strip = "\"' " + + for param in params: + param = param.strip() + if param: + key, value = param, True + index_of_equals = param.find("=") + if index_of_equals != -1: + key = param[:index_of_equals].strip(items_to_strip) + value = param[index_of_equals + 1 :].strip(items_to_strip) + params_dict[key.lower()] = value + return content_type, params_dict + + +def get_encoding_from_headers(headers): + """Returns encodings from given HTTP Header Dict. + + :param headers: dictionary to extract encoding from. + :rtype: str + """ + + content_type = headers.get("content-type") + + if not content_type: + return None + + content_type, params = _parse_content_type_header(content_type) + + if "charset" in params: + return params["charset"].strip("'\"") + + if "text" in content_type: + return "ISO-8859-1" + + if "application/json" in content_type: + # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset + return "utf-8" + + +def stream_decode_response_unicode(iterator, r): + """Stream decodes an iterator.""" + + if r.encoding is None: + yield from iterator + return + + decoder = codecs.getincrementaldecoder(r.encoding)(errors="replace") + for chunk in iterator: + rv = decoder.decode(chunk) + if rv: + yield rv + rv = decoder.decode(b"", final=True) + if rv: + yield rv + + +def iter_slices(string, slice_length): + """Iterate over slices of a string.""" + pos = 0 + if slice_length is None or slice_length <= 0: + slice_length = len(string) + while pos < len(string): + yield string[pos : pos + slice_length] + pos += slice_length + + +def get_unicode_from_response(r): + """Returns the requested content back in unicode. + + :param r: Response object to get unicode content from. + + Tried: + + 1. charset from content-type + 2. fall back and replace all unicode characters + + :rtype: str + """ + warnings.warn( + ( + "In requests 3.0, get_unicode_from_response will be removed. For " + "more information, please see the discussion on issue #2266. (This" + " warning should only appear once.)" + ), + DeprecationWarning, + ) + + tried_encodings = [] + + # Try charset from content-type + encoding = get_encoding_from_headers(r.headers) + + if encoding: + try: + return str(r.content, encoding) + except UnicodeError: + tried_encodings.append(encoding) + + # Fall back: + try: + return str(r.content, encoding, errors="replace") + except TypeError: + return r.content + + +# The unreserved URI characters (RFC 3986) +UNRESERVED_SET = frozenset( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~" +) + + +def unquote_unreserved(uri): + """Un-escape any percent-escape sequences in a URI that are unreserved + characters. This leaves all reserved, illegal and non-ASCII bytes encoded. + + :rtype: str + """ + parts = uri.split("%") + for i in range(1, len(parts)): + h = parts[i][0:2] + if len(h) == 2 and h.isalnum(): + try: + c = chr(int(h, 16)) + except ValueError: + raise InvalidURL(f"Invalid percent-escape sequence: '{h}'") + + if c in UNRESERVED_SET: + parts[i] = c + parts[i][2:] + else: + parts[i] = f"%{parts[i]}" + else: + parts[i] = f"%{parts[i]}" + return "".join(parts) + + +def requote_uri(uri): + """Re-quote the given URI. + + This function passes the given URI through an unquote/quote cycle to + ensure that it is fully and consistently quoted. + + :rtype: str + """ + safe_with_percent = "!#$%&'()*+,/:;=?@[]~" + safe_without_percent = "!#$&'()*+,/:;=?@[]~" + try: + # Unquote only the unreserved characters + # Then quote only illegal characters (do not quote reserved, + # unreserved, or '%') + return quote(unquote_unreserved(uri), safe=safe_with_percent) + except InvalidURL: + # We couldn't unquote the given URI, so let's try quoting it, but + # there may be unquoted '%'s in the URI. We need to make sure they're + # properly quoted so they do not cause issues elsewhere. + return quote(uri, safe=safe_without_percent) + + +def address_in_network(ip, net): + """This function allows you to check if an IP belongs to a network subnet + + Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 + returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 + + :rtype: bool + """ + ipaddr = struct.unpack("=L", socket.inet_aton(ip))[0] + netaddr, bits = net.split("/") + netmask = struct.unpack("=L", socket.inet_aton(dotted_netmask(int(bits))))[0] + network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask + return (ipaddr & netmask) == (network & netmask) + + +def dotted_netmask(mask): + """Converts mask from /xx format to xxx.xxx.xxx.xxx + + Example: if mask is 24 function returns 255.255.255.0 + + :rtype: str + """ + bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1 + return socket.inet_ntoa(struct.pack(">I", bits)) + + +def is_ipv4_address(string_ip): + """ + :rtype: bool + """ + try: + socket.inet_aton(string_ip) + except OSError: + return False + return True + + +def is_valid_cidr(string_network): + """ + Very simple check of the cidr format in no_proxy variable. + + :rtype: bool + """ + if string_network.count("/") == 1: + try: + mask = int(string_network.split("/")[1]) + except ValueError: + return False + + if mask < 1 or mask > 32: + return False + + try: + socket.inet_aton(string_network.split("/")[0]) + except OSError: + return False + else: + return False + return True + + +@contextlib.contextmanager +def set_environ(env_name, value): + """Set the environment variable 'env_name' to 'value' + + Save previous value, yield, and then restore the previous value stored in + the environment variable 'env_name'. + + If 'value' is None, do nothing""" + value_changed = value is not None + if value_changed: + old_value = os.environ.get(env_name) + os.environ[env_name] = value + try: + yield + finally: + if value_changed: + if old_value is None: + del os.environ[env_name] + else: + os.environ[env_name] = old_value + + +def should_bypass_proxies(url, no_proxy): + """ + Returns whether we should bypass proxies or not. + + :rtype: bool + """ + + # Prioritize lowercase environment variables over uppercase + # to keep a consistent behaviour with other http projects (curl, wget). + def get_proxy(key): + return os.environ.get(key) or os.environ.get(key.upper()) + + # First check whether no_proxy is defined. If it is, check that the URL + # we're getting isn't in the no_proxy list. + no_proxy_arg = no_proxy + if no_proxy is None: + no_proxy = get_proxy("no_proxy") + parsed = urlparse(url) + + if parsed.hostname is None: + # URLs don't always have hostnames, e.g. file:/// urls. + return True + + if no_proxy: + # We need to check whether we match here. We need to see if we match + # the end of the hostname, both with and without the port. + no_proxy = (host for host in no_proxy.replace(" ", "").split(",") if host) + + if is_ipv4_address(parsed.hostname): + for proxy_ip in no_proxy: + if is_valid_cidr(proxy_ip): + if address_in_network(parsed.hostname, proxy_ip): + return True + elif parsed.hostname == proxy_ip: + # If no_proxy ip was defined in plain IP notation instead of cidr notation & + # matches the IP of the index + return True + else: + host_with_port = parsed.hostname + if parsed.port: + host_with_port += f":{parsed.port}" + + for host in no_proxy: + if parsed.hostname.endswith(host) or host_with_port.endswith(host): + # The URL does match something in no_proxy, so we don't want + # to apply the proxies on this URL. + return True + + with set_environ("no_proxy", no_proxy_arg): + # parsed.hostname can be `None` in cases such as a file URI. + try: + bypass = proxy_bypass(parsed.hostname) + except (TypeError, socket.gaierror): + bypass = False + + if bypass: + return True + + return False + + +def get_environ_proxies(url, no_proxy=None): + """ + Return a dict of environment proxies. + + :rtype: dict + """ + if should_bypass_proxies(url, no_proxy=no_proxy): + return {} + else: + return getproxies() + + +def select_proxy(url, proxies): + """Select a proxy for the url, if applicable. + + :param url: The url being for the request + :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs + """ + proxies = proxies or {} + urlparts = urlparse(url) + if urlparts.hostname is None: + return proxies.get(urlparts.scheme, proxies.get("all")) + + proxy_keys = [ + urlparts.scheme + "://" + urlparts.hostname, + urlparts.scheme, + "all://" + urlparts.hostname, + "all", + ] + proxy = None + for proxy_key in proxy_keys: + if proxy_key in proxies: + proxy = proxies[proxy_key] + break + + return proxy + + +def resolve_proxies(request, proxies, trust_env=True): + """This method takes proxy information from a request and configuration + input to resolve a mapping of target proxies. This will consider settings + such as NO_PROXY to strip proxy configurations. + + :param request: Request or PreparedRequest + :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs + :param trust_env: Boolean declaring whether to trust environment configs + + :rtype: dict + """ + proxies = proxies if proxies is not None else {} + url = request.url + scheme = urlparse(url).scheme + no_proxy = proxies.get("no_proxy") + new_proxies = proxies.copy() + + if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy): + environ_proxies = get_environ_proxies(url, no_proxy=no_proxy) + + proxy = environ_proxies.get(scheme, environ_proxies.get("all")) + + if proxy: + new_proxies.setdefault(scheme, proxy) + return new_proxies + + +def default_user_agent(name="python-requests"): + """ + Return a string representing the default user agent. + + :rtype: str + """ + return f"{name}/{__version__}" + + +def default_headers(): + """ + :rtype: requests.structures.CaseInsensitiveDict + """ + return CaseInsensitiveDict( + { + "User-Agent": default_user_agent(), + "Accept-Encoding": DEFAULT_ACCEPT_ENCODING, + "Accept": "*/*", + "Connection": "keep-alive", + } + ) + + +def parse_header_links(value): + """Return a list of parsed link headers proxies. + + i.e. Link: ; rel=front; type="image/jpeg",; rel=back;type="image/jpeg" + + :rtype: list + """ + + links = [] + + replace_chars = " '\"" + + value = value.strip(replace_chars) + if not value: + return links + + for val in re.split(", *<", value): + try: + url, params = val.split(";", 1) + except ValueError: + url, params = val, "" + + link = {"url": url.strip("<> '\"")} + + for param in params.split(";"): + try: + key, value = param.split("=") + except ValueError: + break + + link[key.strip(replace_chars)] = value.strip(replace_chars) + + links.append(link) + + return links + + +# Null bytes; no need to recreate these on each call to guess_json_utf +_null = "\x00".encode("ascii") # encoding to ASCII for Python 3 +_null2 = _null * 2 +_null3 = _null * 3 + + +def guess_json_utf(data): + """ + :rtype: str + """ + # JSON always starts with two ASCII characters, so detection is as + # easy as counting the nulls and from their location and count + # determine the encoding. Also detect a BOM, if present. + sample = data[:4] + if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE): + return "utf-32" # BOM included + if sample[:3] == codecs.BOM_UTF8: + return "utf-8-sig" # BOM included, MS style (discouraged) + if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE): + return "utf-16" # BOM included + nullcount = sample.count(_null) + if nullcount == 0: + return "utf-8" + if nullcount == 2: + if sample[::2] == _null2: # 1st and 3rd are null + return "utf-16-be" + if sample[1::2] == _null2: # 2nd and 4th are null + return "utf-16-le" + # Did not detect 2 valid UTF-16 ascii-range characters + if nullcount == 3: + if sample[:3] == _null3: + return "utf-32-be" + if sample[1:] == _null3: + return "utf-32-le" + # Did not detect a valid UTF-32 ascii-range character + return None + + +def prepend_scheme_if_needed(url, new_scheme): + """Given a URL that may or may not have a scheme, prepend the given scheme. + Does not replace a present scheme with the one provided as an argument. + + :rtype: str + """ + parsed = parse_url(url) + scheme, auth, host, port, path, query, fragment = parsed + + # A defect in urlparse determines that there isn't a netloc present in some + # urls. We previously assumed parsing was overly cautious, and swapped the + # netloc and path. Due to a lack of tests on the original defect, this is + # maintained with parse_url for backwards compatibility. + netloc = parsed.netloc + if not netloc: + netloc, path = path, netloc + + if auth: + # parse_url doesn't provide the netloc with auth + # so we'll add it ourselves. + netloc = "@".join([auth, netloc]) + if scheme is None: + scheme = new_scheme + if path is None: + path = "" + + return urlunparse((scheme, netloc, path, "", query, fragment)) + + +def get_auth_from_url(url): + """Given a url with authentication components, extract them into a tuple of + username,password. + + :rtype: (str,str) + """ + parsed = urlparse(url) + + try: + auth = (unquote(parsed.username), unquote(parsed.password)) + except (AttributeError, TypeError): + auth = ("", "") + + return auth + + +def check_header_validity(header): + """Verifies that header parts don't contain leading whitespace + reserved characters, or return characters. + + :param header: tuple, in the format (name, value). + """ + name, value = header + _validate_header_part(header, name, 0) + _validate_header_part(header, value, 1) + + +def _validate_header_part(header, header_part, header_validator_index): + if isinstance(header_part, str): + validator = _HEADER_VALIDATORS_STR[header_validator_index] + elif isinstance(header_part, bytes): + validator = _HEADER_VALIDATORS_BYTE[header_validator_index] + else: + raise InvalidHeader( + f"Header part ({header_part!r}) from {header} " + f"must be of type str or bytes, not {type(header_part)}" + ) + + if not validator.match(header_part): + header_kind = "name" if header_validator_index == 0 else "value" + raise InvalidHeader( + f"Invalid leading whitespace, reserved character(s), or return " + f"character(s) in header {header_kind}: {header_part!r}" + ) + + +def urldefragauth(url): + """ + Given a url remove the fragment and the authentication part. + + :rtype: str + """ + scheme, netloc, path, params, query, fragment = urlparse(url) + + # see func:`prepend_scheme_if_needed` + if not netloc: + netloc, path = path, netloc + + netloc = netloc.rsplit("@", 1)[-1] + + return urlunparse((scheme, netloc, path, params, query, "")) + + +def rewind_body(prepared_request): + """Move file pointer back to its recorded starting position + so it can be read again on redirect. + """ + body_seek = getattr(prepared_request.body, "seek", None) + if body_seek is not None and isinstance( + prepared_request._body_position, integer_types + ): + try: + body_seek(prepared_request._body_position) + except OSError: + raise UnrewindableBodyError( + "An error occurred when rewinding request body for redirect." + ) + else: + raise UnrewindableBodyError("Unable to rewind request body for redirect.") diff --git a/venv/Lib/site-packages/sniffio/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/sniffio/__pycache__/__init__.cpython-312.pyc index 5dd648f6..a430e2ab 100644 Binary files a/venv/Lib/site-packages/sniffio/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/sniffio/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/sniffio/__pycache__/_impl.cpython-312.pyc b/venv/Lib/site-packages/sniffio/__pycache__/_impl.cpython-312.pyc index d9333ce8..eddebc3d 100644 Binary files a/venv/Lib/site-packages/sniffio/__pycache__/_impl.cpython-312.pyc and b/venv/Lib/site-packages/sniffio/__pycache__/_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/sniffio/__pycache__/_version.cpython-312.pyc b/venv/Lib/site-packages/sniffio/__pycache__/_version.cpython-312.pyc index 8bbe5e70..e4535d80 100644 Binary files a/venv/Lib/site-packages/sniffio/__pycache__/_version.cpython-312.pyc and b/venv/Lib/site-packages/sniffio/__pycache__/_version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette-0.46.2.dist-info/INSTALLER b/venv/Lib/site-packages/starlette-0.46.2.dist-info/INSTALLER new file mode 100644 index 00000000..a1b589e3 --- /dev/null +++ b/venv/Lib/site-packages/starlette-0.46.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/Lib/site-packages/starlette-0.46.2.dist-info/METADATA b/venv/Lib/site-packages/starlette-0.46.2.dist-info/METADATA new file mode 100644 index 00000000..bb1935a2 --- /dev/null +++ b/venv/Lib/site-packages/starlette-0.46.2.dist-info/METADATA @@ -0,0 +1,176 @@ +Metadata-Version: 2.4 +Name: starlette +Version: 0.46.2 +Summary: The little ASGI library that shines. +Project-URL: Homepage, https://github.com/encode/starlette +Project-URL: Documentation, https://www.starlette.io/ +Project-URL: Changelog, https://www.starlette.io/release-notes/ +Project-URL: Funding, https://github.com/sponsors/encode +Project-URL: Source, https://github.com/encode/starlette +Author-email: Tom Christie +License-Expression: BSD-3-Clause +License-File: LICENSE.md +Classifier: Development Status :: 3 - Alpha +Classifier: Environment :: Web Environment +Classifier: Framework :: AnyIO +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Topic :: Internet :: WWW/HTTP +Requires-Python: >=3.9 +Requires-Dist: anyio<5,>=3.6.2 +Requires-Dist: typing-extensions>=3.10.0; python_version < '3.10' +Provides-Extra: full +Requires-Dist: httpx<0.29.0,>=0.27.0; extra == 'full' +Requires-Dist: itsdangerous; extra == 'full' +Requires-Dist: jinja2; extra == 'full' +Requires-Dist: python-multipart>=0.0.18; extra == 'full' +Requires-Dist: pyyaml; extra == 'full' +Description-Content-Type: text/markdown + +

+ + + + starlette-logo + +

+ +

+ ✨ The little ASGI framework that shines. ✨ +

+ +--- + +[![Build Status](https://github.com/encode/starlette/workflows/Test%20Suite/badge.svg)](https://github.com/encode/starlette/actions) +[![Package version](https://badge.fury.io/py/starlette.svg)](https://pypi.python.org/pypi/starlette) +[![Supported Python Version](https://img.shields.io/pypi/pyversions/starlette.svg?color=%2334D058)](https://pypi.org/project/starlette) + +--- + +**Documentation**: https://www.starlette.io + +**Source Code**: https://github.com/encode/starlette + +--- + +# Starlette + +Starlette is a lightweight [ASGI][asgi] framework/toolkit, +which is ideal for building async web services in Python. + +It is production-ready, and gives you the following: + +* A lightweight, low-complexity HTTP web framework. +* WebSocket support. +* In-process background tasks. +* Startup and shutdown events. +* Test client built on `httpx`. +* CORS, GZip, Static Files, Streaming responses. +* Session and Cookie support. +* 100% test coverage. +* 100% type annotated codebase. +* Few hard dependencies. +* Compatible with `asyncio` and `trio` backends. +* Great overall performance [against independent benchmarks][techempower]. + +## Installation + +```shell +$ pip install starlette +``` + +You'll also want to install an ASGI server, such as [uvicorn](https://www.uvicorn.org/), [daphne](https://github.com/django/daphne/), or [hypercorn](https://hypercorn.readthedocs.io/en/latest/). + +```shell +$ pip install uvicorn +``` + +## Example + +```python title="main.py" +from starlette.applications import Starlette +from starlette.responses import JSONResponse +from starlette.routing import Route + + +async def homepage(request): + return JSONResponse({'hello': 'world'}) + +routes = [ + Route("/", endpoint=homepage) +] + +app = Starlette(debug=True, routes=routes) +``` + +Then run the application using Uvicorn: + +```shell +$ uvicorn main:app +``` + +## Dependencies + +Starlette only requires `anyio`, and the following are optional: + +* [`httpx`][httpx] - Required if you want to use the `TestClient`. +* [`jinja2`][jinja2] - Required if you want to use `Jinja2Templates`. +* [`python-multipart`][python-multipart] - Required if you want to support form parsing, with `request.form()`. +* [`itsdangerous`][itsdangerous] - Required for `SessionMiddleware` support. +* [`pyyaml`][pyyaml] - Required for `SchemaGenerator` support. + +You can install all of these with `pip install starlette[full]`. + +## Framework or Toolkit + +Starlette is designed to be used either as a complete framework, or as +an ASGI toolkit. You can use any of its components independently. + +```python +from starlette.responses import PlainTextResponse + + +async def app(scope, receive, send): + assert scope['type'] == 'http' + response = PlainTextResponse('Hello, world!') + await response(scope, receive, send) +``` + +Run the `app` application in `example.py`: + +```shell +$ uvicorn example:app +INFO: Started server process [11509] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +Run uvicorn with `--reload` to enable auto-reloading on code changes. + +## Modularity + +The modularity that Starlette is designed on promotes building re-usable +components that can be shared between any ASGI framework. This should enable +an ecosystem of shared middleware and mountable applications. + +The clean API separation also means it's easier to understand each component +in isolation. + +--- + +

Starlette is BSD licensed code.
Designed & crafted with care.

— ⭐️ —

+ +[asgi]: https://asgi.readthedocs.io/en/latest/ +[httpx]: https://www.python-httpx.org/ +[jinja2]: https://jinja.palletsprojects.com/ +[python-multipart]: https://multipart.fastapiexpert.com/ +[itsdangerous]: https://itsdangerous.palletsprojects.com/ +[sqlalchemy]: https://www.sqlalchemy.org +[pyyaml]: https://pyyaml.org/wiki/PyYAMLDocumentation +[techempower]: https://www.techempower.com/benchmarks/#hw=ph&test=fortune&l=zijzen-sf diff --git a/venv/Lib/site-packages/starlette-0.46.2.dist-info/RECORD b/venv/Lib/site-packages/starlette-0.46.2.dist-info/RECORD new file mode 100644 index 00000000..f3f64a1c --- /dev/null +++ b/venv/Lib/site-packages/starlette-0.46.2.dist-info/RECORD @@ -0,0 +1,74 @@ +starlette-0.46.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +starlette-0.46.2.dist-info/METADATA,sha256=ZQ65swcGWuW1-L0UrDKo2SaF90Jux18XK9OmZBmtEyg,6167 +starlette-0.46.2.dist-info/RECORD,, +starlette-0.46.2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +starlette-0.46.2.dist-info/licenses/LICENSE.md,sha256=3LlWd6AiQCQxh-lk-UGEfRmxeCHPmeWvrmhPqzKMGb8,1518 +starlette/__init__.py,sha256=lWEdbG8IshPF1zUeQxPyfsi3uFhuXQmN7phOE5OaeI8,23 +starlette/__pycache__/__init__.cpython-312.pyc,, +starlette/__pycache__/_exception_handler.cpython-312.pyc,, +starlette/__pycache__/_utils.cpython-312.pyc,, +starlette/__pycache__/applications.cpython-312.pyc,, +starlette/__pycache__/authentication.cpython-312.pyc,, +starlette/__pycache__/background.cpython-312.pyc,, +starlette/__pycache__/concurrency.cpython-312.pyc,, +starlette/__pycache__/config.cpython-312.pyc,, +starlette/__pycache__/convertors.cpython-312.pyc,, +starlette/__pycache__/datastructures.cpython-312.pyc,, +starlette/__pycache__/endpoints.cpython-312.pyc,, +starlette/__pycache__/exceptions.cpython-312.pyc,, +starlette/__pycache__/formparsers.cpython-312.pyc,, +starlette/__pycache__/requests.cpython-312.pyc,, +starlette/__pycache__/responses.cpython-312.pyc,, +starlette/__pycache__/routing.cpython-312.pyc,, +starlette/__pycache__/schemas.cpython-312.pyc,, +starlette/__pycache__/staticfiles.cpython-312.pyc,, +starlette/__pycache__/status.cpython-312.pyc,, +starlette/__pycache__/templating.cpython-312.pyc,, +starlette/__pycache__/testclient.cpython-312.pyc,, +starlette/__pycache__/types.cpython-312.pyc,, +starlette/__pycache__/websockets.cpython-312.pyc,, +starlette/_exception_handler.py,sha256=OM4H48d5iyv8_ofxBDYy1PflsJGlr40jFZPI3DYZTQg,2219 +starlette/_utils.py,sha256=Lg65uXpJ3Tq0lqik0t-A6nQDNhxMl9NttI7fjxY0hxM,2764 +starlette/applications.py,sha256=hNiaF39WBGRPt8Ht6Zw67XJ5B1CzCUj2cC-8KIZGddk,10678 +starlette/authentication.py,sha256=9dlyeykDMhoxgmI9hFVZ38uu8Nl6k2NZiaoa607Z8hc,4948 +starlette/background.py,sha256=50zBQ_50lV9YGRGevBUFQ4DOwisU47pUV_PfiBG9Cg4,1257 +starlette/concurrency.py,sha256=zjBYz9UPaXpUKx1qVzocVQHlxDDi90wOOUKubXjXWTI,1746 +starlette/config.py,sha256=xCXgQTgMaeuyXaHRFor7EJiAVMUdjnu6Hgwz4rr6sUU,4445 +starlette/convertors.py,sha256=RBd7q6UynlJl4xP_MXDrRmtH8N55re8d_SQaztmwPQw,2302 +starlette/datastructures.py,sha256=7IkoXZ5b0EaieymYa46Sncwd7GVAnyJ5RI-LQvKLFx0,22262 +starlette/endpoints.py,sha256=RgFXHAw8_Ktgqea5T5e4jEWY73LbB822odx6LXI-_6I,5098 +starlette/exceptions.py,sha256=tIphlZa8EsQfKw3-xw5J3ZN1GjaR4UcxfJK69Ad2hG8,1066 +starlette/formparsers.py,sha256=GxhueF4HrJeLJDFGpPFm5WZn7C90VBGS2Faz90JP1gY,11045 +starlette/middleware/__init__.py,sha256=3WljcfADnSltJrVUuFgpvJiZKcjsjC1Ih9aqYUvSknk,1224 +starlette/middleware/__pycache__/__init__.cpython-312.pyc,, +starlette/middleware/__pycache__/authentication.cpython-312.pyc,, +starlette/middleware/__pycache__/base.cpython-312.pyc,, +starlette/middleware/__pycache__/cors.cpython-312.pyc,, +starlette/middleware/__pycache__/errors.cpython-312.pyc,, +starlette/middleware/__pycache__/exceptions.cpython-312.pyc,, +starlette/middleware/__pycache__/gzip.cpython-312.pyc,, +starlette/middleware/__pycache__/httpsredirect.cpython-312.pyc,, +starlette/middleware/__pycache__/sessions.cpython-312.pyc,, +starlette/middleware/__pycache__/trustedhost.cpython-312.pyc,, +starlette/middleware/__pycache__/wsgi.cpython-312.pyc,, +starlette/middleware/authentication.py,sha256=ftWVVbETxrr0gOwtxwULww362Wkt1s9iOVu4s1LJ53I,1791 +starlette/middleware/base.py,sha256=O8u_zoxndbFGaykG5peYd42koxjp_mYDk76OKVuCYO8,8971 +starlette/middleware/cors.py,sha256=-ih4JxmeRaKhmv076DcJE-wd0K2FJbo23gzZdLrJb00,7051 +starlette/middleware/errors.py,sha256=bomTUfQIo7CIwnZQ8fFz4BCDY5idQnrsrhGSpZNiH-s,8066 +starlette/middleware/exceptions.py,sha256=Q96acXz9bRIUZORAKjlsbcaFuI0-m61cSXmfFq_ND60,2791 +starlette/middleware/gzip.py,sha256=VaNOHZleGS_YWueBFVFZ-RboWQmcQI8hjgZDKLVklOM,5697 +starlette/middleware/httpsredirect.py,sha256=SNTleaYALGoITV7xwbic4gB6VYdM8Ylea_ykciUz31g,848 +starlette/middleware/sessions.py,sha256=Cpbql_BTanVqDbhPGdoUrNvHIKf9D3Yuc48cJZerFTU,3566 +starlette/middleware/trustedhost.py,sha256=dXbW22C3RYNp3TsdfCuE0MNS-VZFcN8B_S3wYrzETm8,2203 +starlette/middleware/wsgi.py,sha256=0vLstcalV-kq2YyqQR9NCLiPNgokW7nDvyRqQpj_5iQ,5386 +starlette/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +starlette/requests.py,sha256=X_rmfl_pgnndvqk0Kxd_bCjxIe_PUO0N64DJMpeOUBE,11693 +starlette/responses.py,sha256=_9PWDCpoqZzT9iVTwLNuQ47RuMTzp6NbSknaW4lpJwM,20226 +starlette/routing.py,sha256=mKt5XcuSBg_08__XdXp5WVh3qCJMPLMaYfe1bXFzI8w,34550 +starlette/schemas.py,sha256=kKVRFG_kicD8geEnlfHoEsBCE-8MsdXyPE0VM4f2Q24,5181 +starlette/staticfiles.py,sha256=pmxmrueM67-X16sYAVHEIu61BJr221XNfq5d1UbFls4,8474 +starlette/status.py,sha256=e70xV6wYFR5bdmkYkgYCSwZk1L2FdKDwA6u4zCjmypQ,2820 +starlette/templating.py,sha256=HzG3S0THU-r7q-1AqRZyaxLJOwVyYAcxwvzIwU7tQZ0,8408 +starlette/testclient.py,sha256=G0Db7thEEaE6unArj34D_qG3NT_OI_1Io-3P4z_psFM,27987 +starlette/types.py,sha256=I2yIP5R1qyVD1GBiJZQ_I9dprcYUOVVK8fHa6UQVsqg,1048 +starlette/websockets.py,sha256=M_8gmQmthBHvqdVfLIzs4yuQpup7B853tPSaNQB_UMo,8332 diff --git a/venv/Lib/site-packages/starlette-0.46.2.dist-info/WHEEL b/venv/Lib/site-packages/starlette-0.46.2.dist-info/WHEEL new file mode 100644 index 00000000..12228d41 --- /dev/null +++ b/venv/Lib/site-packages/starlette-0.46.2.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/venv/Lib/site-packages/starlette-0.46.2.dist-info/licenses/LICENSE.md b/venv/Lib/site-packages/starlette-0.46.2.dist-info/licenses/LICENSE.md new file mode 100644 index 00000000..d16a60ec --- /dev/null +++ b/venv/Lib/site-packages/starlette-0.46.2.dist-info/licenses/LICENSE.md @@ -0,0 +1,27 @@ +Copyright © 2018, [Encode OSS Ltd](https://www.encode.io/). +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/venv/Lib/site-packages/starlette/__init__.py b/venv/Lib/site-packages/starlette/__init__.py new file mode 100644 index 00000000..8583baf6 --- /dev/null +++ b/venv/Lib/site-packages/starlette/__init__.py @@ -0,0 +1 @@ +__version__ = "0.46.2" diff --git a/venv/Lib/site-packages/starlette/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/starlette/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..ac753e71 Binary files /dev/null and b/venv/Lib/site-packages/starlette/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/__pycache__/_exception_handler.cpython-312.pyc b/venv/Lib/site-packages/starlette/__pycache__/_exception_handler.cpython-312.pyc new file mode 100644 index 00000000..c0fef323 Binary files /dev/null and b/venv/Lib/site-packages/starlette/__pycache__/_exception_handler.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/__pycache__/_utils.cpython-312.pyc b/venv/Lib/site-packages/starlette/__pycache__/_utils.cpython-312.pyc new file mode 100644 index 00000000..a52e0b83 Binary files /dev/null and b/venv/Lib/site-packages/starlette/__pycache__/_utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/__pycache__/applications.cpython-312.pyc b/venv/Lib/site-packages/starlette/__pycache__/applications.cpython-312.pyc new file mode 100644 index 00000000..dcdaa55b Binary files /dev/null and b/venv/Lib/site-packages/starlette/__pycache__/applications.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/__pycache__/authentication.cpython-312.pyc b/venv/Lib/site-packages/starlette/__pycache__/authentication.cpython-312.pyc new file mode 100644 index 00000000..1c490a59 Binary files /dev/null and b/venv/Lib/site-packages/starlette/__pycache__/authentication.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/__pycache__/background.cpython-312.pyc b/venv/Lib/site-packages/starlette/__pycache__/background.cpython-312.pyc new file mode 100644 index 00000000..f38c13cc Binary files /dev/null and b/venv/Lib/site-packages/starlette/__pycache__/background.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/__pycache__/concurrency.cpython-312.pyc b/venv/Lib/site-packages/starlette/__pycache__/concurrency.cpython-312.pyc new file mode 100644 index 00000000..af3f0828 Binary files /dev/null and b/venv/Lib/site-packages/starlette/__pycache__/concurrency.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/__pycache__/config.cpython-312.pyc b/venv/Lib/site-packages/starlette/__pycache__/config.cpython-312.pyc new file mode 100644 index 00000000..c941b3c9 Binary files /dev/null and b/venv/Lib/site-packages/starlette/__pycache__/config.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/__pycache__/convertors.cpython-312.pyc b/venv/Lib/site-packages/starlette/__pycache__/convertors.cpython-312.pyc new file mode 100644 index 00000000..01450614 Binary files /dev/null and b/venv/Lib/site-packages/starlette/__pycache__/convertors.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/__pycache__/datastructures.cpython-312.pyc b/venv/Lib/site-packages/starlette/__pycache__/datastructures.cpython-312.pyc new file mode 100644 index 00000000..fd700760 Binary files /dev/null and b/venv/Lib/site-packages/starlette/__pycache__/datastructures.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/__pycache__/endpoints.cpython-312.pyc b/venv/Lib/site-packages/starlette/__pycache__/endpoints.cpython-312.pyc new file mode 100644 index 00000000..47667258 Binary files /dev/null and b/venv/Lib/site-packages/starlette/__pycache__/endpoints.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/__pycache__/exceptions.cpython-312.pyc b/venv/Lib/site-packages/starlette/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 00000000..041fd1cd Binary files /dev/null and b/venv/Lib/site-packages/starlette/__pycache__/exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/__pycache__/formparsers.cpython-312.pyc b/venv/Lib/site-packages/starlette/__pycache__/formparsers.cpython-312.pyc new file mode 100644 index 00000000..9b811219 Binary files /dev/null and b/venv/Lib/site-packages/starlette/__pycache__/formparsers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/__pycache__/requests.cpython-312.pyc b/venv/Lib/site-packages/starlette/__pycache__/requests.cpython-312.pyc new file mode 100644 index 00000000..2fd66378 Binary files /dev/null and b/venv/Lib/site-packages/starlette/__pycache__/requests.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/__pycache__/responses.cpython-312.pyc b/venv/Lib/site-packages/starlette/__pycache__/responses.cpython-312.pyc new file mode 100644 index 00000000..496ab92f Binary files /dev/null and b/venv/Lib/site-packages/starlette/__pycache__/responses.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/__pycache__/routing.cpython-312.pyc b/venv/Lib/site-packages/starlette/__pycache__/routing.cpython-312.pyc new file mode 100644 index 00000000..74df3f1c Binary files /dev/null and b/venv/Lib/site-packages/starlette/__pycache__/routing.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/__pycache__/schemas.cpython-312.pyc b/venv/Lib/site-packages/starlette/__pycache__/schemas.cpython-312.pyc new file mode 100644 index 00000000..bbe360a5 Binary files /dev/null and b/venv/Lib/site-packages/starlette/__pycache__/schemas.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/__pycache__/staticfiles.cpython-312.pyc b/venv/Lib/site-packages/starlette/__pycache__/staticfiles.cpython-312.pyc new file mode 100644 index 00000000..7773e669 Binary files /dev/null and b/venv/Lib/site-packages/starlette/__pycache__/staticfiles.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/__pycache__/status.cpython-312.pyc b/venv/Lib/site-packages/starlette/__pycache__/status.cpython-312.pyc new file mode 100644 index 00000000..c01b3510 Binary files /dev/null and b/venv/Lib/site-packages/starlette/__pycache__/status.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/__pycache__/templating.cpython-312.pyc b/venv/Lib/site-packages/starlette/__pycache__/templating.cpython-312.pyc new file mode 100644 index 00000000..71de33b2 Binary files /dev/null and b/venv/Lib/site-packages/starlette/__pycache__/templating.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/__pycache__/testclient.cpython-312.pyc b/venv/Lib/site-packages/starlette/__pycache__/testclient.cpython-312.pyc new file mode 100644 index 00000000..da0cf264 Binary files /dev/null and b/venv/Lib/site-packages/starlette/__pycache__/testclient.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/__pycache__/types.cpython-312.pyc b/venv/Lib/site-packages/starlette/__pycache__/types.cpython-312.pyc new file mode 100644 index 00000000..5ff7fb16 Binary files /dev/null and b/venv/Lib/site-packages/starlette/__pycache__/types.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/__pycache__/websockets.cpython-312.pyc b/venv/Lib/site-packages/starlette/__pycache__/websockets.cpython-312.pyc new file mode 100644 index 00000000..0e6dabfc Binary files /dev/null and b/venv/Lib/site-packages/starlette/__pycache__/websockets.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/_exception_handler.py b/venv/Lib/site-packages/starlette/_exception_handler.py new file mode 100644 index 00000000..72bc89d9 --- /dev/null +++ b/venv/Lib/site-packages/starlette/_exception_handler.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +import typing + +from starlette._utils import is_async_callable +from starlette.concurrency import run_in_threadpool +from starlette.exceptions import HTTPException +from starlette.requests import Request +from starlette.types import ASGIApp, ExceptionHandler, Message, Receive, Scope, Send +from starlette.websockets import WebSocket + +ExceptionHandlers = dict[typing.Any, ExceptionHandler] +StatusHandlers = dict[int, ExceptionHandler] + + +def _lookup_exception_handler(exc_handlers: ExceptionHandlers, exc: Exception) -> ExceptionHandler | None: + for cls in type(exc).__mro__: + if cls in exc_handlers: + return exc_handlers[cls] + return None + + +def wrap_app_handling_exceptions(app: ASGIApp, conn: Request | WebSocket) -> ASGIApp: + exception_handlers: ExceptionHandlers + status_handlers: StatusHandlers + try: + exception_handlers, status_handlers = conn.scope["starlette.exception_handlers"] + except KeyError: + exception_handlers, status_handlers = {}, {} + + async def wrapped_app(scope: Scope, receive: Receive, send: Send) -> None: + response_started = False + + async def sender(message: Message) -> None: + nonlocal response_started + + if message["type"] == "http.response.start": + response_started = True + await send(message) + + try: + await app(scope, receive, sender) + except Exception as exc: + handler = None + + if isinstance(exc, HTTPException): + handler = status_handlers.get(exc.status_code) + + if handler is None: + handler = _lookup_exception_handler(exception_handlers, exc) + + if handler is None: + raise exc + + if response_started: + raise RuntimeError("Caught handled exception, but response already started.") from exc + + if is_async_callable(handler): + response = await handler(conn, exc) + else: + response = await run_in_threadpool(handler, conn, exc) # type: ignore + if response is not None: + await response(scope, receive, sender) + + return wrapped_app diff --git a/venv/Lib/site-packages/starlette/_utils.py b/venv/Lib/site-packages/starlette/_utils.py new file mode 100644 index 00000000..8001c472 --- /dev/null +++ b/venv/Lib/site-packages/starlette/_utils.py @@ -0,0 +1,100 @@ +from __future__ import annotations + +import functools +import inspect +import sys +import typing +from contextlib import contextmanager + +from starlette.types import Scope + +if sys.version_info >= (3, 10): # pragma: no cover + from typing import TypeGuard +else: # pragma: no cover + from typing_extensions import TypeGuard + +has_exceptiongroups = True +if sys.version_info < (3, 11): # pragma: no cover + try: + from exceptiongroup import BaseExceptionGroup # type: ignore[unused-ignore,import-not-found] + except ImportError: + has_exceptiongroups = False + +T = typing.TypeVar("T") +AwaitableCallable = typing.Callable[..., typing.Awaitable[T]] + + +@typing.overload +def is_async_callable(obj: AwaitableCallable[T]) -> TypeGuard[AwaitableCallable[T]]: ... + + +@typing.overload +def is_async_callable(obj: typing.Any) -> TypeGuard[AwaitableCallable[typing.Any]]: ... + + +def is_async_callable(obj: typing.Any) -> typing.Any: + while isinstance(obj, functools.partial): + obj = obj.func + + return inspect.iscoroutinefunction(obj) or (callable(obj) and inspect.iscoroutinefunction(obj.__call__)) + + +T_co = typing.TypeVar("T_co", covariant=True) + + +class AwaitableOrContextManager(typing.Awaitable[T_co], typing.AsyncContextManager[T_co], typing.Protocol[T_co]): ... + + +class SupportsAsyncClose(typing.Protocol): + async def close(self) -> None: ... # pragma: no cover + + +SupportsAsyncCloseType = typing.TypeVar("SupportsAsyncCloseType", bound=SupportsAsyncClose, covariant=False) + + +class AwaitableOrContextManagerWrapper(typing.Generic[SupportsAsyncCloseType]): + __slots__ = ("aw", "entered") + + def __init__(self, aw: typing.Awaitable[SupportsAsyncCloseType]) -> None: + self.aw = aw + + def __await__(self) -> typing.Generator[typing.Any, None, SupportsAsyncCloseType]: + return self.aw.__await__() + + async def __aenter__(self) -> SupportsAsyncCloseType: + self.entered = await self.aw + return self.entered + + async def __aexit__(self, *args: typing.Any) -> None | bool: + await self.entered.close() + return None + + +@contextmanager +def collapse_excgroups() -> typing.Generator[None, None, None]: + try: + yield + except BaseException as exc: + if has_exceptiongroups: # pragma: no cover + while isinstance(exc, BaseExceptionGroup) and len(exc.exceptions) == 1: + exc = exc.exceptions[0] + + raise exc + + +def get_route_path(scope: Scope) -> str: + path: str = scope["path"] + root_path = scope.get("root_path", "") + if not root_path: + return path + + if not path.startswith(root_path): + return path + + if path == root_path: + return "" + + if path[len(root_path)] == "/": + return path[len(root_path) :] + + return path diff --git a/venv/Lib/site-packages/starlette/applications.py b/venv/Lib/site-packages/starlette/applications.py new file mode 100644 index 00000000..6df5a707 --- /dev/null +++ b/venv/Lib/site-packages/starlette/applications.py @@ -0,0 +1,249 @@ +from __future__ import annotations + +import sys +import typing +import warnings + +if sys.version_info >= (3, 10): # pragma: no cover + from typing import ParamSpec +else: # pragma: no cover + from typing_extensions import ParamSpec + +from starlette.datastructures import State, URLPath +from starlette.middleware import Middleware, _MiddlewareFactory +from starlette.middleware.base import BaseHTTPMiddleware +from starlette.middleware.errors import ServerErrorMiddleware +from starlette.middleware.exceptions import ExceptionMiddleware +from starlette.requests import Request +from starlette.responses import Response +from starlette.routing import BaseRoute, Router +from starlette.types import ASGIApp, ExceptionHandler, Lifespan, Receive, Scope, Send +from starlette.websockets import WebSocket + +AppType = typing.TypeVar("AppType", bound="Starlette") +P = ParamSpec("P") + + +class Starlette: + """Creates an Starlette application.""" + + def __init__( + self: AppType, + debug: bool = False, + routes: typing.Sequence[BaseRoute] | None = None, + middleware: typing.Sequence[Middleware] | None = None, + exception_handlers: typing.Mapping[typing.Any, ExceptionHandler] | None = None, + on_startup: typing.Sequence[typing.Callable[[], typing.Any]] | None = None, + on_shutdown: typing.Sequence[typing.Callable[[], typing.Any]] | None = None, + lifespan: Lifespan[AppType] | None = None, + ) -> None: + """Initializes the application. + + Parameters: + debug: Boolean indicating if debug tracebacks should be returned on errors. + routes: A list of routes to serve incoming HTTP and WebSocket requests. + middleware: A list of middleware to run for every request. A starlette + application will always automatically include two middleware classes. + `ServerErrorMiddleware` is added as the very outermost middleware, to handle + any uncaught errors occurring anywhere in the entire stack. + `ExceptionMiddleware` is added as the very innermost middleware, to deal + with handled exception cases occurring in the routing or endpoints. + exception_handlers: A mapping of either integer status codes, + or exception class types onto callables which handle the exceptions. + Exception handler callables should be of the form + `handler(request, exc) -> response` and may be either standard functions, or + async functions. + on_startup: A list of callables to run on application startup. + Startup handler callables do not take any arguments, and may be either + standard functions, or async functions. + on_shutdown: A list of callables to run on application shutdown. + Shutdown handler callables do not take any arguments, and may be either + standard functions, or async functions. + lifespan: A lifespan context function, which can be used to perform + startup and shutdown tasks. This is a newer style that replaces the + `on_startup` and `on_shutdown` handlers. Use one or the other, not both. + """ + # The lifespan context function is a newer style that replaces + # on_startup / on_shutdown handlers. Use one or the other, not both. + assert lifespan is None or (on_startup is None and on_shutdown is None), ( + "Use either 'lifespan' or 'on_startup'/'on_shutdown', not both." + ) + + self.debug = debug + self.state = State() + self.router = Router(routes, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan) + self.exception_handlers = {} if exception_handlers is None else dict(exception_handlers) + self.user_middleware = [] if middleware is None else list(middleware) + self.middleware_stack: ASGIApp | None = None + + def build_middleware_stack(self) -> ASGIApp: + debug = self.debug + error_handler = None + exception_handlers: dict[typing.Any, typing.Callable[[Request, Exception], Response]] = {} + + for key, value in self.exception_handlers.items(): + if key in (500, Exception): + error_handler = value + else: + exception_handlers[key] = value + + middleware = ( + [Middleware(ServerErrorMiddleware, handler=error_handler, debug=debug)] + + self.user_middleware + + [Middleware(ExceptionMiddleware, handlers=exception_handlers, debug=debug)] + ) + + app = self.router + for cls, args, kwargs in reversed(middleware): + app = cls(app, *args, **kwargs) + return app + + @property + def routes(self) -> list[BaseRoute]: + return self.router.routes + + def url_path_for(self, name: str, /, **path_params: typing.Any) -> URLPath: + return self.router.url_path_for(name, **path_params) + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + scope["app"] = self + if self.middleware_stack is None: + self.middleware_stack = self.build_middleware_stack() + await self.middleware_stack(scope, receive, send) + + def on_event(self, event_type: str) -> typing.Callable: # type: ignore[type-arg] + return self.router.on_event(event_type) # pragma: no cover + + def mount(self, path: str, app: ASGIApp, name: str | None = None) -> None: + self.router.mount(path, app=app, name=name) # pragma: no cover + + def host(self, host: str, app: ASGIApp, name: str | None = None) -> None: + self.router.host(host, app=app, name=name) # pragma: no cover + + def add_middleware( + self, + middleware_class: _MiddlewareFactory[P], + *args: P.args, + **kwargs: P.kwargs, + ) -> None: + if self.middleware_stack is not None: # pragma: no cover + raise RuntimeError("Cannot add middleware after an application has started") + self.user_middleware.insert(0, Middleware(middleware_class, *args, **kwargs)) + + def add_exception_handler( + self, + exc_class_or_status_code: int | type[Exception], + handler: ExceptionHandler, + ) -> None: # pragma: no cover + self.exception_handlers[exc_class_or_status_code] = handler + + def add_event_handler( + self, + event_type: str, + func: typing.Callable, # type: ignore[type-arg] + ) -> None: # pragma: no cover + self.router.add_event_handler(event_type, func) + + def add_route( + self, + path: str, + route: typing.Callable[[Request], typing.Awaitable[Response] | Response], + methods: list[str] | None = None, + name: str | None = None, + include_in_schema: bool = True, + ) -> None: # pragma: no cover + self.router.add_route(path, route, methods=methods, name=name, include_in_schema=include_in_schema) + + def add_websocket_route( + self, + path: str, + route: typing.Callable[[WebSocket], typing.Awaitable[None]], + name: str | None = None, + ) -> None: # pragma: no cover + self.router.add_websocket_route(path, route, name=name) + + def exception_handler(self, exc_class_or_status_code: int | type[Exception]) -> typing.Callable: # type: ignore[type-arg] + warnings.warn( + "The `exception_handler` decorator is deprecated, and will be removed in version 1.0.0. " + "Refer to https://www.starlette.io/exceptions/ for the recommended approach.", + DeprecationWarning, + ) + + def decorator(func: typing.Callable) -> typing.Callable: # type: ignore[type-arg] + self.add_exception_handler(exc_class_or_status_code, func) + return func + + return decorator + + def route( + self, + path: str, + methods: list[str] | None = None, + name: str | None = None, + include_in_schema: bool = True, + ) -> typing.Callable: # type: ignore[type-arg] + """ + We no longer document this decorator style API, and its usage is discouraged. + Instead you should use the following approach: + + >>> routes = [Route(path, endpoint=...), ...] + >>> app = Starlette(routes=routes) + """ + warnings.warn( + "The `route` decorator is deprecated, and will be removed in version 1.0.0. " + "Refer to https://www.starlette.io/routing/ for the recommended approach.", + DeprecationWarning, + ) + + def decorator(func: typing.Callable) -> typing.Callable: # type: ignore[type-arg] + self.router.add_route( + path, + func, + methods=methods, + name=name, + include_in_schema=include_in_schema, + ) + return func + + return decorator + + def websocket_route(self, path: str, name: str | None = None) -> typing.Callable: # type: ignore[type-arg] + """ + We no longer document this decorator style API, and its usage is discouraged. + Instead you should use the following approach: + + >>> routes = [WebSocketRoute(path, endpoint=...), ...] + >>> app = Starlette(routes=routes) + """ + warnings.warn( + "The `websocket_route` decorator is deprecated, and will be removed in version 1.0.0. " + "Refer to https://www.starlette.io/routing/#websocket-routing for the recommended approach.", + DeprecationWarning, + ) + + def decorator(func: typing.Callable) -> typing.Callable: # type: ignore[type-arg] + self.router.add_websocket_route(path, func, name=name) + return func + + return decorator + + def middleware(self, middleware_type: str) -> typing.Callable: # type: ignore[type-arg] + """ + We no longer document this decorator style API, and its usage is discouraged. + Instead you should use the following approach: + + >>> middleware = [Middleware(...), ...] + >>> app = Starlette(middleware=middleware) + """ + warnings.warn( + "The `middleware` decorator is deprecated, and will be removed in version 1.0.0. " + "Refer to https://www.starlette.io/middleware/#using-middleware for recommended approach.", + DeprecationWarning, + ) + assert middleware_type == "http", 'Currently only middleware("http") is supported.' + + def decorator(func: typing.Callable) -> typing.Callable: # type: ignore[type-arg] + self.add_middleware(BaseHTTPMiddleware, dispatch=func) + return func + + return decorator diff --git a/venv/Lib/site-packages/starlette/authentication.py b/venv/Lib/site-packages/starlette/authentication.py new file mode 100644 index 00000000..4fd86641 --- /dev/null +++ b/venv/Lib/site-packages/starlette/authentication.py @@ -0,0 +1,147 @@ +from __future__ import annotations + +import functools +import inspect +import sys +import typing +from urllib.parse import urlencode + +if sys.version_info >= (3, 10): # pragma: no cover + from typing import ParamSpec +else: # pragma: no cover + from typing_extensions import ParamSpec + +from starlette._utils import is_async_callable +from starlette.exceptions import HTTPException +from starlette.requests import HTTPConnection, Request +from starlette.responses import RedirectResponse +from starlette.websockets import WebSocket + +_P = ParamSpec("_P") + + +def has_required_scope(conn: HTTPConnection, scopes: typing.Sequence[str]) -> bool: + for scope in scopes: + if scope not in conn.auth.scopes: + return False + return True + + +def requires( + scopes: str | typing.Sequence[str], + status_code: int = 403, + redirect: str | None = None, +) -> typing.Callable[[typing.Callable[_P, typing.Any]], typing.Callable[_P, typing.Any]]: + scopes_list = [scopes] if isinstance(scopes, str) else list(scopes) + + def decorator( + func: typing.Callable[_P, typing.Any], + ) -> typing.Callable[_P, typing.Any]: + sig = inspect.signature(func) + for idx, parameter in enumerate(sig.parameters.values()): + if parameter.name == "request" or parameter.name == "websocket": + type_ = parameter.name + break + else: + raise Exception(f'No "request" or "websocket" argument on function "{func}"') + + if type_ == "websocket": + # Handle websocket functions. (Always async) + @functools.wraps(func) + async def websocket_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> None: + websocket = kwargs.get("websocket", args[idx] if idx < len(args) else None) + assert isinstance(websocket, WebSocket) + + if not has_required_scope(websocket, scopes_list): + await websocket.close() + else: + await func(*args, **kwargs) + + return websocket_wrapper + + elif is_async_callable(func): + # Handle async request/response functions. + @functools.wraps(func) + async def async_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> typing.Any: + request = kwargs.get("request", args[idx] if idx < len(args) else None) + assert isinstance(request, Request) + + if not has_required_scope(request, scopes_list): + if redirect is not None: + orig_request_qparam = urlencode({"next": str(request.url)}) + next_url = f"{request.url_for(redirect)}?{orig_request_qparam}" + return RedirectResponse(url=next_url, status_code=303) + raise HTTPException(status_code=status_code) + return await func(*args, **kwargs) + + return async_wrapper + + else: + # Handle sync request/response functions. + @functools.wraps(func) + def sync_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> typing.Any: + request = kwargs.get("request", args[idx] if idx < len(args) else None) + assert isinstance(request, Request) + + if not has_required_scope(request, scopes_list): + if redirect is not None: + orig_request_qparam = urlencode({"next": str(request.url)}) + next_url = f"{request.url_for(redirect)}?{orig_request_qparam}" + return RedirectResponse(url=next_url, status_code=303) + raise HTTPException(status_code=status_code) + return func(*args, **kwargs) + + return sync_wrapper + + return decorator + + +class AuthenticationError(Exception): + pass + + +class AuthenticationBackend: + async def authenticate(self, conn: HTTPConnection) -> tuple[AuthCredentials, BaseUser] | None: + raise NotImplementedError() # pragma: no cover + + +class AuthCredentials: + def __init__(self, scopes: typing.Sequence[str] | None = None): + self.scopes = [] if scopes is None else list(scopes) + + +class BaseUser: + @property + def is_authenticated(self) -> bool: + raise NotImplementedError() # pragma: no cover + + @property + def display_name(self) -> str: + raise NotImplementedError() # pragma: no cover + + @property + def identity(self) -> str: + raise NotImplementedError() # pragma: no cover + + +class SimpleUser(BaseUser): + def __init__(self, username: str) -> None: + self.username = username + + @property + def is_authenticated(self) -> bool: + return True + + @property + def display_name(self) -> str: + return self.username + + +class UnauthenticatedUser(BaseUser): + @property + def is_authenticated(self) -> bool: + return False + + @property + def display_name(self) -> str: + return "" diff --git a/venv/Lib/site-packages/starlette/background.py b/venv/Lib/site-packages/starlette/background.py new file mode 100644 index 00000000..0430fc08 --- /dev/null +++ b/venv/Lib/site-packages/starlette/background.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +import sys +import typing + +if sys.version_info >= (3, 10): # pragma: no cover + from typing import ParamSpec +else: # pragma: no cover + from typing_extensions import ParamSpec + +from starlette._utils import is_async_callable +from starlette.concurrency import run_in_threadpool + +P = ParamSpec("P") + + +class BackgroundTask: + def __init__(self, func: typing.Callable[P, typing.Any], *args: P.args, **kwargs: P.kwargs) -> None: + self.func = func + self.args = args + self.kwargs = kwargs + self.is_async = is_async_callable(func) + + async def __call__(self) -> None: + if self.is_async: + await self.func(*self.args, **self.kwargs) + else: + await run_in_threadpool(self.func, *self.args, **self.kwargs) + + +class BackgroundTasks(BackgroundTask): + def __init__(self, tasks: typing.Sequence[BackgroundTask] | None = None): + self.tasks = list(tasks) if tasks else [] + + def add_task(self, func: typing.Callable[P, typing.Any], *args: P.args, **kwargs: P.kwargs) -> None: + task = BackgroundTask(func, *args, **kwargs) + self.tasks.append(task) + + async def __call__(self) -> None: + for task in self.tasks: + await task() diff --git a/venv/Lib/site-packages/starlette/concurrency.py b/venv/Lib/site-packages/starlette/concurrency.py new file mode 100644 index 00000000..494f3420 --- /dev/null +++ b/venv/Lib/site-packages/starlette/concurrency.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +import functools +import sys +import typing +import warnings + +import anyio.to_thread + +if sys.version_info >= (3, 10): # pragma: no cover + from typing import ParamSpec +else: # pragma: no cover + from typing_extensions import ParamSpec + +P = ParamSpec("P") +T = typing.TypeVar("T") + + +async def run_until_first_complete(*args: tuple[typing.Callable, dict]) -> None: # type: ignore[type-arg] + warnings.warn( + "run_until_first_complete is deprecated and will be removed in a future version.", + DeprecationWarning, + ) + + async with anyio.create_task_group() as task_group: + + async def run(func: typing.Callable[[], typing.Coroutine]) -> None: # type: ignore[type-arg] + await func() + task_group.cancel_scope.cancel() + + for func, kwargs in args: + task_group.start_soon(run, functools.partial(func, **kwargs)) + + +async def run_in_threadpool(func: typing.Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T: + func = functools.partial(func, *args, **kwargs) + return await anyio.to_thread.run_sync(func) + + +class _StopIteration(Exception): + pass + + +def _next(iterator: typing.Iterator[T]) -> T: + # We can't raise `StopIteration` from within the threadpool iterator + # and catch it outside that context, so we coerce them into a different + # exception type. + try: + return next(iterator) + except StopIteration: + raise _StopIteration + + +async def iterate_in_threadpool( + iterator: typing.Iterable[T], +) -> typing.AsyncIterator[T]: + as_iterator = iter(iterator) + while True: + try: + yield await anyio.to_thread.run_sync(_next, as_iterator) + except _StopIteration: + break diff --git a/venv/Lib/site-packages/starlette/config.py b/venv/Lib/site-packages/starlette/config.py new file mode 100644 index 00000000..ca15c564 --- /dev/null +++ b/venv/Lib/site-packages/starlette/config.py @@ -0,0 +1,138 @@ +from __future__ import annotations + +import os +import typing +import warnings +from pathlib import Path + + +class undefined: + pass + + +class EnvironError(Exception): + pass + + +class Environ(typing.MutableMapping[str, str]): + def __init__(self, environ: typing.MutableMapping[str, str] = os.environ): + self._environ = environ + self._has_been_read: set[str] = set() + + def __getitem__(self, key: str) -> str: + self._has_been_read.add(key) + return self._environ.__getitem__(key) + + def __setitem__(self, key: str, value: str) -> None: + if key in self._has_been_read: + raise EnvironError(f"Attempting to set environ['{key}'], but the value has already been read.") + self._environ.__setitem__(key, value) + + def __delitem__(self, key: str) -> None: + if key in self._has_been_read: + raise EnvironError(f"Attempting to delete environ['{key}'], but the value has already been read.") + self._environ.__delitem__(key) + + def __iter__(self) -> typing.Iterator[str]: + return iter(self._environ) + + def __len__(self) -> int: + return len(self._environ) + + +environ = Environ() + +T = typing.TypeVar("T") + + +class Config: + def __init__( + self, + env_file: str | Path | None = None, + environ: typing.Mapping[str, str] = environ, + env_prefix: str = "", + ) -> None: + self.environ = environ + self.env_prefix = env_prefix + self.file_values: dict[str, str] = {} + if env_file is not None: + if not os.path.isfile(env_file): + warnings.warn(f"Config file '{env_file}' not found.") + else: + self.file_values = self._read_file(env_file) + + @typing.overload + def __call__(self, key: str, *, default: None) -> str | None: ... + + @typing.overload + def __call__(self, key: str, cast: type[T], default: T = ...) -> T: ... + + @typing.overload + def __call__(self, key: str, cast: type[str] = ..., default: str = ...) -> str: ... + + @typing.overload + def __call__( + self, + key: str, + cast: typing.Callable[[typing.Any], T] = ..., + default: typing.Any = ..., + ) -> T: ... + + @typing.overload + def __call__(self, key: str, cast: type[str] = ..., default: T = ...) -> T | str: ... + + def __call__( + self, + key: str, + cast: typing.Callable[[typing.Any], typing.Any] | None = None, + default: typing.Any = undefined, + ) -> typing.Any: + return self.get(key, cast, default) + + def get( + self, + key: str, + cast: typing.Callable[[typing.Any], typing.Any] | None = None, + default: typing.Any = undefined, + ) -> typing.Any: + key = self.env_prefix + key + if key in self.environ: + value = self.environ[key] + return self._perform_cast(key, value, cast) + if key in self.file_values: + value = self.file_values[key] + return self._perform_cast(key, value, cast) + if default is not undefined: + return self._perform_cast(key, default, cast) + raise KeyError(f"Config '{key}' is missing, and has no default.") + + def _read_file(self, file_name: str | Path) -> dict[str, str]: + file_values: dict[str, str] = {} + with open(file_name) as input_file: + for line in input_file.readlines(): + line = line.strip() + if "=" in line and not line.startswith("#"): + key, value = line.split("=", 1) + key = key.strip() + value = value.strip().strip("\"'") + file_values[key] = value + return file_values + + def _perform_cast( + self, + key: str, + value: typing.Any, + cast: typing.Callable[[typing.Any], typing.Any] | None = None, + ) -> typing.Any: + if cast is None or value is None: + return value + elif cast is bool and isinstance(value, str): + mapping = {"true": True, "1": True, "false": False, "0": False} + value = value.lower() + if value not in mapping: + raise ValueError(f"Config '{key}' has value '{value}'. Not a valid bool.") + return mapping[value] + try: + return cast(value) + except (TypeError, ValueError): + raise ValueError(f"Config '{key}' has value '{value}'. Not a valid {cast.__name__}.") diff --git a/venv/Lib/site-packages/starlette/convertors.py b/venv/Lib/site-packages/starlette/convertors.py new file mode 100644 index 00000000..84df87a5 --- /dev/null +++ b/venv/Lib/site-packages/starlette/convertors.py @@ -0,0 +1,89 @@ +from __future__ import annotations + +import math +import typing +import uuid + +T = typing.TypeVar("T") + + +class Convertor(typing.Generic[T]): + regex: typing.ClassVar[str] = "" + + def convert(self, value: str) -> T: + raise NotImplementedError() # pragma: no cover + + def to_string(self, value: T) -> str: + raise NotImplementedError() # pragma: no cover + + +class StringConvertor(Convertor[str]): + regex = "[^/]+" + + def convert(self, value: str) -> str: + return value + + def to_string(self, value: str) -> str: + value = str(value) + assert "/" not in value, "May not contain path separators" + assert value, "Must not be empty" + return value + + +class PathConvertor(Convertor[str]): + regex = ".*" + + def convert(self, value: str) -> str: + return str(value) + + def to_string(self, value: str) -> str: + return str(value) + + +class IntegerConvertor(Convertor[int]): + regex = "[0-9]+" + + def convert(self, value: str) -> int: + return int(value) + + def to_string(self, value: int) -> str: + value = int(value) + assert value >= 0, "Negative integers are not supported" + return str(value) + + +class FloatConvertor(Convertor[float]): + regex = r"[0-9]+(\.[0-9]+)?" + + def convert(self, value: str) -> float: + return float(value) + + def to_string(self, value: float) -> str: + value = float(value) + assert value >= 0.0, "Negative floats are not supported" + assert not math.isnan(value), "NaN values are not supported" + assert not math.isinf(value), "Infinite values are not supported" + return ("%0.20f" % value).rstrip("0").rstrip(".") + + +class UUIDConvertor(Convertor[uuid.UUID]): + regex = "[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12}" + + def convert(self, value: str) -> uuid.UUID: + return uuid.UUID(value) + + def to_string(self, value: uuid.UUID) -> str: + return str(value) + + +CONVERTOR_TYPES: dict[str, Convertor[typing.Any]] = { + "str": StringConvertor(), + "path": PathConvertor(), + "int": IntegerConvertor(), + "float": FloatConvertor(), + "uuid": UUIDConvertor(), +} + + +def register_url_convertor(key: str, convertor: Convertor[typing.Any]) -> None: + CONVERTOR_TYPES[key] = convertor diff --git a/venv/Lib/site-packages/starlette/datastructures.py b/venv/Lib/site-packages/starlette/datastructures.py new file mode 100644 index 00000000..f5d74d25 --- /dev/null +++ b/venv/Lib/site-packages/starlette/datastructures.py @@ -0,0 +1,674 @@ +from __future__ import annotations + +import typing +from shlex import shlex +from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit + +from starlette.concurrency import run_in_threadpool +from starlette.types import Scope + + +class Address(typing.NamedTuple): + host: str + port: int + + +_KeyType = typing.TypeVar("_KeyType") +# Mapping keys are invariant but their values are covariant since +# you can only read them +# that is, you can't do `Mapping[str, Animal]()["fido"] = Dog()` +_CovariantValueType = typing.TypeVar("_CovariantValueType", covariant=True) + + +class URL: + def __init__( + self, + url: str = "", + scope: Scope | None = None, + **components: typing.Any, + ) -> None: + if scope is not None: + assert not url, 'Cannot set both "url" and "scope".' + assert not components, 'Cannot set both "scope" and "**components".' + scheme = scope.get("scheme", "http") + server = scope.get("server", None) + path = scope["path"] + query_string = scope.get("query_string", b"") + + host_header = None + for key, value in scope["headers"]: + if key == b"host": + host_header = value.decode("latin-1") + break + + if host_header is not None: + url = f"{scheme}://{host_header}{path}" + elif server is None: + url = path + else: + host, port = server + default_port = {"http": 80, "https": 443, "ws": 80, "wss": 443}[scheme] + if port == default_port: + url = f"{scheme}://{host}{path}" + else: + url = f"{scheme}://{host}:{port}{path}" + + if query_string: + url += "?" + query_string.decode() + elif components: + assert not url, 'Cannot set both "url" and "**components".' + url = URL("").replace(**components).components.geturl() + + self._url = url + + @property + def components(self) -> SplitResult: + if not hasattr(self, "_components"): + self._components = urlsplit(self._url) + return self._components + + @property + def scheme(self) -> str: + return self.components.scheme + + @property + def netloc(self) -> str: + return self.components.netloc + + @property + def path(self) -> str: + return self.components.path + + @property + def query(self) -> str: + return self.components.query + + @property + def fragment(self) -> str: + return self.components.fragment + + @property + def username(self) -> None | str: + return self.components.username + + @property + def password(self) -> None | str: + return self.components.password + + @property + def hostname(self) -> None | str: + return self.components.hostname + + @property + def port(self) -> int | None: + return self.components.port + + @property + def is_secure(self) -> bool: + return self.scheme in ("https", "wss") + + def replace(self, **kwargs: typing.Any) -> URL: + if "username" in kwargs or "password" in kwargs or "hostname" in kwargs or "port" in kwargs: + hostname = kwargs.pop("hostname", None) + port = kwargs.pop("port", self.port) + username = kwargs.pop("username", self.username) + password = kwargs.pop("password", self.password) + + if hostname is None: + netloc = self.netloc + _, _, hostname = netloc.rpartition("@") + + if hostname[-1] != "]": + hostname = hostname.rsplit(":", 1)[0] + + netloc = hostname + if port is not None: + netloc += f":{port}" + if username is not None: + userpass = username + if password is not None: + userpass += f":{password}" + netloc = f"{userpass}@{netloc}" + + kwargs["netloc"] = netloc + + components = self.components._replace(**kwargs) + return self.__class__(components.geturl()) + + def include_query_params(self, **kwargs: typing.Any) -> URL: + params = MultiDict(parse_qsl(self.query, keep_blank_values=True)) + params.update({str(key): str(value) for key, value in kwargs.items()}) + query = urlencode(params.multi_items()) + return self.replace(query=query) + + def replace_query_params(self, **kwargs: typing.Any) -> URL: + query = urlencode([(str(key), str(value)) for key, value in kwargs.items()]) + return self.replace(query=query) + + def remove_query_params(self, keys: str | typing.Sequence[str]) -> URL: + if isinstance(keys, str): + keys = [keys] + params = MultiDict(parse_qsl(self.query, keep_blank_values=True)) + for key in keys: + params.pop(key, None) + query = urlencode(params.multi_items()) + return self.replace(query=query) + + def __eq__(self, other: typing.Any) -> bool: + return str(self) == str(other) + + def __str__(self) -> str: + return self._url + + def __repr__(self) -> str: + url = str(self) + if self.password: + url = str(self.replace(password="********")) + return f"{self.__class__.__name__}({repr(url)})" + + +class URLPath(str): + """ + A URL path string that may also hold an associated protocol and/or host. + Used by the routing to return `url_path_for` matches. + """ + + def __new__(cls, path: str, protocol: str = "", host: str = "") -> URLPath: + assert protocol in ("http", "websocket", "") + return str.__new__(cls, path) + + def __init__(self, path: str, protocol: str = "", host: str = "") -> None: + self.protocol = protocol + self.host = host + + def make_absolute_url(self, base_url: str | URL) -> URL: + if isinstance(base_url, str): + base_url = URL(base_url) + if self.protocol: + scheme = { + "http": {True: "https", False: "http"}, + "websocket": {True: "wss", False: "ws"}, + }[self.protocol][base_url.is_secure] + else: + scheme = base_url.scheme + + netloc = self.host or base_url.netloc + path = base_url.path.rstrip("/") + str(self) + return URL(scheme=scheme, netloc=netloc, path=path) + + +class Secret: + """ + Holds a string value that should not be revealed in tracebacks etc. + You should cast the value to `str` at the point it is required. + """ + + def __init__(self, value: str): + self._value = value + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + return f"{class_name}('**********')" + + def __str__(self) -> str: + return self._value + + def __bool__(self) -> bool: + return bool(self._value) + + +class CommaSeparatedStrings(typing.Sequence[str]): + def __init__(self, value: str | typing.Sequence[str]): + if isinstance(value, str): + splitter = shlex(value, posix=True) + splitter.whitespace = "," + splitter.whitespace_split = True + self._items = [item.strip() for item in splitter] + else: + self._items = list(value) + + def __len__(self) -> int: + return len(self._items) + + def __getitem__(self, index: int | slice) -> typing.Any: + return self._items[index] + + def __iter__(self) -> typing.Iterator[str]: + return iter(self._items) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + items = [item for item in self] + return f"{class_name}({items!r})" + + def __str__(self) -> str: + return ", ".join(repr(item) for item in self) + + +class ImmutableMultiDict(typing.Mapping[_KeyType, _CovariantValueType]): + _dict: dict[_KeyType, _CovariantValueType] + + def __init__( + self, + *args: ImmutableMultiDict[_KeyType, _CovariantValueType] + | typing.Mapping[_KeyType, _CovariantValueType] + | typing.Iterable[tuple[_KeyType, _CovariantValueType]], + **kwargs: typing.Any, + ) -> None: + assert len(args) < 2, "Too many arguments." + + value: typing.Any = args[0] if args else [] + if kwargs: + value = ImmutableMultiDict(value).multi_items() + ImmutableMultiDict(kwargs).multi_items() + + if not value: + _items: list[tuple[typing.Any, typing.Any]] = [] + elif hasattr(value, "multi_items"): + value = typing.cast(ImmutableMultiDict[_KeyType, _CovariantValueType], value) + _items = list(value.multi_items()) + elif hasattr(value, "items"): + value = typing.cast(typing.Mapping[_KeyType, _CovariantValueType], value) + _items = list(value.items()) + else: + value = typing.cast("list[tuple[typing.Any, typing.Any]]", value) + _items = list(value) + + self._dict = {k: v for k, v in _items} + self._list = _items + + def getlist(self, key: typing.Any) -> list[_CovariantValueType]: + return [item_value for item_key, item_value in self._list if item_key == key] + + def keys(self) -> typing.KeysView[_KeyType]: + return self._dict.keys() + + def values(self) -> typing.ValuesView[_CovariantValueType]: + return self._dict.values() + + def items(self) -> typing.ItemsView[_KeyType, _CovariantValueType]: + return self._dict.items() + + def multi_items(self) -> list[tuple[_KeyType, _CovariantValueType]]: + return list(self._list) + + def __getitem__(self, key: _KeyType) -> _CovariantValueType: + return self._dict[key] + + def __contains__(self, key: typing.Any) -> bool: + return key in self._dict + + def __iter__(self) -> typing.Iterator[_KeyType]: + return iter(self.keys()) + + def __len__(self) -> int: + return len(self._dict) + + def __eq__(self, other: typing.Any) -> bool: + if not isinstance(other, self.__class__): + return False + return sorted(self._list) == sorted(other._list) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + items = self.multi_items() + return f"{class_name}({items!r})" + + +class MultiDict(ImmutableMultiDict[typing.Any, typing.Any]): + def __setitem__(self, key: typing.Any, value: typing.Any) -> None: + self.setlist(key, [value]) + + def __delitem__(self, key: typing.Any) -> None: + self._list = [(k, v) for k, v in self._list if k != key] + del self._dict[key] + + def pop(self, key: typing.Any, default: typing.Any = None) -> typing.Any: + self._list = [(k, v) for k, v in self._list if k != key] + return self._dict.pop(key, default) + + def popitem(self) -> tuple[typing.Any, typing.Any]: + key, value = self._dict.popitem() + self._list = [(k, v) for k, v in self._list if k != key] + return key, value + + def poplist(self, key: typing.Any) -> list[typing.Any]: + values = [v for k, v in self._list if k == key] + self.pop(key) + return values + + def clear(self) -> None: + self._dict.clear() + self._list.clear() + + def setdefault(self, key: typing.Any, default: typing.Any = None) -> typing.Any: + if key not in self: + self._dict[key] = default + self._list.append((key, default)) + + return self[key] + + def setlist(self, key: typing.Any, values: list[typing.Any]) -> None: + if not values: + self.pop(key, None) + else: + existing_items = [(k, v) for (k, v) in self._list if k != key] + self._list = existing_items + [(key, value) for value in values] + self._dict[key] = values[-1] + + def append(self, key: typing.Any, value: typing.Any) -> None: + self._list.append((key, value)) + self._dict[key] = value + + def update( + self, + *args: MultiDict | typing.Mapping[typing.Any, typing.Any] | list[tuple[typing.Any, typing.Any]], + **kwargs: typing.Any, + ) -> None: + value = MultiDict(*args, **kwargs) + existing_items = [(k, v) for (k, v) in self._list if k not in value.keys()] + self._list = existing_items + value.multi_items() + self._dict.update(value) + + +class QueryParams(ImmutableMultiDict[str, str]): + """ + An immutable multidict. + """ + + def __init__( + self, + *args: ImmutableMultiDict[typing.Any, typing.Any] + | typing.Mapping[typing.Any, typing.Any] + | list[tuple[typing.Any, typing.Any]] + | str + | bytes, + **kwargs: typing.Any, + ) -> None: + assert len(args) < 2, "Too many arguments." + + value = args[0] if args else [] + + if isinstance(value, str): + super().__init__(parse_qsl(value, keep_blank_values=True), **kwargs) + elif isinstance(value, bytes): + super().__init__(parse_qsl(value.decode("latin-1"), keep_blank_values=True), **kwargs) + else: + super().__init__(*args, **kwargs) # type: ignore[arg-type] + self._list = [(str(k), str(v)) for k, v in self._list] + self._dict = {str(k): str(v) for k, v in self._dict.items()} + + def __str__(self) -> str: + return urlencode(self._list) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + query_string = str(self) + return f"{class_name}({query_string!r})" + + +class UploadFile: + """ + An uploaded file included as part of the request data. + """ + + def __init__( + self, + file: typing.BinaryIO, + *, + size: int | None = None, + filename: str | None = None, + headers: Headers | None = None, + ) -> None: + self.filename = filename + self.file = file + self.size = size + self.headers = headers or Headers() + + @property + def content_type(self) -> str | None: + return self.headers.get("content-type", None) + + @property + def _in_memory(self) -> bool: + # check for SpooledTemporaryFile._rolled + rolled_to_disk = getattr(self.file, "_rolled", True) + return not rolled_to_disk + + async def write(self, data: bytes) -> None: + if self.size is not None: + self.size += len(data) + + if self._in_memory: + self.file.write(data) + else: + await run_in_threadpool(self.file.write, data) + + async def read(self, size: int = -1) -> bytes: + if self._in_memory: + return self.file.read(size) + return await run_in_threadpool(self.file.read, size) + + async def seek(self, offset: int) -> None: + if self._in_memory: + self.file.seek(offset) + else: + await run_in_threadpool(self.file.seek, offset) + + async def close(self) -> None: + if self._in_memory: + self.file.close() + else: + await run_in_threadpool(self.file.close) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(filename={self.filename!r}, size={self.size!r}, headers={self.headers!r})" + + +class FormData(ImmutableMultiDict[str, typing.Union[UploadFile, str]]): + """ + An immutable multidict, containing both file uploads and text input. + """ + + def __init__( + self, + *args: FormData | typing.Mapping[str, str | UploadFile] | list[tuple[str, str | UploadFile]], + **kwargs: str | UploadFile, + ) -> None: + super().__init__(*args, **kwargs) + + async def close(self) -> None: + for key, value in self.multi_items(): + if isinstance(value, UploadFile): + await value.close() + + +class Headers(typing.Mapping[str, str]): + """ + An immutable, case-insensitive multidict. + """ + + def __init__( + self, + headers: typing.Mapping[str, str] | None = None, + raw: list[tuple[bytes, bytes]] | None = None, + scope: typing.MutableMapping[str, typing.Any] | None = None, + ) -> None: + self._list: list[tuple[bytes, bytes]] = [] + if headers is not None: + assert raw is None, 'Cannot set both "headers" and "raw".' + assert scope is None, 'Cannot set both "headers" and "scope".' + self._list = [(key.lower().encode("latin-1"), value.encode("latin-1")) for key, value in headers.items()] + elif raw is not None: + assert scope is None, 'Cannot set both "raw" and "scope".' + self._list = raw + elif scope is not None: + # scope["headers"] isn't necessarily a list + # it might be a tuple or other iterable + self._list = scope["headers"] = list(scope["headers"]) + + @property + def raw(self) -> list[tuple[bytes, bytes]]: + return list(self._list) + + def keys(self) -> list[str]: # type: ignore[override] + return [key.decode("latin-1") for key, value in self._list] + + def values(self) -> list[str]: # type: ignore[override] + return [value.decode("latin-1") for key, value in self._list] + + def items(self) -> list[tuple[str, str]]: # type: ignore[override] + return [(key.decode("latin-1"), value.decode("latin-1")) for key, value in self._list] + + def getlist(self, key: str) -> list[str]: + get_header_key = key.lower().encode("latin-1") + return [item_value.decode("latin-1") for item_key, item_value in self._list if item_key == get_header_key] + + def mutablecopy(self) -> MutableHeaders: + return MutableHeaders(raw=self._list[:]) + + def __getitem__(self, key: str) -> str: + get_header_key = key.lower().encode("latin-1") + for header_key, header_value in self._list: + if header_key == get_header_key: + return header_value.decode("latin-1") + raise KeyError(key) + + def __contains__(self, key: typing.Any) -> bool: + get_header_key = key.lower().encode("latin-1") + for header_key, header_value in self._list: + if header_key == get_header_key: + return True + return False + + def __iter__(self) -> typing.Iterator[typing.Any]: + return iter(self.keys()) + + def __len__(self) -> int: + return len(self._list) + + def __eq__(self, other: typing.Any) -> bool: + if not isinstance(other, Headers): + return False + return sorted(self._list) == sorted(other._list) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + as_dict = dict(self.items()) + if len(as_dict) == len(self): + return f"{class_name}({as_dict!r})" + return f"{class_name}(raw={self.raw!r})" + + +class MutableHeaders(Headers): + def __setitem__(self, key: str, value: str) -> None: + """ + Set the header `key` to `value`, removing any duplicate entries. + Retains insertion order. + """ + set_key = key.lower().encode("latin-1") + set_value = value.encode("latin-1") + + found_indexes: list[int] = [] + for idx, (item_key, item_value) in enumerate(self._list): + if item_key == set_key: + found_indexes.append(idx) + + for idx in reversed(found_indexes[1:]): + del self._list[idx] + + if found_indexes: + idx = found_indexes[0] + self._list[idx] = (set_key, set_value) + else: + self._list.append((set_key, set_value)) + + def __delitem__(self, key: str) -> None: + """ + Remove the header `key`. + """ + del_key = key.lower().encode("latin-1") + + pop_indexes: list[int] = [] + for idx, (item_key, item_value) in enumerate(self._list): + if item_key == del_key: + pop_indexes.append(idx) + + for idx in reversed(pop_indexes): + del self._list[idx] + + def __ior__(self, other: typing.Mapping[str, str]) -> MutableHeaders: + if not isinstance(other, typing.Mapping): + raise TypeError(f"Expected a mapping but got {other.__class__.__name__}") + self.update(other) + return self + + def __or__(self, other: typing.Mapping[str, str]) -> MutableHeaders: + if not isinstance(other, typing.Mapping): + raise TypeError(f"Expected a mapping but got {other.__class__.__name__}") + new = self.mutablecopy() + new.update(other) + return new + + @property + def raw(self) -> list[tuple[bytes, bytes]]: + return self._list + + def setdefault(self, key: str, value: str) -> str: + """ + If the header `key` does not exist, then set it to `value`. + Returns the header value. + """ + set_key = key.lower().encode("latin-1") + set_value = value.encode("latin-1") + + for idx, (item_key, item_value) in enumerate(self._list): + if item_key == set_key: + return item_value.decode("latin-1") + self._list.append((set_key, set_value)) + return value + + def update(self, other: typing.Mapping[str, str]) -> None: + for key, val in other.items(): + self[key] = val + + def append(self, key: str, value: str) -> None: + """ + Append a header, preserving any duplicate entries. + """ + append_key = key.lower().encode("latin-1") + append_value = value.encode("latin-1") + self._list.append((append_key, append_value)) + + def add_vary_header(self, vary: str) -> None: + existing = self.get("vary") + if existing is not None: + vary = ", ".join([existing, vary]) + self["vary"] = vary + + +class State: + """ + An object that can be used to store arbitrary state. + + Used for `request.state` and `app.state`. + """ + + _state: dict[str, typing.Any] + + def __init__(self, state: dict[str, typing.Any] | None = None): + if state is None: + state = {} + super().__setattr__("_state", state) + + def __setattr__(self, key: typing.Any, value: typing.Any) -> None: + self._state[key] = value + + def __getattr__(self, key: typing.Any) -> typing.Any: + try: + return self._state[key] + except KeyError: + message = "'{}' object has no attribute '{}'" + raise AttributeError(message.format(self.__class__.__name__, key)) + + def __delattr__(self, key: typing.Any) -> None: + del self._state[key] diff --git a/venv/Lib/site-packages/starlette/endpoints.py b/venv/Lib/site-packages/starlette/endpoints.py new file mode 100644 index 00000000..10769026 --- /dev/null +++ b/venv/Lib/site-packages/starlette/endpoints.py @@ -0,0 +1,122 @@ +from __future__ import annotations + +import json +import typing + +from starlette import status +from starlette._utils import is_async_callable +from starlette.concurrency import run_in_threadpool +from starlette.exceptions import HTTPException +from starlette.requests import Request +from starlette.responses import PlainTextResponse, Response +from starlette.types import Message, Receive, Scope, Send +from starlette.websockets import WebSocket + + +class HTTPEndpoint: + def __init__(self, scope: Scope, receive: Receive, send: Send) -> None: + assert scope["type"] == "http" + self.scope = scope + self.receive = receive + self.send = send + self._allowed_methods = [ + method + for method in ("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS") + if getattr(self, method.lower(), None) is not None + ] + + def __await__(self) -> typing.Generator[typing.Any, None, None]: + return self.dispatch().__await__() + + async def dispatch(self) -> None: + request = Request(self.scope, receive=self.receive) + handler_name = "get" if request.method == "HEAD" and not hasattr(self, "head") else request.method.lower() + + handler: typing.Callable[[Request], typing.Any] = getattr(self, handler_name, self.method_not_allowed) + is_async = is_async_callable(handler) + if is_async: + response = await handler(request) + else: + response = await run_in_threadpool(handler, request) + await response(self.scope, self.receive, self.send) + + async def method_not_allowed(self, request: Request) -> Response: + # If we're running inside a starlette application then raise an + # exception, so that the configurable exception handler can deal with + # returning the response. For plain ASGI apps, just return the response. + headers = {"Allow": ", ".join(self._allowed_methods)} + if "app" in self.scope: + raise HTTPException(status_code=405, headers=headers) + return PlainTextResponse("Method Not Allowed", status_code=405, headers=headers) + + +class WebSocketEndpoint: + encoding: str | None = None # May be "text", "bytes", or "json". + + def __init__(self, scope: Scope, receive: Receive, send: Send) -> None: + assert scope["type"] == "websocket" + self.scope = scope + self.receive = receive + self.send = send + + def __await__(self) -> typing.Generator[typing.Any, None, None]: + return self.dispatch().__await__() + + async def dispatch(self) -> None: + websocket = WebSocket(self.scope, receive=self.receive, send=self.send) + await self.on_connect(websocket) + + close_code = status.WS_1000_NORMAL_CLOSURE + + try: + while True: + message = await websocket.receive() + if message["type"] == "websocket.receive": + data = await self.decode(websocket, message) + await self.on_receive(websocket, data) + elif message["type"] == "websocket.disconnect": # pragma: no branch + close_code = int(message.get("code") or status.WS_1000_NORMAL_CLOSURE) + break + except Exception as exc: + close_code = status.WS_1011_INTERNAL_ERROR + raise exc + finally: + await self.on_disconnect(websocket, close_code) + + async def decode(self, websocket: WebSocket, message: Message) -> typing.Any: + if self.encoding == "text": + if "text" not in message: + await websocket.close(code=status.WS_1003_UNSUPPORTED_DATA) + raise RuntimeError("Expected text websocket messages, but got bytes") + return message["text"] + + elif self.encoding == "bytes": + if "bytes" not in message: + await websocket.close(code=status.WS_1003_UNSUPPORTED_DATA) + raise RuntimeError("Expected bytes websocket messages, but got text") + return message["bytes"] + + elif self.encoding == "json": + if message.get("text") is not None: + text = message["text"] + else: + text = message["bytes"].decode("utf-8") + + try: + return json.loads(text) + except json.decoder.JSONDecodeError: + await websocket.close(code=status.WS_1003_UNSUPPORTED_DATA) + raise RuntimeError("Malformed JSON data received.") + + assert self.encoding is None, f"Unsupported 'encoding' attribute {self.encoding}" + return message["text"] if message.get("text") else message["bytes"] + + async def on_connect(self, websocket: WebSocket) -> None: + """Override to handle an incoming websocket connection""" + await websocket.accept() + + async def on_receive(self, websocket: WebSocket, data: typing.Any) -> None: + """Override to handle an incoming websocket message""" + + async def on_disconnect(self, websocket: WebSocket, close_code: int) -> None: + """Override to handle a disconnecting websocket""" diff --git a/venv/Lib/site-packages/starlette/exceptions.py b/venv/Lib/site-packages/starlette/exceptions.py new file mode 100644 index 00000000..9ad3527b --- /dev/null +++ b/venv/Lib/site-packages/starlette/exceptions.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +import http +from collections.abc import Mapping + + +class HTTPException(Exception): + def __init__(self, status_code: int, detail: str | None = None, headers: Mapping[str, str] | None = None) -> None: + if detail is None: + detail = http.HTTPStatus(status_code).phrase + self.status_code = status_code + self.detail = detail + self.headers = headers + + def __str__(self) -> str: + return f"{self.status_code}: {self.detail}" + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + return f"{class_name}(status_code={self.status_code!r}, detail={self.detail!r})" + + +class WebSocketException(Exception): + def __init__(self, code: int, reason: str | None = None) -> None: + self.code = code + self.reason = reason or "" + + def __str__(self) -> str: + return f"{self.code}: {self.reason}" + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + return f"{class_name}(code={self.code!r}, reason={self.reason!r})" diff --git a/venv/Lib/site-packages/starlette/formparsers.py b/venv/Lib/site-packages/starlette/formparsers.py new file mode 100644 index 00000000..4551d688 --- /dev/null +++ b/venv/Lib/site-packages/starlette/formparsers.py @@ -0,0 +1,275 @@ +from __future__ import annotations + +import typing +from dataclasses import dataclass, field +from enum import Enum +from tempfile import SpooledTemporaryFile +from urllib.parse import unquote_plus + +from starlette.datastructures import FormData, Headers, UploadFile + +if typing.TYPE_CHECKING: + import python_multipart as multipart + from python_multipart.multipart import MultipartCallbacks, QuerystringCallbacks, parse_options_header +else: + try: + try: + import python_multipart as multipart + from python_multipart.multipart import parse_options_header + except ModuleNotFoundError: # pragma: no cover + import multipart + from multipart.multipart import parse_options_header + except ModuleNotFoundError: # pragma: no cover + multipart = None + parse_options_header = None + + +class FormMessage(Enum): + FIELD_START = 1 + FIELD_NAME = 2 + FIELD_DATA = 3 + FIELD_END = 4 + END = 5 + + +@dataclass +class MultipartPart: + content_disposition: bytes | None = None + field_name: str = "" + data: bytearray = field(default_factory=bytearray) + file: UploadFile | None = None + item_headers: list[tuple[bytes, bytes]] = field(default_factory=list) + + +def _user_safe_decode(src: bytes | bytearray, codec: str) -> str: + try: + return src.decode(codec) + except (UnicodeDecodeError, LookupError): + return src.decode("latin-1") + + +class MultiPartException(Exception): + def __init__(self, message: str) -> None: + self.message = message + + +class FormParser: + def __init__(self, headers: Headers, stream: typing.AsyncGenerator[bytes, None]) -> None: + assert multipart is not None, "The `python-multipart` library must be installed to use form parsing." + self.headers = headers + self.stream = stream + self.messages: list[tuple[FormMessage, bytes]] = [] + + def on_field_start(self) -> None: + message = (FormMessage.FIELD_START, b"") + self.messages.append(message) + + def on_field_name(self, data: bytes, start: int, end: int) -> None: + message = (FormMessage.FIELD_NAME, data[start:end]) + self.messages.append(message) + + def on_field_data(self, data: bytes, start: int, end: int) -> None: + message = (FormMessage.FIELD_DATA, data[start:end]) + self.messages.append(message) + + def on_field_end(self) -> None: + message = (FormMessage.FIELD_END, b"") + self.messages.append(message) + + def on_end(self) -> None: + message = (FormMessage.END, b"") + self.messages.append(message) + + async def parse(self) -> FormData: + # Callbacks dictionary. + callbacks: QuerystringCallbacks = { + "on_field_start": self.on_field_start, + "on_field_name": self.on_field_name, + "on_field_data": self.on_field_data, + "on_field_end": self.on_field_end, + "on_end": self.on_end, + } + + # Create the parser. + parser = multipart.QuerystringParser(callbacks) + field_name = b"" + field_value = b"" + + items: list[tuple[str, str | UploadFile]] = [] + + # Feed the parser with data from the request. + async for chunk in self.stream: + if chunk: + parser.write(chunk) + else: + parser.finalize() + messages = list(self.messages) + self.messages.clear() + for message_type, message_bytes in messages: + if message_type == FormMessage.FIELD_START: + field_name = b"" + field_value = b"" + elif message_type == FormMessage.FIELD_NAME: + field_name += message_bytes + elif message_type == FormMessage.FIELD_DATA: + field_value += message_bytes + elif message_type == FormMessage.FIELD_END: + name = unquote_plus(field_name.decode("latin-1")) + value = unquote_plus(field_value.decode("latin-1")) + items.append((name, value)) + + return FormData(items) + + +class MultiPartParser: + spool_max_size = 1024 * 1024 # 1MB + """The maximum size of the spooled temporary file used to store file data.""" + max_part_size = 1024 * 1024 # 1MB + """The maximum size of a part in the multipart request.""" + + def __init__( + self, + headers: Headers, + stream: typing.AsyncGenerator[bytes, None], + *, + max_files: int | float = 1000, + max_fields: int | float = 1000, + max_part_size: int = 1024 * 1024, # 1MB + ) -> None: + assert multipart is not None, "The `python-multipart` library must be installed to use form parsing." + self.headers = headers + self.stream = stream + self.max_files = max_files + self.max_fields = max_fields + self.items: list[tuple[str, str | UploadFile]] = [] + self._current_files = 0 + self._current_fields = 0 + self._current_partial_header_name: bytes = b"" + self._current_partial_header_value: bytes = b"" + self._current_part = MultipartPart() + self._charset = "" + self._file_parts_to_write: list[tuple[MultipartPart, bytes]] = [] + self._file_parts_to_finish: list[MultipartPart] = [] + self._files_to_close_on_error: list[SpooledTemporaryFile[bytes]] = [] + self.max_part_size = max_part_size + + def on_part_begin(self) -> None: + self._current_part = MultipartPart() + + def on_part_data(self, data: bytes, start: int, end: int) -> None: + message_bytes = data[start:end] + if self._current_part.file is None: + if len(self._current_part.data) + len(message_bytes) > self.max_part_size: + raise MultiPartException(f"Part exceeded maximum size of {int(self.max_part_size / 1024)}KB.") + self._current_part.data.extend(message_bytes) + else: + self._file_parts_to_write.append((self._current_part, message_bytes)) + + def on_part_end(self) -> None: + if self._current_part.file is None: + self.items.append( + ( + self._current_part.field_name, + _user_safe_decode(self._current_part.data, self._charset), + ) + ) + else: + self._file_parts_to_finish.append(self._current_part) + # The file can be added to the items right now even though it's not + # finished yet, because it will be finished in the `parse()` method, before + # self.items is used in the return value. + self.items.append((self._current_part.field_name, self._current_part.file)) + + def on_header_field(self, data: bytes, start: int, end: int) -> None: + self._current_partial_header_name += data[start:end] + + def on_header_value(self, data: bytes, start: int, end: int) -> None: + self._current_partial_header_value += data[start:end] + + def on_header_end(self) -> None: + field = self._current_partial_header_name.lower() + if field == b"content-disposition": + self._current_part.content_disposition = self._current_partial_header_value + self._current_part.item_headers.append((field, self._current_partial_header_value)) + self._current_partial_header_name = b"" + self._current_partial_header_value = b"" + + def on_headers_finished(self) -> None: + disposition, options = parse_options_header(self._current_part.content_disposition) + try: + self._current_part.field_name = _user_safe_decode(options[b"name"], self._charset) + except KeyError: + raise MultiPartException('The Content-Disposition header field "name" must be provided.') + if b"filename" in options: + self._current_files += 1 + if self._current_files > self.max_files: + raise MultiPartException(f"Too many files. Maximum number of files is {self.max_files}.") + filename = _user_safe_decode(options[b"filename"], self._charset) + tempfile = SpooledTemporaryFile(max_size=self.spool_max_size) + self._files_to_close_on_error.append(tempfile) + self._current_part.file = UploadFile( + file=tempfile, # type: ignore[arg-type] + size=0, + filename=filename, + headers=Headers(raw=self._current_part.item_headers), + ) + else: + self._current_fields += 1 + if self._current_fields > self.max_fields: + raise MultiPartException(f"Too many fields. Maximum number of fields is {self.max_fields}.") + self._current_part.file = None + + def on_end(self) -> None: + pass + + async def parse(self) -> FormData: + # Parse the Content-Type header to get the multipart boundary. + _, params = parse_options_header(self.headers["Content-Type"]) + charset = params.get(b"charset", "utf-8") + if isinstance(charset, bytes): + charset = charset.decode("latin-1") + self._charset = charset + try: + boundary = params[b"boundary"] + except KeyError: + raise MultiPartException("Missing boundary in multipart.") + + # Callbacks dictionary. + callbacks: MultipartCallbacks = { + "on_part_begin": self.on_part_begin, + "on_part_data": self.on_part_data, + "on_part_end": self.on_part_end, + "on_header_field": self.on_header_field, + "on_header_value": self.on_header_value, + "on_header_end": self.on_header_end, + "on_headers_finished": self.on_headers_finished, + "on_end": self.on_end, + } + + # Create the parser. + parser = multipart.MultipartParser(boundary, callbacks) + try: + # Feed the parser with data from the request. + async for chunk in self.stream: + parser.write(chunk) + # Write file data, it needs to use await with the UploadFile methods + # that call the corresponding file methods *in a threadpool*, + # otherwise, if they were called directly in the callback methods above + # (regular, non-async functions), that would block the event loop in + # the main thread. + for part, data in self._file_parts_to_write: + assert part.file # for type checkers + await part.file.write(data) + for part in self._file_parts_to_finish: + assert part.file # for type checkers + await part.file.seek(0) + self._file_parts_to_write.clear() + self._file_parts_to_finish.clear() + except MultiPartException as exc: + # Close all the files if there was an error. + for file in self._files_to_close_on_error: + file.close() + raise exc + + parser.finalize() + return FormData(self.items) diff --git a/venv/Lib/site-packages/starlette/middleware/__init__.py b/venv/Lib/site-packages/starlette/middleware/__init__.py new file mode 100644 index 00000000..b99538a2 --- /dev/null +++ b/venv/Lib/site-packages/starlette/middleware/__init__.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +import sys +from collections.abc import Iterator +from typing import Any, Protocol + +if sys.version_info >= (3, 10): # pragma: no cover + from typing import ParamSpec +else: # pragma: no cover + from typing_extensions import ParamSpec + +from starlette.types import ASGIApp + +P = ParamSpec("P") + + +class _MiddlewareFactory(Protocol[P]): + def __call__(self, app: ASGIApp, /, *args: P.args, **kwargs: P.kwargs) -> ASGIApp: ... # pragma: no cover + + +class Middleware: + def __init__( + self, + cls: _MiddlewareFactory[P], + *args: P.args, + **kwargs: P.kwargs, + ) -> None: + self.cls = cls + self.args = args + self.kwargs = kwargs + + def __iter__(self) -> Iterator[Any]: + as_tuple = (self.cls, self.args, self.kwargs) + return iter(as_tuple) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + args_strings = [f"{value!r}" for value in self.args] + option_strings = [f"{key}={value!r}" for key, value in self.kwargs.items()] + name = getattr(self.cls, "__name__", "") + args_repr = ", ".join([name] + args_strings + option_strings) + return f"{class_name}({args_repr})" diff --git a/venv/Lib/site-packages/starlette/middleware/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/starlette/middleware/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..cac1348b Binary files /dev/null and b/venv/Lib/site-packages/starlette/middleware/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/middleware/__pycache__/authentication.cpython-312.pyc b/venv/Lib/site-packages/starlette/middleware/__pycache__/authentication.cpython-312.pyc new file mode 100644 index 00000000..e4a82221 Binary files /dev/null and b/venv/Lib/site-packages/starlette/middleware/__pycache__/authentication.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/middleware/__pycache__/base.cpython-312.pyc b/venv/Lib/site-packages/starlette/middleware/__pycache__/base.cpython-312.pyc new file mode 100644 index 00000000..c13f12d2 Binary files /dev/null and b/venv/Lib/site-packages/starlette/middleware/__pycache__/base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/middleware/__pycache__/cors.cpython-312.pyc b/venv/Lib/site-packages/starlette/middleware/__pycache__/cors.cpython-312.pyc new file mode 100644 index 00000000..f89f3933 Binary files /dev/null and b/venv/Lib/site-packages/starlette/middleware/__pycache__/cors.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/middleware/__pycache__/errors.cpython-312.pyc b/venv/Lib/site-packages/starlette/middleware/__pycache__/errors.cpython-312.pyc new file mode 100644 index 00000000..a9a10bc4 Binary files /dev/null and b/venv/Lib/site-packages/starlette/middleware/__pycache__/errors.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/middleware/__pycache__/exceptions.cpython-312.pyc b/venv/Lib/site-packages/starlette/middleware/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 00000000..67c154b7 Binary files /dev/null and b/venv/Lib/site-packages/starlette/middleware/__pycache__/exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/middleware/__pycache__/gzip.cpython-312.pyc b/venv/Lib/site-packages/starlette/middleware/__pycache__/gzip.cpython-312.pyc new file mode 100644 index 00000000..ec594bf6 Binary files /dev/null and b/venv/Lib/site-packages/starlette/middleware/__pycache__/gzip.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/middleware/__pycache__/httpsredirect.cpython-312.pyc b/venv/Lib/site-packages/starlette/middleware/__pycache__/httpsredirect.cpython-312.pyc new file mode 100644 index 00000000..79031b0f Binary files /dev/null and b/venv/Lib/site-packages/starlette/middleware/__pycache__/httpsredirect.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/middleware/__pycache__/sessions.cpython-312.pyc b/venv/Lib/site-packages/starlette/middleware/__pycache__/sessions.cpython-312.pyc new file mode 100644 index 00000000..47f34a15 Binary files /dev/null and b/venv/Lib/site-packages/starlette/middleware/__pycache__/sessions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/middleware/__pycache__/trustedhost.cpython-312.pyc b/venv/Lib/site-packages/starlette/middleware/__pycache__/trustedhost.cpython-312.pyc new file mode 100644 index 00000000..9addc6be Binary files /dev/null and b/venv/Lib/site-packages/starlette/middleware/__pycache__/trustedhost.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/middleware/__pycache__/wsgi.cpython-312.pyc b/venv/Lib/site-packages/starlette/middleware/__pycache__/wsgi.cpython-312.pyc new file mode 100644 index 00000000..fc01280d Binary files /dev/null and b/venv/Lib/site-packages/starlette/middleware/__pycache__/wsgi.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/starlette/middleware/authentication.py b/venv/Lib/site-packages/starlette/middleware/authentication.py new file mode 100644 index 00000000..8555ee07 --- /dev/null +++ b/venv/Lib/site-packages/starlette/middleware/authentication.py @@ -0,0 +1,52 @@ +from __future__ import annotations + +import typing + +from starlette.authentication import ( + AuthCredentials, + AuthenticationBackend, + AuthenticationError, + UnauthenticatedUser, +) +from starlette.requests import HTTPConnection +from starlette.responses import PlainTextResponse, Response +from starlette.types import ASGIApp, Receive, Scope, Send + + +class AuthenticationMiddleware: + def __init__( + self, + app: ASGIApp, + backend: AuthenticationBackend, + on_error: typing.Callable[[HTTPConnection, AuthenticationError], Response] | None = None, + ) -> None: + self.app = app + self.backend = backend + self.on_error: typing.Callable[[HTTPConnection, AuthenticationError], Response] = ( + on_error if on_error is not None else self.default_on_error + ) + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] not in ["http", "websocket"]: + await self.app(scope, receive, send) + return + + conn = HTTPConnection(scope) + try: + auth_result = await self.backend.authenticate(conn) + except AuthenticationError as exc: + response = self.on_error(conn, exc) + if scope["type"] == "websocket": + await send({"type": "websocket.close", "code": 1000}) + else: + await response(scope, receive, send) + return + + if auth_result is None: + auth_result = AuthCredentials(), UnauthenticatedUser() + scope["auth"], scope["user"] = auth_result + await self.app(scope, receive, send) + + @staticmethod + def default_on_error(conn: HTTPConnection, exc: Exception) -> Response: + return PlainTextResponse(str(exc), status_code=400) diff --git a/venv/Lib/site-packages/starlette/middleware/base.py b/venv/Lib/site-packages/starlette/middleware/base.py new file mode 100644 index 00000000..b49ab611 --- /dev/null +++ b/venv/Lib/site-packages/starlette/middleware/base.py @@ -0,0 +1,222 @@ +from __future__ import annotations + +import typing + +import anyio + +from starlette._utils import collapse_excgroups +from starlette.requests import ClientDisconnect, Request +from starlette.responses import AsyncContentStream, Response +from starlette.types import ASGIApp, Message, Receive, Scope, Send + +RequestResponseEndpoint = typing.Callable[[Request], typing.Awaitable[Response]] +DispatchFunction = typing.Callable[[Request, RequestResponseEndpoint], typing.Awaitable[Response]] +T = typing.TypeVar("T") + + +class _CachedRequest(Request): + """ + If the user calls Request.body() from their dispatch function + we cache the entire request body in memory and pass that to downstream middlewares, + but if they call Request.stream() then all we do is send an + empty body so that downstream things don't hang forever. + """ + + def __init__(self, scope: Scope, receive: Receive): + super().__init__(scope, receive) + self._wrapped_rcv_disconnected = False + self._wrapped_rcv_consumed = False + self._wrapped_rc_stream = self.stream() + + async def wrapped_receive(self) -> Message: + # wrapped_rcv state 1: disconnected + if self._wrapped_rcv_disconnected: + # we've already sent a disconnect to the downstream app + # we don't need to wait to get another one + # (although most ASGI servers will just keep sending it) + return {"type": "http.disconnect"} + # wrapped_rcv state 1: consumed but not yet disconnected + if self._wrapped_rcv_consumed: + # since the downstream app has consumed us all that is left + # is to send it a disconnect + if self._is_disconnected: + # the middleware has already seen the disconnect + # since we know the client is disconnected no need to wait + # for the message + self._wrapped_rcv_disconnected = True + return {"type": "http.disconnect"} + # we don't know yet if the client is disconnected or not + # so we'll wait until we get that message + msg = await self.receive() + if msg["type"] != "http.disconnect": # pragma: no cover + # at this point a disconnect is all that we should be receiving + # if we get something else, things went wrong somewhere + raise RuntimeError(f"Unexpected message received: {msg['type']}") + self._wrapped_rcv_disconnected = True + return msg + + # wrapped_rcv state 3: not yet consumed + if getattr(self, "_body", None) is not None: + # body() was called, we return it even if the client disconnected + self._wrapped_rcv_consumed = True + return { + "type": "http.request", + "body": self._body, + "more_body": False, + } + elif self._stream_consumed: + # stream() was called to completion + # return an empty body so that downstream apps don't hang + # waiting for a disconnect + self._wrapped_rcv_consumed = True + return { + "type": "http.request", + "body": b"", + "more_body": False, + } + else: + # body() was never called and stream() wasn't consumed + try: + stream = self.stream() + chunk = await stream.__anext__() + self._wrapped_rcv_consumed = self._stream_consumed + return { + "type": "http.request", + "body": chunk, + "more_body": not self._stream_consumed, + } + except ClientDisconnect: + self._wrapped_rcv_disconnected = True + return {"type": "http.disconnect"} + + +class BaseHTTPMiddleware: + def __init__(self, app: ASGIApp, dispatch: DispatchFunction | None = None) -> None: + self.app = app + self.dispatch_func = self.dispatch if dispatch is None else dispatch + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http": + await self.app(scope, receive, send) + return + + request = _CachedRequest(scope, receive) + wrapped_receive = request.wrapped_receive + response_sent = anyio.Event() + app_exc: Exception | None = None + exception_already_raised = False + + async def call_next(request: Request) -> Response: + async def receive_or_disconnect() -> Message: + if response_sent.is_set(): + return {"type": "http.disconnect"} + + async with anyio.create_task_group() as task_group: + + async def wrap(func: typing.Callable[[], typing.Awaitable[T]]) -> T: + result = await func() + task_group.cancel_scope.cancel() + return result + + task_group.start_soon(wrap, response_sent.wait) + message = await wrap(wrapped_receive) + + if response_sent.is_set(): + return {"type": "http.disconnect"} + + return message + + async def send_no_error(message: Message) -> None: + try: + await send_stream.send(message) + except anyio.BrokenResourceError: + # recv_stream has been closed, i.e. response_sent has been set. + return + + async def coro() -> None: + nonlocal app_exc + + with send_stream: + try: + await self.app(scope, receive_or_disconnect, send_no_error) + except Exception as exc: + app_exc = exc + + task_group.start_soon(coro) + + try: + message = await recv_stream.receive() + info = message.get("info", None) + if message["type"] == "http.response.debug" and info is not None: + message = await recv_stream.receive() + except anyio.EndOfStream: + if app_exc is not None: + nonlocal exception_already_raised + exception_already_raised = True + raise app_exc + raise RuntimeError("No response returned.") + + assert message["type"] == "http.response.start" + + async def body_stream() -> typing.AsyncGenerator[bytes, None]: + async for message in recv_stream: + assert message["type"] == "http.response.body" + body = message.get("body", b"") + if body: + yield body + if not message.get("more_body", False): + break + + response = _StreamingResponse(status_code=message["status"], content=body_stream(), info=info) + response.raw_headers = message["headers"] + return response + + streams: anyio.create_memory_object_stream[Message] = anyio.create_memory_object_stream() + send_stream, recv_stream = streams + with recv_stream, send_stream, collapse_excgroups(): + async with anyio.create_task_group() as task_group: + response = await self.dispatch_func(request, call_next) + await response(scope, wrapped_receive, send) + response_sent.set() + recv_stream.close() + if app_exc is not None and not exception_already_raised: + raise app_exc + + async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response: + raise NotImplementedError() # pragma: no cover + + +class _StreamingResponse(Response): + def __init__( + self, + content: AsyncContentStream, + status_code: int = 200, + headers: typing.Mapping[str, str] | None = None, + media_type: str | None = None, + info: typing.Mapping[str, typing.Any] | None = None, + ) -> None: + self.info = info + self.body_iterator = content + self.status_code = status_code + self.media_type = media_type + self.init_headers(headers) + self.background = None + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if self.info is not None: + await send({"type": "http.response.debug", "info": self.info}) + await send( + { + "type": "http.response.start", + "status": self.status_code, + "headers": self.raw_headers, + } + ) + + async for chunk in self.body_iterator: + await send({"type": "http.response.body", "body": chunk, "more_body": True}) + + await send({"type": "http.response.body", "body": b"", "more_body": False}) + + if self.background: + await self.background() diff --git a/venv/Lib/site-packages/starlette/middleware/cors.py b/venv/Lib/site-packages/starlette/middleware/cors.py new file mode 100644 index 00000000..61502691 --- /dev/null +++ b/venv/Lib/site-packages/starlette/middleware/cors.py @@ -0,0 +1,172 @@ +from __future__ import annotations + +import functools +import re +import typing + +from starlette.datastructures import Headers, MutableHeaders +from starlette.responses import PlainTextResponse, Response +from starlette.types import ASGIApp, Message, Receive, Scope, Send + +ALL_METHODS = ("DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT") +SAFELISTED_HEADERS = {"Accept", "Accept-Language", "Content-Language", "Content-Type"} + + +class CORSMiddleware: + def __init__( + self, + app: ASGIApp, + allow_origins: typing.Sequence[str] = (), + allow_methods: typing.Sequence[str] = ("GET",), + allow_headers: typing.Sequence[str] = (), + allow_credentials: bool = False, + allow_origin_regex: str | None = None, + expose_headers: typing.Sequence[str] = (), + max_age: int = 600, + ) -> None: + if "*" in allow_methods: + allow_methods = ALL_METHODS + + compiled_allow_origin_regex = None + if allow_origin_regex is not None: + compiled_allow_origin_regex = re.compile(allow_origin_regex) + + allow_all_origins = "*" in allow_origins + allow_all_headers = "*" in allow_headers + preflight_explicit_allow_origin = not allow_all_origins or allow_credentials + + simple_headers = {} + if allow_all_origins: + simple_headers["Access-Control-Allow-Origin"] = "*" + if allow_credentials: + simple_headers["Access-Control-Allow-Credentials"] = "true" + if expose_headers: + simple_headers["Access-Control-Expose-Headers"] = ", ".join(expose_headers) + + preflight_headers = {} + if preflight_explicit_allow_origin: + # The origin value will be set in preflight_response() if it is allowed. + preflight_headers["Vary"] = "Origin" + else: + preflight_headers["Access-Control-Allow-Origin"] = "*" + preflight_headers.update( + { + "Access-Control-Allow-Methods": ", ".join(allow_methods), + "Access-Control-Max-Age": str(max_age), + } + ) + allow_headers = sorted(SAFELISTED_HEADERS | set(allow_headers)) + if allow_headers and not allow_all_headers: + preflight_headers["Access-Control-Allow-Headers"] = ", ".join(allow_headers) + if allow_credentials: + preflight_headers["Access-Control-Allow-Credentials"] = "true" + + self.app = app + self.allow_origins = allow_origins + self.allow_methods = allow_methods + self.allow_headers = [h.lower() for h in allow_headers] + self.allow_all_origins = allow_all_origins + self.allow_all_headers = allow_all_headers + self.preflight_explicit_allow_origin = preflight_explicit_allow_origin + self.allow_origin_regex = compiled_allow_origin_regex + self.simple_headers = simple_headers + self.preflight_headers = preflight_headers + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http": # pragma: no cover + await self.app(scope, receive, send) + return + + method = scope["method"] + headers = Headers(scope=scope) + origin = headers.get("origin") + + if origin is None: + await self.app(scope, receive, send) + return + + if method == "OPTIONS" and "access-control-request-method" in headers: + response = self.preflight_response(request_headers=headers) + await response(scope, receive, send) + return + + await self.simple_response(scope, receive, send, request_headers=headers) + + def is_allowed_origin(self, origin: str) -> bool: + if self.allow_all_origins: + return True + + if self.allow_origin_regex is not None and self.allow_origin_regex.fullmatch(origin): + return True + + return origin in self.allow_origins + + def preflight_response(self, request_headers: Headers) -> Response: + requested_origin = request_headers["origin"] + requested_method = request_headers["access-control-request-method"] + requested_headers = request_headers.get("access-control-request-headers") + + headers = dict(self.preflight_headers) + failures = [] + + if self.is_allowed_origin(origin=requested_origin): + if self.preflight_explicit_allow_origin: + # The "else" case is already accounted for in self.preflight_headers + # and the value would be "*". + headers["Access-Control-Allow-Origin"] = requested_origin + else: + failures.append("origin") + + if requested_method not in self.allow_methods: + failures.append("method") + + # If we allow all headers, then we have to mirror back any requested + # headers in the response. + if self.allow_all_headers and requested_headers is not None: + headers["Access-Control-Allow-Headers"] = requested_headers + elif requested_headers is not None: + for header in [h.lower() for h in requested_headers.split(",")]: + if header.strip() not in self.allow_headers: + failures.append("headers") + break + + # We don't strictly need to use 400 responses here, since its up to + # the browser to enforce the CORS policy, but its more informative + # if we do. + if failures: + failure_text = "Disallowed CORS " + ", ".join(failures) + return PlainTextResponse(failure_text, status_code=400, headers=headers) + + return PlainTextResponse("OK", status_code=200, headers=headers) + + async def simple_response(self, scope: Scope, receive: Receive, send: Send, request_headers: Headers) -> None: + send = functools.partial(self.send, send=send, request_headers=request_headers) + await self.app(scope, receive, send) + + async def send(self, message: Message, send: Send, request_headers: Headers) -> None: + if message["type"] != "http.response.start": + await send(message) + return + + message.setdefault("headers", []) + headers = MutableHeaders(scope=message) + headers.update(self.simple_headers) + origin = request_headers["Origin"] + has_cookie = "cookie" in request_headers + + # If request includes any cookie headers, then we must respond + # with the specific origin instead of '*'. + if self.allow_all_origins and has_cookie: + self.allow_explicit_origin(headers, origin) + + # If we only allow specific origins, then we have to mirror back + # the Origin header in the response. + elif not self.allow_all_origins and self.is_allowed_origin(origin=origin): + self.allow_explicit_origin(headers, origin) + + await send(message) + + @staticmethod + def allow_explicit_origin(headers: MutableHeaders, origin: str) -> None: + headers["Access-Control-Allow-Origin"] = origin + headers.add_vary_header("Origin") diff --git a/venv/Lib/site-packages/starlette/middleware/errors.py b/venv/Lib/site-packages/starlette/middleware/errors.py new file mode 100644 index 00000000..76ad776b --- /dev/null +++ b/venv/Lib/site-packages/starlette/middleware/errors.py @@ -0,0 +1,260 @@ +from __future__ import annotations + +import html +import inspect +import sys +import traceback +import typing + +from starlette._utils import is_async_callable +from starlette.concurrency import run_in_threadpool +from starlette.requests import Request +from starlette.responses import HTMLResponse, PlainTextResponse, Response +from starlette.types import ASGIApp, Message, Receive, Scope, Send + +STYLES = """ +p { + color: #211c1c; +} +.traceback-container { + border: 1px solid #038BB8; +} +.traceback-title { + background-color: #038BB8; + color: lemonchiffon; + padding: 12px; + font-size: 20px; + margin-top: 0px; +} +.frame-line { + padding-left: 10px; + font-family: monospace; +} +.frame-filename { + font-family: monospace; +} +.center-line { + background-color: #038BB8; + color: #f9f6e1; + padding: 5px 0px 5px 5px; +} +.lineno { + margin-right: 5px; +} +.frame-title { + font-weight: unset; + padding: 10px 10px 10px 10px; + background-color: #E4F4FD; + margin-right: 10px; + color: #191f21; + font-size: 17px; + border: 1px solid #c7dce8; +} +.collapse-btn { + float: right; + padding: 0px 5px 1px 5px; + border: solid 1px #96aebb; + cursor: pointer; +} +.collapsed { + display: none; +} +.source-code { + font-family: courier; + font-size: small; + padding-bottom: 10px; +} +""" + +JS = """ + +""" + +TEMPLATE = """ + + + + Starlette Debugger + + +

500 Server Error

+

{error}

+
+

Traceback

+
{exc_html}
+
+ {js} + + +""" + +FRAME_TEMPLATE = """ +
+

File {frame_filename}, + line {frame_lineno}, + in {frame_name} + {collapse_button} +

+
{code_context}
+
+""" # noqa: E501 + +LINE = """ +

+{lineno}. {line}

+""" + +CENTER_LINE = """ +

+{lineno}. {line}

+""" + + +class ServerErrorMiddleware: + """ + Handles returning 500 responses when a server error occurs. + + If 'debug' is set, then traceback responses will be returned, + otherwise the designated 'handler' will be called. + + This middleware class should generally be used to wrap *everything* + else up, so that unhandled exceptions anywhere in the stack + always result in an appropriate 500 response. + """ + + def __init__( + self, + app: ASGIApp, + handler: typing.Callable[[Request, Exception], typing.Any] | None = None, + debug: bool = False, + ) -> None: + self.app = app + self.handler = handler + self.debug = debug + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http": + await self.app(scope, receive, send) + return + + response_started = False + + async def _send(message: Message) -> None: + nonlocal response_started, send + + if message["type"] == "http.response.start": + response_started = True + await send(message) + + try: + await self.app(scope, receive, _send) + except Exception as exc: + request = Request(scope) + if self.debug: + # In debug mode, return traceback responses. + response = self.debug_response(request, exc) + elif self.handler is None: + # Use our default 500 error handler. + response = self.error_response(request, exc) + else: + # Use an installed 500 error handler. + if is_async_callable(self.handler): + response = await self.handler(request, exc) + else: + response = await run_in_threadpool(self.handler, request, exc) + + if not response_started: + await response(scope, receive, send) + + # We always continue to raise the exception. + # This allows servers to log the error, or allows test clients + # to optionally raise the error within the test case. + raise exc + + def format_line(self, index: int, line: str, frame_lineno: int, frame_index: int) -> str: + values = { + # HTML escape - line could contain < or > + "line": html.escape(line).replace(" ", " "), + "lineno": (frame_lineno - frame_index) + index, + } + + if index != frame_index: + return LINE.format(**values) + return CENTER_LINE.format(**values) + + def generate_frame_html(self, frame: inspect.FrameInfo, is_collapsed: bool) -> str: + code_context = "".join( + self.format_line( + index, + line, + frame.lineno, + frame.index, # type: ignore[arg-type] + ) + for index, line in enumerate(frame.code_context or []) + ) + + values = { + # HTML escape - filename could contain < or >, especially if it's a virtual + # file e.g. in the REPL + "frame_filename": html.escape(frame.filename), + "frame_lineno": frame.lineno, + # HTML escape - if you try very hard it's possible to name a function with < + # or > + "frame_name": html.escape(frame.function), + "code_context": code_context, + "collapsed": "collapsed" if is_collapsed else "", + "collapse_button": "+" if is_collapsed else "‒", + } + return FRAME_TEMPLATE.format(**values) + + def generate_html(self, exc: Exception, limit: int = 7) -> str: + traceback_obj = traceback.TracebackException.from_exception(exc, capture_locals=True) + + exc_html = "" + is_collapsed = False + exc_traceback = exc.__traceback__ + if exc_traceback is not None: + frames = inspect.getinnerframes(exc_traceback, limit) + for frame in reversed(frames): + exc_html += self.generate_frame_html(frame, is_collapsed) + is_collapsed = True + + if sys.version_info >= (3, 13): # pragma: no cover + exc_type_str = traceback_obj.exc_type_str + else: # pragma: no cover + exc_type_str = traceback_obj.exc_type.__name__ + + # escape error class and text + error = f"{html.escape(exc_type_str)}: {html.escape(str(traceback_obj))}" + + return TEMPLATE.format(styles=STYLES, js=JS, error=error, exc_html=exc_html) + + def generate_plain_text(self, exc: Exception) -> str: + return "".join(traceback.format_exception(type(exc), exc, exc.__traceback__)) + + def debug_response(self, request: Request, exc: Exception) -> Response: + accept = request.headers.get("accept", "") + + if "text/html" in accept: + content = self.generate_html(exc) + return HTMLResponse(content, status_code=500) + content = self.generate_plain_text(exc) + return PlainTextResponse(content, status_code=500) + + def error_response(self, request: Request, exc: Exception) -> Response: + return PlainTextResponse("Internal Server Error", status_code=500) diff --git a/venv/Lib/site-packages/starlette/middleware/exceptions.py b/venv/Lib/site-packages/starlette/middleware/exceptions.py new file mode 100644 index 00000000..981d2fca --- /dev/null +++ b/venv/Lib/site-packages/starlette/middleware/exceptions.py @@ -0,0 +1,72 @@ +from __future__ import annotations + +import typing + +from starlette._exception_handler import ( + ExceptionHandlers, + StatusHandlers, + wrap_app_handling_exceptions, +) +from starlette.exceptions import HTTPException, WebSocketException +from starlette.requests import Request +from starlette.responses import PlainTextResponse, Response +from starlette.types import ASGIApp, Receive, Scope, Send +from starlette.websockets import WebSocket + + +class ExceptionMiddleware: + def __init__( + self, + app: ASGIApp, + handlers: typing.Mapping[typing.Any, typing.Callable[[Request, Exception], Response]] | None = None, + debug: bool = False, + ) -> None: + self.app = app + self.debug = debug # TODO: We ought to handle 404 cases if debug is set. + self._status_handlers: StatusHandlers = {} + self._exception_handlers: ExceptionHandlers = { + HTTPException: self.http_exception, + WebSocketException: self.websocket_exception, + } + if handlers is not None: # pragma: no branch + for key, value in handlers.items(): + self.add_exception_handler(key, value) + + def add_exception_handler( + self, + exc_class_or_status_code: int | type[Exception], + handler: typing.Callable[[Request, Exception], Response], + ) -> None: + if isinstance(exc_class_or_status_code, int): + self._status_handlers[exc_class_or_status_code] = handler + else: + assert issubclass(exc_class_or_status_code, Exception) + self._exception_handlers[exc_class_or_status_code] = handler + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] not in ("http", "websocket"): + await self.app(scope, receive, send) + return + + scope["starlette.exception_handlers"] = ( + self._exception_handlers, + self._status_handlers, + ) + + conn: Request | WebSocket + if scope["type"] == "http": + conn = Request(scope, receive, send) + else: + conn = WebSocket(scope, receive, send) + + await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) + + def http_exception(self, request: Request, exc: Exception) -> Response: + assert isinstance(exc, HTTPException) + if exc.status_code in {204, 304}: + return Response(status_code=exc.status_code, headers=exc.headers) + return PlainTextResponse(exc.detail, status_code=exc.status_code, headers=exc.headers) + + async def websocket_exception(self, websocket: WebSocket, exc: Exception) -> None: + assert isinstance(exc, WebSocketException) + await websocket.close(code=exc.code, reason=exc.reason) # pragma: no cover diff --git a/venv/Lib/site-packages/starlette/middleware/gzip.py b/venv/Lib/site-packages/starlette/middleware/gzip.py new file mode 100644 index 00000000..c7fd5b77 --- /dev/null +++ b/venv/Lib/site-packages/starlette/middleware/gzip.py @@ -0,0 +1,141 @@ +import gzip +import io +import typing + +from starlette.datastructures import Headers, MutableHeaders +from starlette.types import ASGIApp, Message, Receive, Scope, Send + +DEFAULT_EXCLUDED_CONTENT_TYPES = ("text/event-stream",) + + +class GZipMiddleware: + def __init__(self, app: ASGIApp, minimum_size: int = 500, compresslevel: int = 9) -> None: + self.app = app + self.minimum_size = minimum_size + self.compresslevel = compresslevel + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http": # pragma: no cover + await self.app(scope, receive, send) + return + + headers = Headers(scope=scope) + responder: ASGIApp + if "gzip" in headers.get("Accept-Encoding", ""): + responder = GZipResponder(self.app, self.minimum_size, compresslevel=self.compresslevel) + else: + responder = IdentityResponder(self.app, self.minimum_size) + + await responder(scope, receive, send) + + +class IdentityResponder: + content_encoding: str + + def __init__(self, app: ASGIApp, minimum_size: int) -> None: + self.app = app + self.minimum_size = minimum_size + self.send: Send = unattached_send + self.initial_message: Message = {} + self.started = False + self.content_encoding_set = False + self.content_type_is_excluded = False + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + self.send = send + await self.app(scope, receive, self.send_with_compression) + + async def send_with_compression(self, message: Message) -> None: + message_type = message["type"] + if message_type == "http.response.start": + # Don't send the initial message until we've determined how to + # modify the outgoing headers correctly. + self.initial_message = message + headers = Headers(raw=self.initial_message["headers"]) + self.content_encoding_set = "content-encoding" in headers + self.content_type_is_excluded = headers.get("content-type", "").startswith(DEFAULT_EXCLUDED_CONTENT_TYPES) + elif message_type == "http.response.body" and (self.content_encoding_set or self.content_type_is_excluded): + if not self.started: + self.started = True + await self.send(self.initial_message) + await self.send(message) + elif message_type == "http.response.body" and not self.started: + self.started = True + body = message.get("body", b"") + more_body = message.get("more_body", False) + if len(body) < self.minimum_size and not more_body: + # Don't apply compression to small outgoing responses. + await self.send(self.initial_message) + await self.send(message) + elif not more_body: + # Standard response. + body = self.apply_compression(body, more_body=False) + + headers = MutableHeaders(raw=self.initial_message["headers"]) + headers.add_vary_header("Accept-Encoding") + if body != message["body"]: + headers["Content-Encoding"] = self.content_encoding + headers["Content-Length"] = str(len(body)) + message["body"] = body + + await self.send(self.initial_message) + await self.send(message) + else: + # Initial body in streaming response. + body = self.apply_compression(body, more_body=True) + + headers = MutableHeaders(raw=self.initial_message["headers"]) + headers.add_vary_header("Accept-Encoding") + if body != message["body"]: + headers["Content-Encoding"] = self.content_encoding + del headers["Content-Length"] + message["body"] = body + + await self.send(self.initial_message) + await self.send(message) + elif message_type == "http.response.body": # pragma: no branch + # Remaining body in streaming response. + body = message.get("body", b"") + more_body = message.get("more_body", False) + + message["body"] = self.apply_compression(body, more_body=more_body) + + await self.send(message) + + def apply_compression(self, body: bytes, *, more_body: bool) -> bytes: + """Apply compression on the response body. + + If more_body is False, any compression file should be closed. If it + isn't, it won't be closed automatically until all background tasks + complete. + """ + return body + + +class GZipResponder(IdentityResponder): + content_encoding = "gzip" + + def __init__(self, app: ASGIApp, minimum_size: int, compresslevel: int = 9) -> None: + super().__init__(app, minimum_size) + + self.gzip_buffer = io.BytesIO() + self.gzip_file = gzip.GzipFile(mode="wb", fileobj=self.gzip_buffer, compresslevel=compresslevel) + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + with self.gzip_buffer, self.gzip_file: + await super().__call__(scope, receive, send) + + def apply_compression(self, body: bytes, *, more_body: bool) -> bytes: + self.gzip_file.write(body) + if not more_body: + self.gzip_file.close() + + body = self.gzip_buffer.getvalue() + self.gzip_buffer.seek(0) + self.gzip_buffer.truncate() + + return body + + +async def unattached_send(message: Message) -> typing.NoReturn: + raise RuntimeError("send awaitable not set") # pragma: no cover diff --git a/venv/Lib/site-packages/starlette/middleware/httpsredirect.py b/venv/Lib/site-packages/starlette/middleware/httpsredirect.py new file mode 100644 index 00000000..a8359067 --- /dev/null +++ b/venv/Lib/site-packages/starlette/middleware/httpsredirect.py @@ -0,0 +1,19 @@ +from starlette.datastructures import URL +from starlette.responses import RedirectResponse +from starlette.types import ASGIApp, Receive, Scope, Send + + +class HTTPSRedirectMiddleware: + def __init__(self, app: ASGIApp) -> None: + self.app = app + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] in ("http", "websocket") and scope["scheme"] in ("http", "ws"): + url = URL(scope=scope) + redirect_scheme = {"http": "https", "ws": "wss"}[url.scheme] + netloc = url.hostname if url.port in (80, 443) else url.netloc + url = url.replace(scheme=redirect_scheme, netloc=netloc) + response = RedirectResponse(url, status_code=307) + await response(scope, receive, send) + else: + await self.app(scope, receive, send) diff --git a/venv/Lib/site-packages/starlette/middleware/sessions.py b/venv/Lib/site-packages/starlette/middleware/sessions.py new file mode 100644 index 00000000..5f9fcd88 --- /dev/null +++ b/venv/Lib/site-packages/starlette/middleware/sessions.py @@ -0,0 +1,85 @@ +from __future__ import annotations + +import json +import typing +from base64 import b64decode, b64encode + +import itsdangerous +from itsdangerous.exc import BadSignature + +from starlette.datastructures import MutableHeaders, Secret +from starlette.requests import HTTPConnection +from starlette.types import ASGIApp, Message, Receive, Scope, Send + + +class SessionMiddleware: + def __init__( + self, + app: ASGIApp, + secret_key: str | Secret, + session_cookie: str = "session", + max_age: int | None = 14 * 24 * 60 * 60, # 14 days, in seconds + path: str = "/", + same_site: typing.Literal["lax", "strict", "none"] = "lax", + https_only: bool = False, + domain: str | None = None, + ) -> None: + self.app = app + self.signer = itsdangerous.TimestampSigner(str(secret_key)) + self.session_cookie = session_cookie + self.max_age = max_age + self.path = path + self.security_flags = "httponly; samesite=" + same_site + if https_only: # Secure flag can be used with HTTPS only + self.security_flags += "; secure" + if domain is not None: + self.security_flags += f"; domain={domain}" + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] not in ("http", "websocket"): # pragma: no cover + await self.app(scope, receive, send) + return + + connection = HTTPConnection(scope) + initial_session_was_empty = True + + if self.session_cookie in connection.cookies: + data = connection.cookies[self.session_cookie].encode("utf-8") + try: + data = self.signer.unsign(data, max_age=self.max_age) + scope["session"] = json.loads(b64decode(data)) + initial_session_was_empty = False + except BadSignature: + scope["session"] = {} + else: + scope["session"] = {} + + async def send_wrapper(message: Message) -> None: + if message["type"] == "http.response.start": + if scope["session"]: + # We have session data to persist. + data = b64encode(json.dumps(scope["session"]).encode("utf-8")) + data = self.signer.sign(data) + headers = MutableHeaders(scope=message) + header_value = "{session_cookie}={data}; path={path}; {max_age}{security_flags}".format( + session_cookie=self.session_cookie, + data=data.decode("utf-8"), + path=self.path, + max_age=f"Max-Age={self.max_age}; " if self.max_age else "", + security_flags=self.security_flags, + ) + headers.append("Set-Cookie", header_value) + elif not initial_session_was_empty: + # The session has been cleared. + headers = MutableHeaders(scope=message) + header_value = "{session_cookie}={data}; path={path}; {expires}{security_flags}".format( + session_cookie=self.session_cookie, + data="null", + path=self.path, + expires="expires=Thu, 01 Jan 1970 00:00:00 GMT; ", + security_flags=self.security_flags, + ) + headers.append("Set-Cookie", header_value) + await send(message) + + await self.app(scope, receive, send_wrapper) diff --git a/venv/Lib/site-packages/starlette/middleware/trustedhost.py b/venv/Lib/site-packages/starlette/middleware/trustedhost.py new file mode 100644 index 00000000..2d1c999e --- /dev/null +++ b/venv/Lib/site-packages/starlette/middleware/trustedhost.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +import typing + +from starlette.datastructures import URL, Headers +from starlette.responses import PlainTextResponse, RedirectResponse, Response +from starlette.types import ASGIApp, Receive, Scope, Send + +ENFORCE_DOMAIN_WILDCARD = "Domain wildcard patterns must be like '*.example.com'." + + +class TrustedHostMiddleware: + def __init__( + self, + app: ASGIApp, + allowed_hosts: typing.Sequence[str] | None = None, + www_redirect: bool = True, + ) -> None: + if allowed_hosts is None: + allowed_hosts = ["*"] + + for pattern in allowed_hosts: + assert "*" not in pattern[1:], ENFORCE_DOMAIN_WILDCARD + if pattern.startswith("*") and pattern != "*": + assert pattern.startswith("*."), ENFORCE_DOMAIN_WILDCARD + self.app = app + self.allowed_hosts = list(allowed_hosts) + self.allow_any = "*" in allowed_hosts + self.www_redirect = www_redirect + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if self.allow_any or scope["type"] not in ( + "http", + "websocket", + ): # pragma: no cover + await self.app(scope, receive, send) + return + + headers = Headers(scope=scope) + host = headers.get("host", "").split(":")[0] + is_valid_host = False + found_www_redirect = False + for pattern in self.allowed_hosts: + if host == pattern or (pattern.startswith("*") and host.endswith(pattern[1:])): + is_valid_host = True + break + elif "www." + host == pattern: + found_www_redirect = True + + if is_valid_host: + await self.app(scope, receive, send) + else: + response: Response + if found_www_redirect and self.www_redirect: + url = URL(scope=scope) + redirect_url = url.replace(netloc="www." + url.netloc) + response = RedirectResponse(url=str(redirect_url)) + else: + response = PlainTextResponse("Invalid host header", status_code=400) + await response(scope, receive, send) diff --git a/venv/Lib/site-packages/starlette/middleware/wsgi.py b/venv/Lib/site-packages/starlette/middleware/wsgi.py new file mode 100644 index 00000000..6e0a3fae --- /dev/null +++ b/venv/Lib/site-packages/starlette/middleware/wsgi.py @@ -0,0 +1,152 @@ +from __future__ import annotations + +import io +import math +import sys +import typing +import warnings + +import anyio +from anyio.abc import ObjectReceiveStream, ObjectSendStream + +from starlette.types import Receive, Scope, Send + +warnings.warn( + "starlette.middleware.wsgi is deprecated and will be removed in a future release. " + "Please refer to https://github.com/abersheeran/a2wsgi as a replacement.", + DeprecationWarning, +) + + +def build_environ(scope: Scope, body: bytes) -> dict[str, typing.Any]: + """ + Builds a scope and request body into a WSGI environ object. + """ + + script_name = scope.get("root_path", "").encode("utf8").decode("latin1") + path_info = scope["path"].encode("utf8").decode("latin1") + if path_info.startswith(script_name): + path_info = path_info[len(script_name) :] + + environ = { + "REQUEST_METHOD": scope["method"], + "SCRIPT_NAME": script_name, + "PATH_INFO": path_info, + "QUERY_STRING": scope["query_string"].decode("ascii"), + "SERVER_PROTOCOL": f"HTTP/{scope['http_version']}", + "wsgi.version": (1, 0), + "wsgi.url_scheme": scope.get("scheme", "http"), + "wsgi.input": io.BytesIO(body), + "wsgi.errors": sys.stdout, + "wsgi.multithread": True, + "wsgi.multiprocess": True, + "wsgi.run_once": False, + } + + # Get server name and port - required in WSGI, not in ASGI + server = scope.get("server") or ("localhost", 80) + environ["SERVER_NAME"] = server[0] + environ["SERVER_PORT"] = server[1] + + # Get client IP address + if scope.get("client"): + environ["REMOTE_ADDR"] = scope["client"][0] + + # Go through headers and make them into environ entries + for name, value in scope.get("headers", []): + name = name.decode("latin1") + if name == "content-length": + corrected_name = "CONTENT_LENGTH" + elif name == "content-type": + corrected_name = "CONTENT_TYPE" + else: + corrected_name = f"HTTP_{name}".upper().replace("-", "_") + # HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in + # case + value = value.decode("latin1") + if corrected_name in environ: + value = environ[corrected_name] + "," + value + environ[corrected_name] = value + return environ + + +class WSGIMiddleware: + def __init__(self, app: typing.Callable[..., typing.Any]) -> None: + self.app = app + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + assert scope["type"] == "http" + responder = WSGIResponder(self.app, scope) + await responder(receive, send) + + +class WSGIResponder: + stream_send: ObjectSendStream[typing.MutableMapping[str, typing.Any]] + stream_receive: ObjectReceiveStream[typing.MutableMapping[str, typing.Any]] + + def __init__(self, app: typing.Callable[..., typing.Any], scope: Scope) -> None: + self.app = app + self.scope = scope + self.status = None + self.response_headers = None + self.stream_send, self.stream_receive = anyio.create_memory_object_stream(math.inf) + self.response_started = False + self.exc_info: typing.Any = None + + async def __call__(self, receive: Receive, send: Send) -> None: + body = b"" + more_body = True + while more_body: + message = await receive() + body += message.get("body", b"") + more_body = message.get("more_body", False) + environ = build_environ(self.scope, body) + + async with anyio.create_task_group() as task_group: + task_group.start_soon(self.sender, send) + async with self.stream_send: + await anyio.to_thread.run_sync(self.wsgi, environ, self.start_response) + if self.exc_info is not None: + raise self.exc_info[0].with_traceback(self.exc_info[1], self.exc_info[2]) + + async def sender(self, send: Send) -> None: + async with self.stream_receive: + async for message in self.stream_receive: + await send(message) + + def start_response( + self, + status: str, + response_headers: list[tuple[str, str]], + exc_info: typing.Any = None, + ) -> None: + self.exc_info = exc_info + if not self.response_started: # pragma: no branch + self.response_started = True + status_code_string, _ = status.split(" ", 1) + status_code = int(status_code_string) + headers = [ + (name.strip().encode("ascii").lower(), value.strip().encode("ascii")) + for name, value in response_headers + ] + anyio.from_thread.run( + self.stream_send.send, + { + "type": "http.response.start", + "status": status_code, + "headers": headers, + }, + ) + + def wsgi( + self, + environ: dict[str, typing.Any], + start_response: typing.Callable[..., typing.Any], + ) -> None: + for chunk in self.app(environ, start_response): + anyio.from_thread.run( + self.stream_send.send, + {"type": "http.response.body", "body": chunk, "more_body": True}, + ) + + anyio.from_thread.run(self.stream_send.send, {"type": "http.response.body", "body": b""}) diff --git a/venv/Lib/site-packages/starlette/py.typed b/venv/Lib/site-packages/starlette/py.typed new file mode 100644 index 00000000..e69de29b diff --git a/venv/Lib/site-packages/starlette/requests.py b/venv/Lib/site-packages/starlette/requests.py new file mode 100644 index 00000000..7dc04a74 --- /dev/null +++ b/venv/Lib/site-packages/starlette/requests.py @@ -0,0 +1,322 @@ +from __future__ import annotations + +import json +import typing +from http import cookies as http_cookies + +import anyio + +from starlette._utils import AwaitableOrContextManager, AwaitableOrContextManagerWrapper +from starlette.datastructures import URL, Address, FormData, Headers, QueryParams, State +from starlette.exceptions import HTTPException +from starlette.formparsers import FormParser, MultiPartException, MultiPartParser +from starlette.types import Message, Receive, Scope, Send + +if typing.TYPE_CHECKING: + from python_multipart.multipart import parse_options_header + + from starlette.applications import Starlette + from starlette.routing import Router +else: + try: + try: + from python_multipart.multipart import parse_options_header + except ModuleNotFoundError: # pragma: no cover + from multipart.multipart import parse_options_header + except ModuleNotFoundError: # pragma: no cover + parse_options_header = None + + +SERVER_PUSH_HEADERS_TO_COPY = { + "accept", + "accept-encoding", + "accept-language", + "cache-control", + "user-agent", +} + + +def cookie_parser(cookie_string: str) -> dict[str, str]: + """ + This function parses a ``Cookie`` HTTP header into a dict of key/value pairs. + + It attempts to mimic browser cookie parsing behavior: browsers and web servers + frequently disregard the spec (RFC 6265) when setting and reading cookies, + so we attempt to suit the common scenarios here. + + This function has been adapted from Django 3.1.0. + Note: we are explicitly _NOT_ using `SimpleCookie.load` because it is based + on an outdated spec and will fail on lots of input we want to support + """ + cookie_dict: dict[str, str] = {} + for chunk in cookie_string.split(";"): + if "=" in chunk: + key, val = chunk.split("=", 1) + else: + # Assume an empty name per + # https://bugzilla.mozilla.org/show_bug.cgi?id=169091 + key, val = "", chunk + key, val = key.strip(), val.strip() + if key or val: + # unquote using Python's algorithm. + cookie_dict[key] = http_cookies._unquote(val) + return cookie_dict + + +class ClientDisconnect(Exception): + pass + + +class HTTPConnection(typing.Mapping[str, typing.Any]): + """ + A base class for incoming HTTP connections, that is used to provide + any functionality that is common to both `Request` and `WebSocket`. + """ + + def __init__(self, scope: Scope, receive: Receive | None = None) -> None: + assert scope["type"] in ("http", "websocket") + self.scope = scope + + def __getitem__(self, key: str) -> typing.Any: + return self.scope[key] + + def __iter__(self) -> typing.Iterator[str]: + return iter(self.scope) + + def __len__(self) -> int: + return len(self.scope) + + # Don't use the `abc.Mapping.__eq__` implementation. + # Connection instances should never be considered equal + # unless `self is other`. + __eq__ = object.__eq__ + __hash__ = object.__hash__ + + @property + def app(self) -> typing.Any: + return self.scope["app"] + + @property + def url(self) -> URL: + if not hasattr(self, "_url"): # pragma: no branch + self._url = URL(scope=self.scope) + return self._url + + @property + def base_url(self) -> URL: + if not hasattr(self, "_base_url"): + base_url_scope = dict(self.scope) + # This is used by request.url_for, it might be used inside a Mount which + # would have its own child scope with its own root_path, but the base URL + # for url_for should still be the top level app root path. + app_root_path = base_url_scope.get("app_root_path", base_url_scope.get("root_path", "")) + path = app_root_path + if not path.endswith("/"): + path += "/" + base_url_scope["path"] = path + base_url_scope["query_string"] = b"" + base_url_scope["root_path"] = app_root_path + self._base_url = URL(scope=base_url_scope) + return self._base_url + + @property + def headers(self) -> Headers: + if not hasattr(self, "_headers"): + self._headers = Headers(scope=self.scope) + return self._headers + + @property + def query_params(self) -> QueryParams: + if not hasattr(self, "_query_params"): # pragma: no branch + self._query_params = QueryParams(self.scope["query_string"]) + return self._query_params + + @property + def path_params(self) -> dict[str, typing.Any]: + return self.scope.get("path_params", {}) + + @property + def cookies(self) -> dict[str, str]: + if not hasattr(self, "_cookies"): + cookies: dict[str, str] = {} + cookie_header = self.headers.get("cookie") + + if cookie_header: + cookies = cookie_parser(cookie_header) + self._cookies = cookies + return self._cookies + + @property + def client(self) -> Address | None: + # client is a 2 item tuple of (host, port), None if missing + host_port = self.scope.get("client") + if host_port is not None: + return Address(*host_port) + return None + + @property + def session(self) -> dict[str, typing.Any]: + assert "session" in self.scope, "SessionMiddleware must be installed to access request.session" + return self.scope["session"] # type: ignore[no-any-return] + + @property + def auth(self) -> typing.Any: + assert "auth" in self.scope, "AuthenticationMiddleware must be installed to access request.auth" + return self.scope["auth"] + + @property + def user(self) -> typing.Any: + assert "user" in self.scope, "AuthenticationMiddleware must be installed to access request.user" + return self.scope["user"] + + @property + def state(self) -> State: + if not hasattr(self, "_state"): + # Ensure 'state' has an empty dict if it's not already populated. + self.scope.setdefault("state", {}) + # Create a state instance with a reference to the dict in which it should + # store info + self._state = State(self.scope["state"]) + return self._state + + def url_for(self, name: str, /, **path_params: typing.Any) -> URL: + url_path_provider: Router | Starlette | None = self.scope.get("router") or self.scope.get("app") + if url_path_provider is None: + raise RuntimeError("The `url_for` method can only be used inside a Starlette application or with a router.") + url_path = url_path_provider.url_path_for(name, **path_params) + return url_path.make_absolute_url(base_url=self.base_url) + + +async def empty_receive() -> typing.NoReturn: + raise RuntimeError("Receive channel has not been made available") + + +async def empty_send(message: Message) -> typing.NoReturn: + raise RuntimeError("Send channel has not been made available") + + +class Request(HTTPConnection): + _form: FormData | None + + def __init__(self, scope: Scope, receive: Receive = empty_receive, send: Send = empty_send): + super().__init__(scope) + assert scope["type"] == "http" + self._receive = receive + self._send = send + self._stream_consumed = False + self._is_disconnected = False + self._form = None + + @property + def method(self) -> str: + return typing.cast(str, self.scope["method"]) + + @property + def receive(self) -> Receive: + return self._receive + + async def stream(self) -> typing.AsyncGenerator[bytes, None]: + if hasattr(self, "_body"): + yield self._body + yield b"" + return + if self._stream_consumed: + raise RuntimeError("Stream consumed") + while not self._stream_consumed: + message = await self._receive() + if message["type"] == "http.request": + body = message.get("body", b"") + if not message.get("more_body", False): + self._stream_consumed = True + if body: + yield body + elif message["type"] == "http.disconnect": # pragma: no branch + self._is_disconnected = True + raise ClientDisconnect() + yield b"" + + async def body(self) -> bytes: + if not hasattr(self, "_body"): + chunks: list[bytes] = [] + async for chunk in self.stream(): + chunks.append(chunk) + self._body = b"".join(chunks) + return self._body + + async def json(self) -> typing.Any: + if not hasattr(self, "_json"): # pragma: no branch + body = await self.body() + self._json = json.loads(body) + return self._json + + async def _get_form( + self, + *, + max_files: int | float = 1000, + max_fields: int | float = 1000, + max_part_size: int = 1024 * 1024, + ) -> FormData: + if self._form is None: # pragma: no branch + assert parse_options_header is not None, ( + "The `python-multipart` library must be installed to use form parsing." + ) + content_type_header = self.headers.get("Content-Type") + content_type: bytes + content_type, _ = parse_options_header(content_type_header) + if content_type == b"multipart/form-data": + try: + multipart_parser = MultiPartParser( + self.headers, + self.stream(), + max_files=max_files, + max_fields=max_fields, + max_part_size=max_part_size, + ) + self._form = await multipart_parser.parse() + except MultiPartException as exc: + if "app" in self.scope: + raise HTTPException(status_code=400, detail=exc.message) + raise exc + elif content_type == b"application/x-www-form-urlencoded": + form_parser = FormParser(self.headers, self.stream()) + self._form = await form_parser.parse() + else: + self._form = FormData() + return self._form + + def form( + self, + *, + max_files: int | float = 1000, + max_fields: int | float = 1000, + max_part_size: int = 1024 * 1024, + ) -> AwaitableOrContextManager[FormData]: + return AwaitableOrContextManagerWrapper( + self._get_form(max_files=max_files, max_fields=max_fields, max_part_size=max_part_size) + ) + + async def close(self) -> None: + if self._form is not None: # pragma: no branch + await self._form.close() + + async def is_disconnected(self) -> bool: + if not self._is_disconnected: + message: Message = {} + + # If message isn't immediately available, move on + with anyio.CancelScope() as cs: + cs.cancel() + message = await self._receive() + + if message.get("type") == "http.disconnect": + self._is_disconnected = True + + return self._is_disconnected + + async def send_push_promise(self, path: str) -> None: + if "http.response.push" in self.scope.get("extensions", {}): + raw_headers: list[tuple[bytes, bytes]] = [] + for name in SERVER_PUSH_HEADERS_TO_COPY: + for value in self.headers.getlist(name): + raw_headers.append((name.encode("latin-1"), value.encode("latin-1"))) + await self._send({"type": "http.response.push", "path": path, "headers": raw_headers}) diff --git a/venv/Lib/site-packages/starlette/responses.py b/venv/Lib/site-packages/starlette/responses.py new file mode 100644 index 00000000..81e89fae --- /dev/null +++ b/venv/Lib/site-packages/starlette/responses.py @@ -0,0 +1,536 @@ +from __future__ import annotations + +import hashlib +import http.cookies +import json +import os +import re +import stat +import typing +import warnings +from datetime import datetime +from email.utils import format_datetime, formatdate +from functools import partial +from mimetypes import guess_type +from secrets import token_hex +from urllib.parse import quote + +import anyio +import anyio.to_thread + +from starlette._utils import collapse_excgroups +from starlette.background import BackgroundTask +from starlette.concurrency import iterate_in_threadpool +from starlette.datastructures import URL, Headers, MutableHeaders +from starlette.requests import ClientDisconnect +from starlette.types import Receive, Scope, Send + + +class Response: + media_type = None + charset = "utf-8" + + def __init__( + self, + content: typing.Any = None, + status_code: int = 200, + headers: typing.Mapping[str, str] | None = None, + media_type: str | None = None, + background: BackgroundTask | None = None, + ) -> None: + self.status_code = status_code + if media_type is not None: + self.media_type = media_type + self.background = background + self.body = self.render(content) + self.init_headers(headers) + + def render(self, content: typing.Any) -> bytes | memoryview: + if content is None: + return b"" + if isinstance(content, (bytes, memoryview)): + return content + return content.encode(self.charset) # type: ignore + + def init_headers(self, headers: typing.Mapping[str, str] | None = None) -> None: + if headers is None: + raw_headers: list[tuple[bytes, bytes]] = [] + populate_content_length = True + populate_content_type = True + else: + raw_headers = [(k.lower().encode("latin-1"), v.encode("latin-1")) for k, v in headers.items()] + keys = [h[0] for h in raw_headers] + populate_content_length = b"content-length" not in keys + populate_content_type = b"content-type" not in keys + + body = getattr(self, "body", None) + if ( + body is not None + and populate_content_length + and not (self.status_code < 200 or self.status_code in (204, 304)) + ): + content_length = str(len(body)) + raw_headers.append((b"content-length", content_length.encode("latin-1"))) + + content_type = self.media_type + if content_type is not None and populate_content_type: + if content_type.startswith("text/") and "charset=" not in content_type.lower(): + content_type += "; charset=" + self.charset + raw_headers.append((b"content-type", content_type.encode("latin-1"))) + + self.raw_headers = raw_headers + + @property + def headers(self) -> MutableHeaders: + if not hasattr(self, "_headers"): + self._headers = MutableHeaders(raw=self.raw_headers) + return self._headers + + def set_cookie( + self, + key: str, + value: str = "", + max_age: int | None = None, + expires: datetime | str | int | None = None, + path: str | None = "/", + domain: str | None = None, + secure: bool = False, + httponly: bool = False, + samesite: typing.Literal["lax", "strict", "none"] | None = "lax", + ) -> None: + cookie: http.cookies.BaseCookie[str] = http.cookies.SimpleCookie() + cookie[key] = value + if max_age is not None: + cookie[key]["max-age"] = max_age + if expires is not None: + if isinstance(expires, datetime): + cookie[key]["expires"] = format_datetime(expires, usegmt=True) + else: + cookie[key]["expires"] = expires + if path is not None: + cookie[key]["path"] = path + if domain is not None: + cookie[key]["domain"] = domain + if secure: + cookie[key]["secure"] = True + if httponly: + cookie[key]["httponly"] = True + if samesite is not None: + assert samesite.lower() in [ + "strict", + "lax", + "none", + ], "samesite must be either 'strict', 'lax' or 'none'" + cookie[key]["samesite"] = samesite + cookie_val = cookie.output(header="").strip() + self.raw_headers.append((b"set-cookie", cookie_val.encode("latin-1"))) + + def delete_cookie( + self, + key: str, + path: str = "/", + domain: str | None = None, + secure: bool = False, + httponly: bool = False, + samesite: typing.Literal["lax", "strict", "none"] | None = "lax", + ) -> None: + self.set_cookie( + key, + max_age=0, + expires=0, + path=path, + domain=domain, + secure=secure, + httponly=httponly, + samesite=samesite, + ) + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + prefix = "websocket." if scope["type"] == "websocket" else "" + await send( + { + "type": prefix + "http.response.start", + "status": self.status_code, + "headers": self.raw_headers, + } + ) + await send({"type": prefix + "http.response.body", "body": self.body}) + + if self.background is not None: + await self.background() + + +class HTMLResponse(Response): + media_type = "text/html" + + +class PlainTextResponse(Response): + media_type = "text/plain" + + +class JSONResponse(Response): + media_type = "application/json" + + def __init__( + self, + content: typing.Any, + status_code: int = 200, + headers: typing.Mapping[str, str] | None = None, + media_type: str | None = None, + background: BackgroundTask | None = None, + ) -> None: + super().__init__(content, status_code, headers, media_type, background) + + def render(self, content: typing.Any) -> bytes: + return json.dumps( + content, + ensure_ascii=False, + allow_nan=False, + indent=None, + separators=(",", ":"), + ).encode("utf-8") + + +class RedirectResponse(Response): + def __init__( + self, + url: str | URL, + status_code: int = 307, + headers: typing.Mapping[str, str] | None = None, + background: BackgroundTask | None = None, + ) -> None: + super().__init__(content=b"", status_code=status_code, headers=headers, background=background) + self.headers["location"] = quote(str(url), safe=":/%#?=@[]!$&'()*+,;") + + +Content = typing.Union[str, bytes, memoryview] +SyncContentStream = typing.Iterable[Content] +AsyncContentStream = typing.AsyncIterable[Content] +ContentStream = typing.Union[AsyncContentStream, SyncContentStream] + + +class StreamingResponse(Response): + body_iterator: AsyncContentStream + + def __init__( + self, + content: ContentStream, + status_code: int = 200, + headers: typing.Mapping[str, str] | None = None, + media_type: str | None = None, + background: BackgroundTask | None = None, + ) -> None: + if isinstance(content, typing.AsyncIterable): + self.body_iterator = content + else: + self.body_iterator = iterate_in_threadpool(content) + self.status_code = status_code + self.media_type = self.media_type if media_type is None else media_type + self.background = background + self.init_headers(headers) + + async def listen_for_disconnect(self, receive: Receive) -> None: + while True: + message = await receive() + if message["type"] == "http.disconnect": + break + + async def stream_response(self, send: Send) -> None: + await send( + { + "type": "http.response.start", + "status": self.status_code, + "headers": self.raw_headers, + } + ) + async for chunk in self.body_iterator: + if not isinstance(chunk, (bytes, memoryview)): + chunk = chunk.encode(self.charset) + await send({"type": "http.response.body", "body": chunk, "more_body": True}) + + await send({"type": "http.response.body", "body": b"", "more_body": False}) + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + spec_version = tuple(map(int, scope.get("asgi", {}).get("spec_version", "2.0").split("."))) + + if spec_version >= (2, 4): + try: + await self.stream_response(send) + except OSError: + raise ClientDisconnect() + else: + with collapse_excgroups(): + async with anyio.create_task_group() as task_group: + + async def wrap(func: typing.Callable[[], typing.Awaitable[None]]) -> None: + await func() + task_group.cancel_scope.cancel() + + task_group.start_soon(wrap, partial(self.stream_response, send)) + await wrap(partial(self.listen_for_disconnect, receive)) + + if self.background is not None: + await self.background() + + +class MalformedRangeHeader(Exception): + def __init__(self, content: str = "Malformed range header.") -> None: + self.content = content + + +class RangeNotSatisfiable(Exception): + def __init__(self, max_size: int) -> None: + self.max_size = max_size + + +_RANGE_PATTERN = re.compile(r"(\d*)-(\d*)") + + +class FileResponse(Response): + chunk_size = 64 * 1024 + + def __init__( + self, + path: str | os.PathLike[str], + status_code: int = 200, + headers: typing.Mapping[str, str] | None = None, + media_type: str | None = None, + background: BackgroundTask | None = None, + filename: str | None = None, + stat_result: os.stat_result | None = None, + method: str | None = None, + content_disposition_type: str = "attachment", + ) -> None: + self.path = path + self.status_code = status_code + self.filename = filename + if method is not None: + warnings.warn( + "The 'method' parameter is not used, and it will be removed.", + DeprecationWarning, + ) + if media_type is None: + media_type = guess_type(filename or path)[0] or "text/plain" + self.media_type = media_type + self.background = background + self.init_headers(headers) + self.headers.setdefault("accept-ranges", "bytes") + if self.filename is not None: + content_disposition_filename = quote(self.filename) + if content_disposition_filename != self.filename: + content_disposition = f"{content_disposition_type}; filename*=utf-8''{content_disposition_filename}" + else: + content_disposition = f'{content_disposition_type}; filename="{self.filename}"' + self.headers.setdefault("content-disposition", content_disposition) + self.stat_result = stat_result + if stat_result is not None: + self.set_stat_headers(stat_result) + + def set_stat_headers(self, stat_result: os.stat_result) -> None: + content_length = str(stat_result.st_size) + last_modified = formatdate(stat_result.st_mtime, usegmt=True) + etag_base = str(stat_result.st_mtime) + "-" + str(stat_result.st_size) + etag = f'"{hashlib.md5(etag_base.encode(), usedforsecurity=False).hexdigest()}"' + + self.headers.setdefault("content-length", content_length) + self.headers.setdefault("last-modified", last_modified) + self.headers.setdefault("etag", etag) + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + send_header_only: bool = scope["method"].upper() == "HEAD" + if self.stat_result is None: + try: + stat_result = await anyio.to_thread.run_sync(os.stat, self.path) + self.set_stat_headers(stat_result) + except FileNotFoundError: + raise RuntimeError(f"File at path {self.path} does not exist.") + else: + mode = stat_result.st_mode + if not stat.S_ISREG(mode): + raise RuntimeError(f"File at path {self.path} is not a file.") + else: + stat_result = self.stat_result + + headers = Headers(scope=scope) + http_range = headers.get("range") + http_if_range = headers.get("if-range") + + if http_range is None or (http_if_range is not None and not self._should_use_range(http_if_range)): + await self._handle_simple(send, send_header_only) + else: + try: + ranges = self._parse_range_header(http_range, stat_result.st_size) + except MalformedRangeHeader as exc: + return await PlainTextResponse(exc.content, status_code=400)(scope, receive, send) + except RangeNotSatisfiable as exc: + response = PlainTextResponse(status_code=416, headers={"Content-Range": f"*/{exc.max_size}"}) + return await response(scope, receive, send) + + if len(ranges) == 1: + start, end = ranges[0] + await self._handle_single_range(send, start, end, stat_result.st_size, send_header_only) + else: + await self._handle_multiple_ranges(send, ranges, stat_result.st_size, send_header_only) + + if self.background is not None: + await self.background() + + async def _handle_simple(self, send: Send, send_header_only: bool) -> None: + await send({"type": "http.response.start", "status": self.status_code, "headers": self.raw_headers}) + if send_header_only: + await send({"type": "http.response.body", "body": b"", "more_body": False}) + else: + async with await anyio.open_file(self.path, mode="rb") as file: + more_body = True + while more_body: + chunk = await file.read(self.chunk_size) + more_body = len(chunk) == self.chunk_size + await send({"type": "http.response.body", "body": chunk, "more_body": more_body}) + + async def _handle_single_range( + self, send: Send, start: int, end: int, file_size: int, send_header_only: bool + ) -> None: + self.headers["content-range"] = f"bytes {start}-{end - 1}/{file_size}" + self.headers["content-length"] = str(end - start) + await send({"type": "http.response.start", "status": 206, "headers": self.raw_headers}) + if send_header_only: + await send({"type": "http.response.body", "body": b"", "more_body": False}) + else: + async with await anyio.open_file(self.path, mode="rb") as file: + await file.seek(start) + more_body = True + while more_body: + chunk = await file.read(min(self.chunk_size, end - start)) + start += len(chunk) + more_body = len(chunk) == self.chunk_size and start < end + await send({"type": "http.response.body", "body": chunk, "more_body": more_body}) + + async def _handle_multiple_ranges( + self, + send: Send, + ranges: list[tuple[int, int]], + file_size: int, + send_header_only: bool, + ) -> None: + # In firefox and chrome, they use boundary with 95-96 bits entropy (that's roughly 13 bytes). + boundary = token_hex(13) + content_length, header_generator = self.generate_multipart( + ranges, boundary, file_size, self.headers["content-type"] + ) + self.headers["content-range"] = f"multipart/byteranges; boundary={boundary}" + self.headers["content-length"] = str(content_length) + await send({"type": "http.response.start", "status": 206, "headers": self.raw_headers}) + if send_header_only: + await send({"type": "http.response.body", "body": b"", "more_body": False}) + else: + async with await anyio.open_file(self.path, mode="rb") as file: + for start, end in ranges: + await send({"type": "http.response.body", "body": header_generator(start, end), "more_body": True}) + await file.seek(start) + while start < end: + chunk = await file.read(min(self.chunk_size, end - start)) + start += len(chunk) + await send({"type": "http.response.body", "body": chunk, "more_body": True}) + await send({"type": "http.response.body", "body": b"\n", "more_body": True}) + await send( + { + "type": "http.response.body", + "body": f"\n--{boundary}--\n".encode("latin-1"), + "more_body": False, + } + ) + + def _should_use_range(self, http_if_range: str) -> bool: + return http_if_range == self.headers["last-modified"] or http_if_range == self.headers["etag"] + + @staticmethod + def _parse_range_header(http_range: str, file_size: int) -> list[tuple[int, int]]: + ranges: list[tuple[int, int]] = [] + try: + units, range_ = http_range.split("=", 1) + except ValueError: + raise MalformedRangeHeader() + + units = units.strip().lower() + + if units != "bytes": + raise MalformedRangeHeader("Only support bytes range") + + ranges = [ + ( + int(_[0]) if _[0] else file_size - int(_[1]), + int(_[1]) + 1 if _[0] and _[1] and int(_[1]) < file_size else file_size, + ) + for _ in _RANGE_PATTERN.findall(range_) + if _ != ("", "") + ] + + if len(ranges) == 0: + raise MalformedRangeHeader("Range header: range must be requested") + + if any(not (0 <= start < file_size) for start, _ in ranges): + raise RangeNotSatisfiable(file_size) + + if any(start > end for start, end in ranges): + raise MalformedRangeHeader("Range header: start must be less than end") + + if len(ranges) == 1: + return ranges + + # Merge ranges + result: list[tuple[int, int]] = [] + for start, end in ranges: + for p in range(len(result)): + p_start, p_end = result[p] + if start > p_end: + continue + elif end < p_start: + result.insert(p, (start, end)) # THIS IS NOT REACHED! + break + else: + result[p] = (min(start, p_start), max(end, p_end)) + break + else: + result.append((start, end)) + + return result + + def generate_multipart( + self, + ranges: typing.Sequence[tuple[int, int]], + boundary: str, + max_size: int, + content_type: str, + ) -> tuple[int, typing.Callable[[int, int], bytes]]: + r""" + Multipart response headers generator. + + ``` + --{boundary}\n + Content-Type: {content_type}\n + Content-Range: bytes {start}-{end-1}/{max_size}\n + \n + ..........content...........\n + --{boundary}\n + Content-Type: {content_type}\n + Content-Range: bytes {start}-{end-1}/{max_size}\n + \n + ..........content...........\n + --{boundary}--\n + ``` + """ + boundary_len = len(boundary) + static_header_part_len = 44 + boundary_len + len(content_type) + len(str(max_size)) + content_length = sum( + (len(str(start)) + len(str(end - 1)) + static_header_part_len) # Headers + + (end - start) # Content + for start, end in ranges + ) + ( + 5 + boundary_len # --boundary--\n + ) + return ( + content_length, + lambda start, end: ( + f"--{boundary}\nContent-Type: {content_type}\nContent-Range: bytes {start}-{end - 1}/{max_size}\n\n" + ).encode("latin-1"), + ) diff --git a/venv/Lib/site-packages/starlette/routing.py b/venv/Lib/site-packages/starlette/routing.py new file mode 100644 index 00000000..add7df0c --- /dev/null +++ b/venv/Lib/site-packages/starlette/routing.py @@ -0,0 +1,874 @@ +from __future__ import annotations + +import contextlib +import functools +import inspect +import re +import traceback +import types +import typing +import warnings +from contextlib import asynccontextmanager +from enum import Enum + +from starlette._exception_handler import wrap_app_handling_exceptions +from starlette._utils import get_route_path, is_async_callable +from starlette.concurrency import run_in_threadpool +from starlette.convertors import CONVERTOR_TYPES, Convertor +from starlette.datastructures import URL, Headers, URLPath +from starlette.exceptions import HTTPException +from starlette.middleware import Middleware +from starlette.requests import Request +from starlette.responses import PlainTextResponse, RedirectResponse, Response +from starlette.types import ASGIApp, Lifespan, Receive, Scope, Send +from starlette.websockets import WebSocket, WebSocketClose + + +class NoMatchFound(Exception): + """ + Raised by `.url_for(name, **path_params)` and `.url_path_for(name, **path_params)` + if no matching route exists. + """ + + def __init__(self, name: str, path_params: dict[str, typing.Any]) -> None: + params = ", ".join(list(path_params.keys())) + super().__init__(f'No route exists for name "{name}" and params "{params}".') + + +class Match(Enum): + NONE = 0 + PARTIAL = 1 + FULL = 2 + + +def iscoroutinefunction_or_partial(obj: typing.Any) -> bool: # pragma: no cover + """ + Correctly determines if an object is a coroutine function, + including those wrapped in functools.partial objects. + """ + warnings.warn( + "iscoroutinefunction_or_partial is deprecated, and will be removed in a future release.", + DeprecationWarning, + ) + while isinstance(obj, functools.partial): + obj = obj.func + return inspect.iscoroutinefunction(obj) + + +def request_response( + func: typing.Callable[[Request], typing.Awaitable[Response] | Response], +) -> ASGIApp: + """ + Takes a function or coroutine `func(request) -> response`, + and returns an ASGI application. + """ + f: typing.Callable[[Request], typing.Awaitable[Response]] = ( + func if is_async_callable(func) else functools.partial(run_in_threadpool, func) # type:ignore + ) + + async def app(scope: Scope, receive: Receive, send: Send) -> None: + request = Request(scope, receive, send) + + async def app(scope: Scope, receive: Receive, send: Send) -> None: + response = await f(request) + await response(scope, receive, send) + + await wrap_app_handling_exceptions(app, request)(scope, receive, send) + + return app + + +def websocket_session( + func: typing.Callable[[WebSocket], typing.Awaitable[None]], +) -> ASGIApp: + """ + Takes a coroutine `func(session)`, and returns an ASGI application. + """ + # assert asyncio.iscoroutinefunction(func), "WebSocket endpoints must be async" + + async def app(scope: Scope, receive: Receive, send: Send) -> None: + session = WebSocket(scope, receive=receive, send=send) + + async def app(scope: Scope, receive: Receive, send: Send) -> None: + await func(session) + + await wrap_app_handling_exceptions(app, session)(scope, receive, send) + + return app + + +def get_name(endpoint: typing.Callable[..., typing.Any]) -> str: + return getattr(endpoint, "__name__", endpoint.__class__.__name__) + + +def replace_params( + path: str, + param_convertors: dict[str, Convertor[typing.Any]], + path_params: dict[str, str], +) -> tuple[str, dict[str, str]]: + for key, value in list(path_params.items()): + if "{" + key + "}" in path: + convertor = param_convertors[key] + value = convertor.to_string(value) + path = path.replace("{" + key + "}", value) + path_params.pop(key) + return path, path_params + + +# Match parameters in URL paths, eg. '{param}', and '{param:int}' +PARAM_REGEX = re.compile("{([a-zA-Z_][a-zA-Z0-9_]*)(:[a-zA-Z_][a-zA-Z0-9_]*)?}") + + +def compile_path( + path: str, +) -> tuple[typing.Pattern[str], str, dict[str, Convertor[typing.Any]]]: + """ + Given a path string, like: "/{username:str}", + or a host string, like: "{subdomain}.mydomain.org", return a three-tuple + of (regex, format, {param_name:convertor}). + + regex: "/(?P[^/]+)" + format: "/{username}" + convertors: {"username": StringConvertor()} + """ + is_host = not path.startswith("/") + + path_regex = "^" + path_format = "" + duplicated_params = set() + + idx = 0 + param_convertors = {} + for match in PARAM_REGEX.finditer(path): + param_name, convertor_type = match.groups("str") + convertor_type = convertor_type.lstrip(":") + assert convertor_type in CONVERTOR_TYPES, f"Unknown path convertor '{convertor_type}'" + convertor = CONVERTOR_TYPES[convertor_type] + + path_regex += re.escape(path[idx : match.start()]) + path_regex += f"(?P<{param_name}>{convertor.regex})" + + path_format += path[idx : match.start()] + path_format += "{%s}" % param_name + + if param_name in param_convertors: + duplicated_params.add(param_name) + + param_convertors[param_name] = convertor + + idx = match.end() + + if duplicated_params: + names = ", ".join(sorted(duplicated_params)) + ending = "s" if len(duplicated_params) > 1 else "" + raise ValueError(f"Duplicated param name{ending} {names} at path {path}") + + if is_host: + # Align with `Host.matches()` behavior, which ignores port. + hostname = path[idx:].split(":")[0] + path_regex += re.escape(hostname) + "$" + else: + path_regex += re.escape(path[idx:]) + "$" + + path_format += path[idx:] + + return re.compile(path_regex), path_format, param_convertors + + +class BaseRoute: + def matches(self, scope: Scope) -> tuple[Match, Scope]: + raise NotImplementedError() # pragma: no cover + + def url_path_for(self, name: str, /, **path_params: typing.Any) -> URLPath: + raise NotImplementedError() # pragma: no cover + + async def handle(self, scope: Scope, receive: Receive, send: Send) -> None: + raise NotImplementedError() # pragma: no cover + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + """ + A route may be used in isolation as a stand-alone ASGI app. + This is a somewhat contrived case, as they'll almost always be used + within a Router, but could be useful for some tooling and minimal apps. + """ + match, child_scope = self.matches(scope) + if match == Match.NONE: + if scope["type"] == "http": + response = PlainTextResponse("Not Found", status_code=404) + await response(scope, receive, send) + elif scope["type"] == "websocket": # pragma: no branch + websocket_close = WebSocketClose() + await websocket_close(scope, receive, send) + return + + scope.update(child_scope) + await self.handle(scope, receive, send) + + +class Route(BaseRoute): + def __init__( + self, + path: str, + endpoint: typing.Callable[..., typing.Any], + *, + methods: list[str] | None = None, + name: str | None = None, + include_in_schema: bool = True, + middleware: typing.Sequence[Middleware] | None = None, + ) -> None: + assert path.startswith("/"), "Routed paths must start with '/'" + self.path = path + self.endpoint = endpoint + self.name = get_name(endpoint) if name is None else name + self.include_in_schema = include_in_schema + + endpoint_handler = endpoint + while isinstance(endpoint_handler, functools.partial): + endpoint_handler = endpoint_handler.func + if inspect.isfunction(endpoint_handler) or inspect.ismethod(endpoint_handler): + # Endpoint is function or method. Treat it as `func(request) -> response`. + self.app = request_response(endpoint) + if methods is None: + methods = ["GET"] + else: + # Endpoint is a class. Treat it as ASGI. + self.app = endpoint + + if middleware is not None: + for cls, args, kwargs in reversed(middleware): + self.app = cls(self.app, *args, **kwargs) + + if methods is None: + self.methods = None + else: + self.methods = {method.upper() for method in methods} + if "GET" in self.methods: + self.methods.add("HEAD") + + self.path_regex, self.path_format, self.param_convertors = compile_path(path) + + def matches(self, scope: Scope) -> tuple[Match, Scope]: + path_params: dict[str, typing.Any] + if scope["type"] == "http": + route_path = get_route_path(scope) + match = self.path_regex.match(route_path) + if match: + matched_params = match.groupdict() + for key, value in matched_params.items(): + matched_params[key] = self.param_convertors[key].convert(value) + path_params = dict(scope.get("path_params", {})) + path_params.update(matched_params) + child_scope = {"endpoint": self.endpoint, "path_params": path_params} + if self.methods and scope["method"] not in self.methods: + return Match.PARTIAL, child_scope + else: + return Match.FULL, child_scope + return Match.NONE, {} + + def url_path_for(self, name: str, /, **path_params: typing.Any) -> URLPath: + seen_params = set(path_params.keys()) + expected_params = set(self.param_convertors.keys()) + + if name != self.name or seen_params != expected_params: + raise NoMatchFound(name, path_params) + + path, remaining_params = replace_params(self.path_format, self.param_convertors, path_params) + assert not remaining_params + return URLPath(path=path, protocol="http") + + async def handle(self, scope: Scope, receive: Receive, send: Send) -> None: + if self.methods and scope["method"] not in self.methods: + headers = {"Allow": ", ".join(self.methods)} + if "app" in scope: + raise HTTPException(status_code=405, headers=headers) + else: + response = PlainTextResponse("Method Not Allowed", status_code=405, headers=headers) + await response(scope, receive, send) + else: + await self.app(scope, receive, send) + + def __eq__(self, other: typing.Any) -> bool: + return ( + isinstance(other, Route) + and self.path == other.path + and self.endpoint == other.endpoint + and self.methods == other.methods + ) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + methods = sorted(self.methods or []) + path, name = self.path, self.name + return f"{class_name}(path={path!r}, name={name!r}, methods={methods!r})" + + +class WebSocketRoute(BaseRoute): + def __init__( + self, + path: str, + endpoint: typing.Callable[..., typing.Any], + *, + name: str | None = None, + middleware: typing.Sequence[Middleware] | None = None, + ) -> None: + assert path.startswith("/"), "Routed paths must start with '/'" + self.path = path + self.endpoint = endpoint + self.name = get_name(endpoint) if name is None else name + + endpoint_handler = endpoint + while isinstance(endpoint_handler, functools.partial): + endpoint_handler = endpoint_handler.func + if inspect.isfunction(endpoint_handler) or inspect.ismethod(endpoint_handler): + # Endpoint is function or method. Treat it as `func(websocket)`. + self.app = websocket_session(endpoint) + else: + # Endpoint is a class. Treat it as ASGI. + self.app = endpoint + + if middleware is not None: + for cls, args, kwargs in reversed(middleware): + self.app = cls(self.app, *args, **kwargs) + + self.path_regex, self.path_format, self.param_convertors = compile_path(path) + + def matches(self, scope: Scope) -> tuple[Match, Scope]: + path_params: dict[str, typing.Any] + if scope["type"] == "websocket": + route_path = get_route_path(scope) + match = self.path_regex.match(route_path) + if match: + matched_params = match.groupdict() + for key, value in matched_params.items(): + matched_params[key] = self.param_convertors[key].convert(value) + path_params = dict(scope.get("path_params", {})) + path_params.update(matched_params) + child_scope = {"endpoint": self.endpoint, "path_params": path_params} + return Match.FULL, child_scope + return Match.NONE, {} + + def url_path_for(self, name: str, /, **path_params: typing.Any) -> URLPath: + seen_params = set(path_params.keys()) + expected_params = set(self.param_convertors.keys()) + + if name != self.name or seen_params != expected_params: + raise NoMatchFound(name, path_params) + + path, remaining_params = replace_params(self.path_format, self.param_convertors, path_params) + assert not remaining_params + return URLPath(path=path, protocol="websocket") + + async def handle(self, scope: Scope, receive: Receive, send: Send) -> None: + await self.app(scope, receive, send) + + def __eq__(self, other: typing.Any) -> bool: + return isinstance(other, WebSocketRoute) and self.path == other.path and self.endpoint == other.endpoint + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(path={self.path!r}, name={self.name!r})" + + +class Mount(BaseRoute): + def __init__( + self, + path: str, + app: ASGIApp | None = None, + routes: typing.Sequence[BaseRoute] | None = None, + name: str | None = None, + *, + middleware: typing.Sequence[Middleware] | None = None, + ) -> None: + assert path == "" or path.startswith("/"), "Routed paths must start with '/'" + assert app is not None or routes is not None, "Either 'app=...', or 'routes=' must be specified" + self.path = path.rstrip("/") + if app is not None: + self._base_app: ASGIApp = app + else: + self._base_app = Router(routes=routes) + self.app = self._base_app + if middleware is not None: + for cls, args, kwargs in reversed(middleware): + self.app = cls(self.app, *args, **kwargs) + self.name = name + self.path_regex, self.path_format, self.param_convertors = compile_path(self.path + "/{path:path}") + + @property + def routes(self) -> list[BaseRoute]: + return getattr(self._base_app, "routes", []) + + def matches(self, scope: Scope) -> tuple[Match, Scope]: + path_params: dict[str, typing.Any] + if scope["type"] in ("http", "websocket"): # pragma: no branch + root_path = scope.get("root_path", "") + route_path = get_route_path(scope) + match = self.path_regex.match(route_path) + if match: + matched_params = match.groupdict() + for key, value in matched_params.items(): + matched_params[key] = self.param_convertors[key].convert(value) + remaining_path = "/" + matched_params.pop("path") + matched_path = route_path[: -len(remaining_path)] + path_params = dict(scope.get("path_params", {})) + path_params.update(matched_params) + child_scope = { + "path_params": path_params, + # app_root_path will only be set at the top level scope, + # initialized with the (optional) value of a root_path + # set above/before Starlette. And even though any + # mount will have its own child scope with its own respective + # root_path, the app_root_path will always be available in all + # the child scopes with the same top level value because it's + # set only once here with a default, any other child scope will + # just inherit that app_root_path default value stored in the + # scope. All this is needed to support Request.url_for(), as it + # uses the app_root_path to build the URL path. + "app_root_path": scope.get("app_root_path", root_path), + "root_path": root_path + matched_path, + "endpoint": self.app, + } + return Match.FULL, child_scope + return Match.NONE, {} + + def url_path_for(self, name: str, /, **path_params: typing.Any) -> URLPath: + if self.name is not None and name == self.name and "path" in path_params: + # 'name' matches "". + path_params["path"] = path_params["path"].lstrip("/") + path, remaining_params = replace_params(self.path_format, self.param_convertors, path_params) + if not remaining_params: + return URLPath(path=path) + elif self.name is None or name.startswith(self.name + ":"): + if self.name is None: + # No mount name. + remaining_name = name + else: + # 'name' matches ":". + remaining_name = name[len(self.name) + 1 :] + path_kwarg = path_params.get("path") + path_params["path"] = "" + path_prefix, remaining_params = replace_params(self.path_format, self.param_convertors, path_params) + if path_kwarg is not None: + remaining_params["path"] = path_kwarg + for route in self.routes or []: + try: + url = route.url_path_for(remaining_name, **remaining_params) + return URLPath(path=path_prefix.rstrip("/") + str(url), protocol=url.protocol) + except NoMatchFound: + pass + raise NoMatchFound(name, path_params) + + async def handle(self, scope: Scope, receive: Receive, send: Send) -> None: + await self.app(scope, receive, send) + + def __eq__(self, other: typing.Any) -> bool: + return isinstance(other, Mount) and self.path == other.path and self.app == other.app + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + name = self.name or "" + return f"{class_name}(path={self.path!r}, name={name!r}, app={self.app!r})" + + +class Host(BaseRoute): + def __init__(self, host: str, app: ASGIApp, name: str | None = None) -> None: + assert not host.startswith("/"), "Host must not start with '/'" + self.host = host + self.app = app + self.name = name + self.host_regex, self.host_format, self.param_convertors = compile_path(host) + + @property + def routes(self) -> list[BaseRoute]: + return getattr(self.app, "routes", []) + + def matches(self, scope: Scope) -> tuple[Match, Scope]: + if scope["type"] in ("http", "websocket"): # pragma:no branch + headers = Headers(scope=scope) + host = headers.get("host", "").split(":")[0] + match = self.host_regex.match(host) + if match: + matched_params = match.groupdict() + for key, value in matched_params.items(): + matched_params[key] = self.param_convertors[key].convert(value) + path_params = dict(scope.get("path_params", {})) + path_params.update(matched_params) + child_scope = {"path_params": path_params, "endpoint": self.app} + return Match.FULL, child_scope + return Match.NONE, {} + + def url_path_for(self, name: str, /, **path_params: typing.Any) -> URLPath: + if self.name is not None and name == self.name and "path" in path_params: + # 'name' matches "". + path = path_params.pop("path") + host, remaining_params = replace_params(self.host_format, self.param_convertors, path_params) + if not remaining_params: + return URLPath(path=path, host=host) + elif self.name is None or name.startswith(self.name + ":"): + if self.name is None: + # No mount name. + remaining_name = name + else: + # 'name' matches ":". + remaining_name = name[len(self.name) + 1 :] + host, remaining_params = replace_params(self.host_format, self.param_convertors, path_params) + for route in self.routes or []: + try: + url = route.url_path_for(remaining_name, **remaining_params) + return URLPath(path=str(url), protocol=url.protocol, host=host) + except NoMatchFound: + pass + raise NoMatchFound(name, path_params) + + async def handle(self, scope: Scope, receive: Receive, send: Send) -> None: + await self.app(scope, receive, send) + + def __eq__(self, other: typing.Any) -> bool: + return isinstance(other, Host) and self.host == other.host and self.app == other.app + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + name = self.name or "" + return f"{class_name}(host={self.host!r}, name={name!r}, app={self.app!r})" + + +_T = typing.TypeVar("_T") + + +class _AsyncLiftContextManager(typing.AsyncContextManager[_T]): + def __init__(self, cm: typing.ContextManager[_T]): + self._cm = cm + + async def __aenter__(self) -> _T: + return self._cm.__enter__() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: types.TracebackType | None, + ) -> bool | None: + return self._cm.__exit__(exc_type, exc_value, traceback) + + +def _wrap_gen_lifespan_context( + lifespan_context: typing.Callable[[typing.Any], typing.Generator[typing.Any, typing.Any, typing.Any]], +) -> typing.Callable[[typing.Any], typing.AsyncContextManager[typing.Any]]: + cmgr = contextlib.contextmanager(lifespan_context) + + @functools.wraps(cmgr) + def wrapper(app: typing.Any) -> _AsyncLiftContextManager[typing.Any]: + return _AsyncLiftContextManager(cmgr(app)) + + return wrapper + + +class _DefaultLifespan: + def __init__(self, router: Router): + self._router = router + + async def __aenter__(self) -> None: + await self._router.startup() + + async def __aexit__(self, *exc_info: object) -> None: + await self._router.shutdown() + + def __call__(self: _T, app: object) -> _T: + return self + + +class Router: + def __init__( + self, + routes: typing.Sequence[BaseRoute] | None = None, + redirect_slashes: bool = True, + default: ASGIApp | None = None, + on_startup: typing.Sequence[typing.Callable[[], typing.Any]] | None = None, + on_shutdown: typing.Sequence[typing.Callable[[], typing.Any]] | None = None, + # the generic to Lifespan[AppType] is the type of the top level application + # which the router cannot know statically, so we use typing.Any + lifespan: Lifespan[typing.Any] | None = None, + *, + middleware: typing.Sequence[Middleware] | None = None, + ) -> None: + self.routes = [] if routes is None else list(routes) + self.redirect_slashes = redirect_slashes + self.default = self.not_found if default is None else default + self.on_startup = [] if on_startup is None else list(on_startup) + self.on_shutdown = [] if on_shutdown is None else list(on_shutdown) + + if on_startup or on_shutdown: + warnings.warn( + "The on_startup and on_shutdown parameters are deprecated, and they " + "will be removed on version 1.0. Use the lifespan parameter instead. " + "See more about it on https://www.starlette.io/lifespan/.", + DeprecationWarning, + ) + if lifespan: + warnings.warn( + "The `lifespan` parameter cannot be used with `on_startup` or " + "`on_shutdown`. Both `on_startup` and `on_shutdown` will be " + "ignored." + ) + + if lifespan is None: + self.lifespan_context: Lifespan[typing.Any] = _DefaultLifespan(self) + + elif inspect.isasyncgenfunction(lifespan): + warnings.warn( + "async generator function lifespans are deprecated, " + "use an @contextlib.asynccontextmanager function instead", + DeprecationWarning, + ) + self.lifespan_context = asynccontextmanager( + lifespan, + ) + elif inspect.isgeneratorfunction(lifespan): + warnings.warn( + "generator function lifespans are deprecated, use an @contextlib.asynccontextmanager function instead", + DeprecationWarning, + ) + self.lifespan_context = _wrap_gen_lifespan_context( + lifespan, + ) + else: + self.lifespan_context = lifespan + + self.middleware_stack = self.app + if middleware: + for cls, args, kwargs in reversed(middleware): + self.middleware_stack = cls(self.middleware_stack, *args, **kwargs) + + async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] == "websocket": + websocket_close = WebSocketClose() + await websocket_close(scope, receive, send) + return + + # If we're running inside a starlette application then raise an + # exception, so that the configurable exception handler can deal with + # returning the response. For plain ASGI apps, just return the response. + if "app" in scope: + raise HTTPException(status_code=404) + else: + response = PlainTextResponse("Not Found", status_code=404) + await response(scope, receive, send) + + def url_path_for(self, name: str, /, **path_params: typing.Any) -> URLPath: + for route in self.routes: + try: + return route.url_path_for(name, **path_params) + except NoMatchFound: + pass + raise NoMatchFound(name, path_params) + + async def startup(self) -> None: + """ + Run any `.on_startup` event handlers. + """ + for handler in self.on_startup: + if is_async_callable(handler): + await handler() + else: + handler() + + async def shutdown(self) -> None: + """ + Run any `.on_shutdown` event handlers. + """ + for handler in self.on_shutdown: + if is_async_callable(handler): + await handler() + else: + handler() + + async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None: + """ + Handle ASGI lifespan messages, which allows us to manage application + startup and shutdown events. + """ + started = False + app: typing.Any = scope.get("app") + await receive() + try: + async with self.lifespan_context(app) as maybe_state: + if maybe_state is not None: + if "state" not in scope: + raise RuntimeError('The server does not support "state" in the lifespan scope.') + scope["state"].update(maybe_state) + await send({"type": "lifespan.startup.complete"}) + started = True + await receive() + except BaseException: + exc_text = traceback.format_exc() + if started: + await send({"type": "lifespan.shutdown.failed", "message": exc_text}) + else: + await send({"type": "lifespan.startup.failed", "message": exc_text}) + raise + else: + await send({"type": "lifespan.shutdown.complete"}) + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + """ + The main entry point to the Router class. + """ + await self.middleware_stack(scope, receive, send) + + async def app(self, scope: Scope, receive: Receive, send: Send) -> None: + assert scope["type"] in ("http", "websocket", "lifespan") + + if "router" not in scope: + scope["router"] = self + + if scope["type"] == "lifespan": + await self.lifespan(scope, receive, send) + return + + partial = None + + for route in self.routes: + # Determine if any route matches the incoming scope, + # and hand over to the matching route if found. + match, child_scope = route.matches(scope) + if match == Match.FULL: + scope.update(child_scope) + await route.handle(scope, receive, send) + return + elif match == Match.PARTIAL and partial is None: + partial = route + partial_scope = child_scope + + if partial is not None: + #  Handle partial matches. These are cases where an endpoint is + # able to handle the request, but is not a preferred option. + # We use this in particular to deal with "405 Method Not Allowed". + scope.update(partial_scope) + await partial.handle(scope, receive, send) + return + + route_path = get_route_path(scope) + if scope["type"] == "http" and self.redirect_slashes and route_path != "/": + redirect_scope = dict(scope) + if route_path.endswith("/"): + redirect_scope["path"] = redirect_scope["path"].rstrip("/") + else: + redirect_scope["path"] = redirect_scope["path"] + "/" + + for route in self.routes: + match, child_scope = route.matches(redirect_scope) + if match != Match.NONE: + redirect_url = URL(scope=redirect_scope) + response = RedirectResponse(url=str(redirect_url)) + await response(scope, receive, send) + return + + await self.default(scope, receive, send) + + def __eq__(self, other: typing.Any) -> bool: + return isinstance(other, Router) and self.routes == other.routes + + def mount(self, path: str, app: ASGIApp, name: str | None = None) -> None: # pragma: no cover + route = Mount(path, app=app, name=name) + self.routes.append(route) + + def host(self, host: str, app: ASGIApp, name: str | None = None) -> None: # pragma: no cover + route = Host(host, app=app, name=name) + self.routes.append(route) + + def add_route( + self, + path: str, + endpoint: typing.Callable[[Request], typing.Awaitable[Response] | Response], + methods: list[str] | None = None, + name: str | None = None, + include_in_schema: bool = True, + ) -> None: # pragma: no cover + route = Route( + path, + endpoint=endpoint, + methods=methods, + name=name, + include_in_schema=include_in_schema, + ) + self.routes.append(route) + + def add_websocket_route( + self, + path: str, + endpoint: typing.Callable[[WebSocket], typing.Awaitable[None]], + name: str | None = None, + ) -> None: # pragma: no cover + route = WebSocketRoute(path, endpoint=endpoint, name=name) + self.routes.append(route) + + def route( + self, + path: str, + methods: list[str] | None = None, + name: str | None = None, + include_in_schema: bool = True, + ) -> typing.Callable: # type: ignore[type-arg] + """ + We no longer document this decorator style API, and its usage is discouraged. + Instead you should use the following approach: + + >>> routes = [Route(path, endpoint=...), ...] + >>> app = Starlette(routes=routes) + """ + warnings.warn( + "The `route` decorator is deprecated, and will be removed in version 1.0.0." + "Refer to https://www.starlette.io/routing/#http-routing for the recommended approach.", + DeprecationWarning, + ) + + def decorator(func: typing.Callable) -> typing.Callable: # type: ignore[type-arg] + self.add_route( + path, + func, + methods=methods, + name=name, + include_in_schema=include_in_schema, + ) + return func + + return decorator + + def websocket_route(self, path: str, name: str | None = None) -> typing.Callable: # type: ignore[type-arg] + """ + We no longer document this decorator style API, and its usage is discouraged. + Instead you should use the following approach: + + >>> routes = [WebSocketRoute(path, endpoint=...), ...] + >>> app = Starlette(routes=routes) + """ + warnings.warn( + "The `websocket_route` decorator is deprecated, and will be removed in version 1.0.0. Refer to " + "https://www.starlette.io/routing/#websocket-routing for the recommended approach.", + DeprecationWarning, + ) + + def decorator(func: typing.Callable) -> typing.Callable: # type: ignore[type-arg] + self.add_websocket_route(path, func, name=name) + return func + + return decorator + + def add_event_handler(self, event_type: str, func: typing.Callable[[], typing.Any]) -> None: # pragma: no cover + assert event_type in ("startup", "shutdown") + + if event_type == "startup": + self.on_startup.append(func) + else: + self.on_shutdown.append(func) + + def on_event(self, event_type: str) -> typing.Callable: # type: ignore[type-arg] + warnings.warn( + "The `on_event` decorator is deprecated, and will be removed in version 1.0.0. " + "Refer to https://www.starlette.io/lifespan/ for recommended approach.", + DeprecationWarning, + ) + + def decorator(func: typing.Callable) -> typing.Callable: # type: ignore[type-arg] + self.add_event_handler(event_type, func) + return func + + return decorator diff --git a/venv/Lib/site-packages/starlette/schemas.py b/venv/Lib/site-packages/starlette/schemas.py new file mode 100644 index 00000000..bfc40e2a --- /dev/null +++ b/venv/Lib/site-packages/starlette/schemas.py @@ -0,0 +1,147 @@ +from __future__ import annotations + +import inspect +import re +import typing + +from starlette.requests import Request +from starlette.responses import Response +from starlette.routing import BaseRoute, Host, Mount, Route + +try: + import yaml +except ModuleNotFoundError: # pragma: no cover + yaml = None # type: ignore[assignment] + + +class OpenAPIResponse(Response): + media_type = "application/vnd.oai.openapi" + + def render(self, content: typing.Any) -> bytes: + assert yaml is not None, "`pyyaml` must be installed to use OpenAPIResponse." + assert isinstance(content, dict), "The schema passed to OpenAPIResponse should be a dictionary." + return yaml.dump(content, default_flow_style=False).encode("utf-8") + + +class EndpointInfo(typing.NamedTuple): + path: str + http_method: str + func: typing.Callable[..., typing.Any] + + +_remove_converter_pattern = re.compile(r":\w+}") + + +class BaseSchemaGenerator: + def get_schema(self, routes: list[BaseRoute]) -> dict[str, typing.Any]: + raise NotImplementedError() # pragma: no cover + + def get_endpoints(self, routes: list[BaseRoute]) -> list[EndpointInfo]: + """ + Given the routes, yields the following information: + + - path + eg: /users/ + - http_method + one of 'get', 'post', 'put', 'patch', 'delete', 'options' + - func + method ready to extract the docstring + """ + endpoints_info: list[EndpointInfo] = [] + + for route in routes: + if isinstance(route, (Mount, Host)): + routes = route.routes or [] + if isinstance(route, Mount): + path = self._remove_converter(route.path) + else: + path = "" + sub_endpoints = [ + EndpointInfo( + path="".join((path, sub_endpoint.path)), + http_method=sub_endpoint.http_method, + func=sub_endpoint.func, + ) + for sub_endpoint in self.get_endpoints(routes) + ] + endpoints_info.extend(sub_endpoints) + + elif not isinstance(route, Route) or not route.include_in_schema: + continue + + elif inspect.isfunction(route.endpoint) or inspect.ismethod(route.endpoint): + path = self._remove_converter(route.path) + for method in route.methods or ["GET"]: + if method == "HEAD": + continue + endpoints_info.append(EndpointInfo(path, method.lower(), route.endpoint)) + else: + path = self._remove_converter(route.path) + for method in ["get", "post", "put", "patch", "delete", "options"]: + if not hasattr(route.endpoint, method): + continue + func = getattr(route.endpoint, method) + endpoints_info.append(EndpointInfo(path, method.lower(), func)) + + return endpoints_info + + def _remove_converter(self, path: str) -> str: + """ + Remove the converter from the path. + For example, a route like this: + Route("/users/{id:int}", endpoint=get_user, methods=["GET"]) + Should be represented as `/users/{id}` in the OpenAPI schema. + """ + return _remove_converter_pattern.sub("}", path) + + def parse_docstring(self, func_or_method: typing.Callable[..., typing.Any]) -> dict[str, typing.Any]: + """ + Given a function, parse the docstring as YAML and return a dictionary of info. + """ + docstring = func_or_method.__doc__ + if not docstring: + return {} + + assert yaml is not None, "`pyyaml` must be installed to use parse_docstring." + + # We support having regular docstrings before the schema + # definition. Here we return just the schema part from + # the docstring. + docstring = docstring.split("---")[-1] + + parsed = yaml.safe_load(docstring) + + if not isinstance(parsed, dict): + # A regular docstring (not yaml formatted) can return + # a simple string here, which wouldn't follow the schema. + return {} + + return parsed + + def OpenAPIResponse(self, request: Request) -> Response: + routes = request.app.routes + schema = self.get_schema(routes=routes) + return OpenAPIResponse(schema) + + +class SchemaGenerator(BaseSchemaGenerator): + def __init__(self, base_schema: dict[str, typing.Any]) -> None: + self.base_schema = base_schema + + def get_schema(self, routes: list[BaseRoute]) -> dict[str, typing.Any]: + schema = dict(self.base_schema) + schema.setdefault("paths", {}) + endpoints_info = self.get_endpoints(routes) + + for endpoint in endpoints_info: + parsed = self.parse_docstring(endpoint.func) + + if not parsed: + continue + + if endpoint.path not in schema["paths"]: + schema["paths"][endpoint.path] = {} + + schema["paths"][endpoint.path][endpoint.http_method] = parsed + + return schema diff --git a/venv/Lib/site-packages/starlette/staticfiles.py b/venv/Lib/site-packages/starlette/staticfiles.py new file mode 100644 index 00000000..637da648 --- /dev/null +++ b/venv/Lib/site-packages/starlette/staticfiles.py @@ -0,0 +1,220 @@ +from __future__ import annotations + +import errno +import importlib.util +import os +import stat +import typing +from email.utils import parsedate + +import anyio +import anyio.to_thread + +from starlette._utils import get_route_path +from starlette.datastructures import URL, Headers +from starlette.exceptions import HTTPException +from starlette.responses import FileResponse, RedirectResponse, Response +from starlette.types import Receive, Scope, Send + +PathLike = typing.Union[str, "os.PathLike[str]"] + + +class NotModifiedResponse(Response): + NOT_MODIFIED_HEADERS = ( + "cache-control", + "content-location", + "date", + "etag", + "expires", + "vary", + ) + + def __init__(self, headers: Headers): + super().__init__( + status_code=304, + headers={name: value for name, value in headers.items() if name in self.NOT_MODIFIED_HEADERS}, + ) + + +class StaticFiles: + def __init__( + self, + *, + directory: PathLike | None = None, + packages: list[str | tuple[str, str]] | None = None, + html: bool = False, + check_dir: bool = True, + follow_symlink: bool = False, + ) -> None: + self.directory = directory + self.packages = packages + self.all_directories = self.get_directories(directory, packages) + self.html = html + self.config_checked = False + self.follow_symlink = follow_symlink + if check_dir and directory is not None and not os.path.isdir(directory): + raise RuntimeError(f"Directory '{directory}' does not exist") + + def get_directories( + self, + directory: PathLike | None = None, + packages: list[str | tuple[str, str]] | None = None, + ) -> list[PathLike]: + """ + Given `directory` and `packages` arguments, return a list of all the + directories that should be used for serving static files from. + """ + directories = [] + if directory is not None: + directories.append(directory) + + for package in packages or []: + if isinstance(package, tuple): + package, statics_dir = package + else: + statics_dir = "statics" + spec = importlib.util.find_spec(package) + assert spec is not None, f"Package {package!r} could not be found." + assert spec.origin is not None, f"Package {package!r} could not be found." + package_directory = os.path.normpath(os.path.join(spec.origin, "..", statics_dir)) + assert os.path.isdir(package_directory), ( + f"Directory '{statics_dir!r}' in package {package!r} could not be found." + ) + directories.append(package_directory) + + return directories + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + """ + The ASGI entry point. + """ + assert scope["type"] == "http" + + if not self.config_checked: + await self.check_config() + self.config_checked = True + + path = self.get_path(scope) + response = await self.get_response(path, scope) + await response(scope, receive, send) + + def get_path(self, scope: Scope) -> str: + """ + Given the ASGI scope, return the `path` string to serve up, + with OS specific path separators, and any '..', '.' components removed. + """ + route_path = get_route_path(scope) + return os.path.normpath(os.path.join(*route_path.split("/"))) + + async def get_response(self, path: str, scope: Scope) -> Response: + """ + Returns an HTTP response, given the incoming path, method and request headers. + """ + if scope["method"] not in ("GET", "HEAD"): + raise HTTPException(status_code=405) + + try: + full_path, stat_result = await anyio.to_thread.run_sync(self.lookup_path, path) + except PermissionError: + raise HTTPException(status_code=401) + except OSError as exc: + # Filename is too long, so it can't be a valid static file. + if exc.errno == errno.ENAMETOOLONG: + raise HTTPException(status_code=404) + + raise exc + + if stat_result and stat.S_ISREG(stat_result.st_mode): + # We have a static file to serve. + return self.file_response(full_path, stat_result, scope) + + elif stat_result and stat.S_ISDIR(stat_result.st_mode) and self.html: + # We're in HTML mode, and have got a directory URL. + # Check if we have 'index.html' file to serve. + index_path = os.path.join(path, "index.html") + full_path, stat_result = await anyio.to_thread.run_sync(self.lookup_path, index_path) + if stat_result is not None and stat.S_ISREG(stat_result.st_mode): + if not scope["path"].endswith("/"): + # Directory URLs should redirect to always end in "/". + url = URL(scope=scope) + url = url.replace(path=url.path + "/") + return RedirectResponse(url=url) + return self.file_response(full_path, stat_result, scope) + + if self.html: + # Check for '404.html' if we're in HTML mode. + full_path, stat_result = await anyio.to_thread.run_sync(self.lookup_path, "404.html") + if stat_result and stat.S_ISREG(stat_result.st_mode): + return FileResponse(full_path, stat_result=stat_result, status_code=404) + raise HTTPException(status_code=404) + + def lookup_path(self, path: str) -> tuple[str, os.stat_result | None]: + for directory in self.all_directories: + joined_path = os.path.join(directory, path) + if self.follow_symlink: + full_path = os.path.abspath(joined_path) + directory = os.path.abspath(directory) + else: + full_path = os.path.realpath(joined_path) + directory = os.path.realpath(directory) + if os.path.commonpath([full_path, directory]) != str(directory): + # Don't allow misbehaving clients to break out of the static files directory. + continue + try: + return full_path, os.stat(full_path) + except (FileNotFoundError, NotADirectoryError): + continue + return "", None + + def file_response( + self, + full_path: PathLike, + stat_result: os.stat_result, + scope: Scope, + status_code: int = 200, + ) -> Response: + request_headers = Headers(scope=scope) + + response = FileResponse(full_path, status_code=status_code, stat_result=stat_result) + if self.is_not_modified(response.headers, request_headers): + return NotModifiedResponse(response.headers) + return response + + async def check_config(self) -> None: + """ + Perform a one-off configuration check that StaticFiles is actually + pointed at a directory, so that we can raise loud errors rather than + just returning 404 responses. + """ + if self.directory is None: + return + + try: + stat_result = await anyio.to_thread.run_sync(os.stat, self.directory) + except FileNotFoundError: + raise RuntimeError(f"StaticFiles directory '{self.directory}' does not exist.") + if not (stat.S_ISDIR(stat_result.st_mode) or stat.S_ISLNK(stat_result.st_mode)): + raise RuntimeError(f"StaticFiles path '{self.directory}' is not a directory.") + + def is_not_modified(self, response_headers: Headers, request_headers: Headers) -> bool: + """ + Given the request and response headers, return `True` if an HTTP + "Not Modified" response could be returned instead. + """ + try: + if_none_match = request_headers["if-none-match"] + etag = response_headers["etag"] + if etag in [tag.strip(" W/") for tag in if_none_match.split(",")]: + return True + except KeyError: + pass + + try: + if_modified_since = parsedate(request_headers["if-modified-since"]) + last_modified = parsedate(response_headers["last-modified"]) + if if_modified_since is not None and last_modified is not None and if_modified_since >= last_modified: + return True + except KeyError: + pass + + return False diff --git a/venv/Lib/site-packages/starlette/status.py b/venv/Lib/site-packages/starlette/status.py new file mode 100644 index 00000000..54c1fb7d --- /dev/null +++ b/venv/Lib/site-packages/starlette/status.py @@ -0,0 +1,95 @@ +""" +HTTP codes +See HTTP Status Code Registry: +https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml + +And RFC 2324 - https://tools.ietf.org/html/rfc2324 +""" + +from __future__ import annotations + +HTTP_100_CONTINUE = 100 +HTTP_101_SWITCHING_PROTOCOLS = 101 +HTTP_102_PROCESSING = 102 +HTTP_103_EARLY_HINTS = 103 +HTTP_200_OK = 200 +HTTP_201_CREATED = 201 +HTTP_202_ACCEPTED = 202 +HTTP_203_NON_AUTHORITATIVE_INFORMATION = 203 +HTTP_204_NO_CONTENT = 204 +HTTP_205_RESET_CONTENT = 205 +HTTP_206_PARTIAL_CONTENT = 206 +HTTP_207_MULTI_STATUS = 207 +HTTP_208_ALREADY_REPORTED = 208 +HTTP_226_IM_USED = 226 +HTTP_300_MULTIPLE_CHOICES = 300 +HTTP_301_MOVED_PERMANENTLY = 301 +HTTP_302_FOUND = 302 +HTTP_303_SEE_OTHER = 303 +HTTP_304_NOT_MODIFIED = 304 +HTTP_305_USE_PROXY = 305 +HTTP_306_RESERVED = 306 +HTTP_307_TEMPORARY_REDIRECT = 307 +HTTP_308_PERMANENT_REDIRECT = 308 +HTTP_400_BAD_REQUEST = 400 +HTTP_401_UNAUTHORIZED = 401 +HTTP_402_PAYMENT_REQUIRED = 402 +HTTP_403_FORBIDDEN = 403 +HTTP_404_NOT_FOUND = 404 +HTTP_405_METHOD_NOT_ALLOWED = 405 +HTTP_406_NOT_ACCEPTABLE = 406 +HTTP_407_PROXY_AUTHENTICATION_REQUIRED = 407 +HTTP_408_REQUEST_TIMEOUT = 408 +HTTP_409_CONFLICT = 409 +HTTP_410_GONE = 410 +HTTP_411_LENGTH_REQUIRED = 411 +HTTP_412_PRECONDITION_FAILED = 412 +HTTP_413_REQUEST_ENTITY_TOO_LARGE = 413 +HTTP_414_REQUEST_URI_TOO_LONG = 414 +HTTP_415_UNSUPPORTED_MEDIA_TYPE = 415 +HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE = 416 +HTTP_417_EXPECTATION_FAILED = 417 +HTTP_418_IM_A_TEAPOT = 418 +HTTP_421_MISDIRECTED_REQUEST = 421 +HTTP_422_UNPROCESSABLE_ENTITY = 422 +HTTP_423_LOCKED = 423 +HTTP_424_FAILED_DEPENDENCY = 424 +HTTP_425_TOO_EARLY = 425 +HTTP_426_UPGRADE_REQUIRED = 426 +HTTP_428_PRECONDITION_REQUIRED = 428 +HTTP_429_TOO_MANY_REQUESTS = 429 +HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE = 431 +HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS = 451 +HTTP_500_INTERNAL_SERVER_ERROR = 500 +HTTP_501_NOT_IMPLEMENTED = 501 +HTTP_502_BAD_GATEWAY = 502 +HTTP_503_SERVICE_UNAVAILABLE = 503 +HTTP_504_GATEWAY_TIMEOUT = 504 +HTTP_505_HTTP_VERSION_NOT_SUPPORTED = 505 +HTTP_506_VARIANT_ALSO_NEGOTIATES = 506 +HTTP_507_INSUFFICIENT_STORAGE = 507 +HTTP_508_LOOP_DETECTED = 508 +HTTP_510_NOT_EXTENDED = 510 +HTTP_511_NETWORK_AUTHENTICATION_REQUIRED = 511 + + +""" +WebSocket codes +https://www.iana.org/assignments/websocket/websocket.xml#close-code-number +https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent +""" +WS_1000_NORMAL_CLOSURE = 1000 +WS_1001_GOING_AWAY = 1001 +WS_1002_PROTOCOL_ERROR = 1002 +WS_1003_UNSUPPORTED_DATA = 1003 +WS_1005_NO_STATUS_RCVD = 1005 +WS_1006_ABNORMAL_CLOSURE = 1006 +WS_1007_INVALID_FRAME_PAYLOAD_DATA = 1007 +WS_1008_POLICY_VIOLATION = 1008 +WS_1009_MESSAGE_TOO_BIG = 1009 +WS_1010_MANDATORY_EXT = 1010 +WS_1011_INTERNAL_ERROR = 1011 +WS_1012_SERVICE_RESTART = 1012 +WS_1013_TRY_AGAIN_LATER = 1013 +WS_1014_BAD_GATEWAY = 1014 +WS_1015_TLS_HANDSHAKE = 1015 diff --git a/venv/Lib/site-packages/starlette/templating.py b/venv/Lib/site-packages/starlette/templating.py new file mode 100644 index 00000000..f764858b --- /dev/null +++ b/venv/Lib/site-packages/starlette/templating.py @@ -0,0 +1,216 @@ +from __future__ import annotations + +import typing +import warnings +from os import PathLike + +from starlette.background import BackgroundTask +from starlette.datastructures import URL +from starlette.requests import Request +from starlette.responses import HTMLResponse +from starlette.types import Receive, Scope, Send + +try: + import jinja2 + + # @contextfunction was renamed to @pass_context in Jinja 3.0, and was removed in 3.1 + # hence we try to get pass_context (most installs will be >=3.1) + # and fall back to contextfunction, + # adding a type ignore for mypy to let us access an attribute that may not exist + if hasattr(jinja2, "pass_context"): + pass_context = jinja2.pass_context + else: # pragma: no cover + pass_context = jinja2.contextfunction # type: ignore[attr-defined] +except ModuleNotFoundError: # pragma: no cover + jinja2 = None # type: ignore[assignment] + + +class _TemplateResponse(HTMLResponse): + def __init__( + self, + template: typing.Any, + context: dict[str, typing.Any], + status_code: int = 200, + headers: typing.Mapping[str, str] | None = None, + media_type: str | None = None, + background: BackgroundTask | None = None, + ): + self.template = template + self.context = context + content = template.render(context) + super().__init__(content, status_code, headers, media_type, background) + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + request = self.context.get("request", {}) + extensions = request.get("extensions", {}) + if "http.response.debug" in extensions: # pragma: no branch + await send( + { + "type": "http.response.debug", + "info": { + "template": self.template, + "context": self.context, + }, + } + ) + await super().__call__(scope, receive, send) + + +class Jinja2Templates: + """ + templates = Jinja2Templates("templates") + + return templates.TemplateResponse("index.html", {"request": request}) + """ + + @typing.overload + def __init__( + self, + directory: str | PathLike[str] | typing.Sequence[str | PathLike[str]], + *, + context_processors: list[typing.Callable[[Request], dict[str, typing.Any]]] | None = None, + **env_options: typing.Any, + ) -> None: ... + + @typing.overload + def __init__( + self, + *, + env: jinja2.Environment, + context_processors: list[typing.Callable[[Request], dict[str, typing.Any]]] | None = None, + ) -> None: ... + + def __init__( + self, + directory: str | PathLike[str] | typing.Sequence[str | PathLike[str]] | None = None, + *, + context_processors: list[typing.Callable[[Request], dict[str, typing.Any]]] | None = None, + env: jinja2.Environment | None = None, + **env_options: typing.Any, + ) -> None: + if env_options: + warnings.warn( + "Extra environment options are deprecated. Use a preconfigured jinja2.Environment instead.", + DeprecationWarning, + ) + assert jinja2 is not None, "jinja2 must be installed to use Jinja2Templates" + assert bool(directory) ^ bool(env), "either 'directory' or 'env' arguments must be passed" + self.context_processors = context_processors or [] + if directory is not None: + self.env = self._create_env(directory, **env_options) + elif env is not None: # pragma: no branch + self.env = env + + self._setup_env_defaults(self.env) + + def _create_env( + self, + directory: str | PathLike[str] | typing.Sequence[str | PathLike[str]], + **env_options: typing.Any, + ) -> jinja2.Environment: + loader = jinja2.FileSystemLoader(directory) + env_options.setdefault("loader", loader) + env_options.setdefault("autoescape", True) + + return jinja2.Environment(**env_options) + + def _setup_env_defaults(self, env: jinja2.Environment) -> None: + @pass_context + def url_for( + context: dict[str, typing.Any], + name: str, + /, + **path_params: typing.Any, + ) -> URL: + request: Request = context["request"] + return request.url_for(name, **path_params) + + env.globals.setdefault("url_for", url_for) + + def get_template(self, name: str) -> jinja2.Template: + return self.env.get_template(name) + + @typing.overload + def TemplateResponse( + self, + request: Request, + name: str, + context: dict[str, typing.Any] | None = None, + status_code: int = 200, + headers: typing.Mapping[str, str] | None = None, + media_type: str | None = None, + background: BackgroundTask | None = None, + ) -> _TemplateResponse: ... + + @typing.overload + def TemplateResponse( + self, + name: str, + context: dict[str, typing.Any] | None = None, + status_code: int = 200, + headers: typing.Mapping[str, str] | None = None, + media_type: str | None = None, + background: BackgroundTask | None = None, + ) -> _TemplateResponse: + # Deprecated usage + ... + + def TemplateResponse(self, *args: typing.Any, **kwargs: typing.Any) -> _TemplateResponse: + if args: + if isinstance(args[0], str): # the first argument is template name (old style) + warnings.warn( + "The `name` is not the first parameter anymore. " + "The first parameter should be the `Request` instance.\n" + 'Replace `TemplateResponse(name, {"request": request})` by `TemplateResponse(request, name)`.', + DeprecationWarning, + ) + + name = args[0] + context = args[1] if len(args) > 1 else kwargs.get("context", {}) + status_code = args[2] if len(args) > 2 else kwargs.get("status_code", 200) + headers = args[3] if len(args) > 3 else kwargs.get("headers") + media_type = args[4] if len(args) > 4 else kwargs.get("media_type") + background = args[5] if len(args) > 5 else kwargs.get("background") + + if "request" not in context: + raise ValueError('context must include a "request" key') + request = context["request"] + else: # the first argument is a request instance (new style) + request = args[0] + name = args[1] if len(args) > 1 else kwargs["name"] + context = args[2] if len(args) > 2 else kwargs.get("context", {}) + status_code = args[3] if len(args) > 3 else kwargs.get("status_code", 200) + headers = args[4] if len(args) > 4 else kwargs.get("headers") + media_type = args[5] if len(args) > 5 else kwargs.get("media_type") + background = args[6] if len(args) > 6 else kwargs.get("background") + else: # all arguments are kwargs + if "request" not in kwargs: + warnings.warn( + "The `TemplateResponse` now requires the `request` argument.\n" + 'Replace `TemplateResponse(name, {"context": context})` by `TemplateResponse(request, name)`.', + DeprecationWarning, + ) + if "request" not in kwargs.get("context", {}): + raise ValueError('context must include a "request" key') + + context = kwargs.get("context", {}) + request = kwargs.get("request", context.get("request")) + name = typing.cast(str, kwargs["name"]) + status_code = kwargs.get("status_code", 200) + headers = kwargs.get("headers") + media_type = kwargs.get("media_type") + background = kwargs.get("background") + + context.setdefault("request", request) + for context_processor in self.context_processors: + context.update(context_processor(request)) + + template = self.get_template(name) + return _TemplateResponse( + template, + context, + status_code=status_code, + headers=headers, + media_type=media_type, + background=background, + ) diff --git a/venv/Lib/site-packages/starlette/testclient.py b/venv/Lib/site-packages/starlette/testclient.py new file mode 100644 index 00000000..d54025e5 --- /dev/null +++ b/venv/Lib/site-packages/starlette/testclient.py @@ -0,0 +1,731 @@ +from __future__ import annotations + +import contextlib +import inspect +import io +import json +import math +import sys +import typing +import warnings +from concurrent.futures import Future +from types import GeneratorType +from urllib.parse import unquote, urljoin + +import anyio +import anyio.abc +import anyio.from_thread +from anyio.streams.stapled import StapledObjectStream + +from starlette._utils import is_async_callable +from starlette.types import ASGIApp, Message, Receive, Scope, Send +from starlette.websockets import WebSocketDisconnect + +if sys.version_info >= (3, 10): # pragma: no cover + from typing import TypeGuard +else: # pragma: no cover + from typing_extensions import TypeGuard + +try: + import httpx +except ModuleNotFoundError: # pragma: no cover + raise RuntimeError( + "The starlette.testclient module requires the httpx package to be installed.\n" + "You can install this with:\n" + " $ pip install httpx\n" + ) +_PortalFactoryType = typing.Callable[[], typing.ContextManager[anyio.abc.BlockingPortal]] + +ASGIInstance = typing.Callable[[Receive, Send], typing.Awaitable[None]] +ASGI2App = typing.Callable[[Scope], ASGIInstance] +ASGI3App = typing.Callable[[Scope, Receive, Send], typing.Awaitable[None]] + + +_RequestData = typing.Mapping[str, typing.Union[str, typing.Iterable[str], bytes]] + + +def _is_asgi3(app: ASGI2App | ASGI3App) -> TypeGuard[ASGI3App]: + if inspect.isclass(app): + return hasattr(app, "__await__") + return is_async_callable(app) + + +class _WrapASGI2: + """ + Provide an ASGI3 interface onto an ASGI2 app. + """ + + def __init__(self, app: ASGI2App) -> None: + self.app = app + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + instance = self.app(scope) + await instance(receive, send) + + +class _AsyncBackend(typing.TypedDict): + backend: str + backend_options: dict[str, typing.Any] + + +class _Upgrade(Exception): + def __init__(self, session: WebSocketTestSession) -> None: + self.session = session + + +class WebSocketDenialResponse( # type: ignore[misc] + httpx.Response, + WebSocketDisconnect, +): + """ + A special case of `WebSocketDisconnect`, raised in the `TestClient` if the + `WebSocket` is closed before being accepted with a `send_denial_response()`. + """ + + +class WebSocketTestSession: + def __init__( + self, + app: ASGI3App, + scope: Scope, + portal_factory: _PortalFactoryType, + ) -> None: + self.app = app + self.scope = scope + self.accepted_subprotocol = None + self.portal_factory = portal_factory + self.extra_headers = None + + def __enter__(self) -> WebSocketTestSession: + with contextlib.ExitStack() as stack: + self.portal = portal = stack.enter_context(self.portal_factory()) + fut, cs = portal.start_task(self._run) + stack.callback(fut.result) + stack.callback(portal.call, cs.cancel) + self.send({"type": "websocket.connect"}) + message = self.receive() + self._raise_on_close(message) + self.accepted_subprotocol = message.get("subprotocol", None) + self.extra_headers = message.get("headers", None) + stack.callback(self.close, 1000) + self.exit_stack = stack.pop_all() + return self + + def __exit__(self, *args: typing.Any) -> bool | None: + return self.exit_stack.__exit__(*args) + + async def _run(self, *, task_status: anyio.abc.TaskStatus[anyio.CancelScope]) -> None: + """ + The sub-thread in which the websocket session runs. + """ + send: anyio.create_memory_object_stream[Message] = anyio.create_memory_object_stream(math.inf) + send_tx, send_rx = send + receive: anyio.create_memory_object_stream[Message] = anyio.create_memory_object_stream(math.inf) + receive_tx, receive_rx = receive + with send_tx, send_rx, receive_tx, receive_rx, anyio.CancelScope() as cs: + self._receive_tx = receive_tx + self._send_rx = send_rx + task_status.started(cs) + await self.app(self.scope, receive_rx.receive, send_tx.send) + + # wait for cs.cancel to be called before closing streams + await anyio.sleep_forever() + + def _raise_on_close(self, message: Message) -> None: + if message["type"] == "websocket.close": + raise WebSocketDisconnect(code=message.get("code", 1000), reason=message.get("reason", "")) + elif message["type"] == "websocket.http.response.start": + status_code: int = message["status"] + headers: list[tuple[bytes, bytes]] = message["headers"] + body: list[bytes] = [] + while True: + message = self.receive() + assert message["type"] == "websocket.http.response.body" + body.append(message["body"]) + if not message.get("more_body", False): + break + raise WebSocketDenialResponse(status_code=status_code, headers=headers, content=b"".join(body)) + + def send(self, message: Message) -> None: + self.portal.call(self._receive_tx.send, message) + + def send_text(self, data: str) -> None: + self.send({"type": "websocket.receive", "text": data}) + + def send_bytes(self, data: bytes) -> None: + self.send({"type": "websocket.receive", "bytes": data}) + + def send_json(self, data: typing.Any, mode: typing.Literal["text", "binary"] = "text") -> None: + text = json.dumps(data, separators=(",", ":"), ensure_ascii=False) + if mode == "text": + self.send({"type": "websocket.receive", "text": text}) + else: + self.send({"type": "websocket.receive", "bytes": text.encode("utf-8")}) + + def close(self, code: int = 1000, reason: str | None = None) -> None: + self.send({"type": "websocket.disconnect", "code": code, "reason": reason}) + + def receive(self) -> Message: + return self.portal.call(self._send_rx.receive) + + def receive_text(self) -> str: + message = self.receive() + self._raise_on_close(message) + return typing.cast(str, message["text"]) + + def receive_bytes(self) -> bytes: + message = self.receive() + self._raise_on_close(message) + return typing.cast(bytes, message["bytes"]) + + def receive_json(self, mode: typing.Literal["text", "binary"] = "text") -> typing.Any: + message = self.receive() + self._raise_on_close(message) + if mode == "text": + text = message["text"] + else: + text = message["bytes"].decode("utf-8") + return json.loads(text) + + +class _TestClientTransport(httpx.BaseTransport): + def __init__( + self, + app: ASGI3App, + portal_factory: _PortalFactoryType, + raise_server_exceptions: bool = True, + root_path: str = "", + *, + client: tuple[str, int], + app_state: dict[str, typing.Any], + ) -> None: + self.app = app + self.raise_server_exceptions = raise_server_exceptions + self.root_path = root_path + self.portal_factory = portal_factory + self.app_state = app_state + self.client = client + + def handle_request(self, request: httpx.Request) -> httpx.Response: + scheme = request.url.scheme + netloc = request.url.netloc.decode(encoding="ascii") + path = request.url.path + raw_path = request.url.raw_path + query = request.url.query.decode(encoding="ascii") + + default_port = {"http": 80, "ws": 80, "https": 443, "wss": 443}[scheme] + + if ":" in netloc: + host, port_string = netloc.split(":", 1) + port = int(port_string) + else: + host = netloc + port = default_port + + # Include the 'host' header. + if "host" in request.headers: + headers: list[tuple[bytes, bytes]] = [] + elif port == default_port: # pragma: no cover + headers = [(b"host", host.encode())] + else: # pragma: no cover + headers = [(b"host", (f"{host}:{port}").encode())] + + # Include other request headers. + headers += [(key.lower().encode(), value.encode()) for key, value in request.headers.multi_items()] + + scope: dict[str, typing.Any] + + if scheme in {"ws", "wss"}: + subprotocol = request.headers.get("sec-websocket-protocol", None) + if subprotocol is None: + subprotocols: typing.Sequence[str] = [] + else: + subprotocols = [value.strip() for value in subprotocol.split(",")] + scope = { + "type": "websocket", + "path": unquote(path), + "raw_path": raw_path.split(b"?", 1)[0], + "root_path": self.root_path, + "scheme": scheme, + "query_string": query.encode(), + "headers": headers, + "client": self.client, + "server": [host, port], + "subprotocols": subprotocols, + "state": self.app_state.copy(), + "extensions": {"websocket.http.response": {}}, + } + session = WebSocketTestSession(self.app, scope, self.portal_factory) + raise _Upgrade(session) + + scope = { + "type": "http", + "http_version": "1.1", + "method": request.method, + "path": unquote(path), + "raw_path": raw_path.split(b"?", 1)[0], + "root_path": self.root_path, + "scheme": scheme, + "query_string": query.encode(), + "headers": headers, + "client": self.client, + "server": [host, port], + "extensions": {"http.response.debug": {}}, + "state": self.app_state.copy(), + } + + request_complete = False + response_started = False + response_complete: anyio.Event + raw_kwargs: dict[str, typing.Any] = {"stream": io.BytesIO()} + template = None + context = None + + async def receive() -> Message: + nonlocal request_complete + + if request_complete: + if not response_complete.is_set(): + await response_complete.wait() + return {"type": "http.disconnect"} + + body = request.read() + if isinstance(body, str): + body_bytes: bytes = body.encode("utf-8") # pragma: no cover + elif body is None: + body_bytes = b"" # pragma: no cover + elif isinstance(body, GeneratorType): + try: # pragma: no cover + chunk = body.send(None) + if isinstance(chunk, str): + chunk = chunk.encode("utf-8") + return {"type": "http.request", "body": chunk, "more_body": True} + except StopIteration: # pragma: no cover + request_complete = True + return {"type": "http.request", "body": b""} + else: + body_bytes = body + + request_complete = True + return {"type": "http.request", "body": body_bytes} + + async def send(message: Message) -> None: + nonlocal raw_kwargs, response_started, template, context + + if message["type"] == "http.response.start": + assert not response_started, 'Received multiple "http.response.start" messages.' + raw_kwargs["status_code"] = message["status"] + raw_kwargs["headers"] = [(key.decode(), value.decode()) for key, value in message.get("headers", [])] + response_started = True + elif message["type"] == "http.response.body": + assert response_started, 'Received "http.response.body" without "http.response.start".' + assert not response_complete.is_set(), 'Received "http.response.body" after response completed.' + body = message.get("body", b"") + more_body = message.get("more_body", False) + if request.method != "HEAD": + raw_kwargs["stream"].write(body) + if not more_body: + raw_kwargs["stream"].seek(0) + response_complete.set() + elif message["type"] == "http.response.debug": + template = message["info"]["template"] + context = message["info"]["context"] + + try: + with self.portal_factory() as portal: + response_complete = portal.call(anyio.Event) + portal.call(self.app, scope, receive, send) + except BaseException as exc: + if self.raise_server_exceptions: + raise exc + + if self.raise_server_exceptions: + assert response_started, "TestClient did not receive any response." + elif not response_started: + raw_kwargs = { + "status_code": 500, + "headers": [], + "stream": io.BytesIO(), + } + + raw_kwargs["stream"] = httpx.ByteStream(raw_kwargs["stream"].read()) + + response = httpx.Response(**raw_kwargs, request=request) + if template is not None: + response.template = template # type: ignore[attr-defined] + response.context = context # type: ignore[attr-defined] + return response + + +class TestClient(httpx.Client): + __test__ = False + task: Future[None] + portal: anyio.abc.BlockingPortal | None = None + + def __init__( + self, + app: ASGIApp, + base_url: str = "http://testserver", + raise_server_exceptions: bool = True, + root_path: str = "", + backend: typing.Literal["asyncio", "trio"] = "asyncio", + backend_options: dict[str, typing.Any] | None = None, + cookies: httpx._types.CookieTypes | None = None, + headers: dict[str, str] | None = None, + follow_redirects: bool = True, + client: tuple[str, int] = ("testclient", 50000), + ) -> None: + self.async_backend = _AsyncBackend(backend=backend, backend_options=backend_options or {}) + if _is_asgi3(app): + asgi_app = app + else: + app = typing.cast(ASGI2App, app) # type: ignore[assignment] + asgi_app = _WrapASGI2(app) # type: ignore[arg-type] + self.app = asgi_app + self.app_state: dict[str, typing.Any] = {} + transport = _TestClientTransport( + self.app, + portal_factory=self._portal_factory, + raise_server_exceptions=raise_server_exceptions, + root_path=root_path, + app_state=self.app_state, + client=client, + ) + if headers is None: + headers = {} + headers.setdefault("user-agent", "testclient") + super().__init__( + base_url=base_url, + headers=headers, + transport=transport, + follow_redirects=follow_redirects, + cookies=cookies, + ) + + @contextlib.contextmanager + def _portal_factory(self) -> typing.Generator[anyio.abc.BlockingPortal, None, None]: + if self.portal is not None: + yield self.portal + else: + with anyio.from_thread.start_blocking_portal(**self.async_backend) as portal: + yield portal + + def request( # type: ignore[override] + self, + method: str, + url: httpx._types.URLTypes, + *, + content: httpx._types.RequestContent | None = None, + data: _RequestData | None = None, + files: httpx._types.RequestFiles | None = None, + json: typing.Any = None, + params: httpx._types.QueryParamTypes | None = None, + headers: httpx._types.HeaderTypes | None = None, + cookies: httpx._types.CookieTypes | None = None, + auth: httpx._types.AuthTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT, + follow_redirects: bool | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT, + timeout: httpx._types.TimeoutTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT, + extensions: dict[str, typing.Any] | None = None, + ) -> httpx.Response: + if timeout is not httpx.USE_CLIENT_DEFAULT: + warnings.warn( + "You should not use the 'timeout' argument with the TestClient. " + "See https://github.com/encode/starlette/issues/1108 for more information.", + DeprecationWarning, + ) + url = self._merge_url(url) + return super().request( + method, + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def get( # type: ignore[override] + self, + url: httpx._types.URLTypes, + *, + params: httpx._types.QueryParamTypes | None = None, + headers: httpx._types.HeaderTypes | None = None, + cookies: httpx._types.CookieTypes | None = None, + auth: httpx._types.AuthTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT, + follow_redirects: bool | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT, + timeout: httpx._types.TimeoutTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT, + extensions: dict[str, typing.Any] | None = None, + ) -> httpx.Response: + return super().get( + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def options( # type: ignore[override] + self, + url: httpx._types.URLTypes, + *, + params: httpx._types.QueryParamTypes | None = None, + headers: httpx._types.HeaderTypes | None = None, + cookies: httpx._types.CookieTypes | None = None, + auth: httpx._types.AuthTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT, + follow_redirects: bool | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT, + timeout: httpx._types.TimeoutTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT, + extensions: dict[str, typing.Any] | None = None, + ) -> httpx.Response: + return super().options( + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def head( # type: ignore[override] + self, + url: httpx._types.URLTypes, + *, + params: httpx._types.QueryParamTypes | None = None, + headers: httpx._types.HeaderTypes | None = None, + cookies: httpx._types.CookieTypes | None = None, + auth: httpx._types.AuthTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT, + follow_redirects: bool | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT, + timeout: httpx._types.TimeoutTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT, + extensions: dict[str, typing.Any] | None = None, + ) -> httpx.Response: + return super().head( + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def post( # type: ignore[override] + self, + url: httpx._types.URLTypes, + *, + content: httpx._types.RequestContent | None = None, + data: _RequestData | None = None, + files: httpx._types.RequestFiles | None = None, + json: typing.Any = None, + params: httpx._types.QueryParamTypes | None = None, + headers: httpx._types.HeaderTypes | None = None, + cookies: httpx._types.CookieTypes | None = None, + auth: httpx._types.AuthTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT, + follow_redirects: bool | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT, + timeout: httpx._types.TimeoutTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT, + extensions: dict[str, typing.Any] | None = None, + ) -> httpx.Response: + return super().post( + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def put( # type: ignore[override] + self, + url: httpx._types.URLTypes, + *, + content: httpx._types.RequestContent | None = None, + data: _RequestData | None = None, + files: httpx._types.RequestFiles | None = None, + json: typing.Any = None, + params: httpx._types.QueryParamTypes | None = None, + headers: httpx._types.HeaderTypes | None = None, + cookies: httpx._types.CookieTypes | None = None, + auth: httpx._types.AuthTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT, + follow_redirects: bool | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT, + timeout: httpx._types.TimeoutTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT, + extensions: dict[str, typing.Any] | None = None, + ) -> httpx.Response: + return super().put( + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def patch( # type: ignore[override] + self, + url: httpx._types.URLTypes, + *, + content: httpx._types.RequestContent | None = None, + data: _RequestData | None = None, + files: httpx._types.RequestFiles | None = None, + json: typing.Any = None, + params: httpx._types.QueryParamTypes | None = None, + headers: httpx._types.HeaderTypes | None = None, + cookies: httpx._types.CookieTypes | None = None, + auth: httpx._types.AuthTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT, + follow_redirects: bool | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT, + timeout: httpx._types.TimeoutTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT, + extensions: dict[str, typing.Any] | None = None, + ) -> httpx.Response: + return super().patch( + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def delete( # type: ignore[override] + self, + url: httpx._types.URLTypes, + *, + params: httpx._types.QueryParamTypes | None = None, + headers: httpx._types.HeaderTypes | None = None, + cookies: httpx._types.CookieTypes | None = None, + auth: httpx._types.AuthTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT, + follow_redirects: bool | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT, + timeout: httpx._types.TimeoutTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT, + extensions: dict[str, typing.Any] | None = None, + ) -> httpx.Response: + return super().delete( + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def websocket_connect( + self, + url: str, + subprotocols: typing.Sequence[str] | None = None, + **kwargs: typing.Any, + ) -> WebSocketTestSession: + url = urljoin("ws://testserver", url) + headers = kwargs.get("headers", {}) + headers.setdefault("connection", "upgrade") + headers.setdefault("sec-websocket-key", "testserver==") + headers.setdefault("sec-websocket-version", "13") + if subprotocols is not None: + headers.setdefault("sec-websocket-protocol", ", ".join(subprotocols)) + kwargs["headers"] = headers + try: + super().request("GET", url, **kwargs) + except _Upgrade as exc: + session = exc.session + else: + raise RuntimeError("Expected WebSocket upgrade") # pragma: no cover + + return session + + def __enter__(self) -> TestClient: + with contextlib.ExitStack() as stack: + self.portal = portal = stack.enter_context(anyio.from_thread.start_blocking_portal(**self.async_backend)) + + @stack.callback + def reset_portal() -> None: + self.portal = None + + send: anyio.create_memory_object_stream[typing.MutableMapping[str, typing.Any] | None] = ( + anyio.create_memory_object_stream(math.inf) + ) + receive: anyio.create_memory_object_stream[typing.MutableMapping[str, typing.Any]] = ( + anyio.create_memory_object_stream(math.inf) + ) + for channel in (*send, *receive): + stack.callback(channel.close) + self.stream_send = StapledObjectStream(*send) + self.stream_receive = StapledObjectStream(*receive) + self.task = portal.start_task_soon(self.lifespan) + portal.call(self.wait_startup) + + @stack.callback + def wait_shutdown() -> None: + portal.call(self.wait_shutdown) + + self.exit_stack = stack.pop_all() + + return self + + def __exit__(self, *args: typing.Any) -> None: + self.exit_stack.close() + + async def lifespan(self) -> None: + scope = {"type": "lifespan", "state": self.app_state} + try: + await self.app(scope, self.stream_receive.receive, self.stream_send.send) + finally: + await self.stream_send.send(None) + + async def wait_startup(self) -> None: + await self.stream_receive.send({"type": "lifespan.startup"}) + + async def receive() -> typing.Any: + message = await self.stream_send.receive() + if message is None: + self.task.result() + return message + + message = await receive() + assert message["type"] in ( + "lifespan.startup.complete", + "lifespan.startup.failed", + ) + if message["type"] == "lifespan.startup.failed": + await receive() + + async def wait_shutdown(self) -> None: + async def receive() -> typing.Any: + message = await self.stream_send.receive() + if message is None: + self.task.result() + return message + + await self.stream_receive.send({"type": "lifespan.shutdown"}) + message = await receive() + assert message["type"] in ( + "lifespan.shutdown.complete", + "lifespan.shutdown.failed", + ) + if message["type"] == "lifespan.shutdown.failed": + await receive() diff --git a/venv/Lib/site-packages/starlette/types.py b/venv/Lib/site-packages/starlette/types.py new file mode 100644 index 00000000..893f8729 --- /dev/null +++ b/venv/Lib/site-packages/starlette/types.py @@ -0,0 +1,24 @@ +import typing + +if typing.TYPE_CHECKING: + from starlette.requests import Request + from starlette.responses import Response + from starlette.websockets import WebSocket + +AppType = typing.TypeVar("AppType") + +Scope = typing.MutableMapping[str, typing.Any] +Message = typing.MutableMapping[str, typing.Any] + +Receive = typing.Callable[[], typing.Awaitable[Message]] +Send = typing.Callable[[Message], typing.Awaitable[None]] + +ASGIApp = typing.Callable[[Scope, Receive, Send], typing.Awaitable[None]] + +StatelessLifespan = typing.Callable[[AppType], typing.AsyncContextManager[None]] +StatefulLifespan = typing.Callable[[AppType], typing.AsyncContextManager[typing.Mapping[str, typing.Any]]] +Lifespan = typing.Union[StatelessLifespan[AppType], StatefulLifespan[AppType]] + +HTTPExceptionHandler = typing.Callable[["Request", Exception], "Response | typing.Awaitable[Response]"] +WebSocketExceptionHandler = typing.Callable[["WebSocket", Exception], typing.Awaitable[None]] +ExceptionHandler = typing.Union[HTTPExceptionHandler, WebSocketExceptionHandler] diff --git a/venv/Lib/site-packages/starlette/websockets.py b/venv/Lib/site-packages/starlette/websockets.py new file mode 100644 index 00000000..6b46f4ea --- /dev/null +++ b/venv/Lib/site-packages/starlette/websockets.py @@ -0,0 +1,195 @@ +from __future__ import annotations + +import enum +import json +import typing + +from starlette.requests import HTTPConnection +from starlette.responses import Response +from starlette.types import Message, Receive, Scope, Send + + +class WebSocketState(enum.Enum): + CONNECTING = 0 + CONNECTED = 1 + DISCONNECTED = 2 + RESPONSE = 3 + + +class WebSocketDisconnect(Exception): + def __init__(self, code: int = 1000, reason: str | None = None) -> None: + self.code = code + self.reason = reason or "" + + +class WebSocket(HTTPConnection): + def __init__(self, scope: Scope, receive: Receive, send: Send) -> None: + super().__init__(scope) + assert scope["type"] == "websocket" + self._receive = receive + self._send = send + self.client_state = WebSocketState.CONNECTING + self.application_state = WebSocketState.CONNECTING + + async def receive(self) -> Message: + """ + Receive ASGI websocket messages, ensuring valid state transitions. + """ + if self.client_state == WebSocketState.CONNECTING: + message = await self._receive() + message_type = message["type"] + if message_type != "websocket.connect": + raise RuntimeError(f'Expected ASGI message "websocket.connect", but got {message_type!r}') + self.client_state = WebSocketState.CONNECTED + return message + elif self.client_state == WebSocketState.CONNECTED: + message = await self._receive() + message_type = message["type"] + if message_type not in {"websocket.receive", "websocket.disconnect"}: + raise RuntimeError( + f'Expected ASGI message "websocket.receive" or "websocket.disconnect", but got {message_type!r}' + ) + if message_type == "websocket.disconnect": + self.client_state = WebSocketState.DISCONNECTED + return message + else: + raise RuntimeError('Cannot call "receive" once a disconnect message has been received.') + + async def send(self, message: Message) -> None: + """ + Send ASGI websocket messages, ensuring valid state transitions. + """ + if self.application_state == WebSocketState.CONNECTING: + message_type = message["type"] + if message_type not in {"websocket.accept", "websocket.close", "websocket.http.response.start"}: + raise RuntimeError( + 'Expected ASGI message "websocket.accept", "websocket.close" or "websocket.http.response.start", ' + f"but got {message_type!r}" + ) + if message_type == "websocket.close": + self.application_state = WebSocketState.DISCONNECTED + elif message_type == "websocket.http.response.start": + self.application_state = WebSocketState.RESPONSE + else: + self.application_state = WebSocketState.CONNECTED + await self._send(message) + elif self.application_state == WebSocketState.CONNECTED: + message_type = message["type"] + if message_type not in {"websocket.send", "websocket.close"}: + raise RuntimeError( + f'Expected ASGI message "websocket.send" or "websocket.close", but got {message_type!r}' + ) + if message_type == "websocket.close": + self.application_state = WebSocketState.DISCONNECTED + try: + await self._send(message) + except OSError: + self.application_state = WebSocketState.DISCONNECTED + raise WebSocketDisconnect(code=1006) + elif self.application_state == WebSocketState.RESPONSE: + message_type = message["type"] + if message_type != "websocket.http.response.body": + raise RuntimeError(f'Expected ASGI message "websocket.http.response.body", but got {message_type!r}') + if not message.get("more_body", False): + self.application_state = WebSocketState.DISCONNECTED + await self._send(message) + else: + raise RuntimeError('Cannot call "send" once a close message has been sent.') + + async def accept( + self, + subprotocol: str | None = None, + headers: typing.Iterable[tuple[bytes, bytes]] | None = None, + ) -> None: + headers = headers or [] + + if self.client_state == WebSocketState.CONNECTING: # pragma: no branch + # If we haven't yet seen the 'connect' message, then wait for it first. + await self.receive() + await self.send({"type": "websocket.accept", "subprotocol": subprotocol, "headers": headers}) + + def _raise_on_disconnect(self, message: Message) -> None: + if message["type"] == "websocket.disconnect": + raise WebSocketDisconnect(message["code"], message.get("reason")) + + async def receive_text(self) -> str: + if self.application_state != WebSocketState.CONNECTED: + raise RuntimeError('WebSocket is not connected. Need to call "accept" first.') + message = await self.receive() + self._raise_on_disconnect(message) + return typing.cast(str, message["text"]) + + async def receive_bytes(self) -> bytes: + if self.application_state != WebSocketState.CONNECTED: + raise RuntimeError('WebSocket is not connected. Need to call "accept" first.') + message = await self.receive() + self._raise_on_disconnect(message) + return typing.cast(bytes, message["bytes"]) + + async def receive_json(self, mode: str = "text") -> typing.Any: + if mode not in {"text", "binary"}: + raise RuntimeError('The "mode" argument should be "text" or "binary".') + if self.application_state != WebSocketState.CONNECTED: + raise RuntimeError('WebSocket is not connected. Need to call "accept" first.') + message = await self.receive() + self._raise_on_disconnect(message) + + if mode == "text": + text = message["text"] + else: + text = message["bytes"].decode("utf-8") + return json.loads(text) + + async def iter_text(self) -> typing.AsyncIterator[str]: + try: + while True: + yield await self.receive_text() + except WebSocketDisconnect: + pass + + async def iter_bytes(self) -> typing.AsyncIterator[bytes]: + try: + while True: + yield await self.receive_bytes() + except WebSocketDisconnect: + pass + + async def iter_json(self) -> typing.AsyncIterator[typing.Any]: + try: + while True: + yield await self.receive_json() + except WebSocketDisconnect: + pass + + async def send_text(self, data: str) -> None: + await self.send({"type": "websocket.send", "text": data}) + + async def send_bytes(self, data: bytes) -> None: + await self.send({"type": "websocket.send", "bytes": data}) + + async def send_json(self, data: typing.Any, mode: str = "text") -> None: + if mode not in {"text", "binary"}: + raise RuntimeError('The "mode" argument should be "text" or "binary".') + text = json.dumps(data, separators=(",", ":"), ensure_ascii=False) + if mode == "text": + await self.send({"type": "websocket.send", "text": text}) + else: + await self.send({"type": "websocket.send", "bytes": text.encode("utf-8")}) + + async def close(self, code: int = 1000, reason: str | None = None) -> None: + await self.send({"type": "websocket.close", "code": code, "reason": reason or ""}) + + async def send_denial_response(self, response: Response) -> None: + if "websocket.http.response" in self.scope.get("extensions", {}): + await response(self.scope, self.receive, self.send) + else: + raise RuntimeError("The server doesn't support the Websocket Denial Response extension.") + + +class WebSocketClose: + def __init__(self, code: int = 1000, reason: str | None = None) -> None: + self.code = code + self.reason = reason or "" + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + await send({"type": "websocket.close", "code": self.code, "reason": self.reason}) diff --git a/venv/Lib/site-packages/twilio-9.6.3.dist-info/INSTALLER b/venv/Lib/site-packages/twilio-9.6.3.dist-info/INSTALLER new file mode 100644 index 00000000..a1b589e3 --- /dev/null +++ b/venv/Lib/site-packages/twilio-9.6.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/Lib/site-packages/twilio-9.6.3.dist-info/METADATA b/venv/Lib/site-packages/twilio-9.6.3.dist-info/METADATA new file mode 100644 index 00000000..268ccefc --- /dev/null +++ b/venv/Lib/site-packages/twilio-9.6.3.dist-info/METADATA @@ -0,0 +1,362 @@ +Metadata-Version: 2.4 +Name: twilio +Version: 9.6.3 +Summary: Twilio API client and TwiML generator +Home-page: https://github.com/twilio/twilio-python/ +Author: Twilio +License: MIT +Keywords: twilio,twiml +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Communications :: Telephony +Requires-Python: >=3.7.0 +Description-Content-Type: text/markdown +License-File: LICENSE +License-File: AUTHORS.md +Requires-Dist: requests>=2.0.0 +Requires-Dist: PyJWT<3.0.0,>=2.0.0 +Requires-Dist: aiohttp>=3.8.4 +Requires-Dist: aiohttp-retry>=2.8.3 +Dynamic: author +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: keywords +Dynamic: license-file +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + +# twilio-python + +[![Tests](https://github.com/twilio/twilio-python/actions/workflows/test-and-deploy.yml/badge.svg)](https://github.com/twilio/twilio-python/actions/workflows/test-and-deploy.yml) +[![PyPI](https://img.shields.io/pypi/v/twilio.svg)](https://pypi.python.org/pypi/twilio) +[![PyPI](https://img.shields.io/pypi/pyversions/twilio.svg)](https://pypi.python.org/pypi/twilio) +[![Learn OSS Contribution in TwilioQuest](https://img.shields.io/static/v1?label=TwilioQuest&message=Learn%20to%20contribute%21&color=F22F46&labelColor=1f243c&style=flat-square&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAMAAAD04JH5AAAASFBMVEUAAAAZGRkcHBwjIyMoKCgAAABgYGBoaGiAgICMjIyzs7PJycnMzMzNzc3UoBfd3d3m5ubqrhfrMEDu7u739/f4vSb/3AD///9tbdyEAAAABXRSTlMAAAAAAMJrBrEAAAKoSURBVHgB7ZrRcuI6EESdyxXGYoNFvMD//+l2bSszRgyUYpFAsXOeiJGmj4NkuWx1Qeh+Ekl9DgEXOBwOx+Px5xyQhDykfgq4wG63MxxaR4ddIkg6Ul3g84vCIcjPBA5gmUMeXESrlukuoK33+33uID8TWeLAdOWsKpJYzwVMB7bOzYSGOciyUlXSn0/ABXTosJ1M1SbypZ4O4MbZuIDMU02PMbauhhHMHXbmebmALIiEbbbbbUrpF1gwE9kFfRNAJaP+FQEXCCTGyJ4ngDrjOFo3jEL5JdqjF/pueR4cCeCGgAtwmuRS6gDwaRiGvu+DMFwSBLTE3+jF8JyuV1okPZ+AC4hDFhCHyHQjdjPHUKFDlHSJkHQXMB3KpSwXNGJPcwwTdZiXlRN0gSp0zpWxNtM0beYE0nRH6QIbO7rawwXaBYz0j78gxjokDuv12gVeUuBD0MDi0OQCLvDaAho4juP1Q/jkAncXqIcCfd+7gAu4QLMACCLxpRsSuQh0igu0C9Svhi7weAGZg50L3IE3cai4IfkNZAC8dfdhsUD3CgKBVC9JE5ABAFzg4QL/taYPAAWrHdYcgfLaIgAXWJ7OV38n1LEF8tt2TH29E+QAoDoO5Ve/LtCQDmKM9kPbvCEBApK+IXzbcSJ0cIGF6e8gpcRhUDogWZ8JnaWjPXc/fNnBBUKRngiHgTUSivSzDRDgHZQOLvBQgf8rRt+VdBUUhwkU6VpJ+xcOwQUqZr+mR0kvBUgv6cB4+37hQAkXqE8PwGisGhJtN4xAHMzrsgvI7rccXqSvKh6jltGlrOHA3Xk1At3LC4QiPdX9/0ndHpGVvTjR4bZA1ypAKgVcwE5vx74ulwIugDt8e/X7JgfkucBMIAr26ndnB4UCLnDOqvteQsHlgX9N4A+c4cW3DXSPbwAAAABJRU5ErkJggg==)](https://twil.io/learn-open-source) + +## Documentation + +The documentation for the Twilio API can be found [here][apidocs]. + +The Python library documentation can be found [here][libdocs]. + +## Versions + +`twilio-python` uses a modified version of [Semantic Versioning](https://semver.org) for all changes. [See this document](VERSIONS.md) for details. + +### Supported Python Versions + +This library supports the following Python implementations: + +- Python 3.7 +- Python 3.8 +- Python 3.9 +- Python 3.10 +- Python 3.11 + +## Installation + +Install from PyPi using [pip](https://pip.pypa.io/en/latest/), a +package manager for Python. + +```shell +pip3 install twilio +``` + +If pip install fails on Windows, check the path length of the directory. If it is greater 260 characters then enable [Long Paths](https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation) or choose other shorter location. + +Don't have pip installed? Try installing it, by running this from the command +line: + +```shell +curl https://bootstrap.pypa.io/get-pip.py | python +``` + +Or, you can [download the source code +(ZIP)](https://github.com/twilio/twilio-python/zipball/main 'twilio-python +source code') for `twilio-python`, and then run: + +```shell +python3 setup.py install +``` + +> **Info** +> If the command line gives you an error message that says Permission Denied, try running the above commands with `sudo` (e.g., `sudo pip3 install twilio`). + +### Test your installation + +Try sending yourself an SMS message. Save the following code sample to your computer with a text editor. Be sure to update the `account_sid`, `auth_token`, and `from_` phone number with values from your [Twilio account](https://console.twilio.com). The `to` phone number will be your own mobile phone. + +```python +from twilio.rest import Client + +# Your Account SID and Auth Token from console.twilio.com +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +auth_token = "your_auth_token" + +client = Client(account_sid, auth_token) + +message = client.messages.create( + to="+15558675309", + from_="+15017250604", + body="Hello from Python!") + +print(message.sid) +``` + +Save the file as `send_sms.py`. In the terminal, `cd` to the directory containing the file you just saved then run: + +```shell +python3 send_sms.py +``` + +After a brief delay, you will receive the text message on your phone. + +> **Warning** +> It's okay to hardcode your credentials when testing locally, but you should use environment variables to keep them secret before committing any code or deploying to production. Check out [How to Set Environment Variables](https://www.twilio.com/blog/2017/01/how-to-set-environment-variables.html) for more information. + +## OAuth Feature for Twilio APIs +We are introducing Client Credentials Flow-based OAuth 2.0 authentication. This feature is currently in beta and its implementation is subject to change. + +API examples [here](https://github.com/twilio/twilio-python/blob/main/examples/public_oauth.py) + +Organisation API examples [here](https://github.com/twilio/twilio-python/blob/main/examples/organization_api.py) + +## Use the helper library + +### API Credentials + +The `Twilio` client needs your Twilio credentials. You can either pass these directly to the constructor (see the code below) or via environment variables. + +Authenticating with Account SID and Auth Token: + +```python +from twilio.rest import Client + +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +auth_token = "your_auth_token" +client = Client(account_sid, auth_token) +``` + +Authenticating with API Key and API Secret: + +```python +from twilio.rest import Client + +api_key = "XXXXXXXXXXXXXXXXX" +api_secret = "YYYYYYYYYYYYYYYYYY" +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +client = Client(api_key, api_secret, account_sid) +``` + +Alternatively, a `Client` constructor without these parameters will +look for `TWILIO_ACCOUNT_SID` and `TWILIO_AUTH_TOKEN` variables inside the +current environment. + +We suggest storing your credentials as environment variables. Why? You'll never +have to worry about committing your credentials and accidentally posting them +somewhere public. + +```python +from twilio.rest import Client +client = Client() +``` + +### Specify Region and/or Edge + +To take advantage of Twilio's [Global Infrastructure](https://www.twilio.com/docs/global-infrastructure), specify the target Region and Edge for the client: + +> **Note:** When specifying a `region` parameter for a helper library client, be sure to also specify the `edge` parameter. For backward compatibility purposes, specifying a `region` without specifying an `edge` will result in requests being routed to US1. + +```python +from twilio.rest import Client + +client = Client(region='au1', edge='sydney') +``` + +A `Client` constructor without these parameters will also look for `TWILIO_REGION` and `TWILIO_EDGE` variables inside the current environment. + +Alternatively, you may specify the edge and/or region after constructing the Twilio client: + +```python +from twilio.rest import Client + +client = Client() +client.region = 'au1' +client.edge = 'sydney' +``` + +This will result in the `hostname` transforming from `api.twilio.com` to `api.sydney.au1.twilio.com`. + +### Make a Call + +```python +from twilio.rest import Client + +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +auth_token = "your_auth_token" +client = Client(account_sid, auth_token) + +call = client.calls.create(to="9991231234", + from_="9991231234", + url="http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient") +print(call.sid) +``` + +### Get data about an existing call + +```python +from twilio.rest import Client + +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +auth_token = "your_auth_token" +client = Client(account_sid, auth_token) + +call = client.calls.get("CA42ed11f93dc08b952027ffbc406d0868") +print(call.to) +``` + +### Iterate through records + +The library automatically handles paging for you. Collections, such as `calls` and `messages`, have `list` and `stream` methods that page under the hood. With both `list` and `stream`, you can specify the number of records you want to receive (`limit`) and the maximum size you want each page fetch to be (`page_size`). The library will then handle the task for you. + +`list` eagerly fetches all records and returns them as a list, whereas `stream` returns an iterator and lazily retrieves pages of records as you iterate over the collection. You can also page manually using the `page` method. + +`page_size` as a parameter is used to tell how many records should we get in every page and `limit` parameter is used to limit the max number of records we want to fetch. + +#### Use the `list` method + +```python +from twilio.rest import Client + +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +auth_token = "your_auth_token" +client = Client(account_sid, auth_token) + +for sms in client.messages.list(): + print(sms.to) +``` + +```python +client.messages.list(limit=20, page_size=20) +``` +This will make 1 call that will fetch 20 records from backend service. + +```python +client.messages.list(limit=20, page_size=10) +``` +This will make 2 calls that will fetch 10 records each from backend service. + +```python +client.messages.list(limit=20, page_size=100) +``` +This will make 1 call which will fetch 100 records but user will get only 20 records. + +### Asynchronous API Requests + +By default, the Twilio Client will make synchronous requests to the Twilio API. To allow for asynchronous, non-blocking requests, we've included an optional asynchronous HTTP client. When used with the Client and the accompanying `*_async` methods, requests made to the Twilio API will be performed asynchronously. + +```python +from twilio.http.async_http_client import AsyncTwilioHttpClient +from twilio.rest import Client + +async def main(): + account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + auth_token = "your_auth_token" + http_client = AsyncTwilioHttpClient() + client = Client(account_sid, auth_token, http_client=http_client) + + message = await client.messages.create_async(to="+12316851234", from_="+15555555555", + body="Hello there!") + +asyncio.run(main()) +``` + +### Enable Debug Logging + +Log the API request and response data to the console: + +```python +import logging + +client = Client(account_sid, auth_token) +logging.basicConfig() +client.http_client.logger.setLevel(logging.INFO) +``` + +Log the API request and response data to a file: + +```python +import logging + +client = Client(account_sid, auth_token) +logging.basicConfig(filename='./log.txt') +client.http_client.logger.setLevel(logging.INFO) +``` + +### Handling Exceptions + +Version 8.x of `twilio-python` exports an exception class to help you handle exceptions that are specific to Twilio methods. To use it, import `TwilioRestException` and catch exceptions as follows: + +```python +from twilio.rest import Client +from twilio.base.exceptions import TwilioRestException + +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +auth_token = "your_auth_token" +client = Client(account_sid, auth_token) + +try: + message = client.messages.create(to="+12316851234", from_="+15555555555", + body="Hello there!") +except TwilioRestException as e: + print(e) +``` + +### Generating TwiML + +To control phone calls, your application needs to output [TwiML][twiml]. + +Use `twilio.twiml.Response` to easily create such responses. + +```python +from twilio.twiml.voice_response import VoiceResponse + +r = VoiceResponse() +r.say("Welcome to twilio!") +print(str(r)) +``` + +```xml + +Welcome to twilio! +``` + +### Other advanced examples + +- [Learn how to create your own custom HTTP client](./advanced-examples/custom-http-client.md) + +### Docker Image + +The `Dockerfile` present in this repository and its respective `twilio/twilio-python` Docker image are currently used by Twilio for testing purposes only. + +### Getting help + +If you need help installing or using the library, please check the [Twilio Support Help Center](https://support.twilio.com) first, and [file a support ticket](https://twilio.com/help/contact) if you don't find an answer to your question. + +If you've instead found a bug in the library or would like new features added, go ahead and open issues or pull requests against this repo! + +[apidocs]: https://www.twilio.com/docs/api +[twiml]: https://www.twilio.com/docs/api/twiml +[libdocs]: https://twilio.github.io/twilio-python diff --git a/venv/Lib/site-packages/twilio-9.6.3.dist-info/RECORD b/venv/Lib/site-packages/twilio-9.6.3.dist-info/RECORD new file mode 100644 index 00000000..1a4253f0 --- /dev/null +++ b/venv/Lib/site-packages/twilio-9.6.3.dist-info/RECORD @@ -0,0 +1,1368 @@ +twilio-9.6.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +twilio-9.6.3.dist-info/METADATA,sha256=QJN1GFIpg-3TCVxgNQPspyhipDKWXVPejFVIbViJZXk,13510 +twilio-9.6.3.dist-info/RECORD,, +twilio-9.6.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +twilio-9.6.3.dist-info/WHEEL,sha256=JNWh1Fm1UdwIQV075glCn4MVuCRs0sotJIq-J6rbxCU,109 +twilio-9.6.3.dist-info/licenses/AUTHORS.md,sha256=o3292UoaDN3jrjNs-qzN7yDnhvH6TqV7EzSfJdnCf4Q,1387 +twilio-9.6.3.dist-info/licenses/LICENSE,sha256=8UK19n5LbVBeSP2SuveHtbmQ2BMV-Dat89xZ8As-YZ0,1108 +twilio-9.6.3.dist-info/top_level.txt,sha256=fAdnbTJw2Q-bY1dyTpCPQR9_kIISEW1tNn4jYb-g3Ic,7 +twilio/__init__.py,sha256=VcHftSjmpZe8gXTigvYpbaBJZm535eHadrPCB39HPZs,76 +twilio/__pycache__/__init__.cpython-312.pyc,, +twilio/__pycache__/request_validator.cpython-312.pyc,, +twilio/auth_strategy/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +twilio/auth_strategy/__pycache__/__init__.cpython-312.pyc,, +twilio/auth_strategy/__pycache__/auth_strategy.cpython-312.pyc,, +twilio/auth_strategy/__pycache__/auth_type.cpython-312.pyc,, +twilio/auth_strategy/__pycache__/no_auth_strategy.cpython-312.pyc,, +twilio/auth_strategy/__pycache__/token_auth_strategy.cpython-312.pyc,, +twilio/auth_strategy/auth_strategy.py,sha256=fY6KQdzezUB5EE0mt5tKU01-pvi2u1ugxeyy3b62MnE,521 +twilio/auth_strategy/auth_type.py,sha256=IwG71YYNfc9TJPL-T-lgJH0l-CSDcEIVaTx6UDeNAJA,240 +twilio/auth_strategy/no_auth_strategy.py,sha256=i87zDWRF42wInZGhigHMepo7904I8CkHx-ozJvfpX7s,322 +twilio/auth_strategy/token_auth_strategy.py,sha256=z0OBeGTpZrhArWGXEVgB7uieNgLszNlMq6UL6YO6KpU,1894 +twilio/base/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +twilio/base/__pycache__/__init__.cpython-312.pyc,, +twilio/base/__pycache__/client_base.cpython-312.pyc,, +twilio/base/__pycache__/deserialize.cpython-312.pyc,, +twilio/base/__pycache__/domain.cpython-312.pyc,, +twilio/base/__pycache__/exceptions.cpython-312.pyc,, +twilio/base/__pycache__/instance_context.cpython-312.pyc,, +twilio/base/__pycache__/instance_resource.cpython-312.pyc,, +twilio/base/__pycache__/list_resource.cpython-312.pyc,, +twilio/base/__pycache__/obsolete.cpython-312.pyc,, +twilio/base/__pycache__/page.cpython-312.pyc,, +twilio/base/__pycache__/serialize.cpython-312.pyc,, +twilio/base/__pycache__/values.cpython-312.pyc,, +twilio/base/__pycache__/version.cpython-312.pyc,, +twilio/base/client_base.py,sha256=cTUD-570kA1nbg-eLAquYGwNvbMgazjFlMinFqHWsbU,9592 +twilio/base/deserialize.py,sha256=ro6hPYvNK1c7WrpWeS3PgM_p0ppjPwJxM2iYVhgCvDk,2005 +twilio/base/domain.py,sha256=z0ESHLf2LEQxfi1JJ2xEQk8tQheW0mU1Bt_r3ko41U4,2978 +twilio/base/exceptions.py,sha256=qYou_kqs04_0ybcVzcfpRqN88RYf41iINB4B8egok7Q,2890 +twilio/base/instance_context.py,sha256=ln0XUHSb6ByjV6oHx0sa7TknQ0ahe8yuk-mhmOM5fMU,147 +twilio/base/instance_resource.py,sha256=84FA89HN55_rSWUQ2rwRFGaABXRYoudcLaYvBQDbQmo,148 +twilio/base/list_resource.py,sha256=WLDg_ByCMR9P7YOHLuQxNjkZvToteF7A3k-ZCb853Xc,144 +twilio/base/obsolete.py,sha256=A5EqW8Nu4aLatse83CIxdrZXxXic8yhaXiQC16RyvVg,1417 +twilio/base/page.py,sha256=YTKd63kVfwb1OHmf74_PJ0ucXS_Vpp3f1IiQP2ZIBoc,5264 +twilio/base/serialize.py,sha256=TlIJtVfXArDLLmH8WyfGZmczffxWZNuUtOckd4d9aJ0,2316 +twilio/base/values.py,sha256=okdxSj7zc0tg_IfScuZYQKOX-fHu99ZXQcFh_XuBAuE,280 +twilio/base/version.py,sha256=eRnp96pRPim0KxdxZtf34phugQ9s-hhVeeOUI7tatn8,14611 +twilio/credential/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +twilio/credential/__pycache__/__init__.cpython-312.pyc,, +twilio/credential/__pycache__/client_credential_provider.cpython-312.pyc,, +twilio/credential/__pycache__/credential_provider.cpython-312.pyc,, +twilio/credential/__pycache__/orgs_credential_provider.cpython-312.pyc,, +twilio/credential/client_credential_provider.py,sha256=VunG0k3knjK9t2UMCTnWxgjdMqerwP3bVu2thYb21Nk,1184 +twilio/credential/credential_provider.py,sha256=1cuNNjCoYBipYVDIfItc-r5HFz-ga5_SK8vPKkttogo,352 +twilio/credential/orgs_credential_provider.py,sha256=ETIthhf1u4OZYhPjoqrP0V2WA6Q1JPPPwojja-Aq10o,1174 +twilio/http/__init__.py,sha256=aklR5-Xl8fnZNgV3jxylkbCcJCBEKQM3nt024ttm-Gs,3434 +twilio/http/__pycache__/__init__.cpython-312.pyc,, +twilio/http/__pycache__/async_http_client.cpython-312.pyc,, +twilio/http/__pycache__/client_token_manager.cpython-312.pyc,, +twilio/http/__pycache__/http_client.cpython-312.pyc,, +twilio/http/__pycache__/orgs_token_manager.cpython-312.pyc,, +twilio/http/__pycache__/request.cpython-312.pyc,, +twilio/http/__pycache__/response.cpython-312.pyc,, +twilio/http/__pycache__/token_manager.cpython-312.pyc,, +twilio/http/__pycache__/validation_client.cpython-312.pyc,, +twilio/http/async_http_client.py,sha256=Ei7OXkbp26n3MAtWsX-0mTVZcEOgBui4Y4y8T20l1x0,4503 +twilio/http/client_token_manager.py,sha256=p6CKaXjnPjYM9ku0n1puHgyFSIJLU2FN-31anjVqPUk,1154 +twilio/http/http_client.py,sha256=FxvtTb-EbuWMcPttpDzLe1BBZZu1P2KWjbWaNX-I6Bo,4141 +twilio/http/orgs_token_manager.py,sha256=WcxkMITQdJRkaT7t7AovdARNfc-_mdilacNIWEQBLUY,1149 +twilio/http/request.py,sha256=kVHsIN0kJQXRySE2VRVQwCPmp9ZycMxJ9zG7FnvArhM,2655 +twilio/http/response.py,sha256=BmDMxrJFDhgAxXQzoLwzO5pZSuw-y9KjEA-i3lz3yY4,518 +twilio/http/token_manager.py,sha256=pmt5lw3LsCGCIinmt7G8hq468TOJwYszYmy5-u8iMUE,128 +twilio/http/validation_client.py,sha256=ndVZrpcpG9i7db10mbrCjmU3ks8rqYu4EDWJeWnKFUM,4818 +twilio/jwt/__init__.py,sha256=MScUNrJ0oRY16IYehs1wYQVGlV5QKxLY0msD9xmjRpo,5085 +twilio/jwt/__pycache__/__init__.cpython-312.pyc,, +twilio/jwt/access_token/__init__.py,sha256=RJOJBVlO4xm3hgiltdFNKOgInJVId3G8CYVkhx6vP54,2415 +twilio/jwt/access_token/__pycache__/__init__.cpython-312.pyc,, +twilio/jwt/access_token/__pycache__/grants.cpython-312.pyc,, +twilio/jwt/access_token/grants.py,sha256=CVuyFTkyRC9nCc8Z70KpBpyYPygYqku08l8hoXO6BOc,4902 +twilio/jwt/client/__init__.py,sha256=GCWbuOKucutdnMIMtTesx0qvjEs25ieB_0upacFT604,3982 +twilio/jwt/client/__pycache__/__init__.cpython-312.pyc,, +twilio/jwt/taskrouter/__init__.py,sha256=2LIrC_6D4qvW278bKvqKM-VDBYLhwXxzwKfuri6LQ9I,5726 +twilio/jwt/taskrouter/__pycache__/__init__.cpython-312.pyc,, +twilio/jwt/taskrouter/__pycache__/capabilities.cpython-312.pyc,, +twilio/jwt/taskrouter/capabilities.py,sha256=TGE-YHo60LL-ubtu4JJitO0sviweqNPQjsRzBjWBzxo,4309 +twilio/jwt/validation/__init__.py,sha256=NSTRTHrEp5aoI-jbcc7KrKCRYIPMK5SITRMKj4y_sKQ,3156 +twilio/jwt/validation/__pycache__/__init__.cpython-312.pyc,, +twilio/request_validator.py,sha256=ZeoQ7BbnPrDGTy-M_RzcLq0l8Hir64Il5VbiqyOJNdc,4100 +twilio/rest/__init__.py,sha256=u46sq9dnCH4fZWlghIxEMxSQfQclMYcKPpaoW7IvP_Q,22772 +twilio/rest/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/accounts/AccountsBase.py,sha256=AqLmd6aIbV985gG5b473bkD2DqejaY4S3lvZaiNwcwg,1211 +twilio/rest/accounts/__init__.py,sha256=Oj-WM5ZDQWaF-2jstKhWRRPpkuCLs5AlDBpQlGDfZ28,1168 +twilio/rest/accounts/__pycache__/AccountsBase.cpython-312.pyc,, +twilio/rest/accounts/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/accounts/v1/__init__.py,sha256=R_igwYsDAEPd2evNtCQC7L1hyulyhJR-cC2_-5Hcm90,3035 +twilio/rest/accounts/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/accounts/v1/__pycache__/auth_token_promotion.cpython-312.pyc,, +twilio/rest/accounts/v1/__pycache__/bulk_consents.cpython-312.pyc,, +twilio/rest/accounts/v1/__pycache__/bulk_contacts.cpython-312.pyc,, +twilio/rest/accounts/v1/__pycache__/safelist.cpython-312.pyc,, +twilio/rest/accounts/v1/__pycache__/secondary_auth_token.cpython-312.pyc,, +twilio/rest/accounts/v1/auth_token_promotion.py,sha256=CEPC3tjgkDuq_qi1oGso40VWYuV9IXUu4ccMeFnZk3k,5693 +twilio/rest/accounts/v1/bulk_consents.py,sha256=luOHxVumkZ7CpCJInni3F8-xkVdh_gbxArWYa6gPWwk,5427 +twilio/rest/accounts/v1/bulk_contacts.py,sha256=aNvChaLiqiSgLPxCcZ6T6-TJcBz8B8KkAkjf5x6bthg,4673 +twilio/rest/accounts/v1/credential/__init__.py,sha256=NsXgoL4scQZKaq3Q1qIpWSGGbjPWF2KzOHfL6iwkLPo,1766 +twilio/rest/accounts/v1/credential/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/accounts/v1/credential/__pycache__/aws.cpython-312.pyc,, +twilio/rest/accounts/v1/credential/__pycache__/public_key.cpython-312.pyc,, +twilio/rest/accounts/v1/credential/aws.py,sha256=G9wy35gNqQwEMeLiqmsTwJzi4AGHBpftderkqEqdcWg,20690 +twilio/rest/accounts/v1/credential/public_key.py,sha256=XqkXV0xJv1In9T8uPea25gxj0ibhXSNcfUgY4uhu0fU,21208 +twilio/rest/accounts/v1/safelist.py,sha256=pT5xFckxFZ5yAPvqfesyjGUsjObQgcuDv_0qEnQFL3Y,6774 +twilio/rest/accounts/v1/secondary_auth_token.py,sha256=v6E6teddkZx0e6Mf8_wxMuYprtiab8VHjlUNg4yymSA,6605 +twilio/rest/api/ApiBase.py,sha256=1118YkG0wU9g7mMByeOtL4HfpUGvePUq4fK3_rpnsKU,1209 +twilio/rest/api/__init__.py,sha256=IF3HTJJA-JYCkkGZ_Mr6Js5AE3DVR7kVVfWZIbabN5Q,8255 +twilio/rest/api/__pycache__/ApiBase.cpython-312.pyc,, +twilio/rest/api/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/api/v2010/__init__.py,sha256=G3bZ5wo8gF9DrYNnYOVztO-T2-vPg_mBvHNXBVAaiSM,1806 +twilio/rest/api/v2010/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/api/v2010/account/__init__.py,sha256=Sm9ZE-1zXfhgMPK7drfcsXPJsbQqljhyRf_0S6m4W2A,37355 +twilio/rest/api/v2010/account/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/api/v2010/account/__pycache__/application.cpython-312.pyc,, +twilio/rest/api/v2010/account/__pycache__/authorized_connect_app.cpython-312.pyc,, +twilio/rest/api/v2010/account/__pycache__/balance.cpython-312.pyc,, +twilio/rest/api/v2010/account/__pycache__/connect_app.cpython-312.pyc,, +twilio/rest/api/v2010/account/__pycache__/key.cpython-312.pyc,, +twilio/rest/api/v2010/account/__pycache__/new_key.cpython-312.pyc,, +twilio/rest/api/v2010/account/__pycache__/new_signing_key.cpython-312.pyc,, +twilio/rest/api/v2010/account/__pycache__/notification.cpython-312.pyc,, +twilio/rest/api/v2010/account/__pycache__/outgoing_caller_id.cpython-312.pyc,, +twilio/rest/api/v2010/account/__pycache__/short_code.cpython-312.pyc,, +twilio/rest/api/v2010/account/__pycache__/signing_key.cpython-312.pyc,, +twilio/rest/api/v2010/account/__pycache__/token.cpython-312.pyc,, +twilio/rest/api/v2010/account/__pycache__/transcription.cpython-312.pyc,, +twilio/rest/api/v2010/account/__pycache__/validation_request.cpython-312.pyc,, +twilio/rest/api/v2010/account/address/__init__.py,sha256=vdZk4EaH3fidb4Th3a_KTaZxTkWFKa2QvUd-hKWvDvw,39062 +twilio/rest/api/v2010/account/address/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/api/v2010/account/address/__pycache__/dependent_phone_number.cpython-312.pyc,, +twilio/rest/api/v2010/account/address/dependent_phone_number.py,sha256=sMQLvzyiphrWC0VVjaCxgXBgyBRz94DjsQXzQfRRoJY,17366 +twilio/rest/api/v2010/account/application.py,sha256=TS8FsKf56PUiCE7B_abo0rvotD7xseg8dhRToypH0uc,49301 +twilio/rest/api/v2010/account/authorized_connect_app.py,sha256=F7PFVW5KZPz90UO3q0WTk1gR4uRJI7TyMVO8A0NyFWQ,17145 +twilio/rest/api/v2010/account/available_phone_number_country/__init__.py,sha256=sqW0aE7vhte9lavKlQyXC3ThpDrLrtvunpiix0peFw4,21896 +twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/local.cpython-312.pyc,, +twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/machine_to_machine.cpython-312.pyc,, +twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/mobile.cpython-312.pyc,, +twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/national.cpython-312.pyc,, +twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/shared_cost.cpython-312.pyc,, +twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/toll_free.cpython-312.pyc,, +twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/voip.cpython-312.pyc,, +twilio/rest/api/v2010/account/available_phone_number_country/local.py,sha256=laEx-fN4FMB_KOpj_c1UGlxR_iE771gboTlULr6lOCc,47262 +twilio/rest/api/v2010/account/available_phone_number_country/machine_to_machine.py,sha256=qcOEMC5jSht_SIva5o4E9AQkVMYuNCFoWFtI9WyVKn0,47233 +twilio/rest/api/v2010/account/available_phone_number_country/mobile.py,sha256=mcgfpgsgv3IPUSLTvY2uxDQyZbUPwITtdl_uEkwR038,46883 +twilio/rest/api/v2010/account/available_phone_number_country/national.py,sha256=7lj-_Cz7YHFWFJlTEJBV--eXEdN9xfJ-V6O51jgrhtQ,46953 +twilio/rest/api/v2010/account/available_phone_number_country/shared_cost.py,sha256=tALZGWREUHPshZ7XHdc8Q8Pgk_VeROu1a1i08BqJy0I,47023 +twilio/rest/api/v2010/account/available_phone_number_country/toll_free.py,sha256=roXo-I5eMYGRo0io77CPNxmEvMxcMeHDO6n49Vc081g,46953 +twilio/rest/api/v2010/account/available_phone_number_country/voip.py,sha256=2YVwsl_2KLYqhaQiZUqveWBmE2y89oyfHz3nvzf0iGY,46813 +twilio/rest/api/v2010/account/balance.py,sha256=K_7BbuHsg8Aeixu1aTGvOxkXahrDrsZGmrHEj_sxaA4,3538 +twilio/rest/api/v2010/account/call/__init__.py,sha256=BYVO4Xk4qxSI07LGZdD8Ehuk9HiOql_nQKNKlfMkVyw,93513 +twilio/rest/api/v2010/account/call/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/api/v2010/account/call/__pycache__/event.cpython-312.pyc,, +twilio/rest/api/v2010/account/call/__pycache__/notification.cpython-312.pyc,, +twilio/rest/api/v2010/account/call/__pycache__/payment.cpython-312.pyc,, +twilio/rest/api/v2010/account/call/__pycache__/recording.cpython-312.pyc,, +twilio/rest/api/v2010/account/call/__pycache__/siprec.cpython-312.pyc,, +twilio/rest/api/v2010/account/call/__pycache__/stream.cpython-312.pyc,, +twilio/rest/api/v2010/account/call/__pycache__/transcription.cpython-312.pyc,, +twilio/rest/api/v2010/account/call/__pycache__/user_defined_message.cpython-312.pyc,, +twilio/rest/api/v2010/account/call/__pycache__/user_defined_message_subscription.cpython-312.pyc,, +twilio/rest/api/v2010/account/call/event.py,sha256=35dC9vby41o3dpr2horEB_9T3y-lL0LcTpkZwkF5gJo,10978 +twilio/rest/api/v2010/account/call/notification.py,sha256=aXiBKdoenFitiDbLHonqdalRg1sv8bLPLkrsAFaatgM,28832 +twilio/rest/api/v2010/account/call/payment.py,sha256=hSxpKIPQvFAc3qj3YyiuQmXfNbGtWHXSo1C_WN3av8U,24310 +twilio/rest/api/v2010/account/call/recording.py,sha256=PopYJRkdLNWsOKneTjOyz20xWbBRjdVdB6qcWrR_1x4,39698 +twilio/rest/api/v2010/account/call/siprec.py,sha256=ih7ryOlR6EizYbaaZ3a9A-jgApmEFEloAd8RyqZRNjc,77906 +twilio/rest/api/v2010/account/call/stream.py,sha256=ZwtFxhtNzHKNIndruUTHb2zUgxJAtmdCHSf4vYmZwoc,77929 +twilio/rest/api/v2010/account/call/transcription.py,sha256=BmAAS6uyqMkYT5GFTSQo6nWTJRUZto5ir_FLpRuIEO0,17830 +twilio/rest/api/v2010/account/call/user_defined_message.py,sha256=lRrMjXP8vTJTd_AVOeNdu8o2qhbL8XDHlwn78fuYjLc,5667 +twilio/rest/api/v2010/account/call/user_defined_message_subscription.py,sha256=v7R8MBXAqZHO4AdojZfTOMRzDW2IlBDmOq-nv4xb8aw,11342 +twilio/rest/api/v2010/account/conference/__init__.py,sha256=tV6mKe9A4NdQdWWr5vPRGzjugsXaMgUwLdroBdSBGdk,47964 +twilio/rest/api/v2010/account/conference/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/api/v2010/account/conference/__pycache__/participant.cpython-312.pyc,, +twilio/rest/api/v2010/account/conference/__pycache__/recording.cpython-312.pyc,, +twilio/rest/api/v2010/account/conference/participant.py,sha256=9t2FkE75w-TWlUA3EmxGc3wwYikRjKHON-y4D3EJUTQ,79654 +twilio/rest/api/v2010/account/conference/recording.py,sha256=Nt715MUKsj1_UxedykHPGbKdTm3wvAfY1W8Fwgjc5nQ,33542 +twilio/rest/api/v2010/account/connect_app.py,sha256=lPHPbHrXq39lSyjfOr_MQZwTl4_aPRHtzj4mliJKJiI,27352 +twilio/rest/api/v2010/account/incoming_phone_number/__init__.py,sha256=X-oJqbA8oRk442_C5ISegdqsNy0oZd0XePub0nJ79sE,74914 +twilio/rest/api/v2010/account/incoming_phone_number/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/api/v2010/account/incoming_phone_number/__pycache__/local.cpython-312.pyc,, +twilio/rest/api/v2010/account/incoming_phone_number/__pycache__/mobile.cpython-312.pyc,, +twilio/rest/api/v2010/account/incoming_phone_number/__pycache__/toll_free.cpython-312.pyc,, +twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/__init__.py,sha256=dMaCWRPylUFGS-rCh7VPcodWv-TaiYYyHB9b6KU4tyI,21663 +twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/__pycache__/assigned_add_on_extension.cpython-312.pyc,, +twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/assigned_add_on_extension.py,sha256=FxyLuWNlPgPNzR2rbP4fH_VXp5ZNzdxFCa2ZjeRN4Pc,18810 +twilio/rest/api/v2010/account/incoming_phone_number/local.py,sha256=2V5X3oWot6bbrjccEFmq_dm7l8nNkft-Fk7RsmUaol0,37854 +twilio/rest/api/v2010/account/incoming_phone_number/mobile.py,sha256=R2rNjLg2J_Xu656cdw9sncT6uGXvty7t8RcptnWMY8I,37938 +twilio/rest/api/v2010/account/incoming_phone_number/toll_free.py,sha256=eKn4qqcxHadSlRKo89UWVGeZqymeOhjzi1CIMOJW8HY,38024 +twilio/rest/api/v2010/account/key.py,sha256=7o10k4zQXssQanG1hHN2ARlwx_LSETXyFzH4Q7ew2P8,18800 +twilio/rest/api/v2010/account/message/__init__.py,sha256=UuqQJGG4QWdXiEoVo9lxghbA_dm5an9l0pkO3sm94-M,58874 +twilio/rest/api/v2010/account/message/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/api/v2010/account/message/__pycache__/feedback.cpython-312.pyc,, +twilio/rest/api/v2010/account/message/__pycache__/media.cpython-312.pyc,, +twilio/rest/api/v2010/account/message/feedback.py,sha256=2gGH74VJbI9pICWkq1wzfokE6viCVg9FCh0nUOMhEIQ,5586 +twilio/rest/api/v2010/account/message/media.py,sha256=58JeQHU_XjVSkND6EZvFp6fvqmcqqZUXldP7m310jkA,28066 +twilio/rest/api/v2010/account/new_key.py,sha256=QQRwQ55JXp008p2VHbjtLcxu222aSYWIIrpOAqYCo7c,5174 +twilio/rest/api/v2010/account/new_signing_key.py,sha256=ml4mwDgkK06FUKJWFI4KSNMho1EmBGwXU4tKJ4u8wpY,5202 +twilio/rest/api/v2010/account/notification.py,sha256=ZzA_0h_ivRe2gRPZPXouJxW-lFBQlk763NdX5n0rcXw,27974 +twilio/rest/api/v2010/account/outgoing_caller_id.py,sha256=FBXTNqu9Fg5Xt34AIZU75rNIGkLH9mvUARzoVL7x--c,23010 +twilio/rest/api/v2010/account/queue/__init__.py,sha256=0NbAGOuAcf4bnSBex_71vxyruCB7p1w2h2Fex7FzQQ4,23629 +twilio/rest/api/v2010/account/queue/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/api/v2010/account/queue/__pycache__/member.cpython-312.pyc,, +twilio/rest/api/v2010/account/queue/member.py,sha256=jVbeoDZ9eh3NgaMYwxqkK79NsMsxA0bqJ_e2YG6psqo,19888 +twilio/rest/api/v2010/account/recording/__init__.py,sha256=iwZNdf2cByvRvosP3MNbnaNllAFx6pYLP_hrHUXFbQE,38236 +twilio/rest/api/v2010/account/recording/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/api/v2010/account/recording/__pycache__/transcription.cpython-312.pyc,, +twilio/rest/api/v2010/account/recording/add_on_result/__init__.py,sha256=SEcSdT9l8zz1FbtOk-BTtek4akBIJ7nq5gvbGHuLmA4,19764 +twilio/rest/api/v2010/account/recording/add_on_result/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/api/v2010/account/recording/add_on_result/payload/__init__.py,sha256=2P-YLw4EX98LXPlvSweN55l9Eh1O8_NIbaEOxFKMeyc,20438 +twilio/rest/api/v2010/account/recording/add_on_result/payload/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/api/v2010/account/recording/add_on_result/payload/__pycache__/data.cpython-312.pyc,, +twilio/rest/api/v2010/account/recording/add_on_result/payload/data.py,sha256=l1XKqSpFwHr_FlWee9LSw83hWpk3DnIU3llAs94Oeu0,7986 +twilio/rest/api/v2010/account/recording/transcription.py,sha256=2Sd-gon5TzQ_VFxypJLzGscq77_Sc-SD-RWbpVe4rhA,19533 +twilio/rest/api/v2010/account/short_code.py,sha256=cGWy0l9ZEgWJ_LeYlyxHT9uxVBY1nGs4oQqPzWOpUUk,27163 +twilio/rest/api/v2010/account/signing_key.py,sha256=xlcskx0qnbRRHDb_-1wSazdVioI07TrflMNNZBVjFj0,18187 +twilio/rest/api/v2010/account/sip/__init__.py,sha256=UNiLJ1eMTojjpoUrhgnV4Pux6F4udK3U7eVOMOHp9ws,2871 +twilio/rest/api/v2010/account/sip/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/api/v2010/account/sip/credential_list/__init__.py,sha256=6Iz29WLYKKfzmqxGwQ00eYF1qR0KM2QH6GRNNTYRMuQ,22479 +twilio/rest/api/v2010/account/sip/credential_list/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/api/v2010/account/sip/credential_list/__pycache__/credential.cpython-312.pyc,, +twilio/rest/api/v2010/account/sip/credential_list/credential.py,sha256=MqjBJV_lVJDBOXAiZPOsjIorJi6fT59y_rNAvWJE2ec,23958 +twilio/rest/api/v2010/account/sip/domain/__init__.py,sha256=N5Fg6CAZVWA0n_NpZWN4b5HDnL3ux3t8zFIeHhgBajY,46828 +twilio/rest/api/v2010/account/sip/domain/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/api/v2010/account/sip/domain/__pycache__/credential_list_mapping.cpython-312.pyc,, +twilio/rest/api/v2010/account/sip/domain/__pycache__/ip_access_control_list_mapping.cpython-312.pyc,, +twilio/rest/api/v2010/account/sip/domain/auth_types/__init__.py,sha256=9e9q4NNr8KnUwHdYNbh2fpuaAVUuZ2OeQCuRQc-gsco,2758 +twilio/rest/api/v2010/account/sip/domain/auth_types/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/__init__.py,sha256=nolfbRsWWIcMstPOS1VXOH9gDrNceSCUQYfcM4OSIXo,3332 +twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/__pycache__/auth_calls_credential_list_mapping.cpython-312.pyc,, +twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/__pycache__/auth_calls_ip_access_control_list_mapping.cpython-312.pyc,, +twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_credential_list_mapping.py,sha256=-qOf-2WU1AxDwO7ASuA62MQ1I8TiXgOhfjpJKcn2uvs,21353 +twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_ip_access_control_list_mapping.py,sha256=ddyvBSX5bi1rybHobzg-yrDfGyqT6yTgwZCiek9IdMM,21894 +twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/__init__.py,sha256=L0TAMoyPSClaHsol6TCehYLaBbNTf9EXMHSM2ipyDKA,2473 +twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/__pycache__/auth_registrations_credential_list_mapping.cpython-312.pyc,, +twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/auth_registrations_credential_list_mapping.py,sha256=tGa7y9pBeZFyzTVea9MJlFzS8Hmo_QoyEAnlLF9m-Tg,21961 +twilio/rest/api/v2010/account/sip/domain/credential_list_mapping.py,sha256=xq5A5I1I_mY7uuAVQSrIXk0SXrTcvarSRDn_u9XPZfg,20806 +twilio/rest/api/v2010/account/sip/domain/ip_access_control_list_mapping.py,sha256=FAhe9JiJBX28oWKuBg7VmxyXjCb2IU-H4icW3s1IZbU,21077 +twilio/rest/api/v2010/account/sip/ip_access_control_list/__init__.py,sha256=a8zaJdVdF2pTtxiaCws9V0ktd-mbb3dCBwxP-pTTCIM,23009 +twilio/rest/api/v2010/account/sip/ip_access_control_list/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/api/v2010/account/sip/ip_access_control_list/__pycache__/ip_address.cpython-312.pyc,, +twilio/rest/api/v2010/account/sip/ip_access_control_list/ip_address.py,sha256=jIYtlIx04iTR4dOJFEAyNfglGAKwJzCJ4g6QeTRplVE,27439 +twilio/rest/api/v2010/account/token.py,sha256=y4Qw6yQgr9uC2lbVxoTQ3YOXE6oEkv1Q8d56uf777D8,5212 +twilio/rest/api/v2010/account/transcription.py,sha256=k_P5_2VUd5CNgN5ia4zV3FoqW6KhMdYbZv_YYGtnDBE,18559 +twilio/rest/api/v2010/account/usage/__init__.py,sha256=uuxXF4PSniarhk76bNQxiOXKpBGhFXDVJhNiO-T69qI,2220 +twilio/rest/api/v2010/account/usage/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/api/v2010/account/usage/__pycache__/trigger.cpython-312.pyc,, +twilio/rest/api/v2010/account/usage/record/__init__.py,sha256=9EjEEbxXJcIIUZjK5v6eQ-581RfhJreccq4lm0qymcc,68865 +twilio/rest/api/v2010/account/usage/record/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/api/v2010/account/usage/record/__pycache__/all_time.cpython-312.pyc,, +twilio/rest/api/v2010/account/usage/record/__pycache__/daily.cpython-312.pyc,, +twilio/rest/api/v2010/account/usage/record/__pycache__/last_month.cpython-312.pyc,, +twilio/rest/api/v2010/account/usage/record/__pycache__/monthly.cpython-312.pyc,, +twilio/rest/api/v2010/account/usage/record/__pycache__/this_month.cpython-312.pyc,, +twilio/rest/api/v2010/account/usage/record/__pycache__/today.cpython-312.pyc,, +twilio/rest/api/v2010/account/usage/record/__pycache__/yearly.cpython-312.pyc,, +twilio/rest/api/v2010/account/usage/record/__pycache__/yesterday.cpython-312.pyc,, +twilio/rest/api/v2010/account/usage/record/all_time.py,sha256=Qj2ph9VT3ezj5_ZK9ANXkT3wJZmLWEHHTEtSz6Xyzqk,65509 +twilio/rest/api/v2010/account/usage/record/daily.py,sha256=puhl_bIMspI9LOypZsupUVgymJ3_e-nbnWvTErCy_5o,65417 +twilio/rest/api/v2010/account/usage/record/last_month.py,sha256=UFnee7ZbLqBt-NbIYwgknLLWvibPFAIQnweFcPUfVZQ,65601 +twilio/rest/api/v2010/account/usage/record/monthly.py,sha256=xj_dsqBtHDm-7ydC2dDNy4zDPTB9h0S0j4K3wECfvyk,65509 +twilio/rest/api/v2010/account/usage/record/this_month.py,sha256=ZBmGSy6XNn2h04l_EY9zojjrKmA-c16DZIQFV_mS_0M,65601 +twilio/rest/api/v2010/account/usage/record/today.py,sha256=X-Tdd0CVL9VpCMbdgntzshadhHsTPcP0ozKj4NFsPZ0,65417 +twilio/rest/api/v2010/account/usage/record/yearly.py,sha256=fuzQdPbzKLB0bDWCHMx5Z2S-m6Edu0RDi5vZ36DkmE0,65463 +twilio/rest/api/v2010/account/usage/record/yesterday.py,sha256=vxoFxArKfrYhxgNh9f5LJIckv3xiZ39MEWJT3JwmeWQ,65601 +twilio/rest/api/v2010/account/usage/trigger.py,sha256=I8UTmyz9IZGKwQ_-RST3zzA1kZdeBoEOivstoCGCJqk,77238 +twilio/rest/api/v2010/account/validation_request.py,sha256=6ySMvEZxVIn5bPbD3j5l5XaUZEyncLkrWnlchEQRds0,7786 +twilio/rest/assistants/AssistantsBase.py,sha256=zEffT94q3Z61xfAO_L5x66CwpLTcwk9d47V8iBAQhyo,1225 +twilio/rest/assistants/__init__.py,sha256=4Wu-shnCXczxJryvZmphy2Zg7vppA4IFTnO-nXqQcrw,1578 +twilio/rest/assistants/__pycache__/AssistantsBase.cpython-312.pyc,, +twilio/rest/assistants/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/assistants/v1/__init__.py,sha256=FHupHKV682ELSutx8B9JUMFqfaBO2X4ELcv0JgHLtqs,2407 +twilio/rest/assistants/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/assistants/v1/__pycache__/policy.cpython-312.pyc,, +twilio/rest/assistants/v1/__pycache__/tool.cpython-312.pyc,, +twilio/rest/assistants/v1/assistant/__init__.py,sha256=Sx5ueNQP0JN19eCDcaME5RPu8jo-CQ6SRLI5glDUpkQ,36305 +twilio/rest/assistants/v1/assistant/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/assistants/v1/assistant/__pycache__/assistants_knowledge.cpython-312.pyc,, +twilio/rest/assistants/v1/assistant/__pycache__/assistants_tool.cpython-312.pyc,, +twilio/rest/assistants/v1/assistant/__pycache__/feedback.cpython-312.pyc,, +twilio/rest/assistants/v1/assistant/__pycache__/message.cpython-312.pyc,, +twilio/rest/assistants/v1/assistant/assistants_knowledge.py,sha256=_mYOFtWdPf6ovwWxuI-64qBSEKzWxIXkYPHDevq1nAs,18788 +twilio/rest/assistants/v1/assistant/assistants_tool.py,sha256=qAv-9ZkPB87A8rwkpsUrdlDkqz5oLsYe1dTl4Z_7WXY,18172 +twilio/rest/assistants/v1/assistant/feedback.py,sha256=hxJ-MMZy-6JuJvFOVVAbHNH0lwcQCLVpsFCCX6MPeh8,15127 +twilio/rest/assistants/v1/assistant/message.py,sha256=HXFkpnClfPGrv75P-XGnt2M8qQSRtecpabI57IOIih8,6751 +twilio/rest/assistants/v1/knowledge/__init__.py,sha256=UQJL3bmsmFhSdV8wC8UIqOLFcYraNHSqReBuwRi9acU,35246 +twilio/rest/assistants/v1/knowledge/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/assistants/v1/knowledge/__pycache__/chunk.cpython-312.pyc,, +twilio/rest/assistants/v1/knowledge/__pycache__/knowledge_status.cpython-312.pyc,, +twilio/rest/assistants/v1/knowledge/chunk.py,sha256=RT8yJBkvAHi828_ogPqFOgSbuLTfnpiXFw-k4dNM8Zc,11243 +twilio/rest/assistants/v1/knowledge/knowledge_status.py,sha256=gtY8hL5aUNCjf9UkUgE4EsMRM_C8mKX8PjWYpFJ2NNw,6049 +twilio/rest/assistants/v1/policy.py,sha256=9mFdp1Ze7cK8PfiU7m2hAj7IO-L1LkcOiNK7GuNJk1M,12955 +twilio/rest/assistants/v1/session/__init__.py,sha256=O_cTY3J_UbVtnPgECu53bM1csISk8nodZkCHcEOWrM0,14943 +twilio/rest/assistants/v1/session/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/assistants/v1/session/__pycache__/message.cpython-312.pyc,, +twilio/rest/assistants/v1/session/message.py,sha256=sZicIuZYgGHv94-QyXJ7esWr65j9nJynzqddU7MhXrE,11964 +twilio/rest/assistants/v1/tool.py,sha256=CZpw1fwlWmRA7Dhoe4z7jdMhbrveigzZEm8EpLEahd8,32256 +twilio/rest/bulkexports/BulkexportsBase.py,sha256=zZVbqHt-GFEwknpCSTIkMnUiy0psGTVr707I65ppqRA,1232 +twilio/rest/bulkexports/__init__.py,sha256=W70NE5bxC2jLDmKtWWL5WUe_hYQeywBIlqfRrQQxsnU,792 +twilio/rest/bulkexports/__pycache__/BulkexportsBase.cpython-312.pyc,, +twilio/rest/bulkexports/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/bulkexports/v1/__init__.py,sha256=17bpWiEa9ctnhyCFjXOlYLQNcrqMILJ28XTUY5MSeXc,1693 +twilio/rest/bulkexports/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/bulkexports/v1/__pycache__/export_configuration.cpython-312.pyc,, +twilio/rest/bulkexports/v1/export/__init__.py,sha256=bgpvSCEkYd2P3eq5vtQgLBrne_OBBECJ6_Okc25Ozjw,7262 +twilio/rest/bulkexports/v1/export/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/bulkexports/v1/export/__pycache__/day.cpython-312.pyc,, +twilio/rest/bulkexports/v1/export/__pycache__/export_custom_job.cpython-312.pyc,, +twilio/rest/bulkexports/v1/export/__pycache__/job.cpython-312.pyc,, +twilio/rest/bulkexports/v1/export/day.py,sha256=IGG0nj_6-nwoUjIaD6o7G1g9DZSaWI8YJO_T-brJSog,14990 +twilio/rest/bulkexports/v1/export/export_custom_job.py,sha256=IWcqxrpR7k-KjL07G6lsYKgS-iV8FF7J7diw3reuVLg,17715 +twilio/rest/bulkexports/v1/export/job.py,sha256=kXTZ7jNMacOhtxVibodj8ZtPrT_pbD5B8H_PqnzxKU0,8457 +twilio/rest/bulkexports/v1/export_configuration.py,sha256=BpPQXqAqfj0eKRYZHLZaH5ZfSBae9wQjTCyIYpIqBaU,11316 +twilio/rest/chat/ChatBase.py,sha256=KD32OSHBJlk3FnRUTh5rYBgVCX-8Wd3FxMK-sMbwfCU,1701 +twilio/rest/chat/__init__.py,sha256=yqheEsHshStD2dZwRJIab6Vd7pJ8l99lx6I1D-SDLaA,970 +twilio/rest/chat/__pycache__/ChatBase.cpython-312.pyc,, +twilio/rest/chat/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/chat/v1/__init__.py,sha256=pIPnbTMhwrC_TrSuEkGC1FMRoI9P0fl7auFCScLZs5g,1570 +twilio/rest/chat/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/chat/v1/__pycache__/credential.cpython-312.pyc,, +twilio/rest/chat/v1/credential.py,sha256=kSIXMoqKDnyASylYeK1AFS1Jg54UtkEf5NUMlTNNzX4,29186 +twilio/rest/chat/v1/service/__init__.py,sha256=lz04U3hL9dU_Qt1VPCFkG3YGsCO_SPzAS_xKvzovqhY,94603 +twilio/rest/chat/v1/service/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/chat/v1/service/__pycache__/role.cpython-312.pyc,, +twilio/rest/chat/v1/service/channel/__init__.py,sha256=z4Hm7Wqpl2jj6svVwaZJnVIGS9bJ88K5E6wr_saEu2k,30170 +twilio/rest/chat/v1/service/channel/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/chat/v1/service/channel/__pycache__/invite.cpython-312.pyc,, +twilio/rest/chat/v1/service/channel/__pycache__/member.cpython-312.pyc,, +twilio/rest/chat/v1/service/channel/__pycache__/message.cpython-312.pyc,, +twilio/rest/chat/v1/service/channel/invite.py,sha256=I1AsyjaFixkMSYORBeQzg_uQ2m3v0FZN7kQgVHzrJWg,23225 +twilio/rest/chat/v1/service/channel/member.py,sha256=YK1ZHjFhefjbSOVIpzygcf8YYCeoazPVpHvJyajPSGw,28912 +twilio/rest/chat/v1/service/channel/message.py,sha256=ppCuv00iaqkP9SSlF9GJWm0G8RRZ9zxhr6lwxBU3txw,27559 +twilio/rest/chat/v1/service/role.py,sha256=AirHxVzWEiFdMnZX3sedeYIMzmRBzEmcU6LWAel4TM0,23034 +twilio/rest/chat/v1/service/user/__init__.py,sha256=Bdihokzz7E0wCsRoufK-fZ8EcX62pYwiYzOtlsrJRKE,27518 +twilio/rest/chat/v1/service/user/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/chat/v1/service/user/__pycache__/user_channel.cpython-312.pyc,, +twilio/rest/chat/v1/service/user/user_channel.py,sha256=7gq6lCWzKU9vknd3Axrqo58lGjKi_euTjoPsqyZ5i1Q,13247 +twilio/rest/chat/v2/__init__.py,sha256=2MmAILBGDLB1r-m1D9B3OuCk0N-b8XosRDGwinn32C0,1570 +twilio/rest/chat/v2/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/chat/v2/__pycache__/credential.cpython-312.pyc,, +twilio/rest/chat/v2/credential.py,sha256=QyNZAtP6HqEvykxZiNXtcGSvugMufKRUEBeFiNQ4hX4,28816 +twilio/rest/chat/v2/service/__init__.py,sha256=DL8U0qjDj2ZCvIVatGdH-M_biqeOYaY9kFsBjQaJeTs,68767 +twilio/rest/chat/v2/service/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/chat/v2/service/__pycache__/binding.cpython-312.pyc,, +twilio/rest/chat/v2/service/__pycache__/role.cpython-312.pyc,, +twilio/rest/chat/v2/service/binding.py,sha256=-g6MZo7KlKODz0ups8aqfXeVW_xbwcvX0TXSknnOvEI,22643 +twilio/rest/chat/v2/service/channel/__init__.py,sha256=lb-UlGCc8j_7ih-LjK5lhXD8_Ur-ZuBuFAbiCT8H7hM,40660 +twilio/rest/chat/v2/service/channel/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/chat/v2/service/channel/__pycache__/invite.cpython-312.pyc,, +twilio/rest/chat/v2/service/channel/__pycache__/member.cpython-312.pyc,, +twilio/rest/chat/v2/service/channel/__pycache__/message.cpython-312.pyc,, +twilio/rest/chat/v2/service/channel/__pycache__/webhook.cpython-312.pyc,, +twilio/rest/chat/v2/service/channel/invite.py,sha256=EWJyb1ZH36q-e4sSgaUbO0eXWfBmwejRNZBuhg5iqCc,23205 +twilio/rest/chat/v2/service/channel/member.py,sha256=ybSJITkqTN6yGwRdWYuI0k54sIOwE1PR9zVd0Y3u578,42648 +twilio/rest/chat/v2/service/channel/message.py,sha256=WLMbljK0eo3SfeUpi67_vQDYgrrRfNA8FpdxwsKyt8k,39082 +twilio/rest/chat/v2/service/channel/webhook.py,sha256=U_NujpfO7Lg07UFZ3ACPJuXFHl8wUmoupi7cvoYpCTk,34973 +twilio/rest/chat/v2/service/role.py,sha256=YulJAE3beY2sR3ZzZVmdvXuPxGNl4dllNCXQz9kjCRI,23435 +twilio/rest/chat/v2/service/user/__init__.py,sha256=haouJvuAu3H-9L2dDmZyIWc1Y45PFOjNd8c84wHeRb0,30560 +twilio/rest/chat/v2/service/user/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/chat/v2/service/user/__pycache__/user_binding.cpython-312.pyc,, +twilio/rest/chat/v2/service/user/__pycache__/user_channel.cpython-312.pyc,, +twilio/rest/chat/v2/service/user/user_binding.py,sha256=0b6_z2ZRybkURNriatBLj6kpbPQSYrZbNkRt-L7Exw8,22434 +twilio/rest/chat/v2/service/user/user_channel.py,sha256=IhLMQn64a0hvrCiY_-29k5oIgG7a7x6wh6lHf71SG5A,27877 +twilio/rest/chat/v3/__init__.py,sha256=iNQ57HwS3IRB3wny2tHXgjL_qW8eN_c37SAGYYMRpAU,1269 +twilio/rest/chat/v3/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/chat/v3/__pycache__/channel.cpython-312.pyc,, +twilio/rest/chat/v3/channel.py,sha256=poEyzBnZNliy4aS1lPXh024oDRnFHJXZ-1ZSYLgjV8A,12259 +twilio/rest/content/ContentBase.py,sha256=dQqMOWOjQ3xMGuDM2r1W9l2mkrxpxBCubglipq8ZdfM,1469 +twilio/rest/content/__init__.py,sha256=Q9Dc5LDsvNo1f1FttcKGP8uwMr2DDOoyrzdVHjgb5YA,1110 +twilio/rest/content/__pycache__/ContentBase.cpython-312.pyc,, +twilio/rest/content/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/content/v1/__init__.py,sha256=OJ_jzAzh2Q0NcAQUb3l5ohrBR08wfwDYfLMNwoQZ4No,2025 +twilio/rest/content/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/content/v1/__pycache__/content_and_approvals.cpython-312.pyc,, +twilio/rest/content/v1/__pycache__/legacy_content.cpython-312.pyc,, +twilio/rest/content/v1/content/__init__.py,sha256=o_f6Xr8Fttjqy5du6f3oYDoyFSXtB82CZkDLbpKHtP4,88781 +twilio/rest/content/v1/content/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/content/v1/content/__pycache__/approval_create.cpython-312.pyc,, +twilio/rest/content/v1/content/__pycache__/approval_fetch.cpython-312.pyc,, +twilio/rest/content/v1/content/approval_create.py,sha256=1LjKaTUSnQU1qCGo6PAv60DPaO6-Et8jeHXLvEmCEM4,5148 +twilio/rest/content/v1/content/approval_fetch.py,sha256=4G4JVwF7-wCC8Nq0vjcyDR-_Z8eAZWzoezXs-c3_z-E,6018 +twilio/rest/content/v1/content_and_approvals.py,sha256=9M0X55_Y-y0Jh-I_gum3c0xQ3oAQ6XYUVZVXIiBFE_4,12244 +twilio/rest/content/v1/legacy_content.py,sha256=icfgdpBAHNHpFqLstktL7e1xQd-siB2R_W6za8NV0k0,12443 +twilio/rest/content/v2/__init__.py,sha256=AEiqhEK9xMUccgKm_QcMCtHuk7cCO_bGTIu-icgBnZ4,1685 +twilio/rest/content/v2/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/content/v2/__pycache__/content.cpython-312.pyc,, +twilio/rest/content/v2/__pycache__/content_and_approvals.cpython-312.pyc,, +twilio/rest/content/v2/content.py,sha256=BRqYh2LROOZQMdcVh4OaP0X_8fd2LRqzU5EbFEqBBrw,22457 +twilio/rest/content/v2/content_and_approvals.py,sha256=KIId6S1cJ5rSYed6fPh78DnHzf4aA8QpKD6qe8qbj2g,22787 +twilio/rest/conversations/ConversationsBase.py,sha256=_xLX2JZyT_NNtyDsHn9NVE3LT3rh9x_gSlqFNE5zxyE,1246 +twilio/rest/conversations/__init__.py,sha256=wrtnbo04IMJ0dAyAXcBU2FPCV3fRFfDjjvQdGtNqbiA,2760 +twilio/rest/conversations/__pycache__/ConversationsBase.cpython-312.pyc,, +twilio/rest/conversations/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/conversations/v1/__init__.py,sha256=8dH1CjGT_tk7xeq5ntTI2gOUnlOPVzVJdKZxIPUoFFE,4218 +twilio/rest/conversations/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/conversations/v1/__pycache__/address_configuration.cpython-312.pyc,, +twilio/rest/conversations/v1/__pycache__/conversation_with_participants.cpython-312.pyc,, +twilio/rest/conversations/v1/__pycache__/credential.cpython-312.pyc,, +twilio/rest/conversations/v1/__pycache__/participant_conversation.cpython-312.pyc,, +twilio/rest/conversations/v1/__pycache__/role.cpython-312.pyc,, +twilio/rest/conversations/v1/address_configuration.py,sha256=mk4leUh4m4KeWSVz6qVCscVdzwcBTXDna4L513apDaw,39180 +twilio/rest/conversations/v1/configuration/__init__.py,sha256=mrnQMOVnFnBd34XA_Gkad6lqnXtClH8aAYgNJGAIqNg,13003 +twilio/rest/conversations/v1/configuration/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/conversations/v1/configuration/__pycache__/webhook.cpython-312.pyc,, +twilio/rest/conversations/v1/configuration/webhook.py,sha256=3MM5VvdVSiuoRZRMgs5nmkri-pzorOrO_ZEc3VT6oeI,13076 +twilio/rest/conversations/v1/conversation/__init__.py,sha256=f2AWwVwbtVxU0LH51yYmJ_bK0nYlcsYmUtnbeUixQpk,51446 +twilio/rest/conversations/v1/conversation/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/conversations/v1/conversation/__pycache__/participant.cpython-312.pyc,, +twilio/rest/conversations/v1/conversation/__pycache__/webhook.cpython-312.pyc,, +twilio/rest/conversations/v1/conversation/message/__init__.py,sha256=g5IAs5OQDbINqx3_JzHbSBeuDNYqKWZ2f3d0eR98XR8,37538 +twilio/rest/conversations/v1/conversation/message/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/conversations/v1/conversation/message/__pycache__/delivery_receipt.cpython-312.pyc,, +twilio/rest/conversations/v1/conversation/message/delivery_receipt.py,sha256=T0yBAlBcYc8HNknohDaYJHwMFeNyHNjctCmKUYlEeYc,18534 +twilio/rest/conversations/v1/conversation/participant.py,sha256=9Wk0CAFor7iX0qgERR-424AssONStbXulEeUY_2N5tI,41653 +twilio/rest/conversations/v1/conversation/webhook.py,sha256=XTmVt7FEMoldiFQiW0KJsSADIOJwu-CE_Z8uR6q_11g,28439 +twilio/rest/conversations/v1/conversation_with_participants.py,sha256=hQfYR85cFKUH9JcFX9ftFj-XByCDAbBVqeL44f_DmnM,13383 +twilio/rest/conversations/v1/credential.py,sha256=AKUOd-i3kzGkvSAJ-5icaVjrP9OulDtluiiZH6fFPQA,29265 +twilio/rest/conversations/v1/participant_conversation.py,sha256=GQ2CBDQPmT2_QnVAtB7jzSzXPfRxDBAehXcD_GCp8RA,19067 +twilio/rest/conversations/v1/role.py,sha256=jBWZCQid-lAbhDiH6eIVeY7KCNUt69GBv0_aGwHU_To,22146 +twilio/rest/conversations/v1/service/__init__.py,sha256=ZwztACi4635N39jM6z87siFcnNjyKVzMxqwvMvH2z4k,21856 +twilio/rest/conversations/v1/service/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/conversations/v1/service/__pycache__/binding.cpython-312.pyc,, +twilio/rest/conversations/v1/service/__pycache__/conversation_with_participants.cpython-312.pyc,, +twilio/rest/conversations/v1/service/__pycache__/participant_conversation.cpython-312.pyc,, +twilio/rest/conversations/v1/service/__pycache__/role.cpython-312.pyc,, +twilio/rest/conversations/v1/service/binding.py,sha256=TKI13VFqXGLGoNG_gciR2QHoBOjg8vDFsIh-hSOTkEc,22814 +twilio/rest/conversations/v1/service/configuration/__init__.py,sha256=vU4xrwjBZX0xbMk_u-Sxm1_ISfgfrgHVV10O7x0uE1k,16599 +twilio/rest/conversations/v1/service/configuration/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/conversations/v1/service/configuration/__pycache__/notification.cpython-312.pyc,, +twilio/rest/conversations/v1/service/configuration/__pycache__/webhook.cpython-312.pyc,, +twilio/rest/conversations/v1/service/configuration/notification.py,sha256=B9Y8Oz1pzZtaPleMLHDsSqdRYHgHzuDaxaj2Bv3IzW4,25509 +twilio/rest/conversations/v1/service/configuration/webhook.py,sha256=cY9V3K2ByznSMatOQeKvpT7lrmfxqU42pmdFyQWlfvA,14319 +twilio/rest/conversations/v1/service/conversation/__init__.py,sha256=uYgWc-u_SLSx16a3oxQ3gv6eEtxs0WmnE7bN68yr0Ng,53297 +twilio/rest/conversations/v1/service/conversation/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/conversations/v1/service/conversation/__pycache__/participant.cpython-312.pyc,, +twilio/rest/conversations/v1/service/conversation/__pycache__/webhook.cpython-312.pyc,, +twilio/rest/conversations/v1/service/conversation/message/__init__.py,sha256=QPH2y1ttmlREN9c-m9gg34p0MZEBLj_SiSvAuTMNMzI,39195 +twilio/rest/conversations/v1/service/conversation/message/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/conversations/v1/service/conversation/message/__pycache__/delivery_receipt.cpython-312.pyc,, +twilio/rest/conversations/v1/service/conversation/message/delivery_receipt.py,sha256=PpNlvz6SH6tsalMba69lkD7UL2Z3eqKi475Ig22SOZE,19869 +twilio/rest/conversations/v1/service/conversation/participant.py,sha256=M3blybA18uatyzT55fI5I45OzRoGkOWwLhczk1ia280,43630 +twilio/rest/conversations/v1/service/conversation/webhook.py,sha256=eJJQim1Q87xIMkNBOy9fXhR9WAhsiNqZnOXIFeY0AgU,30129 +twilio/rest/conversations/v1/service/conversation_with_participants.py,sha256=2MSv8o1xtWq2tlUd0JbR0K1-KAe8kMl4dkLmmGaAg2k,14204 +twilio/rest/conversations/v1/service/participant_conversation.py,sha256=1GCqZGj-BtLkEQlqJf1SWhXQCZcWjGhViIVaGBgJurc,19858 +twilio/rest/conversations/v1/service/role.py,sha256=Lz7PcgnuPvmBDLO7Ml1LmLpxaMFqZgN4jYas1Q9bpCs,23737 +twilio/rest/conversations/v1/service/user/__init__.py,sha256=fjp1dkaaQwL1KSQ0Yp1iIjSdjFO6mbXsb6Lfd_kmV74,31219 +twilio/rest/conversations/v1/service/user/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/conversations/v1/service/user/__pycache__/user_conversation.cpython-312.pyc,, +twilio/rest/conversations/v1/service/user/user_conversation.py,sha256=SHiSIItso8VNGoU3h9_vxl82AG1GUj_U3mbvJn3hM3c,27325 +twilio/rest/conversations/v1/user/__init__.py,sha256=GGbwZDCEJeHoR-CyxYLb333-h3PvsWwhxd_-8-FzY5Q,29553 +twilio/rest/conversations/v1/user/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/conversations/v1/user/__pycache__/user_conversation.cpython-312.pyc,, +twilio/rest/conversations/v1/user/user_conversation.py,sha256=10XdwEZeyEcaRg0XkKOB9qtbXDPbMq5JYm2laPESZAw,26030 +twilio/rest/events/EventsBase.py,sha256=VmnvvHtsOqJHgao-2Db4suiqZbpRmzlbR_0mkXyg-yg,1197 +twilio/rest/events/__init__.py,sha256=0c7O0oWx1KIrwS_tzCy8c34OkPJfqXCK_9lULiGi_7s,1277 +twilio/rest/events/__pycache__/EventsBase.cpython-312.pyc,, +twilio/rest/events/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/events/v1/__init__.py,sha256=gxoinjjx5rqW0zUxOp6Ild8m1mNG8zayV5-nnlbCR-Q,2134 +twilio/rest/events/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/events/v1/__pycache__/event_type.cpython-312.pyc,, +twilio/rest/events/v1/event_type.py,sha256=LP6dyDkCj_SP237YQOAEPoqu1awzUYb51P6Y3vOSElo,16265 +twilio/rest/events/v1/schema/__init__.py,sha256=lY5TfjZ40DF7MTZuOzvUX992RBGlbH2roGhFxlYbmLE,6575 +twilio/rest/events/v1/schema/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/events/v1/schema/__pycache__/schema_version.cpython-312.pyc,, +twilio/rest/events/v1/schema/schema_version.py,sha256=vPU4IXvWWi0lNSg96JaHFqG1lG1n4VJcaGZVQxl9ZRY,15389 +twilio/rest/events/v1/sink/__init__.py,sha256=V1SUPy4QT_rXFfZSOv61L8UPL6ziHfmpt8IswZMqWCc,24157 +twilio/rest/events/v1/sink/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/events/v1/sink/__pycache__/sink_test.cpython-312.pyc,, +twilio/rest/events/v1/sink/__pycache__/sink_validate.cpython-312.pyc,, +twilio/rest/events/v1/sink/sink_test.py,sha256=wqSIshtRm7x1gmDS7wfllqtGBm4vUqxrXxY9uNZnKcs,3048 +twilio/rest/events/v1/sink/sink_validate.py,sha256=px942vCIcWnG9uTd6l7sdUeGO535hoYUB34XfSKzbY0,3747 +twilio/rest/events/v1/subscription/__init__.py,sha256=oqYgQLe3aV_K4IJCBN_GOsXouhoRwQX7Wai8Ns3u0Zg,23810 +twilio/rest/events/v1/subscription/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/events/v1/subscription/__pycache__/subscribed_event.cpython-312.pyc,, +twilio/rest/events/v1/subscription/subscribed_event.py,sha256=KKHkkPzKU5eGtTx8D-aD3JN4-TLaqj7CGTUCCYWOLL8,21483 +twilio/rest/flex_api/FlexApiBase.py,sha256=uej-QbJtfmiUEUj54Hs5nXUoUmeWUnebYCqlHZ__Nck,1472 +twilio/rest/flex_api/__init__.py,sha256=95CohrSn9QGa5NEMqi1FfZ0ojxuqK5rVvszrR0NQd9Q,6332 +twilio/rest/flex_api/__pycache__/FlexApiBase.cpython-312.pyc,, +twilio/rest/flex_api/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/flex_api/v1/__init__.py,sha256=obnvo_MQ0rmSwmTbgQk7DEM9fxHwuMxmkJeL3_4BP30,10023 +twilio/rest/flex_api/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/flex_api/v1/__pycache__/assessments.cpython-312.pyc,, +twilio/rest/flex_api/v1/__pycache__/channel.cpython-312.pyc,, +twilio/rest/flex_api/v1/__pycache__/configuration.cpython-312.pyc,, +twilio/rest/flex_api/v1/__pycache__/flex_flow.cpython-312.pyc,, +twilio/rest/flex_api/v1/__pycache__/insights_assessments_comment.cpython-312.pyc,, +twilio/rest/flex_api/v1/__pycache__/insights_conversations.cpython-312.pyc,, +twilio/rest/flex_api/v1/__pycache__/insights_questionnaires.cpython-312.pyc,, +twilio/rest/flex_api/v1/__pycache__/insights_questionnaires_category.cpython-312.pyc,, +twilio/rest/flex_api/v1/__pycache__/insights_questionnaires_question.cpython-312.pyc,, +twilio/rest/flex_api/v1/__pycache__/insights_segments.cpython-312.pyc,, +twilio/rest/flex_api/v1/__pycache__/insights_session.cpython-312.pyc,, +twilio/rest/flex_api/v1/__pycache__/insights_settings_answer_sets.cpython-312.pyc,, +twilio/rest/flex_api/v1/__pycache__/insights_settings_comment.cpython-312.pyc,, +twilio/rest/flex_api/v1/__pycache__/insights_user_roles.cpython-312.pyc,, +twilio/rest/flex_api/v1/__pycache__/plugin_archive.cpython-312.pyc,, +twilio/rest/flex_api/v1/__pycache__/plugin_configuration_archive.cpython-312.pyc,, +twilio/rest/flex_api/v1/__pycache__/plugin_release.cpython-312.pyc,, +twilio/rest/flex_api/v1/__pycache__/plugin_version_archive.cpython-312.pyc,, +twilio/rest/flex_api/v1/__pycache__/provisioning_status.cpython-312.pyc,, +twilio/rest/flex_api/v1/__pycache__/web_channel.cpython-312.pyc,, +twilio/rest/flex_api/v1/assessments.py,sha256=V9qcvA7siGHPibeVTZrHMFZ7M6x2LaHfMjjHgqFrMpc,24804 +twilio/rest/flex_api/v1/channel.py,sha256=yLGvmFX1n8wGcxYkMu1jtbesmwmwy7Dps3P_dv2mDKs,20775 +twilio/rest/flex_api/v1/configuration.py,sha256=4orBSh9VTT9XR3rXnk6sOtGTcoOgNYjmH7g_fPWI0lQ,16390 +twilio/rest/flex_api/v1/flex_flow.py,sha256=WEc_bJfuyuX6QMrxTYwlHbq6BaXvyMmI1khdAFzL4vA,48692 +twilio/rest/flex_api/v1/insights_assessments_comment.py,sha256=yWj0JBRafpvk2eY_E8RqQOcw_-TDai7AGniC4m8bZ2c,18263 +twilio/rest/flex_api/v1/insights_conversations.py,sha256=e4RDXZL5ixoxia9IMXOQH48pxkYxnikA0xcLfK8AfEE,13403 +twilio/rest/flex_api/v1/insights_questionnaires.py,sha256=YiGf1i74hxkJ0Av3k2f_UpAC7vXhrLEggbwLClWzVkY,29788 +twilio/rest/flex_api/v1/insights_questionnaires_category.py,sha256=9a7q2C35bIhYi9rQchkhBXTtDYfCADz6DyNjpTRA_gw,22522 +twilio/rest/flex_api/v1/insights_questionnaires_question.py,sha256=7WThQaMXdhYzP0BcgUVr-_2mZPKpC1Bm6lYyLvHfBU0,28319 +twilio/rest/flex_api/v1/insights_segments.py,sha256=UELfB0Mdnlm9qodiTh6OFDZPce90CnqEFfcHiYywLbw,16466 +twilio/rest/flex_api/v1/insights_session.py,sha256=bc4_hAx5exIgh0at-hmnAECjAh3ur33MguxMi4JjIRE,5688 +twilio/rest/flex_api/v1/insights_settings_answer_sets.py,sha256=-ti-THOVV7-H3GJyN3WLj1P5DfSMqXtPw9Kmg0Ri1Ao,3987 +twilio/rest/flex_api/v1/insights_settings_comment.py,sha256=CQ8a8-toTifomRxGJqsjiMEC0gMV8mGxU6Q-2N4CbzU,3568 +twilio/rest/flex_api/v1/insights_user_roles.py,sha256=KEmrtjjlSJdXIPqh4L5QwSNKDb7U3O5U9ufpX7CYiMo,5583 +twilio/rest/flex_api/v1/interaction/__init__.py,sha256=056bAYLNB5qkw5g1EAeLC1hzRQTBLhHPpRLP_liqjZk,12738 +twilio/rest/flex_api/v1/interaction/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/flex_api/v1/interaction/interaction_channel/__init__.py,sha256=4h-o492vXOZs1tM7JH5wTvUNbnjLY_ADG_AE_-6OIOE,23059 +twilio/rest/flex_api/v1/interaction/interaction_channel/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/flex_api/v1/interaction/interaction_channel/__pycache__/interaction_channel_invite.cpython-312.pyc,, +twilio/rest/flex_api/v1/interaction/interaction_channel/__pycache__/interaction_channel_participant.cpython-312.pyc,, +twilio/rest/flex_api/v1/interaction/interaction_channel/__pycache__/interaction_transfer.cpython-312.pyc,, +twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_invite.py,sha256=r_9xfu6Cn2IzB8vjOCahqBOKOHRD2WJEXpaRnLy2i0w,14571 +twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_participant.py,sha256=rPlAhdDU4eg-GT4Jm9B_J2C1jXVrzcpgAwGgMHqU_gg,21534 +twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_transfer.py,sha256=sMdG-j_Gqk1R_8bqEu-IV1KOWQ_7RSTHoxNiQ2JMSeI,13562 +twilio/rest/flex_api/v1/plugin/__init__.py,sha256=tDHboT1oPnJ-sqjDY_gZUcUlwNe-W0GFFdCbCIw3yt8,24859 +twilio/rest/flex_api/v1/plugin/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/flex_api/v1/plugin/__pycache__/plugin_versions.cpython-312.pyc,, +twilio/rest/flex_api/v1/plugin/plugin_versions.py,sha256=jAUztORMeQqbKS7W7HzY5JahmEWA0zid4pD00IdJ8IQ,22650 +twilio/rest/flex_api/v1/plugin_archive.py,sha256=C9QY5HU6Ge48qKfVTwAPWo7hNR21gFgH0jS26jQe9eo,7951 +twilio/rest/flex_api/v1/plugin_configuration/__init__.py,sha256=NeTdo-f7C0iPYcV1xCEQbyoulbS6UQbB7ecyMxpEPko,21237 +twilio/rest/flex_api/v1/plugin_configuration/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/flex_api/v1/plugin_configuration/__pycache__/configured_plugin.cpython-312.pyc,, +twilio/rest/flex_api/v1/plugin_configuration/configured_plugin.py,sha256=hXVC4o0uSWnIcq3ULPH7EMHjfBFRa92r-8qM6mRBEbI,20249 +twilio/rest/flex_api/v1/plugin_configuration_archive.py,sha256=6JAyPB76AgNmj290Mtwc4co7nPiVgzB0mpC0lKtBmrU,8094 +twilio/rest/flex_api/v1/plugin_release.py,sha256=DHWrxcVdJNaBofYRlBSxDb5knG39e_bFZndz9jdtrw0,18932 +twilio/rest/flex_api/v1/plugin_version_archive.py,sha256=-dxjlhquldQRPNascrY8TCWHdSlog7XNwGvN0tXzLt0,9101 +twilio/rest/flex_api/v1/provisioning_status.py,sha256=buD8d9ddh3mlingquoYGBQit0Ujuhuwo9CR__Vtu_vA,4918 +twilio/rest/flex_api/v1/web_channel.py,sha256=BxDf5RFPLu4stg9V8rX2tli_veY892He189T-ybdvJ4,22024 +twilio/rest/flex_api/v2/__init__.py,sha256=WMe1F3S9rix25wT-TMn9o4BdKxc65EeMjC1VyDUWgyE,1610 +twilio/rest/flex_api/v2/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/flex_api/v2/__pycache__/flex_user.cpython-312.pyc,, +twilio/rest/flex_api/v2/__pycache__/web_channels.cpython-312.pyc,, +twilio/rest/flex_api/v2/flex_user.py,sha256=atkcufDa6QwJPQM0C3Zk3RNiEs8wIwqjGmUaDQvDbw4,11739 +twilio/rest/flex_api/v2/web_channels.py,sha256=tgBOhRiHkdKKGabc6o0gMDIJSXkiqX2rvop21zJKQjY,6396 +twilio/rest/frontline_api/FrontlineApiBase.py,sha256=LxpGZeNOYqlqYNh8VxMXZoDR_z13_Nh36r-vRQYUDRE,1241 +twilio/rest/frontline_api/__init__.py,sha256=dY4Pp2907z2kTJJ3jaSt4pX9-qP3t36LRK1Zs8Yniog,410 +twilio/rest/frontline_api/__pycache__/FrontlineApiBase.cpython-312.pyc,, +twilio/rest/frontline_api/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/frontline_api/v1/__init__.py,sha256=AcNIDcakdTFSUXD3AF55ot77IsixzC-rJAPP9Cs6A4I,1278 +twilio/rest/frontline_api/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/frontline_api/v1/__pycache__/user.cpython-312.pyc,, +twilio/rest/frontline_api/v1/user.py,sha256=IrXEAr_ZHznL6QlbTqe3RqnzthdiNLyoPfQMLqZo0D0,11329 +twilio/rest/iam/IamBase.py,sha256=2VtqB_DfMQWvBNKmGpnVIv7cFhU_210bV0X_WeP77Z4,1176 +twilio/rest/iam/__init__.py,sha256=LxDMjMsrLsWeQPOe8NPXEs39BB0ngAotZuntX9pew9E,679 +twilio/rest/iam/__pycache__/IamBase.cpython-312.pyc,, +twilio/rest/iam/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/iam/v1/__init__.py,sha256=vMJItvxisyNy-OiJaIKOElhq2z5aUyCsjJvybTGrcNc,2104 +twilio/rest/iam/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/iam/v1/__pycache__/api_key.cpython-312.pyc,, +twilio/rest/iam/v1/__pycache__/get_api_keys.cpython-312.pyc,, +twilio/rest/iam/v1/__pycache__/new_api_key.cpython-312.pyc,, +twilio/rest/iam/v1/__pycache__/token.cpython-312.pyc,, +twilio/rest/iam/v1/api_key.py,sha256=rGuFKiia8IQml7TxUMwdcs_9YNqZDCXm6JJ_UyyKDtk,11776 +twilio/rest/iam/v1/get_api_keys.py,sha256=4svxSithdku2x4NAWSNc9q819QEWJcPSw2ye02mrOq8,12220 +twilio/rest/iam/v1/new_api_key.py,sha256=V4aDUDMpSBdbmHZgG2rvTixnz0pXhLuFp5ASD87U6uk,6387 +twilio/rest/iam/v1/token.py,sha256=P-0XE0J6i2tEjl_W2_BXGjXu1wE_kCNjElN9bN0i_8Y,6048 +twilio/rest/insights/InsightsBase.py,sha256=E0d9cswKhgPZByiFy51V7AGE-TiQ7lZOB1hbGOczY7Q,1211 +twilio/rest/insights/__init__.py,sha256=quAZLguZrWAk1irDvVn1ChI9LgdMewLt9SO_YgfGkzQ,1579 +twilio/rest/insights/__pycache__/InsightsBase.cpython-312.pyc,, +twilio/rest/insights/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/insights/v1/__init__.py,sha256=CQgywgxUWHdv3N_p5I_-SpoczEh6-Q2TvrQE7BZAJoQ,2420 +twilio/rest/insights/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/insights/v1/__pycache__/call_summaries.cpython-312.pyc,, +twilio/rest/insights/v1/__pycache__/setting.cpython-312.pyc,, +twilio/rest/insights/v1/call/__init__.py,sha256=BwO0pCW0XHN3kPsb1cCRsj2l9Xay5mlWsxZEl9xsA-8,7160 +twilio/rest/insights/v1/call/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/insights/v1/call/__pycache__/annotation.cpython-312.pyc,, +twilio/rest/insights/v1/call/__pycache__/call_summary.cpython-312.pyc,, +twilio/rest/insights/v1/call/__pycache__/event.cpython-312.pyc,, +twilio/rest/insights/v1/call/__pycache__/metric.cpython-312.pyc,, +twilio/rest/insights/v1/call/annotation.py,sha256=2hQqz6BcQ9KUVqD4b-yi1x2snCBVvmalUieHkfnQC1Y,18056 +twilio/rest/insights/v1/call/call_summary.py,sha256=P7jJITDSrn5dAwrxWQazAh20OjZnchhKd4peQxKM9E0,11418 +twilio/rest/insights/v1/call/event.py,sha256=foL0V6owoVlDBt3f0Iz8CpCJc0f7QaI-qt8fyHZT0Lw,13972 +twilio/rest/insights/v1/call/metric.py,sha256=15TxR0D7bV-uKkoleu7G-1DuJQLqVSEdEna8WNgPSh0,15144 +twilio/rest/insights/v1/call_summaries.py,sha256=cINt0JH-X6b-56LxEn4_sckHqFYka8AUyPBa8_D5CNI,70422 +twilio/rest/insights/v1/conference/__init__.py,sha256=9aeY6AJKYAdLaQwR-SsomHllZ8wnKeEzQ5-ndYqZNMo,31953 +twilio/rest/insights/v1/conference/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/insights/v1/conference/__pycache__/conference_participant.cpython-312.pyc,, +twilio/rest/insights/v1/conference/conference_participant.py,sha256=ZvkMdXmIS7XjvV6Yj6r-JKYrW6DL0UO3fHiO1rF_I5s,25819 +twilio/rest/insights/v1/room/__init__.py,sha256=Xa5uJ9BUT-RDugYk_tWw_PKZzMpsvrw52fX7-H9VevQ,26172 +twilio/rest/insights/v1/room/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/insights/v1/room/__pycache__/participant.cpython-312.pyc,, +twilio/rest/insights/v1/room/participant.py,sha256=Y4sR3e8KrlqTAle4-QN40Uswn3hWcxhiI2EVxhXBC7E,18834 +twilio/rest/insights/v1/setting.py,sha256=nDlNCACxZwW7GHikDMq3NRmxqYuKfnRdODbpdD8n9iA,9670 +twilio/rest/intelligence/IntelligenceBase.py,sha256=IKwaNvPV9xaBmfpigqsK4zwhtfYDnV5pIf9mmonGVhs,1239 +twilio/rest/intelligence/__init__.py,sha256=F98_JVdUwFkjg-k58c8j6A45f_5HGYyW7mEoCziqMUk,417 +twilio/rest/intelligence/__pycache__/IntelligenceBase.cpython-312.pyc,, +twilio/rest/intelligence/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/intelligence/v2/__init__.py,sha256=fSaSi1PPutIUr8tPsEWTaQ1jijDddwHuHVYjxzPSXPI,3757 +twilio/rest/intelligence/v2/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/intelligence/v2/__pycache__/custom_operator.cpython-312.pyc,, +twilio/rest/intelligence/v2/__pycache__/operator.cpython-312.pyc,, +twilio/rest/intelligence/v2/__pycache__/operator_attachment.cpython-312.pyc,, +twilio/rest/intelligence/v2/__pycache__/operator_attachments.cpython-312.pyc,, +twilio/rest/intelligence/v2/__pycache__/operator_type.cpython-312.pyc,, +twilio/rest/intelligence/v2/__pycache__/prebuilt_operator.cpython-312.pyc,, +twilio/rest/intelligence/v2/__pycache__/service.cpython-312.pyc,, +twilio/rest/intelligence/v2/custom_operator.py,sha256=uctBMPQL810btmlS3LERqNaV5ZMLr0fu0DppbvoA2jQ,26696 +twilio/rest/intelligence/v2/operator.py,sha256=WKTNgW0Axck1mtS-Vah5HROLSE4p3jph4_c5b8H3_nc,18628 +twilio/rest/intelligence/v2/operator_attachment.py,sha256=ulpXpj5ZqtrUoVGIgF7op-UfHI_MPbnhmAXmwRGMqUU,7771 +twilio/rest/intelligence/v2/operator_attachments.py,sha256=XXB99Jvs_mKaH0zFcQ1tGWGplv0y8eT85L7dRm-ppZI,6005 +twilio/rest/intelligence/v2/operator_type.py,sha256=1c1BaUryfGKcANaADnVc-dmmgDZEBhrZwMDkYWM24Cw,16722 +twilio/rest/intelligence/v2/prebuilt_operator.py,sha256=5ymQj1za1_F2ZthxVh-0KL-BNo9gdDYVi1ITLAn2ev0,19605 +twilio/rest/intelligence/v2/service.py,sha256=XkJ20q3KxaQlQG0qrDNy91-Yy1CnEKg_6R9r6xfQ20w,35447 +twilio/rest/intelligence/v2/transcript/__init__.py,sha256=XX_LMUy-4YWJRQfCX2OEgcHkHYYIf8xvEwM4Nbv0k6M,29951 +twilio/rest/intelligence/v2/transcript/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/intelligence/v2/transcript/__pycache__/media.cpython-312.pyc,, +twilio/rest/intelligence/v2/transcript/__pycache__/operator_result.cpython-312.pyc,, +twilio/rest/intelligence/v2/transcript/__pycache__/sentence.cpython-312.pyc,, +twilio/rest/intelligence/v2/transcript/media.py,sha256=FY-Z_NacoIjrwg2Y4QI84uh3aI8uwLGHWYc17KHrwjs,6730 +twilio/rest/intelligence/v2/transcript/operator_result.py,sha256=oqKPKHOG-xx0L3Hq015iClodq8Te_vQg7KKz-Qrpv00,21124 +twilio/rest/intelligence/v2/transcript/sentence.py,sha256=7kw4sl8RwWUVb7PwKgk6wAltu8m0QVOAatXNblX867I,14882 +twilio/rest/ip_messaging/IpMessagingBase.py,sha256=Auoz1W9XNlV8F6owgPNOKpYY93GZnvtpYzUAzYQXyws,1508 +twilio/rest/ip_messaging/__init__.py,sha256=9mxOrxP0A0GodgNQW2cfokhI3-Ejo3MiX9EcPzBrY9s,738 +twilio/rest/ip_messaging/__pycache__/IpMessagingBase.cpython-312.pyc,, +twilio/rest/ip_messaging/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/ip_messaging/v1/__init__.py,sha256=NppQLF43kYaFcWw_ipWY9LDyWN1DH2b_lLbNm2H6okA,1616 +twilio/rest/ip_messaging/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/ip_messaging/v1/__pycache__/credential.cpython-312.pyc,, +twilio/rest/ip_messaging/v1/credential.py,sha256=Lnf1H1sbLUfvpwIQofouScgrobA5BZ6aSD-YE4ygUr8,22962 +twilio/rest/ip_messaging/v1/service/__init__.py,sha256=oY3Or2h1KK3KL8Y_Y5QQX-TnbhjotH21AUfg8nQw8Ic,64889 +twilio/rest/ip_messaging/v1/service/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/ip_messaging/v1/service/__pycache__/role.cpython-312.pyc,, +twilio/rest/ip_messaging/v1/service/channel/__init__.py,sha256=Yo605xbth1i8z6D8VM2TJ3FeYb9urX6LZ_BoMAiN9Rk,25267 +twilio/rest/ip_messaging/v1/service/channel/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/ip_messaging/v1/service/channel/__pycache__/invite.cpython-312.pyc,, +twilio/rest/ip_messaging/v1/service/channel/__pycache__/member.cpython-312.pyc,, +twilio/rest/ip_messaging/v1/service/channel/__pycache__/message.cpython-312.pyc,, +twilio/rest/ip_messaging/v1/service/channel/invite.py,sha256=J8jV8pnxqc0hG9fEZMYLYHBju6nSS0foRObiGne4T8A,19454 +twilio/rest/ip_messaging/v1/service/channel/member.py,sha256=0V9K59QUR7vk-lXwLmiwj3Y_ceneNM21pu-2Fl5KraE,22928 +twilio/rest/ip_messaging/v1/service/channel/message.py,sha256=gOoi_0Bl8VTLXiOLc-05ib4d2_Vaezh6twbUCYdocBY,23021 +twilio/rest/ip_messaging/v1/service/role.py,sha256=hJIZ4WiPVDL2edpLMo5utVzTI3MBN3-5YvMYfeanb2Y,20058 +twilio/rest/ip_messaging/v1/service/user/__init__.py,sha256=rIdOSPhxnSffqxTzLX0H1fG8nR0YeHP8tisppnexS-M,22566 +twilio/rest/ip_messaging/v1/service/user/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/ip_messaging/v1/service/user/__pycache__/user_channel.cpython-312.pyc,, +twilio/rest/ip_messaging/v1/service/user/user_channel.py,sha256=__2mYHonWu6GkyJiXMMV2VEaMBru88OaMnvzL7cY3fc,11870 +twilio/rest/ip_messaging/v2/__init__.py,sha256=7jGoUJ93kos9yv2hkMzA5vflhMYUYzVY92S9Z9B6NlU,1616 +twilio/rest/ip_messaging/v2/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/ip_messaging/v2/__pycache__/credential.cpython-312.pyc,, +twilio/rest/ip_messaging/v2/credential.py,sha256=H88g_73iSdVta78v5IJpLs4XBkTAnrt82Ub_bEUzAJQ,22962 +twilio/rest/ip_messaging/v2/service/__init__.py,sha256=Iu928DalMsJqC2d3BtW32luMh0g-8wgld3TdMftuz3Y,47587 +twilio/rest/ip_messaging/v2/service/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/ip_messaging/v2/service/__pycache__/binding.cpython-312.pyc,, +twilio/rest/ip_messaging/v2/service/__pycache__/role.cpython-312.pyc,, +twilio/rest/ip_messaging/v2/service/binding.py,sha256=gUCWroQ24j-BXqZE7LzTjhnKNCKM_cGJsOz6Q05GBqQ,18432 +twilio/rest/ip_messaging/v2/service/channel/__init__.py,sha256=o49rPokvhl8WjfK7PJ5nwrm3Laf6CQCQGrvVm_hh1GI,32105 +twilio/rest/ip_messaging/v2/service/channel/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/ip_messaging/v2/service/channel/__pycache__/invite.cpython-312.pyc,, +twilio/rest/ip_messaging/v2/service/channel/__pycache__/member.cpython-312.pyc,, +twilio/rest/ip_messaging/v2/service/channel/__pycache__/message.cpython-312.pyc,, +twilio/rest/ip_messaging/v2/service/channel/__pycache__/webhook.cpython-312.pyc,, +twilio/rest/ip_messaging/v2/service/channel/invite.py,sha256=7BYSk3PKypYrrhslndER3REoy70Rb-c9rubgsqeDbQo,19454 +twilio/rest/ip_messaging/v2/service/channel/member.py,sha256=2OgOiAqMWZEmoMHFWDAd5aSe84MS9s1tKMrUxSvJL_M,31059 +twilio/rest/ip_messaging/v2/service/channel/message.py,sha256=OgviUUENynQghtlezC9ZuqLZ-w4YGa6Nknf9cObp0ic,30335 +twilio/rest/ip_messaging/v2/service/channel/webhook.py,sha256=tTvnLCmwG9uia0oYURA12FCA9y6eD_zVqH6WUs0_2LM,27378 +twilio/rest/ip_messaging/v2/service/role.py,sha256=Ug1dUlCedwgJMXhbImwhtOEmMSYGYxF2gEjN72RxX-E,20058 +twilio/rest/ip_messaging/v2/service/user/__init__.py,sha256=nZlU7FtSmZ0CKjZ9Yaoa0_YGwElKmJzGwsRoPYWxnBI,25576 +twilio/rest/ip_messaging/v2/service/user/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/ip_messaging/v2/service/user/__pycache__/user_binding.cpython-312.pyc,, +twilio/rest/ip_messaging/v2/service/user/__pycache__/user_channel.cpython-312.pyc,, +twilio/rest/ip_messaging/v2/service/user/user_binding.py,sha256=u9YDRNfj-vA44eLFBp-yN_ywsJNlP5d2X5712dn7m3k,18717 +twilio/rest/ip_messaging/v2/service/user/user_channel.py,sha256=MVOYLEcKUWGX-1d_dpOEx2IlqzMDX-PWtPcfHUqegGw,22291 +twilio/rest/lookups/LookupsBase.py,sha256=mH77GksjdX4_ynK3OmtPAjMIboayKFZBTcx8fpQk544,1469 +twilio/rest/lookups/__init__.py,sha256=LDDJTWTOQ1TyhW8ZWS-XfJfF3zO93E5PPyaTzR_6j1g,432 +twilio/rest/lookups/__pycache__/LookupsBase.cpython-312.pyc,, +twilio/rest/lookups/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/lookups/v1/__init__.py,sha256=2wsVTUfxrQaxpH18BvIJTnU-00nq-Y3bCOTymJjfTZk,1330 +twilio/rest/lookups/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/lookups/v1/__pycache__/phone_number.cpython-312.pyc,, +twilio/rest/lookups/v1/phone_number.py,sha256=FPgslzNCHuOzQs7q_pfn3h1nnw1RAxzO6OB6ZbC5Ybg,12790 +twilio/rest/lookups/v2/__init__.py,sha256=ngFacNsEH1hxQOpRWj4067Te6fxzhLYeQLr_gr0pBDU,1330 +twilio/rest/lookups/v2/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/lookups/v2/__pycache__/phone_number.cpython-312.pyc,, +twilio/rest/lookups/v2/phone_number.py,sha256=i9HcLX1P6uljXBLvQOEExRDl_no2mdh2X1E_-swny_Q,26525 +twilio/rest/marketplace/MarketplaceBase.py,sha256=1mfggmVz9sJyhE8pjMrplw521ZbCvhDuHO8n1U8BC5A,1232 +twilio/rest/marketplace/__init__.py,sha256=kUvdmbOANktX1ZFzZtF4vuv0RzdDukVFO1IF-r0dSPA,255 +twilio/rest/marketplace/__pycache__/MarketplaceBase.cpython-312.pyc,, +twilio/rest/marketplace/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/marketplace/v1/__init__.py,sha256=v9bI7ImeSQ7dY5szR6cuyQcXQM5nyVTMwkouirJUrqU,2859 +twilio/rest/marketplace/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/marketplace/v1/__pycache__/module_data.cpython-312.pyc,, +twilio/rest/marketplace/v1/__pycache__/module_data_management.cpython-312.pyc,, +twilio/rest/marketplace/v1/__pycache__/referral_conversion.cpython-312.pyc,, +twilio/rest/marketplace/v1/available_add_on/__init__.py,sha256=hY_5irnPG1mp84zp0n9NYAIS4p0FNn13xi0j6s8X2kU,15515 +twilio/rest/marketplace/v1/available_add_on/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/marketplace/v1/available_add_on/__pycache__/available_add_on_extension.cpython-312.pyc,, +twilio/rest/marketplace/v1/available_add_on/available_add_on_extension.py,sha256=BViTDTPYR3hfsXjC-fk9KU-BTM1DqpICu9i3XuywOoQ,16616 +twilio/rest/marketplace/v1/installed_add_on/__init__.py,sha256=tkGiOOet4_rdBoVEmZb_rPzfC4l9Y4_Ch0zu-TIUkp0,25232 +twilio/rest/marketplace/v1/installed_add_on/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/marketplace/v1/installed_add_on/__pycache__/installed_add_on_extension.cpython-312.pyc,, +twilio/rest/marketplace/v1/installed_add_on/__pycache__/installed_add_on_usage.cpython-312.pyc,, +twilio/rest/marketplace/v1/installed_add_on/installed_add_on_extension.py,sha256=kpWthj74_ok2wf-FY_K34V5qTlP9lj8T0tFVB9q0jZk,19352 +twilio/rest/marketplace/v1/installed_add_on/installed_add_on_usage.py,sha256=LpDTGm1IxQxSyJ6CqF4yIQEMqleREOP2jjGPwMX80ss,8309 +twilio/rest/marketplace/v1/module_data.py,sha256=SeSgNjkzMIa6REYi18jtW6Uq344g-mpV1-HlEBnl2rs,6833 +twilio/rest/marketplace/v1/module_data_management.py,sha256=n5SP2hCyfgQ1SMjg-btAW3Qz7Nm5ltt5DjqKsv2ekrk,16162 +twilio/rest/marketplace/v1/referral_conversion.py,sha256=em9lnu-qLHXKhT_Q6EMyt5m_8M8ESBRDsuqPV85qksQ,4122 +twilio/rest/messaging/MessagingBase.py,sha256=X8EKE7NkpXB6ZFrJW6kFEaNCeaSaMgsR7f-qeBnSPUk,1487 +twilio/rest/messaging/__init__.py,sha256=b_aOOaeRTDPGh-xajYYKry13McI3bmeF050u6j2UXa8,3308 +twilio/rest/messaging/__pycache__/MessagingBase.cpython-312.pyc,, +twilio/rest/messaging/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/messaging/v1/__init__.py,sha256=WdGN6ZanVxdTWNmYZBwmvQe5AcQnXbATRC7wMyhGwiA,6006 +twilio/rest/messaging/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/messaging/v1/__pycache__/deactivations.cpython-312.pyc,, +twilio/rest/messaging/v1/__pycache__/domain_certs.cpython-312.pyc,, +twilio/rest/messaging/v1/__pycache__/domain_config.cpython-312.pyc,, +twilio/rest/messaging/v1/__pycache__/domain_config_messaging_service.cpython-312.pyc,, +twilio/rest/messaging/v1/__pycache__/external_campaign.cpython-312.pyc,, +twilio/rest/messaging/v1/__pycache__/linkshortening_messaging_service.cpython-312.pyc,, +twilio/rest/messaging/v1/__pycache__/linkshortening_messaging_service_domain_association.cpython-312.pyc,, +twilio/rest/messaging/v1/__pycache__/request_managed_cert.cpython-312.pyc,, +twilio/rest/messaging/v1/__pycache__/tollfree_verification.cpython-312.pyc,, +twilio/rest/messaging/v1/__pycache__/usecase.cpython-312.pyc,, +twilio/rest/messaging/v1/brand_registration/__init__.py,sha256=vwN1T13tXXqeTQXcnLfvsfXcM-UI0yPa72MgcQaIxjY,25786 +twilio/rest/messaging/v1/brand_registration/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/messaging/v1/brand_registration/__pycache__/brand_registration_otp.cpython-312.pyc,, +twilio/rest/messaging/v1/brand_registration/__pycache__/brand_vetting.cpython-312.pyc,, +twilio/rest/messaging/v1/brand_registration/brand_registration_otp.py,sha256=la1p4GyOQZCkRajdrceZaqPc62vgJQ7UJ7ArqVrY_oU,3863 +twilio/rest/messaging/v1/brand_registration/brand_vetting.py,sha256=0yvCpsT49B80d_vUB6yK_wED8TG6OIn2W8lPgxq67ys,20801 +twilio/rest/messaging/v1/deactivations.py,sha256=_xU8CL1GYSQnmPCm5Fogsy0FlsX4V8hHaE7irqMUpk8,6014 +twilio/rest/messaging/v1/domain_certs.py,sha256=s-DvT8cYizH9c6se-G4GD9OXgiRr0b-H1EpjSNPC1cs,10985 +twilio/rest/messaging/v1/domain_config.py,sha256=rtO1y97rtxBlvFCim4hEML1BRZLKU7vQovXEjme3kz0,14438 +twilio/rest/messaging/v1/domain_config_messaging_service.py,sha256=OnHPXrT7-2mo3l4QjM1N0cYJclhpVm756pn4w9FgSZE,8146 +twilio/rest/messaging/v1/external_campaign.py,sha256=DJ5e4CPCDn01fs9mzhH-yk0jYdf42NNL2Yr77nEhWek,5827 +twilio/rest/messaging/v1/linkshortening_messaging_service.py,sha256=HnbvZrSFQ3lV_qVgJmZZy0Sdv3ik3t8-RnJijv1XEbg,9270 +twilio/rest/messaging/v1/linkshortening_messaging_service_domain_association.py,sha256=F84pNV01Bbe5tn1eGP8CoPZTsEb17YLv0kV3d_xTFG8,7562 +twilio/rest/messaging/v1/request_managed_cert.py,sha256=fg0N6_uR4ygu3njHRE80X_JUFZTZg_GSYr8mn_-pt5k,7362 +twilio/rest/messaging/v1/service/__init__.py,sha256=qUd-KVBwVHa5ByTPn7e5IdxXtj4IgDcWcQ8jJNDM3e0,58925 +twilio/rest/messaging/v1/service/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/messaging/v1/service/__pycache__/alpha_sender.cpython-312.pyc,, +twilio/rest/messaging/v1/service/__pycache__/channel_sender.cpython-312.pyc,, +twilio/rest/messaging/v1/service/__pycache__/destination_alpha_sender.cpython-312.pyc,, +twilio/rest/messaging/v1/service/__pycache__/phone_number.cpython-312.pyc,, +twilio/rest/messaging/v1/service/__pycache__/short_code.cpython-312.pyc,, +twilio/rest/messaging/v1/service/__pycache__/us_app_to_person.cpython-312.pyc,, +twilio/rest/messaging/v1/service/__pycache__/us_app_to_person_usecase.cpython-312.pyc,, +twilio/rest/messaging/v1/service/alpha_sender.py,sha256=YOuoL8KKN6QSRku1m0bG0NJIBBOGGsNxHyA62NjEBJM,19261 +twilio/rest/messaging/v1/service/channel_sender.py,sha256=wxBaS8d6PzBhS_PlHx8ODvxbDgWc29nfzSLfXu2dikk,19693 +twilio/rest/messaging/v1/service/destination_alpha_sender.py,sha256=5--4D-UPjnSIV8yp_6MlM7hBa_qgcpmrOo4zTuuUYJg,22713 +twilio/rest/messaging/v1/service/phone_number.py,sha256=0Bq5ntSJ2Uy_Bhl1c_SKFhbwrict9QbyraiWqXQcluw,19326 +twilio/rest/messaging/v1/service/short_code.py,sha256=E04lWux1kq2RXmKrAXU_DPPfny-dd6tnux9F_OHE1mc,19048 +twilio/rest/messaging/v1/service/us_app_to_person.py,sha256=Ghjh3ejPA7XY-c8xzVmfCn_ohylp4o-vMXtCHrRlNUo,45251 +twilio/rest/messaging/v1/service/us_app_to_person_usecase.py,sha256=OxYKFgTzChJ_o65jBzljNuXVN8dhnJZD4MONzsVzWMk,4517 +twilio/rest/messaging/v1/tollfree_verification.py,sha256=N4dzS_WXCFlMjwo_GuOnrsKRKWCx0poCrYpPhSjzqOs,63270 +twilio/rest/messaging/v1/usecase.py,sha256=nqg6oL7XY5RhV5pELB1VMcpTwhZexK-gHa9cxhSzIZU,2685 +twilio/rest/messaging/v2/__init__.py,sha256=tnGhnc1ogHpyPnkHAb6vn1W09UcqWuiUHlnu0gEcI9Y,1370 +twilio/rest/messaging/v2/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/messaging/v2/__pycache__/channels_sender.cpython-312.pyc,, +twilio/rest/messaging/v2/channels_sender.py,sha256=R6Y8wjkdNf-pbOvzimNKcTF8WEW0YbhRv5_-5fUVPuI,42985 +twilio/rest/microvisor/MicrovisorBase.py,sha256=qAQUxPKy5T4sjQxS1QLzNwZUuHSVNA1R6ANInXmLo1Q,1225 +twilio/rest/microvisor/__init__.py,sha256=VvCLDiEovqv3pvNtlafvwWWGupHDSOqLg0fDFLg-jrQ,1321 +twilio/rest/microvisor/__pycache__/MicrovisorBase.cpython-312.pyc,, +twilio/rest/microvisor/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/microvisor/v1/__init__.py,sha256=FpDCQcXn-wXd9-pDgvYRweUvclcQmcw7q9scbHbiYJU,2212 +twilio/rest/microvisor/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/microvisor/v1/__pycache__/account_config.cpython-312.pyc,, +twilio/rest/microvisor/v1/__pycache__/account_secret.cpython-312.pyc,, +twilio/rest/microvisor/v1/account_config.py,sha256=KpL3ESLPFQ1aNo7x4Q-et796Y1Sf8hQ_B4fPGTt6fz0,19039 +twilio/rest/microvisor/v1/account_secret.py,sha256=8JXOcQlW8KSixp4HB5mjsd2U-Yc39USef4tOOute9hY,18924 +twilio/rest/microvisor/v1/app/__init__.py,sha256=_uNBLnpCjBSAU4M4I9wBPpREyATS6DFbKqAYXj3wuc8,16187 +twilio/rest/microvisor/v1/app/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/microvisor/v1/app/__pycache__/app_manifest.cpython-312.pyc,, +twilio/rest/microvisor/v1/app/app_manifest.py,sha256=nRdO9A1p5m7D9qFFQaBWt55tB48e_yRHiN4-SYGePf0,5713 +twilio/rest/microvisor/v1/device/__init__.py,sha256=gmQZSVDDSK-IthXhM679eZWJTwLmflLHyW2R3r24XZA,21735 +twilio/rest/microvisor/v1/device/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/microvisor/v1/device/__pycache__/device_config.cpython-312.pyc,, +twilio/rest/microvisor/v1/device/__pycache__/device_secret.cpython-312.pyc,, +twilio/rest/microvisor/v1/device/device_config.py,sha256=0PAMSw7IVxoM_regmpfusGH7xzR3onaBE1o5o1H3HRY,20346 +twilio/rest/microvisor/v1/device/device_secret.py,sha256=6N__YRbPFhtwlSjidTbqjojSCHgdT6oxSQ38YjEwVOQ,20231 +twilio/rest/monitor/MonitorBase.py,sha256=ZUBQwu6h9-c-QsjqzqWOjAgKW0CLbhSzWkCaA6T9_I8,1204 +twilio/rest/monitor/__init__.py,sha256=qSQaNLR3BLW7RbTgo4-K5hyUs8WjFpQkejqdEmA1dgo,658 +twilio/rest/monitor/__pycache__/MonitorBase.cpython-312.pyc,, +twilio/rest/monitor/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/monitor/v1/__init__.py,sha256=jKGc7sS5H9TlP4M_SYtRAlTBGuVTG_NHrsmMqKxLaKg,1518 +twilio/rest/monitor/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/monitor/v1/__pycache__/alert.cpython-312.pyc,, +twilio/rest/monitor/v1/__pycache__/event.cpython-312.pyc,, +twilio/rest/monitor/v1/alert.py,sha256=Wbt-Koprj-Fr8v2iqEUm33dHJOeEW-HnYXcOTqW6W9w,23192 +twilio/rest/monitor/v1/event.py,sha256=U0G5AipPfHGHSrCbUydBrm1O0nELS5oFSr3E8lIfj50,26092 +twilio/rest/notify/NotifyBase.py,sha256=63iUENxBxbeJ-AfquhzrOnfHxjA1Oh_ZF4JzKXFjrZQ,1197 +twilio/rest/notify/__init__.py,sha256=fqpFtdtT21ai83xGyuIHVTFFp04n0XS3J2N20Ebn4rc,700 +twilio/rest/notify/__pycache__/NotifyBase.cpython-312.pyc,, +twilio/rest/notify/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/notify/v1/__init__.py,sha256=w5j4Nxwc7PAmhImW90TEa38frEH3mjwUgAxT2Wn2iXA,1582 +twilio/rest/notify/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/notify/v1/__pycache__/credential.cpython-312.pyc,, +twilio/rest/notify/v1/credential.py,sha256=BvvrnWkHOgP8nvI8erdpwc_DmjRy3mgNNB0gKVmh0BQ,29291 +twilio/rest/notify/v1/service/__init__.py,sha256=_aght_AEruxM0zX7EjWfOApvmlC_-Xv2rOkmGL-f0js,48635 +twilio/rest/notify/v1/service/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/notify/v1/service/__pycache__/binding.cpython-312.pyc,, +twilio/rest/notify/v1/service/__pycache__/notification.cpython-312.pyc,, +twilio/rest/notify/v1/service/binding.py,sha256=css5If7sBQ_gMjiQeAWSw7-mL9sW7YxtmhyF2lvtlRI,31187 +twilio/rest/notify/v1/service/notification.py,sha256=uJPJGag_p-XzwIegypxzkBNpR7_r7m5vOdJAttGYt28,25875 +twilio/rest/numbers/NumbersBase.py,sha256=4QlX-Tsp953-WAZAJSdbn4b3hxx67pL_KI4N5rEbq0E,1469 +twilio/rest/numbers/__init__.py,sha256=wIjsaoiSWgzPPa5leWNXsOwttzjCbOg7NhVG0eGV2c8,491 +twilio/rest/numbers/__pycache__/NumbersBase.cpython-312.pyc,, +twilio/rest/numbers/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/numbers/v1/__init__.py,sha256=WxUlp7QgaVdIDvjjCrCWvM_s3qgXuR7EIFfE8LIJoHk,5210 +twilio/rest/numbers/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/numbers/v1/__pycache__/bulk_eligibility.cpython-312.pyc,, +twilio/rest/numbers/v1/__pycache__/eligibility.cpython-312.pyc,, +twilio/rest/numbers/v1/__pycache__/porting_port_in.cpython-312.pyc,, +twilio/rest/numbers/v1/__pycache__/porting_port_in_phone_number.cpython-312.pyc,, +twilio/rest/numbers/v1/__pycache__/porting_portability.cpython-312.pyc,, +twilio/rest/numbers/v1/__pycache__/porting_webhook_configuration.cpython-312.pyc,, +twilio/rest/numbers/v1/__pycache__/porting_webhook_configuration_delete.cpython-312.pyc,, +twilio/rest/numbers/v1/__pycache__/porting_webhook_configuration_fetch.cpython-312.pyc,, +twilio/rest/numbers/v1/__pycache__/signing_request_configuration.cpython-312.pyc,, +twilio/rest/numbers/v1/bulk_eligibility.py,sha256=JaMLcdaH5-Z019koozU63L6XCbZrL0o97nMUut9bcZE,8657 +twilio/rest/numbers/v1/eligibility.py,sha256=-r6-FXwDgg1O1J_NRcUwiQYZOz71-ftdIPH56prVJIg,3686 +twilio/rest/numbers/v1/porting_port_in.py,sha256=tn5y-5Ko6VVP7tYpJxmbUJiAh6SeNuX4i68kSvScIf4,11509 +twilio/rest/numbers/v1/porting_port_in_phone_number.py,sha256=eINfYnzgw4K_0pQS1pDholToP4i5p6QXzeZS9J2ATVM,12813 +twilio/rest/numbers/v1/porting_portability.py,sha256=8vr5i2JmBGC1u-Z7M9IyRF6h7ZQaAw4aXQlOB0NKSlc,10479 +twilio/rest/numbers/v1/porting_webhook_configuration.py,sha256=Exqs-T-E8eZofodAdjC6vF1Hma1Zl-14EPdmbawLIqU,4046 +twilio/rest/numbers/v1/porting_webhook_configuration_delete.py,sha256=8KO4wKvyhEa55qK55Jlin7mAOI0lYLS3Nshx4QjCOO0,3849 +twilio/rest/numbers/v1/porting_webhook_configuration_fetch.py,sha256=VDXsAa8CR6b9AccGByzR-lARd2cqU6CWVRKCWj2eNT8,4288 +twilio/rest/numbers/v1/signing_request_configuration.py,sha256=X_l0ReZhhE2yzvo6NNaU7_o0da6uYDy-Bj-E5SH3H2c,16134 +twilio/rest/numbers/v2/__init__.py,sha256=Qv5QHA7dwnszYN-boixMR4llKlcmqPrB3a_8bjcani4,2968 +twilio/rest/numbers/v2/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/numbers/v2/__pycache__/bulk_hosted_number_order.cpython-312.pyc,, +twilio/rest/numbers/v2/__pycache__/bundle_clone.cpython-312.pyc,, +twilio/rest/numbers/v2/__pycache__/hosted_number_order.cpython-312.pyc,, +twilio/rest/numbers/v2/authorization_document/__init__.py,sha256=q33XwBIEsKPmUV_I4QEM_-x-ucKRNB2Bnh3eb3RVFeA,26285 +twilio/rest/numbers/v2/authorization_document/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/numbers/v2/authorization_document/__pycache__/dependent_hosted_number_order.cpython-312.pyc,, +twilio/rest/numbers/v2/authorization_document/dependent_hosted_number_order.py,sha256=we-we-lsyaJg102TGf4pB-_46WolSF289SsiwQt12fM,22570 +twilio/rest/numbers/v2/bulk_hosted_number_order.py,sha256=XaQRiDk8_b0p6QXJparOW9-j4HvgQrQcqQBtW3s3NYQ,11270 +twilio/rest/numbers/v2/bundle_clone.py,sha256=ifPMAzubZF73XdmpQxY0XNyTm4bO-l-RVIHZt3NtrJs,10336 +twilio/rest/numbers/v2/hosted_number_order.py,sha256=FBisjr-1qMoqHcTvolPhaoHxU-MFmdGiITdYnApCTaE,42405 +twilio/rest/numbers/v2/regulatory_compliance/__init__.py,sha256=om1Yd8YuZ5T0YX0OPdwl__lmeV3rf1uQI9a6VXnlPFo,3690 +twilio/rest/numbers/v2/regulatory_compliance/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/numbers/v2/regulatory_compliance/__pycache__/end_user.cpython-312.pyc,, +twilio/rest/numbers/v2/regulatory_compliance/__pycache__/end_user_type.cpython-312.pyc,, +twilio/rest/numbers/v2/regulatory_compliance/__pycache__/regulation.cpython-312.pyc,, +twilio/rest/numbers/v2/regulatory_compliance/__pycache__/supporting_document.cpython-312.pyc,, +twilio/rest/numbers/v2/regulatory_compliance/__pycache__/supporting_document_type.cpython-312.pyc,, +twilio/rest/numbers/v2/regulatory_compliance/bundle/__init__.py,sha256=u6eUL_hiQNJe3poZMLxIyQiX01HEy4fUS2GPGY3UfkQ,49181 +twilio/rest/numbers/v2/regulatory_compliance/bundle/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/numbers/v2/regulatory_compliance/bundle/__pycache__/bundle_copy.cpython-312.pyc,, +twilio/rest/numbers/v2/regulatory_compliance/bundle/__pycache__/evaluation.cpython-312.pyc,, +twilio/rest/numbers/v2/regulatory_compliance/bundle/__pycache__/item_assignment.cpython-312.pyc,, +twilio/rest/numbers/v2/regulatory_compliance/bundle/__pycache__/replace_items.cpython-312.pyc,, +twilio/rest/numbers/v2/regulatory_compliance/bundle/bundle_copy.py,sha256=gp25rHvCL0z9POpX7ympvvDBzatQpLQx-myAZOad1R0,14592 +twilio/rest/numbers/v2/regulatory_compliance/bundle/evaluation.py,sha256=SaTEnlcZOKVVxlyW4_7jXBcayDDW9LeLaNjwqVY9-u0,16918 +twilio/rest/numbers/v2/regulatory_compliance/bundle/item_assignment.py,sha256=_tJzr1corQuIUB_sBeDcwmpJoEEl1JYq37Zud-JWT3I,18746 +twilio/rest/numbers/v2/regulatory_compliance/bundle/replace_items.py,sha256=NqXzEwGw45-YKNJOYWPuIPzLu_x5EIRR0R2LBpILR4U,6056 +twilio/rest/numbers/v2/regulatory_compliance/end_user.py,sha256=3f6kQrSV-3fKNT_Pc1dCMeAon_Ww80C1EcN-jW7oNRg,21703 +twilio/rest/numbers/v2/regulatory_compliance/end_user_type.py,sha256=IvvMK3UoH7JxdFxzgbLcPFG6ZOS7FN9GTxoQNqnPjO8,14620 +twilio/rest/numbers/v2/regulatory_compliance/regulation.py,sha256=rbezHBPfMT3pdVJGvLjT6DthiKNW7Juala2YifWyx9M,22156 +twilio/rest/numbers/v2/regulatory_compliance/supporting_document.py,sha256=rm6B0xzqpq5EeMqxMXjF_o-inMrNFmkD-SAwfApXvuE,23771 +twilio/rest/numbers/v2/regulatory_compliance/supporting_document_type.py,sha256=BPEX9r78rsoBHDYzq42SvDWN_bCgaYOkMS8Wwx3EvR8,15268 +twilio/rest/oauth/OauthBase.py,sha256=osnf61tFtaKzvSRec80nclNAGL2hjobh7cCzzM7yNnA,1190 +twilio/rest/oauth/__init__.py,sha256=NIyb2ajGCJ85V0wIoDgWvteT7TGUNYG9X3xLBE3RDaA,370 +twilio/rest/oauth/__pycache__/OauthBase.cpython-312.pyc,, +twilio/rest/oauth/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/oauth/v1/__init__.py,sha256=_O7z9N65ZEXjX5DAiMDvj-Sw4rNHP4JvxFhx1_yhRCg,1536 +twilio/rest/oauth/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/oauth/v1/__pycache__/authorize.cpython-312.pyc,, +twilio/rest/oauth/v1/__pycache__/token.cpython-312.pyc,, +twilio/rest/oauth/v1/authorize.py,sha256=Fqlo4Z2C_xVqVlV6R_CkZz20SCsZlDwvTQ2zu5N45ZY,4329 +twilio/rest/oauth/v1/token.py,sha256=X042V3dwmnEBHcDL-tQUa-KOyU-RC9yYTEAjCmHwZgk,6044 +twilio/rest/preview/PreviewBase.py,sha256=4FwwsIDgUAaBNRu0L3IPZuOJY0fmOs7rfqOpRfIvs1I,2027 +twilio/rest/preview/__init__.py,sha256=pPSeRmKwcqT27hzxO7-7ViMAeZcWsUSDVhKZL0cHcso,2889 +twilio/rest/preview/__pycache__/PreviewBase.cpython-312.pyc,, +twilio/rest/preview/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/preview/hosted_numbers/__init__.py,sha256=Q0CYZWP0LWjme7cyzlNZFMMI6BDqN0Fa5uvNtGXcVq8,1893 +twilio/rest/preview/hosted_numbers/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/preview/hosted_numbers/__pycache__/hosted_number_order.cpython-312.pyc,, +twilio/rest/preview/hosted_numbers/authorization_document/__init__.py,sha256=ba-SzDbDhe63CtLoXOi9eneraL_XT-I7X1Wyl85udk4,33527 +twilio/rest/preview/hosted_numbers/authorization_document/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/preview/hosted_numbers/authorization_document/__pycache__/dependent_hosted_number_order.cpython-312.pyc,, +twilio/rest/preview/hosted_numbers/authorization_document/dependent_hosted_number_order.py,sha256=3GajRpiCDWS0yModzEcy8pRlp5VU05snSbQFviZkEAc,25401 +twilio/rest/preview/hosted_numbers/hosted_number_order.py,sha256=KpsnZ8nHYW-4NvNpEqh-ap-m8JL5lbeouJ4-PZR9kI4,49656 +twilio/rest/preview/marketplace/__init__.py,sha256=Z1ULxHOw4TLnAX6wXweELqxekmXLlhysuzjz34rOc9A,1776 +twilio/rest/preview/marketplace/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/preview/marketplace/available_add_on/__init__.py,sha256=kewAJJfdJtF1qLlFer6nLK2r20TnF7G5ehxSP4tZZ8A,15536 +twilio/rest/preview/marketplace/available_add_on/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/preview/marketplace/available_add_on/__pycache__/available_add_on_extension.cpython-312.pyc,, +twilio/rest/preview/marketplace/available_add_on/available_add_on_extension.py,sha256=GG3Tx_OOFyovMG65zx9LqIRBOaWTfEg7T_2mdTfkUks,16632 +twilio/rest/preview/marketplace/installed_add_on/__init__.py,sha256=5DCmwA43LPeSmiMappzOgTYPJw-nU7nxCa2chn6Lnb8,24628 +twilio/rest/preview/marketplace/installed_add_on/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/preview/marketplace/installed_add_on/__pycache__/installed_add_on_extension.cpython-312.pyc,, +twilio/rest/preview/marketplace/installed_add_on/installed_add_on_extension.py,sha256=qTx7ZtS5RUCftsf4YHXNtMUSY051PDVBYSWybOmkyNw,19368 +twilio/rest/preview/wireless/__init__.py,sha256=ZlKINNHwHiqAhehhMb7g_jGDFUNK6XWGzlhA8XdGfZY,1850 +twilio/rest/preview/wireless/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/preview/wireless/__pycache__/command.cpython-312.pyc,, +twilio/rest/preview/wireless/__pycache__/rate_plan.cpython-312.pyc,, +twilio/rest/preview/wireless/command.py,sha256=5OIhP5tj_D2omdixIaejAqrTAnGfMlHy2q0nHVHdsI0,19770 +twilio/rest/preview/wireless/rate_plan.py,sha256=lBlcBCeUKoTTfbXiYtufOaLu5Uyf9YJT-BdTDKa02Hc,23248 +twilio/rest/preview/wireless/sim/__init__.py,sha256=nGW4QXMc_l6qGcor5VHcM_o9ChoeCl3V4olUm8yzWfk,29624 +twilio/rest/preview/wireless/sim/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/preview/wireless/sim/__pycache__/usage.cpython-312.pyc,, +twilio/rest/preview/wireless/sim/usage.py,sha256=ry8_Ney-F51nXRMje0P8mAv6wNpYqZVoI0F8UlGpY6k,6810 +twilio/rest/preview_iam/PreviewIamBase.py,sha256=PoU3blksO0afcjPCmHa_4JzVUD8PuyyZpa1EsjkwIPY,1227 +twilio/rest/preview_iam/__init__.py,sha256=abr7pyb5BO3J654krTvqpPWIqt762cN3G9MVaAwR-Xk,662 +twilio/rest/preview_iam/__pycache__/PreviewIamBase.cpython-312.pyc,, +twilio/rest/preview_iam/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/preview_iam/v1/__init__.py,sha256=nMeH5PgNfXvKemg5wnYJldyrm9_jfOYWGmz9a4Q8Yp4,1644 +twilio/rest/preview_iam/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/preview_iam/v1/__pycache__/authorize.cpython-312.pyc,, +twilio/rest/preview_iam/v1/__pycache__/token.cpython-312.pyc,, +twilio/rest/preview_iam/v1/authorize.py,sha256=vUSPtCJZwSnpoo4Sl7b8Szoh7S0-GaA7duhmOflxtKA,4425 +twilio/rest/preview_iam/v1/token.py,sha256=D9jGVlq-hgYPJoD4JDkTafeZoSXjrp4sqxtd2-R_mkw,6144 +twilio/rest/preview_iam/versionless/__init__.py,sha256=xFbC9PXTOvN9NLNEKOMh1n17dYTeHqR-yJO7fajYzjo,1468 +twilio/rest/preview_iam/versionless/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/preview_iam/versionless/organization/__init__.py,sha256=Mw08g47tZxDPm3DrCiO2aqau95h--xbbz6enOtrMeWw,3916 +twilio/rest/preview_iam/versionless/organization/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/preview_iam/versionless/organization/__pycache__/account.cpython-312.pyc,, +twilio/rest/preview_iam/versionless/organization/__pycache__/role_assignment.cpython-312.pyc,, +twilio/rest/preview_iam/versionless/organization/__pycache__/user.cpython-312.pyc,, +twilio/rest/preview_iam/versionless/organization/account.py,sha256=Sst7OP0EUn6KKQCPdFKqRAdezjEAzxoo6a74WOG8stM,15149 +twilio/rest/preview_iam/versionless/organization/role_assignment.py,sha256=vtHw1f2FdzG6Jh5Dg5g_sN0AONPtD3dXgch8K5dzUF4,20400 +twilio/rest/preview_iam/versionless/organization/user.py,sha256=h-yRzU2OJ2lE9qRbBf1JE14HoncESylywXmLOLd7D1o,38114 +twilio/rest/pricing/PricingBase.py,sha256=NLCOp1P4eV2ZlQikfRsLHd1zUZyqms5HRsl4Y54QtZ8,1469 +twilio/rest/pricing/__init__.py,sha256=ge3TqYJHEMFblpBnfC9X4FW0d0SsO7I5b4qKGY-jkVU,1569 +twilio/rest/pricing/__pycache__/PricingBase.cpython-312.pyc,, +twilio/rest/pricing/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/pricing/v1/__init__.py,sha256=CurnOGdO6y0wIWCGSGxgxt0YdszryeMAmdRbj7Ooeog,1868 +twilio/rest/pricing/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/pricing/v1/messaging/__init__.py,sha256=rSOhH2QMvljfAGkFDYwomtLmOqPZwBjbOkcUfRbqXPA,1443 +twilio/rest/pricing/v1/messaging/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/pricing/v1/messaging/__pycache__/country.cpython-312.pyc,, +twilio/rest/pricing/v1/messaging/country.py,sha256=ZnYb5Gy1xbHzkOGf1peO5jhpPP2N7SfwSanGw84l8wQ,14999 +twilio/rest/pricing/v1/phone_number/__init__.py,sha256=Y5i7NuFEchDtGXMSoTkFMonR8iyMVBzZM8Ud8xXW5ik,1455 +twilio/rest/pricing/v1/phone_number/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/pricing/v1/phone_number/__pycache__/country.cpython-312.pyc,, +twilio/rest/pricing/v1/phone_number/country.py,sha256=OhcpWGvwz8fhGn-Lq7946ZxtTa8qOy9ZuXZkTCttO5c,14592 +twilio/rest/pricing/v1/voice/__init__.py,sha256=I_2ql8yNyelIDbO6xLw_YZOtvdVS4YsJ1_xA5inn4dI,1753 +twilio/rest/pricing/v1/voice/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/pricing/v1/voice/__pycache__/country.cpython-312.pyc,, +twilio/rest/pricing/v1/voice/__pycache__/number.cpython-312.pyc,, +twilio/rest/pricing/v1/voice/country.py,sha256=VwgIhuBsL8lhUcRzb8SsMpZHVe7jKBTS3oF3uVKrK7Y,14885 +twilio/rest/pricing/v1/voice/number.py,sha256=jPe0U15gAiRvUgvyg2EIrZpIho9g9Py1ZsOJJmS33pc,5880 +twilio/rest/pricing/v2/__init__.py,sha256=lt22Da-7bXFid4KEGWNLc5_R4u5Is6fDuYCoVa1wjj0,1802 +twilio/rest/pricing/v2/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/pricing/v2/__pycache__/country.cpython-312.pyc,, +twilio/rest/pricing/v2/__pycache__/number.cpython-312.pyc,, +twilio/rest/pricing/v2/country.py,sha256=7DLs2hvkX12BagctGEgghE129is26RfcmakHGjP3IgY,14939 +twilio/rest/pricing/v2/number.py,sha256=ZRRvI8-dlQ9KHpbYsUv19nl_heZ20V11PUHAQepdzD0,9184 +twilio/rest/pricing/v2/voice/__init__.py,sha256=EV0LqxLaOB0PgH7E182h0InT6g9wmJsoPSBC5e6WSVE,1753 +twilio/rest/pricing/v2/voice/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/pricing/v2/voice/__pycache__/country.cpython-312.pyc,, +twilio/rest/pricing/v2/voice/__pycache__/number.cpython-312.pyc,, +twilio/rest/pricing/v2/voice/country.py,sha256=H4p1Gk5PTSoSDMjbQuBodJpawEW3a3hVcvJ4E_yFieQ,14915 +twilio/rest/pricing/v2/voice/number.py,sha256=FZLh9qSfDJl0f6ndrf1w_Iv5x9uSvaF6nr7z2LO6IK0,9258 +twilio/rest/proxy/ProxyBase.py,sha256=U3nXl8igDx1PLplE9GdldvQ7-_1ZofMO8kPMoptnTPY,1190 +twilio/rest/proxy/__init__.py,sha256=t3suaVnvsgCHvrHOkPBshzKqaK0xZ0OAfoBvPsgS_MA,387 +twilio/rest/proxy/__pycache__/ProxyBase.cpython-312.pyc,, +twilio/rest/proxy/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/proxy/v1/__init__.py,sha256=K_YLKgkAp-_QiAKKVb_RKJF1Bk2ge_6Z16uFrOqdq1Q,1274 +twilio/rest/proxy/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/proxy/v1/service/__init__.py,sha256=ojVop07d0E7CrmQcdgXBTPyvpmrmC08dhvFM8T1GWNA,39366 +twilio/rest/proxy/v1/service/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/proxy/v1/service/__pycache__/phone_number.cpython-312.pyc,, +twilio/rest/proxy/v1/service/__pycache__/short_code.cpython-312.pyc,, +twilio/rest/proxy/v1/service/phone_number.py,sha256=3w1QA2Xk5A4PnHleevnQ1_5pxaHv3hIj5AqnmnpHkVE,25082 +twilio/rest/proxy/v1/service/session/__init__.py,sha256=Wn-cp_eQwBiYs1x_j9d_8qFeGDXNhEacpGhJxPju1wk,28970 +twilio/rest/proxy/v1/service/session/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/proxy/v1/service/session/__pycache__/interaction.cpython-312.pyc,, +twilio/rest/proxy/v1/service/session/interaction.py,sha256=6cyaP98FMIibyCfYioOFxuHiWrQgvEqzkpP5BHE9IPM,21646 +twilio/rest/proxy/v1/service/session/participant/__init__.py,sha256=qGtO9flZ0mCtHza8SiUkBF00HIfY3Dg-4SlsOz580Og,23678 +twilio/rest/proxy/v1/service/session/participant/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/proxy/v1/service/session/participant/__pycache__/message_interaction.cpython-312.pyc,, +twilio/rest/proxy/v1/service/session/participant/message_interaction.py,sha256=p23k8qBF9Bw1evIc2Vkoxa1diklfMR2EgQwn1Dr7y88,24103 +twilio/rest/proxy/v1/service/short_code.py,sha256=etcwcuRI8smorLFDdubKDjcJyZIeqpWeQVYkuoLVlss,22637 +twilio/rest/routes/RoutesBase.py,sha256=Wd7ZCiv13Jkec4cmQTcAEWgftoIU1m57bZ-qkzoriXg,1197 +twilio/rest/routes/__init__.py,sha256=2c-YFuPc4-lbnbloGWO0HBglvgusSEin0PqD7MhDKi4,1003 +twilio/rest/routes/__pycache__/RoutesBase.cpython-312.pyc,, +twilio/rest/routes/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/routes/v2/__init__.py,sha256=yOGIyQHTtHeDgd-yu4LSv5AcLa2KT__TcSmWUYploSo,1877 +twilio/rest/routes/v2/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/routes/v2/__pycache__/phone_number.cpython-312.pyc,, +twilio/rest/routes/v2/__pycache__/sip_domain.cpython-312.pyc,, +twilio/rest/routes/v2/__pycache__/trunk.cpython-312.pyc,, +twilio/rest/routes/v2/phone_number.py,sha256=lKVw4cbxRLYCkHFiOFgLodbbyR3CpsOt97rnuGn8p08,10163 +twilio/rest/routes/v2/sip_domain.py,sha256=UlgBl06DzAP5K4cyqBtd2LYUIP3mCnXKe6zdvUCSths,8755 +twilio/rest/routes/v2/trunk.py,sha256=NAacTltZwq8WjuN3XaIA3gbbmg1oj5bgWbFRCZxDIp8,9972 +twilio/rest/serverless/ServerlessBase.py,sha256=tkHMV_J34VboZ9KpnPZGKoWqoRvQmi7jUKNgGbQif_Y,1225 +twilio/rest/serverless/__init__.py,sha256=RSch0EvaZC7vInV-DXpUwtaitRhC1dpLXllzK-keHIQ,417 +twilio/rest/serverless/__pycache__/ServerlessBase.cpython-312.pyc,, +twilio/rest/serverless/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/serverless/v1/__init__.py,sha256=FE26OpLcLc2D4bdUE9-madIxREcrRBOk8jPT-H99_zw,1299 +twilio/rest/serverless/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/serverless/v1/service/__init__.py,sha256=m4QzN2phun9teH5wkVGB5tZCdZGtVR5jF4AkzQo0SlY,26954 +twilio/rest/serverless/v1/service/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/serverless/v1/service/asset/__init__.py,sha256=9oov6zyI3eOXrWnh-yvCKvxSjOk2mnavs-9x_Cf0jUY,21783 +twilio/rest/serverless/v1/service/asset/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/serverless/v1/service/asset/__pycache__/asset_version.cpython-312.pyc,, +twilio/rest/serverless/v1/service/asset/asset_version.py,sha256=td0TPORDdf4mOEDDnCs03g8MnCI-DlLsBqgbb7ljllI,17185 +twilio/rest/serverless/v1/service/build/__init__.py,sha256=uUrHixsuYAgeb7sVjnMJWn-iTWJvLibR36VIo8U7mjE,21695 +twilio/rest/serverless/v1/service/build/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/serverless/v1/service/build/__pycache__/build_status.cpython-312.pyc,, +twilio/rest/serverless/v1/service/build/build_status.py,sha256=T-gNHyQsiD_AatrctHKaNFm8hzF-yfULrqRggNs0jDA,6686 +twilio/rest/serverless/v1/service/environment/__init__.py,sha256=v_1yRUP5Oc9onosllPi6p3nP3s3wWOi6yLfQguh5GGQ,21922 +twilio/rest/serverless/v1/service/environment/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/serverless/v1/service/environment/__pycache__/deployment.cpython-312.pyc,, +twilio/rest/serverless/v1/service/environment/__pycache__/log.cpython-312.pyc,, +twilio/rest/serverless/v1/service/environment/__pycache__/variable.cpython-312.pyc,, +twilio/rest/serverless/v1/service/environment/deployment.py,sha256=VnPee8tNRgGeIlbeWI_lSf0eV8T7BXAYyAsUCb40Cog,19307 +twilio/rest/serverless/v1/service/environment/log.py,sha256=DnAaJUInzoTTZqRwkHq6WpNwxT2PkUx-SwbKAVRoLVY,21397 +twilio/rest/serverless/v1/service/environment/variable.py,sha256=QN_eyxH-w6t0eKsqD7Btnl5d8dYG3fzqxOm35xZC9kA,23799 +twilio/rest/serverless/v1/service/function/__init__.py,sha256=uZxmjE1VB_UMCnoCD15cbccB4lFSJZgM1hJ6RMlMs1w,22129 +twilio/rest/serverless/v1/service/function/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/serverless/v1/service/function/function_version/__init__.py,sha256=xlZP3O8DVvnOHImF-_JAG6w2JwBrPwuAIdCgJk6Kj1o,18564 +twilio/rest/serverless/v1/service/function/function_version/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/serverless/v1/service/function/function_version/__pycache__/function_version_content.cpython-312.pyc,, +twilio/rest/serverless/v1/service/function/function_version/function_version_content.py,sha256=v9C75LS4AFWf-Ac2r2sAvRqE-8msJAXQgUUd5IuMMh4,7915 +twilio/rest/studio/StudioBase.py,sha256=Ir8Bf4wI_qF2HPpL59i94svqiX_FB0g6Y3Tw02ZA4lQ,1460 +twilio/rest/studio/__init__.py,sha256=VF97OQEqJW5-ycSz4oqnGlxyvDEo-Hzxf0GZQzgv3ts,694 +twilio/rest/studio/__pycache__/StudioBase.cpython-312.pyc,, +twilio/rest/studio/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/studio/v1/__init__.py,sha256=x63ZfUydLZEcampmW0D3vaSqnpCc2mMGH5zg4uckLTA,1249 +twilio/rest/studio/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/studio/v1/flow/__init__.py,sha256=gkghYu5WGSbS2jVi2-NPkAr0bjIL00YASKpHDQ4TGRw,16929 +twilio/rest/studio/v1/flow/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/studio/v1/flow/engagement/__init__.py,sha256=fDQDSuqi92MzdQ__4hN6fqFbqF9FJbjNrz4yRS0RPm8,22281 +twilio/rest/studio/v1/flow/engagement/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/studio/v1/flow/engagement/__pycache__/engagement_context.cpython-312.pyc,, +twilio/rest/studio/v1/flow/engagement/engagement_context.py,sha256=4D7a2a5dlsIF1rQR4LcORBti6v4XZ2C-8qq-kkvPFDk,6899 +twilio/rest/studio/v1/flow/engagement/step/__init__.py,sha256=Znrh_kCQM_YI3m9q9WQs6HlJ99sOHspWf8TkKo5zeLg,17820 +twilio/rest/studio/v1/flow/engagement/step/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/studio/v1/flow/engagement/step/__pycache__/step_context.cpython-312.pyc,, +twilio/rest/studio/v1/flow/engagement/step/step_context.py,sha256=SHjKvjBN7LxxexCtFUvpT2aoZM-MSR-lmZg271MHQNQ,7574 +twilio/rest/studio/v1/flow/execution/__init__.py,sha256=UHcdqa2uGgr83Q_kUpKeN719v9qYGbtr78jFnXfwKZo,28473 +twilio/rest/studio/v1/flow/execution/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/studio/v1/flow/execution/__pycache__/execution_context.cpython-312.pyc,, +twilio/rest/studio/v1/flow/execution/execution_context.py,sha256=PhVrZdllf1lwZJ-dfrZSaa31TQj7f9YUD-kx3c8nwco,7056 +twilio/rest/studio/v1/flow/execution/execution_step/__init__.py,sha256=HlSBUR_Q3Br4PNLnTKtmWueQiTq9ZHhmje0QoY_7iTk,18618 +twilio/rest/studio/v1/flow/execution/execution_step/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/studio/v1/flow/execution/execution_step/__pycache__/execution_step_context.cpython-312.pyc,, +twilio/rest/studio/v1/flow/execution/execution_step/execution_step_context.py,sha256=K-kkFSodl-r5aDErRSlC7XvYbBA2bH0ZQit1ZlqI11Q,7895 +twilio/rest/studio/v2/__init__.py,sha256=W2t8U-5spMVgebzQZzLAkN8fOhceKLAPVTfJ3EWCXCo,1573 +twilio/rest/studio/v2/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/studio/v2/__pycache__/flow_validate.cpython-312.pyc,, +twilio/rest/studio/v2/flow/__init__.py,sha256=OaZPTmOWOeAKrO7gnUp4zR9xvwunSOq4h2NTNy3rch0,24883 +twilio/rest/studio/v2/flow/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/studio/v2/flow/__pycache__/flow_revision.cpython-312.pyc,, +twilio/rest/studio/v2/flow/__pycache__/flow_test_user.cpython-312.pyc,, +twilio/rest/studio/v2/flow/execution/__init__.py,sha256=d6_WO6H3zXxxmrD_saxOkJd8XYjwDTxP08r_p0_mtaE,28357 +twilio/rest/studio/v2/flow/execution/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/studio/v2/flow/execution/__pycache__/execution_context.cpython-312.pyc,, +twilio/rest/studio/v2/flow/execution/execution_context.py,sha256=mZ3_zssbsq-GZzYFLRSGFay_vs2fDLWWP34gJEfUKbM,7056 +twilio/rest/studio/v2/flow/execution/execution_step/__init__.py,sha256=5P-ueoYcoHTjedaGZY4dpb0KripB6L6EPh15Dor-I7g,18489 +twilio/rest/studio/v2/flow/execution/execution_step/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/studio/v2/flow/execution/execution_step/__pycache__/execution_step_context.cpython-312.pyc,, +twilio/rest/studio/v2/flow/execution/execution_step/execution_step_context.py,sha256=mE3HYlu3d4GvynE_Ir4y7ll955q-5dCnnUKyuW2NBZ8,7895 +twilio/rest/studio/v2/flow/flow_revision.py,sha256=8xmJ-lgIRZHTz8itHMzfnSN9PqpNoizjnJ9EZv7c43Q,16541 +twilio/rest/studio/v2/flow/flow_test_user.py,sha256=waIZQz_LUlTJbZOemmi9espZZtaTdMYbzFZHlMhYXq8,7858 +twilio/rest/studio/v2/flow_validate.py,sha256=9YXzVhtkOCg3phCX9xkq9n_CQYsxayjeKXqYvtTtKRQ,4283 +twilio/rest/supersim/SupersimBase.py,sha256=tzDOW6QQb0M_HEBpS5SmrK9AN0FWPkMKxNRgN9bGoxQ,1211 +twilio/rest/supersim/__init__.py,sha256=dRLKZs5p-3LCF1VlFz1_jV9r338yrTYW7kzraj64vuc,2908 +twilio/rest/supersim/__pycache__/SupersimBase.cpython-312.pyc,, +twilio/rest/supersim/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/supersim/v1/__init__.py,sha256=ExvMot1Mt7LpQfp5mlZgaOTf-yVEfZo9hL-lIgPc03Y,3801 +twilio/rest/supersim/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/supersim/v1/__pycache__/esim_profile.cpython-312.pyc,, +twilio/rest/supersim/v1/__pycache__/fleet.cpython-312.pyc,, +twilio/rest/supersim/v1/__pycache__/ip_command.cpython-312.pyc,, +twilio/rest/supersim/v1/__pycache__/network.cpython-312.pyc,, +twilio/rest/supersim/v1/__pycache__/settings_update.cpython-312.pyc,, +twilio/rest/supersim/v1/__pycache__/sms_command.cpython-312.pyc,, +twilio/rest/supersim/v1/__pycache__/usage_record.cpython-312.pyc,, +twilio/rest/supersim/v1/esim_profile.py,sha256=P43eGCYk0UO_A1NMgLqc3hu_vBjgKx-BSKKEgIYoIsM,24581 +twilio/rest/supersim/v1/fleet.py,sha256=IgQI3Bpuowy04j0PHdGsGoE-BhexndrUBlhMaiGi5aQ,36497 +twilio/rest/supersim/v1/ip_command.py,sha256=Y_J6thO-FE9Lt4zOGHXF7fpNaw_aVMNcmB0T9iH0UE8,27525 +twilio/rest/supersim/v1/network.py,sha256=aEtv-jepmc8AGSFfmwsczwOZ6PVskhWORtNIRrMMJaw,18062 +twilio/rest/supersim/v1/network_access_profile/__init__.py,sha256=HQDEuOUfHJx2tNzrR94fUjc7zA19mx79t_Yh6QxKNF0,21218 +twilio/rest/supersim/v1/network_access_profile/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/supersim/v1/network_access_profile/__pycache__/network_access_profile_network.cpython-312.pyc,, +twilio/rest/supersim/v1/network_access_profile/network_access_profile_network.py,sha256=qf7x40ND6e56G4-JHZQiwn5IebrJacKjUfeQaTXy2K8,20283 +twilio/rest/supersim/v1/settings_update.py,sha256=2YQlT2fRw8HdaVtwAshrOaIWMqD_W2bwqU4wCVqPYI4,14539 +twilio/rest/supersim/v1/sim/__init__.py,sha256=qKQXvmEF0ITq495TKtdAcnAyl8233IPiIXB88-TJv18,29881 +twilio/rest/supersim/v1/sim/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/supersim/v1/sim/__pycache__/billing_period.cpython-312.pyc,, +twilio/rest/supersim/v1/sim/__pycache__/sim_ip_address.cpython-312.pyc,, +twilio/rest/supersim/v1/sim/billing_period.py,sha256=yuqyKSGlxodrRPckQNtlbUtaRqq6AoxNHWJIHlc1cuo,12352 +twilio/rest/supersim/v1/sim/sim_ip_address.py,sha256=8KTtLk6dmCnfynWcjPuLyQ7St_qC9uD-_lVcw_TV0w8,10949 +twilio/rest/supersim/v1/sms_command.py,sha256=t-YRhuJ_57y2ASSmKSnmhMYsdUqSrlepHQEYc3GofXw,23862 +twilio/rest/supersim/v1/usage_record.py,sha256=z0jxspCN-7YOtXIWAHGeroCR2GuMtiDOLBpWA-2u4is,27163 +twilio/rest/sync/SyncBase.py,sha256=qfnPzbBdwYLKn45ZV51XawiTF0J9LVVp7WoiWeNNuF8,1183 +twilio/rest/sync/__init__.py,sha256=IV4mK6fA37ohGhjUmJXQMoBrLYhbKu4rExsU7ZhBemI,381 +twilio/rest/sync/__pycache__/SyncBase.cpython-312.pyc,, +twilio/rest/sync/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/sync/v1/__init__.py,sha256=lo8inAzFDENbjugimex6jV8cKsaekYSSdhfnVb-jK08,1269 +twilio/rest/sync/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/sync/v1/service/__init__.py,sha256=fg8SJtsFXdU4Gk4Rqczy_1V-As-fDJY_bzDehzYWxL8,38755 +twilio/rest/sync/v1/service/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/sync/v1/service/document/__init__.py,sha256=Geh-Lsh7bX3V-03JR7puPkIKfSWodWlPl3QhnilOcxk,26694 +twilio/rest/sync/v1/service/document/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/sync/v1/service/document/__pycache__/document_permission.cpython-312.pyc,, +twilio/rest/sync/v1/service/document/document_permission.py,sha256=T5GDe7N6RFKjKYp23YXtPkA9-FrZet_flMMnR61ezTs,22818 +twilio/rest/sync/v1/service/sync_list/__init__.py,sha256=B_og3ugqnSoVSM8WbvfeBGCbz-PpbeAkswbRTZiRgWA,26399 +twilio/rest/sync/v1/service/sync_list/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/sync/v1/service/sync_list/__pycache__/sync_list_item.cpython-312.pyc,, +twilio/rest/sync/v1/service/sync_list/__pycache__/sync_list_permission.cpython-312.pyc,, +twilio/rest/sync/v1/service/sync_list/sync_list_item.py,sha256=BgXaq75g3XseOCuCiLYjUomodmeWpYgn7uFK0VCJXtI,38006 +twilio/rest/sync/v1/service/sync_list/sync_list_permission.py,sha256=LWoy9ULPKi_6rx2QIlQF89z7pedN-NsIwf5B7UNUqoI,22822 +twilio/rest/sync/v1/service/sync_map/__init__.py,sha256=Dlea9vhxxccpECrsJBfJk7ysPkwqguw9xEOM5pzy5yY,26087 +twilio/rest/sync/v1/service/sync_map/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/sync/v1/service/sync_map/__pycache__/sync_map_item.cpython-312.pyc,, +twilio/rest/sync/v1/service/sync_map/__pycache__/sync_map_permission.cpython-312.pyc,, +twilio/rest/sync/v1/service/sync_map/sync_map_item.py,sha256=kglhoY3mqq3HZ3DKlRurNhUdfG-10RklhS_Vn6GUJlo,38565 +twilio/rest/sync/v1/service/sync_map/sync_map_permission.py,sha256=YQ-hUgWsfD_a4pa4xTQcF35c35vXq6edmBvA7Td7VDo,22750 +twilio/rest/sync/v1/service/sync_stream/__init__.py,sha256=GVIf6X8zTeQAE1Xq4NOc2OR45JxtfhJ4q3wpxScXrnA,24100 +twilio/rest/sync/v1/service/sync_stream/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/sync/v1/service/sync_stream/__pycache__/stream_message.cpython-312.pyc,, +twilio/rest/sync/v1/service/sync_stream/stream_message.py,sha256=gPXLse1tM8XNj3bDwD1_24BnJygOkEvWlBzwImRzryA,4704 +twilio/rest/taskrouter/TaskrouterBase.py,sha256=0pduWi9gHRMDnWejrHNLhL1UFtnTbFTD7K4_uBvk698,1225 +twilio/rest/taskrouter/__init__.py,sha256=LsvpBhg8Cg-tYPzdacb1bKJ9fEAwRBd6sdH41_s-CGA,431 +twilio/rest/taskrouter/__pycache__/TaskrouterBase.cpython-312.pyc,, +twilio/rest/taskrouter/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/taskrouter/v1/__init__.py,sha256=dgBlDHuEdkXOOBusvaS3DPEdV6KpgNdnRKPxRPxmvsc,1319 +twilio/rest/taskrouter/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/__init__.py,sha256=-kzAKagMxJtS1OErpphiFX_hyivFm2ZDYXpBa4GAly0,45784 +twilio/rest/taskrouter/v1/workspace/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/__pycache__/activity.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/__pycache__/event.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/__pycache__/task_channel.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/__pycache__/workspace_cumulative_statistics.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/__pycache__/workspace_real_time_statistics.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/__pycache__/workspace_statistics.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/activity.py,sha256=caZQKdRCg3nRWNFCHcFa9iBo-Fliy2xfP8GrKWz7rGk,27256 +twilio/rest/taskrouter/v1/workspace/event.py,sha256=d8-bEDWXiml12ka6t38gRLfkd_L6FpscnjbPAgV5ZtI,33245 +twilio/rest/taskrouter/v1/workspace/task/__init__.py,sha256=5utVTRSw9M7ffEMUxsMlC1F6t3g2QUvC03D2w14JoK8,60103 +twilio/rest/taskrouter/v1/workspace/task/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/task/__pycache__/reservation.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/task/reservation.py,sha256=Su5uvemUYtURHuw-fXFuv_ASJJX-gDeIvG95uDNDNKc,82418 +twilio/rest/taskrouter/v1/workspace/task_channel.py,sha256=b4hteITkASJmfka_j1lKeA9DcTuWhhHwk_2Pki4Vb70,24950 +twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py,sha256=EzzZTUJRbpN49fgRGF5_EX6hx5STB8yUT4ulEngd7qA,41127 +twilio/rest/taskrouter/v1/workspace/task_queue/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/task_queue/__pycache__/task_queue_bulk_real_time_statistics.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/task_queue/__pycache__/task_queue_cumulative_statistics.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/task_queue/__pycache__/task_queue_real_time_statistics.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/task_queue/__pycache__/task_queue_statistics.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/task_queue/__pycache__/task_queues_statistics.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_bulk_real_time_statistics.py,sha256=G-4CmLkSGkrors4P9_S_sbmVZXde-jRb2v1_HNclPxY,5533 +twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_cumulative_statistics.py,sha256=Owzy2GLnZ2chsPZLsUJgFs7r1tHWYWhcLwXlgMDk_K8,18538 +twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_real_time_statistics.py,sha256=oHvXO9ZRSB2HJ49LXE9yVk75CoovfxUbX9opTO1OOd0,11309 +twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_statistics.py,sha256=0OEqLQlKjd6E_eitn_QfG3TyjLg7TNgiHLnZhiIwu4w,13598 +twilio/rest/taskrouter/v1/workspace/task_queue/task_queues_statistics.py,sha256=MsadNOzs6tSp7ihI30AULA5rG2vTbR2mVM3d7RFm-Nk,21635 +twilio/rest/taskrouter/v1/workspace/worker/__init__.py,sha256=UFtA2wNgCYKfwUINg2bGD2_oBbaMHZj8KCZFt1wc7xY,45390 +twilio/rest/taskrouter/v1/workspace/worker/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/worker/__pycache__/reservation.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/worker/__pycache__/worker_channel.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/worker/__pycache__/worker_statistics.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/worker/__pycache__/workers_cumulative_statistics.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/worker/__pycache__/workers_real_time_statistics.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/worker/__pycache__/workers_statistics.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/worker/reservation.py,sha256=mUqm71lfxPzTtLvH_gvpVT8FHHmLQIZVMyxvXY004zE,80200 +twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py,sha256=UkBLmPdLYTNxTZYjce8EjmYIAMLtXWDA7ZIoQiHOO6Y,22917 +twilio/rest/taskrouter/v1/workspace/worker/worker_statistics.py,sha256=W3IBjoY9k6Wj5GvHcHF6yXpa6QWIY6fLncyxb4XZSFw,11948 +twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py,sha256=20N-BV-7b0J4zrr_9c9jnsZNXE6jYtfia5k3Krmptz8,13470 +twilio/rest/taskrouter/v1/workspace/worker/workers_real_time_statistics.py,sha256=HaJEWw4jqTX9egJFxlyK4gSNP3lcEPAd5idhzEyucJ4,8113 +twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py,sha256=3xP9S84x-L1czrTuWYt6J615VLkvmP2dbYgiB38M1KE,13763 +twilio/rest/taskrouter/v1/workspace/workflow/__init__.py,sha256=dZgoAfgMhhb8Yq8puZ1zMPIxHDYkGkOj2AHqn0l3qwU,35780 +twilio/rest/taskrouter/v1/workspace/workflow/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/workflow/__pycache__/workflow_cumulative_statistics.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/workflow/__pycache__/workflow_real_time_statistics.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/workflow/__pycache__/workflow_statistics.cpython-312.pyc,, +twilio/rest/taskrouter/v1/workspace/workflow/workflow_cumulative_statistics.py,sha256=SXjcPAejVN6AyR9Z1pMqOf7OyHfu5uR4-tHVgNf5tO0,19446 +twilio/rest/taskrouter/v1/workspace/workflow/workflow_real_time_statistics.py,sha256=ZzfRIIXLrfut803EK82QX_Y09PXERLpMi1G2O_8ITPo,9907 +twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py,sha256=KiR4khvRrjxHa51tbtag-Gp06l8ZugOQ7BHF9XiIxjE,14919 +twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py,sha256=xJ_CVDVOZhNyqKxc7NLsmYJnQXglUBwLm_a7IyyoKpQ,18383 +twilio/rest/taskrouter/v1/workspace/workspace_real_time_statistics.py,sha256=o8V7VYUXWBrkKEI40gEcTApkYWk6Nc_KHVeeyJ1T8tE,9256 +twilio/rest/taskrouter/v1/workspace/workspace_statistics.py,sha256=svL4Jk3fU8ylmKBCdo3BUBimak6wTvHgUYtFo85PVyA,13782 +twilio/rest/trunking/TrunkingBase.py,sha256=KEpBtt8vyNLrV0C6xgPB0EJy5eEylY48LePvQKhEi4U,1211 +twilio/rest/trunking/__init__.py,sha256=VX22mT-YnOfya6CQBiGMPyk7rHQmYGnJF5oiGiU7Jlg,391 +twilio/rest/trunking/__pycache__/TrunkingBase.cpython-312.pyc,, +twilio/rest/trunking/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/trunking/v1/__init__.py,sha256=qbIMhWiC4TsBoUrQJNtWBduHzJSNW7w0usKKrT1vWXE,1269 +twilio/rest/trunking/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/trunking/v1/trunk/__init__.py,sha256=-0jEpyK6c4e2UEotMvRGLPYeY1_qwmGmeCk7IYMAcVg,41424 +twilio/rest/trunking/v1/trunk/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/trunking/v1/trunk/__pycache__/credential_list.cpython-312.pyc,, +twilio/rest/trunking/v1/trunk/__pycache__/ip_access_control_list.cpython-312.pyc,, +twilio/rest/trunking/v1/trunk/__pycache__/origination_url.cpython-312.pyc,, +twilio/rest/trunking/v1/trunk/__pycache__/phone_number.cpython-312.pyc,, +twilio/rest/trunking/v1/trunk/__pycache__/recording.cpython-312.pyc,, +twilio/rest/trunking/v1/trunk/credential_list.py,sha256=DiaFxSeQHzQVUdQ443HryYev1H2xEguSfOM_o-ZBEXQ,19263 +twilio/rest/trunking/v1/trunk/ip_access_control_list.py,sha256=5w5vNMvcxS7bgAO90EXLuhEPh3FCXyZ3Fz1CTUvNSJ4,19633 +twilio/rest/trunking/v1/trunk/origination_url.py,sha256=wR1_hdm8NbEJsCf_6R0AYRRQ_J2LGYxPw44stYIf4fg,29067 +twilio/rest/trunking/v1/trunk/phone_number.py,sha256=CXghf3xUwyigxnUPpf5Qwv13SZCj7wuom4jH4ikbwOw,23374 +twilio/rest/trunking/v1/trunk/recording.py,sha256=mQy8EGrSX4Xjs11rRJlGZrwbYXeb9grlqMNX2MRYNq8,8619 +twilio/rest/trusthub/TrusthubBase.py,sha256=LSqCTPqT2RLzvjNzVcTXdvmVqwmyGa46Mvp8NmhsSjA,1211 +twilio/rest/trusthub/__init__.py,sha256=HF6EMXEDfJnPqcSZRYnkzrwMEARiFkTxX57LIuhl_uA,2483 +twilio/rest/trusthub/__pycache__/TrusthubBase.cpython-312.pyc,, +twilio/rest/trusthub/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/trusthub/v1/__init__.py,sha256=ylVjXc_ydfpG1fHfAe_zPUENSRXRiFgYw4VlVQmvFcE,4926 +twilio/rest/trusthub/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/trusthub/v1/__pycache__/compliance_inquiries.cpython-312.pyc,, +twilio/rest/trusthub/v1/__pycache__/compliance_registration_inquiries.cpython-312.pyc,, +twilio/rest/trusthub/v1/__pycache__/compliance_tollfree_inquiries.cpython-312.pyc,, +twilio/rest/trusthub/v1/__pycache__/end_user.cpython-312.pyc,, +twilio/rest/trusthub/v1/__pycache__/end_user_type.cpython-312.pyc,, +twilio/rest/trusthub/v1/__pycache__/policies.cpython-312.pyc,, +twilio/rest/trusthub/v1/__pycache__/supporting_document.cpython-312.pyc,, +twilio/rest/trusthub/v1/__pycache__/supporting_document_type.cpython-312.pyc,, +twilio/rest/trusthub/v1/compliance_inquiries.py,sha256=7N_DBUDEfQtTCbjx6s2N7jliKSSaRQbxvxEV_yVUqwk,11702 +twilio/rest/trusthub/v1/compliance_registration_inquiries.py,sha256=nmMqv3S49VTyZMHDXqpLbvcOVtPg_w_2pLmyPVIiGKU,28318 +twilio/rest/trusthub/v1/compliance_tollfree_inquiries.py,sha256=zd4iItGhbhUjVkiil8rJUODrRweyJHJUT_zQGkbt2BQ,14834 +twilio/rest/trusthub/v1/customer_profiles/__init__.py,sha256=tDyUmTRFNDQ7XpH_PY9ppn_KaBbqK6f9kcdkiMxmscY,32132 +twilio/rest/trusthub/v1/customer_profiles/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/trusthub/v1/customer_profiles/__pycache__/customer_profiles_channel_endpoint_assignment.cpython-312.pyc,, +twilio/rest/trusthub/v1/customer_profiles/__pycache__/customer_profiles_entity_assignments.cpython-312.pyc,, +twilio/rest/trusthub/v1/customer_profiles/__pycache__/customer_profiles_evaluations.cpython-312.pyc,, +twilio/rest/trusthub/v1/customer_profiles/customer_profiles_channel_endpoint_assignment.py,sha256=6Bn2Cftxm7mGRjXIPkVCu_WfjoseN9CItbU6Sp0q9K8,24350 +twilio/rest/trusthub/v1/customer_profiles/customer_profiles_entity_assignments.py,sha256=Y9VoVi_dW7rhTWIDr7_fCRsRvcAko_A7lM6vVMVzXM4,22795 +twilio/rest/trusthub/v1/customer_profiles/customer_profiles_evaluations.py,sha256=MBv7dFnstEx-BK-4LMjUEDJ3_EDP2w_61ys5VQY4Ij0,19310 +twilio/rest/trusthub/v1/end_user.py,sha256=FzBSwDDmHdBktQnPKGcIbXBTduaDfBaYwNjLtjjQeRo,21761 +twilio/rest/trusthub/v1/end_user_type.py,sha256=AD37MAi6XDD0iJIxkgSyXHVMzwAabWzHmDif8A9hzlw,14583 +twilio/rest/trusthub/v1/policies.py,sha256=EPIg9jHa8Otq4_NalbxK0QQVYCSSwfnigq20LdFsCNQ,14011 +twilio/rest/trusthub/v1/supporting_document.py,sha256=a_u94ntENL7QZIQjhUB3Tyx8PBJLCTxUkrg8AZobglQ,23394 +twilio/rest/trusthub/v1/supporting_document_type.py,sha256=ZSEwsngIwbaeKBByPFLcgprAabOiK9wtjHtOsmS5gYE,15209 +twilio/rest/trusthub/v1/trust_products/__init__.py,sha256=_zv1dpHZTdjokT8GWLkm0F6D3tcfXB5FOab5mw3Kh48,31492 +twilio/rest/trusthub/v1/trust_products/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/trusthub/v1/trust_products/__pycache__/trust_products_channel_endpoint_assignment.cpython-312.pyc,, +twilio/rest/trusthub/v1/trust_products/__pycache__/trust_products_entity_assignments.cpython-312.pyc,, +twilio/rest/trusthub/v1/trust_products/__pycache__/trust_products_evaluations.cpython-312.pyc,, +twilio/rest/trusthub/v1/trust_products/trust_products_channel_endpoint_assignment.py,sha256=FwxYxXryAXwYkoWGVnOkNRRaRhsZ6y2lw73MnP6234U,24044 +twilio/rest/trusthub/v1/trust_products/trust_products_entity_assignments.py,sha256=dmIQ_F2ZG_Z0uxgLfJXmJSg15Ho6MZk9ne4KPTiNPbs,22366 +twilio/rest/trusthub/v1/trust_products/trust_products_evaluations.py,sha256=rdTiKFlP-m29ZjRO4oC4xRFt3I44uZQ9-FzwTDelJBM,18929 +twilio/rest/verify/VerifyBase.py,sha256=slTn-f0x41HIoCytOvLLAYdWVdgh0Vfdno0Abcx0LC8,1197 +twilio/rest/verify/__init__.py,sha256=64lABdnh-2wHRS-ODTfyTpa3DHZlfAsSxsvLP5O9TK8,2056 +twilio/rest/verify/__pycache__/VerifyBase.cpython-312.pyc,, +twilio/rest/verify/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/verify/v2/__init__.py,sha256=CRuH0It_FUkZwbFGIhF4HmqAvwABDjm1dMUApkLqlFI,2993 +twilio/rest/verify/v2/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/verify/v2/__pycache__/form.cpython-312.pyc,, +twilio/rest/verify/v2/__pycache__/safelist.cpython-312.pyc,, +twilio/rest/verify/v2/__pycache__/template.cpython-312.pyc,, +twilio/rest/verify/v2/__pycache__/verification_attempt.cpython-312.pyc,, +twilio/rest/verify/v2/__pycache__/verification_attempts_summary.cpython-312.pyc,, +twilio/rest/verify/v2/form.py,sha256=909gfUJuAw_bW71J6HARQ4-ARsJ7o3vIstHEdguQC-o,5876 +twilio/rest/verify/v2/safelist.py,sha256=Ag90aA4SOTgXFluJv4Jj8a6vAztCI_yvs3hBCxURFhA,8628 +twilio/rest/verify/v2/service/__init__.py,sha256=WmL8y2Dasd-v80kz_lYjjdrY7gqsAFWNEDEOlHBeBSE,63600 +twilio/rest/verify/v2/service/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/verify/v2/service/__pycache__/access_token.cpython-312.pyc,, +twilio/rest/verify/v2/service/__pycache__/messaging_configuration.cpython-312.pyc,, +twilio/rest/verify/v2/service/__pycache__/verification.cpython-312.pyc,, +twilio/rest/verify/v2/service/__pycache__/verification_check.cpython-312.pyc,, +twilio/rest/verify/v2/service/__pycache__/webhook.cpython-312.pyc,, +twilio/rest/verify/v2/service/access_token.py,sha256=1ZpaHFwwpjWMmXI7y3mJFeFDulTF2SMM-5q5k821jmU,10807 +twilio/rest/verify/v2/service/entity/__init__.py,sha256=itrroE7UTwKM03yPBfC_EnyCLiY_Ufqb_WyNGCC0-4s,21581 +twilio/rest/verify/v2/service/entity/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/verify/v2/service/entity/__pycache__/factor.cpython-312.pyc,, +twilio/rest/verify/v2/service/entity/__pycache__/new_factor.cpython-312.pyc,, +twilio/rest/verify/v2/service/entity/challenge/__init__.py,sha256=iZ_efdWSqqG0LzLZHSqfYCRQ14XrM6-RUsJvFYrsySg,35609 +twilio/rest/verify/v2/service/entity/challenge/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/verify/v2/service/entity/challenge/__pycache__/notification.cpython-312.pyc,, +twilio/rest/verify/v2/service/entity/challenge/notification.py,sha256=jHoqJF5UV0c6BSJ17jf5yDkMXlSwicsdn8FvzgmJ_ns,6946 +twilio/rest/verify/v2/service/entity/factor.py,sha256=8M5KTGNV_myl89zhQh1peYEcPGt52BPcan02CUXPMzU,30406 +twilio/rest/verify/v2/service/entity/new_factor.py,sha256=ZQwCSA25oMDePqlWyhXLSpXfxR0NjO7ceAdWkeUXDKE,16555 +twilio/rest/verify/v2/service/messaging_configuration.py,sha256=10nFnWOIK2GsTc8M_vVGaJYpOqCcbLIMc-z1RLJjkkQ,24500 +twilio/rest/verify/v2/service/rate_limit/__init__.py,sha256=RDqM6xpir69k4fmKs4_s4pl_34nH9t6D2QqAnU-b4n0,22708 +twilio/rest/verify/v2/service/rate_limit/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/verify/v2/service/rate_limit/__pycache__/bucket.cpython-312.pyc,, +twilio/rest/verify/v2/service/rate_limit/bucket.py,sha256=4UfvcaXif8peF_hjPLYazJgGmfqKah8rt28jEs_f-Wk,23443 +twilio/rest/verify/v2/service/verification.py,sha256=UbDYqseVvl265qsGh0PmyIYmTdxYQMU1nmS4M1ee_JQ,24228 +twilio/rest/verify/v2/service/verification_check.py,sha256=773bJ0nSXxC8gng-6sj1Bd-NtcChD5pIb73-kwD41qU,9418 +twilio/rest/verify/v2/service/webhook.py,sha256=h5jSWrl4iozfO7FW7Z3IL6qjnQc9BUcE1G8mKxKDUuk,26592 +twilio/rest/verify/v2/template.py,sha256=YCtBY-w6M6OwtENuBlgQhTxP80NGgFEwQV8yarjhjfM,12051 +twilio/rest/verify/v2/verification_attempt.py,sha256=2ToIzv1ZMa14aYeRQlEo9wnhBjZuFaavIff6-vSSC_0,30897 +twilio/rest/verify/v2/verification_attempts_summary.py,sha256=OHp1b9X1IFP-P4grVYk7illDA9KExQpQBM9bMlML3C0,13606 +twilio/rest/video/VideoBase.py,sha256=qDVCaYofOZ9GyWTLVAkIr-z20L7qJzK6UVkaoCSix7E,1190 +twilio/rest/video/__init__.py,sha256=n0lfmIKLLW72CaH5QxWw4PzNz9xs-sS7lcn3IVFNZZc,2050 +twilio/rest/video/__pycache__/VideoBase.cpython-312.pyc,, +twilio/rest/video/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/video/v1/__init__.py,sha256=dkp1TkZI0FLmxCCZ3nLx3YOtDwdzlm940z3vnPQSwXg,2972 +twilio/rest/video/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/video/v1/__pycache__/composition.cpython-312.pyc,, +twilio/rest/video/v1/__pycache__/composition_hook.cpython-312.pyc,, +twilio/rest/video/v1/__pycache__/composition_settings.cpython-312.pyc,, +twilio/rest/video/v1/__pycache__/recording.cpython-312.pyc,, +twilio/rest/video/v1/__pycache__/recording_settings.cpython-312.pyc,, +twilio/rest/video/v1/composition.py,sha256=RCS6MKuTHXpK-TqoSMbhHs0uZ5BO3Ww5IFLd8H8vf-E,35950 +twilio/rest/video/v1/composition_hook.py,sha256=hMVK3E4orclhDG2rPdilugt7wLC4gOpBCrVXELOtSI0,56200 +twilio/rest/video/v1/composition_settings.py,sha256=kBu6WRkDoV-5YrvVAHXsPlsiGiB95cB_6YPWpmap9uk,14299 +twilio/rest/video/v1/recording.py,sha256=olKXsqVZbLTOUD0BZ_hK23lSF30KRTwBbxORB_N7Wpk,27838 +twilio/rest/video/v1/recording_settings.py,sha256=c8FiVzy4sKp9RIP55nT_zjijKttYTmtE0TzrO4N2WtQ,14130 +twilio/rest/video/v1/room/__init__.py,sha256=53xRHI10FMaa5dZ_qyOqyNr8W2C12Q9AOKLKQTd1q1I,40422 +twilio/rest/video/v1/room/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/video/v1/room/__pycache__/recording_rules.cpython-312.pyc,, +twilio/rest/video/v1/room/__pycache__/room_recording.cpython-312.pyc,, +twilio/rest/video/v1/room/participant/__init__.py,sha256=h9R1KpOb900lpxQctmbXyDXJUCLvdIqxXAfCEo70lzI,29495 +twilio/rest/video/v1/room/participant/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/video/v1/room/participant/__pycache__/anonymize.cpython-312.pyc,, +twilio/rest/video/v1/room/participant/__pycache__/published_track.cpython-312.pyc,, +twilio/rest/video/v1/room/participant/__pycache__/subscribe_rules.cpython-312.pyc,, +twilio/rest/video/v1/room/participant/__pycache__/subscribed_track.cpython-312.pyc,, +twilio/rest/video/v1/room/participant/anonymize.py,sha256=mkGn7zr3wEPVwsgezSyjzRSmGz5gTO47KtrR7P-MFeY,8053 +twilio/rest/video/v1/room/participant/published_track.py,sha256=WJPJep0V2N42HRNKSZhadI33af98Gw9x4MNtI8WV1FY,17358 +twilio/rest/video/v1/room/participant/subscribe_rules.py,sha256=wehmgUSun7ajqKKZj9uArlybLi7gJd90GVfYy8bRpPo,7102 +twilio/rest/video/v1/room/participant/subscribed_track.py,sha256=5g8bV91G-OUrckhHLzXIgdb7QwIo1FSIvBgKNZsJods,17550 +twilio/rest/video/v1/room/recording_rules.py,sha256=-9RUQb-7TRIVJwseEFG5r756rM1V5bsoYe_ztLPrNbw,5798 +twilio/rest/video/v1/room/room_recording.py,sha256=KWomK3OaiLF5ayzg-1JhgPcgfmR_2dAaOk7kx8j8gH4,25271 +twilio/rest/voice/VoiceBase.py,sha256=vx3BwrZ7ey2vqPrenZfgzIkoMV1txQR_vJlPGgMQLn4,1190 +twilio/rest/voice/__init__.py,sha256=mW4XcGaW44Uoa7eyNAKz4Nn4paB0Ck0Mkoub3XQYwwE,2099 +twilio/rest/voice/__pycache__/VoiceBase.cpython-312.pyc,, +twilio/rest/voice/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/voice/v1/__init__.py,sha256=dEg-rToBdmoNw7zta9H53Krf2WCRRe43XEWTXXkf3Hg,3036 +twilio/rest/voice/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/voice/v1/__pycache__/archived_call.cpython-312.pyc,, +twilio/rest/voice/v1/__pycache__/byoc_trunk.cpython-312.pyc,, +twilio/rest/voice/v1/__pycache__/ip_record.cpython-312.pyc,, +twilio/rest/voice/v1/__pycache__/source_ip_mapping.cpython-312.pyc,, +twilio/rest/voice/v1/archived_call.py,sha256=V_i84d8jCU9G-BLqSenCnoB7eLpE3vilbaj2n79rYkY,3402 +twilio/rest/voice/v1/byoc_trunk.py,sha256=WzGIcc7nJBwGfYcvspcU8B2wYbBXrzE3ufNJAxrzh7c,38687 +twilio/rest/voice/v1/connection_policy/__init__.py,sha256=rfdFRasVKd9yVFypPO9zaiBrtWJ5mvqNyvf_zVbLLT4,21685 +twilio/rest/voice/v1/connection_policy/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/voice/v1/connection_policy/__pycache__/connection_policy_target.cpython-312.pyc,, +twilio/rest/voice/v1/connection_policy/connection_policy_target.py,sha256=1ZseM2OXJir4NBZV8xIZi9ggmN3IPkqHD7YBJ3T76a4,30498 +twilio/rest/voice/v1/dialing_permissions/__init__.py,sha256=SJbMDsLFYUD-mkvu8YVDhjUbloobBrKuQwEtRC-Yvgw,2327 +twilio/rest/voice/v1/dialing_permissions/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/voice/v1/dialing_permissions/__pycache__/bulk_country_update.cpython-312.pyc,, +twilio/rest/voice/v1/dialing_permissions/__pycache__/settings.cpython-312.pyc,, +twilio/rest/voice/v1/dialing_permissions/bulk_country_update.py,sha256=giefzUf5SmBDspVb9PWy_GbTCt9aLsfHnfidwIcPNKU,4226 +twilio/rest/voice/v1/dialing_permissions/country/__init__.py,sha256=xOuoc2YYOUFVSrVaRczP2ED5PB3J91R2R0IGjZKbXDI,27816 +twilio/rest/voice/v1/dialing_permissions/country/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/voice/v1/dialing_permissions/country/__pycache__/highrisk_special_prefix.cpython-312.pyc,, +twilio/rest/voice/v1/dialing_permissions/country/highrisk_special_prefix.py,sha256=CG4hyNvOZOXh5C062bQsaimVPkPhhVH0ivBI9yskbMw,11448 +twilio/rest/voice/v1/dialing_permissions/settings.py,sha256=pezyWh8-p55k-CHnb2I0hBMFMpq0TrZgVKcz8yWnfOQ,7576 +twilio/rest/voice/v1/ip_record.py,sha256=meZcdGs5DgInal0HPeeEl-HADgFI76qK9gDM2lXVJlo,21614 +twilio/rest/voice/v1/source_ip_mapping.py,sha256=ATbg-FM9F3O9slFNuEB6kzZLrp3MUEVH0nmHuTbH7GA,20630 +twilio/rest/wireless/WirelessBase.py,sha256=VqCO0nP3Ox8WIkFHHdjMj-6bQeIWIBbW3_YnLYiyBMc,1211 +twilio/rest/wireless/__init__.py,sha256=37apinMOZa6Gr3Dl5SUnt5sy-fQE20i4bUBONAnhdGY,1261 +twilio/rest/wireless/__pycache__/WirelessBase.cpython-312.pyc,, +twilio/rest/wireless/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/wireless/v1/__init__.py,sha256=V2ghA15n9ZpyofyFP0pUiQtAkoDX4-u1a4-PqluNojM,2136 +twilio/rest/wireless/v1/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/wireless/v1/__pycache__/command.cpython-312.pyc,, +twilio/rest/wireless/v1/__pycache__/rate_plan.cpython-312.pyc,, +twilio/rest/wireless/v1/__pycache__/usage_record.cpython-312.pyc,, +twilio/rest/wireless/v1/command.py,sha256=dFVxuu00-yeLGIs26Rvm7LyyGNOm9pWzVKaEwMs3eQo,28457 +twilio/rest/wireless/v1/rate_plan.py,sha256=0NuRmFYBbaNC5jksOW5r_99IS2munT2EXuidh98JbC8,31676 +twilio/rest/wireless/v1/sim/__init__.py,sha256=E_nLykjUOfJRsZABVmm9eGuj0yJ5TqKc7ox6AinB9J4,47034 +twilio/rest/wireless/v1/sim/__pycache__/__init__.cpython-312.pyc,, +twilio/rest/wireless/v1/sim/__pycache__/data_session.cpython-312.pyc,, +twilio/rest/wireless/v1/sim/__pycache__/usage_record.cpython-312.pyc,, +twilio/rest/wireless/v1/sim/data_session.py,sha256=cka3NNQ3laIkeeQ0J6XH90yxWKNq3V1sBDDjZUD9a3Y,14643 +twilio/rest/wireless/v1/sim/usage_record.py,sha256=crqO1JRUbp-T1XLGCIslGFYjB4ZLSpQu7zm6v011ijs,17801 +twilio/rest/wireless/v1/usage_record.py,sha256=COri6A7vFfzfGcB7Y9M3YtcZfs4Ehx9xU_PJG_MB43M,16389 +twilio/twiml/__init__.py,sha256=2RyXWXsT4Nv38P4Gc51drBxMNMVQzyp7Wzmny5G5QjI,3471 +twilio/twiml/__pycache__/__init__.cpython-312.pyc,, +twilio/twiml/__pycache__/fax_response.cpython-312.pyc,, +twilio/twiml/__pycache__/messaging_response.cpython-312.pyc,, +twilio/twiml/__pycache__/voice_response.cpython-312.pyc,, +twilio/twiml/fax_response.py,sha256=tIz38pGfUL6kj2CHGUxyP1CKQtdjJySVFiedm64exKI,1435 +twilio/twiml/messaging_response.py,sha256=R3SFGVbZpkQHKf4v5FOm7S_sj97OyrUfjH2z4X53DXk,3017 +twilio/twiml/voice_response.py,sha256=tNSHigGk7dU-tNcA43u_PnUDRlGEKUjJEbASS1Y6o0k,101574 diff --git a/venv/Lib/site-packages/twilio-9.6.3.dist-info/REQUESTED b/venv/Lib/site-packages/twilio-9.6.3.dist-info/REQUESTED new file mode 100644 index 00000000..e69de29b diff --git a/venv/Lib/site-packages/twilio-9.6.3.dist-info/WHEEL b/venv/Lib/site-packages/twilio-9.6.3.dist-info/WHEEL new file mode 100644 index 00000000..5f133dbb --- /dev/null +++ b/venv/Lib/site-packages/twilio-9.6.3.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/venv/Lib/site-packages/twilio-9.6.3.dist-info/licenses/AUTHORS.md b/venv/Lib/site-packages/twilio-9.6.3.dist-info/licenses/AUTHORS.md new file mode 100644 index 00000000..58eabd02 --- /dev/null +++ b/venv/Lib/site-packages/twilio-9.6.3.dist-info/licenses/AUTHORS.md @@ -0,0 +1,41 @@ +# Authors + +We'd like to thank the following people who have contributed to the +`twilio-python` repository. + +- Adam Ballai +- Alex Brinsmead +- Alex Chan +- Andrew Benton +- Chad Selph +- Comrade DOS +- Dan Yang +- Dennis Pilarinos +- Doug Black +- Evan Fossier +- Fabian Topfstedt +- Florian Le Goff +- Frank Tobia +- Frederik De Bleser +- Guillaume BINET +- Hunter Blanks +- Joël Franusic +- Justin Van Koten +- Kenneth Reitz +- Kevin Burke +- Kyle Conroy +- Michael Parker +- Moses Palmér +- Ryan Horn +- Sam Kimbrel +- Skylar Saveland +- Tiberiu Ana +- Zachary Voase +- aes +- dnathe4th +- isbo +- negeorge +- Evan Cooke +- tysonholub +- Brodan +- Kyle Jones \ No newline at end of file diff --git a/venv/Lib/site-packages/twilio-9.6.3.dist-info/licenses/LICENSE b/venv/Lib/site-packages/twilio-9.6.3.dist-info/licenses/LICENSE new file mode 100644 index 00000000..6485c1f8 --- /dev/null +++ b/venv/Lib/site-packages/twilio-9.6.3.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (C) 2023, Twilio, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/venv/Lib/site-packages/twilio-9.6.3.dist-info/top_level.txt b/venv/Lib/site-packages/twilio-9.6.3.dist-info/top_level.txt new file mode 100644 index 00000000..105a6864 --- /dev/null +++ b/venv/Lib/site-packages/twilio-9.6.3.dist-info/top_level.txt @@ -0,0 +1 @@ +twilio diff --git a/venv/Lib/site-packages/twilio/__init__.py b/venv/Lib/site-packages/twilio/__init__.py new file mode 100644 index 00000000..5ce3ed13 --- /dev/null +++ b/venv/Lib/site-packages/twilio/__init__.py @@ -0,0 +1,2 @@ +__version_info__ = ("9", "6", "3") +__version__ = ".".join(__version_info__) diff --git a/venv/Lib/site-packages/twilio/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..17389793 Binary files /dev/null and b/venv/Lib/site-packages/twilio/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/__pycache__/request_validator.cpython-312.pyc b/venv/Lib/site-packages/twilio/__pycache__/request_validator.cpython-312.pyc new file mode 100644 index 00000000..ca95a1dd Binary files /dev/null and b/venv/Lib/site-packages/twilio/__pycache__/request_validator.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/auth_strategy/__init__.py b/venv/Lib/site-packages/twilio/auth_strategy/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/venv/Lib/site-packages/twilio/auth_strategy/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/auth_strategy/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..6e40f885 Binary files /dev/null and b/venv/Lib/site-packages/twilio/auth_strategy/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/auth_strategy/__pycache__/auth_strategy.cpython-312.pyc b/venv/Lib/site-packages/twilio/auth_strategy/__pycache__/auth_strategy.cpython-312.pyc new file mode 100644 index 00000000..a293019c Binary files /dev/null and b/venv/Lib/site-packages/twilio/auth_strategy/__pycache__/auth_strategy.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/auth_strategy/__pycache__/auth_type.cpython-312.pyc b/venv/Lib/site-packages/twilio/auth_strategy/__pycache__/auth_type.cpython-312.pyc new file mode 100644 index 00000000..c9abb3c3 Binary files /dev/null and b/venv/Lib/site-packages/twilio/auth_strategy/__pycache__/auth_type.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/auth_strategy/__pycache__/no_auth_strategy.cpython-312.pyc b/venv/Lib/site-packages/twilio/auth_strategy/__pycache__/no_auth_strategy.cpython-312.pyc new file mode 100644 index 00000000..ed704893 Binary files /dev/null and b/venv/Lib/site-packages/twilio/auth_strategy/__pycache__/no_auth_strategy.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/auth_strategy/__pycache__/token_auth_strategy.cpython-312.pyc b/venv/Lib/site-packages/twilio/auth_strategy/__pycache__/token_auth_strategy.cpython-312.pyc new file mode 100644 index 00000000..da3a3932 Binary files /dev/null and b/venv/Lib/site-packages/twilio/auth_strategy/__pycache__/token_auth_strategy.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/auth_strategy/auth_strategy.py b/venv/Lib/site-packages/twilio/auth_strategy/auth_strategy.py new file mode 100644 index 00000000..223cbff0 --- /dev/null +++ b/venv/Lib/site-packages/twilio/auth_strategy/auth_strategy.py @@ -0,0 +1,19 @@ +from twilio.auth_strategy.auth_type import AuthType +from abc import abstractmethod + + +class AuthStrategy(object): + def __init__(self, auth_type: AuthType): + self._auth_type = auth_type + + @property + def auth_type(self) -> AuthType: + return self._auth_type + + @abstractmethod + def get_auth_string(self) -> str: + """Return the authentication string.""" + + @abstractmethod + def requires_authentication(self) -> bool: + """Return True if authentication is required, else False.""" diff --git a/venv/Lib/site-packages/twilio/auth_strategy/auth_type.py b/venv/Lib/site-packages/twilio/auth_strategy/auth_type.py new file mode 100644 index 00000000..61886f92 --- /dev/null +++ b/venv/Lib/site-packages/twilio/auth_strategy/auth_type.py @@ -0,0 +1,12 @@ +from enum import Enum + + +class AuthType(Enum): + ORGS_TOKEN = "orgs_stoken" + NO_AUTH = "noauth" + BASIC = "basic" + API_KEY = "api_key" + CLIENT_CREDENTIALS = "client_credentials" + + def __str__(self): + return self.value diff --git a/venv/Lib/site-packages/twilio/auth_strategy/no_auth_strategy.py b/venv/Lib/site-packages/twilio/auth_strategy/no_auth_strategy.py new file mode 100644 index 00000000..a5bfd6d2 --- /dev/null +++ b/venv/Lib/site-packages/twilio/auth_strategy/no_auth_strategy.py @@ -0,0 +1,13 @@ +from auth_type import AuthType +from twilio.auth_strategy.auth_strategy import AuthStrategy + + +class NoAuthStrategy(AuthStrategy): + def __init__(self): + super().__init__(AuthType.NO_AUTH) + + def get_auth_string(self) -> str: + return "" + + def requires_authentication(self) -> bool: + return False diff --git a/venv/Lib/site-packages/twilio/auth_strategy/token_auth_strategy.py b/venv/Lib/site-packages/twilio/auth_strategy/token_auth_strategy.py new file mode 100644 index 00000000..33a8d385 --- /dev/null +++ b/venv/Lib/site-packages/twilio/auth_strategy/token_auth_strategy.py @@ -0,0 +1,55 @@ +import jwt +import threading +import logging +from datetime import datetime, timezone + +from twilio.auth_strategy.auth_type import AuthType +from twilio.auth_strategy.auth_strategy import AuthStrategy +from twilio.http.token_manager import TokenManager + + +class TokenAuthStrategy(AuthStrategy): + def __init__(self, token_manager: TokenManager): + super().__init__(AuthType.ORGS_TOKEN) + self.token_manager = token_manager + self.token = None + self.lock = threading.Lock() + logging.basicConfig(level=logging.INFO) + self.logger = logging.getLogger(__name__) + + def get_auth_string(self) -> str: + self.fetch_token() + return f"Bearer {self.token}" + + def requires_authentication(self) -> bool: + return True + + def fetch_token(self): + if self.token is None or self.token == "" or self.is_token_expired(self.token): + with self.lock: + if ( + self.token is None + or self.token == "" + or self.is_token_expired(self.token) + ): + self.logger.info("New token fetched for accessing organization API") + self.token = self.token_manager.fetch_access_token() + + def is_token_expired(self, token): + try: + decoded = jwt.decode(token, options={"verify_signature": False}) + exp = decoded.get("exp") + + if exp is None: + return True # No expiration time present, consider it expired + + # Check if the expiration time has passed by using time-zone + return datetime.fromtimestamp(exp, tz=timezone.utc) < datetime.now( + timezone.utc + ) + + except jwt.DecodeError: + return True # Token is invalid + except Exception as e: + print(f"An error occurred: {e}") + return True diff --git a/venv/Lib/site-packages/twilio/base/__init__.py b/venv/Lib/site-packages/twilio/base/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/venv/Lib/site-packages/twilio/base/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/base/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..ce0da162 Binary files /dev/null and b/venv/Lib/site-packages/twilio/base/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/base/__pycache__/client_base.cpython-312.pyc b/venv/Lib/site-packages/twilio/base/__pycache__/client_base.cpython-312.pyc new file mode 100644 index 00000000..029a129b Binary files /dev/null and b/venv/Lib/site-packages/twilio/base/__pycache__/client_base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/base/__pycache__/deserialize.cpython-312.pyc b/venv/Lib/site-packages/twilio/base/__pycache__/deserialize.cpython-312.pyc new file mode 100644 index 00000000..fc0e661f Binary files /dev/null and b/venv/Lib/site-packages/twilio/base/__pycache__/deserialize.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/base/__pycache__/domain.cpython-312.pyc b/venv/Lib/site-packages/twilio/base/__pycache__/domain.cpython-312.pyc new file mode 100644 index 00000000..7120c6ef Binary files /dev/null and b/venv/Lib/site-packages/twilio/base/__pycache__/domain.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/base/__pycache__/exceptions.cpython-312.pyc b/venv/Lib/site-packages/twilio/base/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 00000000..b9a77ed1 Binary files /dev/null and b/venv/Lib/site-packages/twilio/base/__pycache__/exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/base/__pycache__/instance_context.cpython-312.pyc b/venv/Lib/site-packages/twilio/base/__pycache__/instance_context.cpython-312.pyc new file mode 100644 index 00000000..3ee6e9a8 Binary files /dev/null and b/venv/Lib/site-packages/twilio/base/__pycache__/instance_context.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/base/__pycache__/instance_resource.cpython-312.pyc b/venv/Lib/site-packages/twilio/base/__pycache__/instance_resource.cpython-312.pyc new file mode 100644 index 00000000..b6f94e32 Binary files /dev/null and b/venv/Lib/site-packages/twilio/base/__pycache__/instance_resource.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/base/__pycache__/list_resource.cpython-312.pyc b/venv/Lib/site-packages/twilio/base/__pycache__/list_resource.cpython-312.pyc new file mode 100644 index 00000000..3ef5467e Binary files /dev/null and b/venv/Lib/site-packages/twilio/base/__pycache__/list_resource.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/base/__pycache__/obsolete.cpython-312.pyc b/venv/Lib/site-packages/twilio/base/__pycache__/obsolete.cpython-312.pyc new file mode 100644 index 00000000..f46eb237 Binary files /dev/null and b/venv/Lib/site-packages/twilio/base/__pycache__/obsolete.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/base/__pycache__/page.cpython-312.pyc b/venv/Lib/site-packages/twilio/base/__pycache__/page.cpython-312.pyc new file mode 100644 index 00000000..f427e27a Binary files /dev/null and b/venv/Lib/site-packages/twilio/base/__pycache__/page.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/base/__pycache__/serialize.cpython-312.pyc b/venv/Lib/site-packages/twilio/base/__pycache__/serialize.cpython-312.pyc new file mode 100644 index 00000000..ffae16b9 Binary files /dev/null and b/venv/Lib/site-packages/twilio/base/__pycache__/serialize.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/base/__pycache__/values.cpython-312.pyc b/venv/Lib/site-packages/twilio/base/__pycache__/values.cpython-312.pyc new file mode 100644 index 00000000..35ea22b7 Binary files /dev/null and b/venv/Lib/site-packages/twilio/base/__pycache__/values.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/base/__pycache__/version.cpython-312.pyc b/venv/Lib/site-packages/twilio/base/__pycache__/version.cpython-312.pyc new file mode 100644 index 00000000..c0df2b06 Binary files /dev/null and b/venv/Lib/site-packages/twilio/base/__pycache__/version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/base/client_base.py b/venv/Lib/site-packages/twilio/base/client_base.py new file mode 100644 index 00000000..b16f85bf --- /dev/null +++ b/venv/Lib/site-packages/twilio/base/client_base.py @@ -0,0 +1,271 @@ +import os +import platform +from typing import Dict, List, MutableMapping, Optional, Tuple +from urllib.parse import urlparse, urlunparse + +from twilio import __version__ +from twilio.http import HttpClient +from twilio.http.http_client import TwilioHttpClient +from twilio.http.response import Response +from twilio.credential.credential_provider import CredentialProvider + + +class ClientBase(object): + """A client for accessing the Twilio API.""" + + def __init__( + self, + username: Optional[str] = None, + password: Optional[str] = None, + account_sid: Optional[str] = None, + region: Optional[str] = None, + http_client: Optional[HttpClient] = None, + environment: Optional[MutableMapping[str, str]] = None, + edge: Optional[str] = None, + user_agent_extensions: Optional[List[str]] = None, + credential_provider: Optional[CredentialProvider] = None, + ): + """ + Initializes the Twilio Client + + :param username: Username to authenticate with + :param password: Password to authenticate with + :param account_sid: Account SID, defaults to Username + :param region: Twilio Region to make requests to, defaults to 'us1' if an edge is provided + :param http_client: HttpClient, defaults to TwilioHttpClient + :param environment: Environment to look for auth details, defaults to os.environ + :param edge: Twilio Edge to make requests to, defaults to None + :param user_agent_extensions: Additions to the user agent string + :param credential_provider: credential provider for authentication method that needs to be used + """ + + environment = environment or os.environ + + self.username = username or environment.get("TWILIO_ACCOUNT_SID") + """ :type : str """ + self.password = password or environment.get("TWILIO_AUTH_TOKEN") + """ :type : str """ + self.edge = edge or environment.get("TWILIO_EDGE") + """ :type : str """ + self.region = region or environment.get("TWILIO_REGION") + """ :type : str """ + self.user_agent_extensions = user_agent_extensions or [] + """ :type : list[str] """ + self.credential_provider = credential_provider or None + """ :type : CredentialProvider """ + + self.account_sid = account_sid or self.username + """ :type : str """ + self.auth = (self.username, self.password) + """ :type : tuple(str, str) """ + self.http_client: HttpClient = http_client or TwilioHttpClient() + """ :type : HttpClient """ + + def request( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: + """ + Makes a request to the Twilio API using the configured http client + Authentication information is automatically added if none is provided + + :param method: HTTP Method + :param uri: Fully qualified url + :param params: Query string parameters + :param data: POST body data + :param headers: HTTP Headers + :param auth: Authentication + :param timeout: Timeout in seconds + :param allow_redirects: Should the client follow redirects + + :returns: Response from the Twilio API + """ + headers = self.get_headers(method, headers) + + if self.credential_provider: + + auth_strategy = self.credential_provider.to_auth_strategy() + headers["Authorization"] = auth_strategy.get_auth_string() + elif self.username is not None and self.password is not None: + auth = self.get_auth(auth) + else: + auth = None + + if method == "DELETE": + del headers["Accept"] + + uri = self.get_hostname(uri) + filtered_data = self.copy_non_none_values(data) + return self.http_client.request( + method, + uri, + params=params, + data=filtered_data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + async def request_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: + """ + Asynchronously makes a request to the Twilio API using the configured http client + The configured http client must be an asynchronous http client + Authentication information is automatically added if none is provided + + :param method: HTTP Method + :param uri: Fully qualified url + :param params: Query string parameters + :param data: POST body data + :param headers: HTTP Headers + :param auth: Authentication + :param timeout: Timeout in seconds + :param allow_redirects: Should the client follow redirects + + :returns: Response from the Twilio API + """ + if not self.http_client.is_async: + raise RuntimeError( + "http_client must be asynchronous to support async API requests" + ) + + headers = self.get_headers(method, headers) + if method == "DELETE": + del headers["Accept"] + + if self.credential_provider: + auth_strategy = self.credential_provider.to_auth_strategy() + headers["Authorization"] = auth_strategy.get_auth_string() + elif self.username is not None and self.password is not None: + auth = self.get_auth(auth) + else: + auth = None + + uri = self.get_hostname(uri) + filtered_data = self.copy_non_none_values(data) + return await self.http_client.request( + method, + uri, + params=params, + data=filtered_data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + def copy_non_none_values(self, data): + if isinstance(data, dict): + return { + k: self.copy_non_none_values(v) + for k, v in data.items() + if v is not None + } + elif isinstance(data, list): + return [ + self.copy_non_none_values(item) for item in data if item is not None + ] + return data + + def get_auth(self, auth: Optional[Tuple[str, str]]) -> Tuple[str, str]: + """ + Get the request authentication object + :param auth: Authentication (username, password) + :returns: The authentication object + """ + return auth or self.auth + + def get_headers( + self, method: str, headers: Optional[Dict[str, str]] + ) -> Dict[str, str]: + """ + Get the request headers including user-agent, extensions, encoding, content-type, MIME type + :param method: HTTP method + :param headers: HTTP headers + :returns: HTTP headers + """ + headers = headers or {} + + # Set User-Agent + pkg_version = __version__ + os_name = platform.system() + os_arch = platform.machine() + python_version = platform.python_version() + headers["User-Agent"] = "twilio-python/{} ({} {}) Python/{}".format( + pkg_version, + os_name, + os_arch, + python_version, + ) + # Extensions + for extension in self.user_agent_extensions: + headers["User-Agent"] += " {}".format(extension) + headers["X-Twilio-Client"] = "python-{}".format(__version__) + + # Types, encodings, etc. + headers["Accept-Charset"] = "utf-8" + if (method == "POST" or method == "PUT") and ("Content-Type" not in headers): + headers["Content-Type"] = "application/x-www-form-urlencoded" + if "Accept" not in headers: + headers["Accept"] = "application/json" + + return headers + + def get_hostname(self, uri: str) -> str: + """ + Determines the proper hostname given edge and region preferences + via client configuration or uri. + + :param uri: Fully qualified url + + :returns: The final uri used to make the request + """ + if not self.edge and not self.region: + return uri + + parsed_url = urlparse(uri) + pieces = parsed_url.netloc.split(".") + prefix = pieces[0] + suffix = ".".join(pieces[-2:]) + region = None + edge = None + if len(pieces) == 4: + # product.region.twilio.com + region = pieces[1] + elif len(pieces) == 5: + # product.edge.region.twilio.com + edge = pieces[1] + region = pieces[2] + + edge = self.edge or edge + region = self.region or region or (edge and "us1") + + parsed_url = parsed_url._replace( + netloc=".".join([part for part in [prefix, edge, region, suffix] if part]) + ) + return str(urlunparse(parsed_url)) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "".format(self.account_sid) diff --git a/venv/Lib/site-packages/twilio/base/deserialize.py b/venv/Lib/site-packages/twilio/base/deserialize.py new file mode 100644 index 00000000..71226c08 --- /dev/null +++ b/venv/Lib/site-packages/twilio/base/deserialize.py @@ -0,0 +1,75 @@ +import datetime +from decimal import BasicContext, Decimal +from email.utils import parsedate +from typing import Optional, Union + +ISO8601_DATE_FORMAT = "%Y-%m-%d" +ISO8601_DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ" + + +def iso8601_date(s: str) -> Union[datetime.date, str]: + """ + Parses an ISO 8601 date string and returns a UTC date object or the string + if the parsing failed. + :param s: ISO 8601-formatted date string (2015-01-25) + :return: + """ + try: + return ( + datetime.datetime.strptime(s, ISO8601_DATE_FORMAT) + .replace(tzinfo=datetime.timezone.utc) + .date() + ) + except (TypeError, ValueError): + return s + + +def iso8601_datetime( + s: str, +) -> Union[datetime.datetime, str]: + """ + Parses an ISO 8601 datetime string and returns a UTC datetime object, + or the string if parsing failed. + :param s: ISO 8601-formatted datetime string (2015-01-25T12:34:56Z) + """ + try: + return datetime.datetime.strptime(s, ISO8601_DATETIME_FORMAT).replace( + tzinfo=datetime.timezone.utc + ) + except (TypeError, ValueError): + return s + + +def rfc2822_datetime(s: str) -> Optional[datetime.datetime]: + """ + Parses an RFC 2822 date string and returns a UTC datetime object, + or the string if parsing failed. + :param s: RFC 2822-formatted string date + :return: datetime or str + """ + date_tuple = parsedate(s) + if date_tuple is None: + return None + return datetime.datetime(*date_tuple[:6]).replace(tzinfo=datetime.timezone.utc) + + +def decimal(d: Optional[str]) -> Union[Decimal, str]: + """ + Parses a decimal string into a Decimal + :param d: decimal string + """ + if not d: + return d + return Decimal(d, BasicContext) + + +def integer(i: str) -> Union[int, str]: + """ + Parses an integer string into an int + :param i: integer string + :return: int + """ + try: + return int(i) + except (TypeError, ValueError): + return i diff --git a/venv/Lib/site-packages/twilio/base/domain.py b/venv/Lib/site-packages/twilio/base/domain.py new file mode 100644 index 00000000..4f8395dd --- /dev/null +++ b/venv/Lib/site-packages/twilio/base/domain.py @@ -0,0 +1,93 @@ +from typing import Dict, Optional, Tuple +from twilio.http.response import Response +from twilio.rest import Client + + +class Domain(object): + """ + This represents at Twilio API subdomain. + + Like, `api.twilio.com` or `lookups.twilio.com'. + """ + + def __init__(self, twilio: Client, base_url: str): + self.twilio = twilio + self.base_url = base_url + + def absolute_url(self, uri: str) -> str: + """ + Converts a relative `uri` to an absolute url. + :param string uri: The relative uri to make absolute. + :return: An absolute url (based off this domain) + """ + return "{}/{}".format(self.base_url.strip("/"), uri.strip("/")) + + def request( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: + """ + Makes an HTTP request to this domain. + :param method: The HTTP method. + :param uri: The HTTP uri. + :param params: Query parameters. + :param data: The request body. + :param headers: The HTTP headers. + :param auth: Basic auth tuple of (username, password) + :param timeout: The request timeout. + :param allow_redirects: True if the client should follow HTTP + redirects. + """ + url = self.absolute_url(uri) + return self.twilio.request( + method, + url, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + async def request_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: + """ + Makes an asynchronous HTTP request to this domain. + :param method: The HTTP method. + :param uri: The HTTP uri. + :param params: Query parameters. + :param data: The request body. + :param headers: The HTTP headers. + :param auth: Basic auth tuple of (username, password) + :param timeout: The request timeout. + :param allow_redirects: True if the client should follow HTTP + redirects. + """ + url = self.absolute_url(uri) + return await self.twilio.request_async( + method, + url, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) diff --git a/venv/Lib/site-packages/twilio/base/exceptions.py b/venv/Lib/site-packages/twilio/base/exceptions.py new file mode 100644 index 00000000..8f3b7cc7 --- /dev/null +++ b/venv/Lib/site-packages/twilio/base/exceptions.py @@ -0,0 +1,82 @@ +# -*- coding: utf-8 -*- +import sys +from typing import Optional + + +class TwilioException(Exception): + pass + + +class TwilioRestException(TwilioException): + """A generic 400 or 500 level exception from the Twilio API + + :param int status: the HTTP status that was returned for the exception + :param str uri: The URI that caused the exception + :param str msg: A human-readable message for the error + :param int|None code: A Twilio-specific error code for the error. This is + not available for all errors. + :param method: The HTTP method used to make the request + :param details: Additional error details returned for the exception + """ + + def __init__( + self, + status: int, + uri: str, + msg: str = "", + code: Optional[int] = None, + method: str = "GET", + details: Optional[object] = None, + ): + self.uri = uri + self.status = status + self.msg = msg + self.code = code + self.method = method + self.details = details + + def __str__(self) -> str: + """Try to pretty-print the exception, if this is going on screen.""" + + def red(words: str) -> str: + return "\033[31m\033[49m%s\033[0m" % words + + def white(words: str) -> str: + return "\033[37m\033[49m%s\033[0m" % words + + def blue(words: str) -> str: + return "\033[34m\033[49m%s\033[0m" % words + + def teal(words: str) -> str: + return "\033[36m\033[49m%s\033[0m" % words + + def get_uri(code: int) -> str: + return "https://www.twilio.com/docs/errors/{0}".format(code) + + # If it makes sense to print a human readable error message, try to + # do it. The one problem is that someone might catch this error and + # try to display the message from it to an end user. + if hasattr(sys.stderr, "isatty") and sys.stderr.isatty(): + msg = ( + "\n{red_error} {request_was}\n\n{http_line}" + "\n\n{twilio_returned}\n\n{message}\n".format( + red_error=red("HTTP Error"), + request_was=white("Your request was:"), + http_line=teal("%s %s" % (self.method, self.uri)), + twilio_returned=white("Twilio returned the following information:"), + message=blue(str(self.msg)), + ) + ) + if self.code: + msg = "".join( + [ + msg, + "\n{more_info}\n\n{uri}\n\n".format( + more_info=white("More information may be available here:"), + uri=blue(get_uri(self.code)), + ), + ] + ) + return msg + else: + return "HTTP {0} error: {1}".format(self.status, self.msg) diff --git a/venv/Lib/site-packages/twilio/base/instance_context.py b/venv/Lib/site-packages/twilio/base/instance_context.py new file mode 100644 index 00000000..44ff9a38 --- /dev/null +++ b/venv/Lib/site-packages/twilio/base/instance_context.py @@ -0,0 +1,6 @@ +from twilio.base.version import Version + + +class InstanceContext(object): + def __init__(self, version: Version): + self._version = version diff --git a/venv/Lib/site-packages/twilio/base/instance_resource.py b/venv/Lib/site-packages/twilio/base/instance_resource.py new file mode 100644 index 00000000..a05aac37 --- /dev/null +++ b/venv/Lib/site-packages/twilio/base/instance_resource.py @@ -0,0 +1,6 @@ +from twilio.base.version import Version + + +class InstanceResource(object): + def __init__(self, version: Version): + self._version = version diff --git a/venv/Lib/site-packages/twilio/base/list_resource.py b/venv/Lib/site-packages/twilio/base/list_resource.py new file mode 100644 index 00000000..e3eb176d --- /dev/null +++ b/venv/Lib/site-packages/twilio/base/list_resource.py @@ -0,0 +1,6 @@ +from twilio.base.version import Version + + +class ListResource(object): + def __init__(self, version: Version): + self._version = version diff --git a/venv/Lib/site-packages/twilio/base/obsolete.py b/venv/Lib/site-packages/twilio/base/obsolete.py new file mode 100644 index 00000000..e0f4a033 --- /dev/null +++ b/venv/Lib/site-packages/twilio/base/obsolete.py @@ -0,0 +1,47 @@ +import warnings +import functools + + +class ObsoleteException(Exception): + """Base class for warnings about obsolete features.""" + + +def obsolete_client(func): + """This is a decorator which can be used to mark Client classes as + obsolete. It will result in an error being emitted when the class is + instantiated.""" + + @functools.wraps(func) + def new_func(*args, **kwargs): + raise ObsoleteException( + "{} has been removed from this version of the library. " + "Please refer to current documentation for guidance.".format(func.__name__) + ) + + return new_func + + +def deprecated_method(new_func=None): + """ + This is a decorator which can be used to mark deprecated methods. + It will report in a DeprecationWarning being emitted to stderr when the deprecated method is used. + """ + + def deprecated_method_wrapper(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + msg = "Function method .{}() is deprecated".format(func.__name__) + msg += ( + " in favor of .{}()".format(new_func) + if isinstance(new_func, str) + else "" + ) + warnings.warn(msg, DeprecationWarning) + return func(*args, **kwargs) + + return wrapper + + if callable(new_func): + return deprecated_method_wrapper(new_func) + + return deprecated_method_wrapper diff --git a/venv/Lib/site-packages/twilio/base/page.py b/venv/Lib/site-packages/twilio/base/page.py new file mode 100644 index 00000000..b5b2da7b --- /dev/null +++ b/venv/Lib/site-packages/twilio/base/page.py @@ -0,0 +1,173 @@ +import json +from typing import Any, Dict, Optional + +from twilio.base.exceptions import TwilioException +from twilio.http.response import Response + + +class Page(object): + """ + Represents a page of records in a collection. + + A `Page` lets you iterate over its records and fetch the next and previous + pages in the collection. + """ + + META_KEYS = { + "end", + "first_page_uri", + "next_page_uri", + "last_page_uri", + "page", + "page_size", + "previous_page_uri", + "total", + "num_pages", + "start", + "uri", + } + + def __init__(self, version, response: Response, solution={}): + payload = self.process_response(response) + + self._version = version + self._payload = payload + self._solution = solution + self._records = iter(self.load_page(payload)) + + def __iter__(self): + """ + A `Page` is a valid iterator. + """ + return self + + def __next__(self): + return self.next() + + def next(self): + """ + Returns the next record in the `Page`. + """ + return self.get_instance(next(self._records)) + + @classmethod + def process_response(cls, response: Response) -> Any: + """ + Load a JSON response. + + :param response: The HTTP response. + :return The JSON-loaded content. + """ + if response.status_code != 200: + raise TwilioException("Unable to fetch page", response) + + return json.loads(response.text) + + def load_page(self, payload: Dict[str, Any]): + """ + Parses the collection of records out of a list payload. + + :param payload: The JSON-loaded content. + :return list: The list of records. + """ + if "meta" in payload and "key" in payload["meta"]: + return payload[payload["meta"]["key"]] + else: + keys = set(payload.keys()) + key = keys - self.META_KEYS + if len(key) == 1: + return payload[key.pop()] + if "Resources" in payload: + return payload["Resources"] + + raise TwilioException("Page Records can not be deserialized") + + @property + def previous_page_url(self) -> Optional[str]: + """ + :return str: Returns a link to the previous_page_url or None if doesn't exist. + """ + if "meta" in self._payload and "previous_page_url" in self._payload["meta"]: + return self._payload["meta"]["previous_page_url"] + elif ( + "previous_page_uri" in self._payload and self._payload["previous_page_uri"] + ): + return self._version.domain.absolute_url(self._payload["previous_page_uri"]) + + return None + + @property + def next_page_url(self) -> Optional[str]: + """ + :return str: Returns a link to the next_page_url or None if doesn't exist. + """ + if "meta" in self._payload and "next_page_url" in self._payload["meta"]: + return self._payload["meta"]["next_page_url"] + elif "next_page_uri" in self._payload and self._payload["next_page_uri"]: + return self._version.domain.absolute_url(self._payload["next_page_uri"]) + + return None + + def get_instance(self, payload: Dict[str, Any]) -> Any: + """ + :param dict payload: A JSON-loaded representation of an instance record. + :return: A rich, resource-dependent object. + """ + raise TwilioException( + "Page.get_instance() must be implemented in the derived class" + ) + + def next_page(self) -> Optional["Page"]: + """ + Return the `Page` after this one. + :return The next page. + """ + if not self.next_page_url: + return None + + response = self._version.domain.twilio.request("GET", self.next_page_url) + cls = type(self) + return cls(self._version, response, self._solution) + + async def next_page_async(self) -> Optional["Page"]: + """ + Asynchronously return the `Page` after this one. + :return The next page. + """ + if not self.next_page_url: + return None + + response = await self._version.domain.twilio.request_async( + "GET", self.next_page_url + ) + cls = type(self) + return cls(self._version, response, self._solution) + + def previous_page(self) -> Optional["Page"]: + """ + Return the `Page` before this one. + :return The previous page. + """ + if not self.previous_page_url: + return None + + response = self._version.domain.twilio.request("GET", self.previous_page_url) + cls = type(self) + return cls(self._version, response, self._solution) + + async def previous_page_async(self) -> Optional["Page"]: + """ + Asynchronously return the `Page` before this one. + :return The previous page. + """ + if not self.previous_page_url: + return None + + response = await self._version.domain.twilio.request_async( + "GET", self.previous_page_url + ) + cls = type(self) + return cls(self._version, response, self._solution) + + def __repr__(self) -> str: + return "" diff --git a/venv/Lib/site-packages/twilio/base/serialize.py b/venv/Lib/site-packages/twilio/base/serialize.py new file mode 100644 index 00000000..cea91b04 --- /dev/null +++ b/venv/Lib/site-packages/twilio/base/serialize.py @@ -0,0 +1,93 @@ +import datetime +import json + +from twilio.base import values + + +def iso8601_date(d): + """ + Return a string representation of a date that the Twilio API understands + Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date + """ + if d == values.unset: + return d + elif isinstance(d, datetime.datetime): + return str(d.date()) + elif isinstance(d, datetime.date): + return str(d) + elif isinstance(d, str): + return d + + +def iso8601_datetime(d): + """ + Return a string representation of a date that the Twilio API understands + Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date + """ + if d == values.unset: + return d + elif isinstance(d, datetime.datetime) or isinstance(d, datetime.date): + return d.strftime("%Y-%m-%dT%H:%M:%SZ") + elif isinstance(d, str): + return d + + +def prefixed_collapsible_map(m, prefix): + """ + Return a dict of params corresponding to those in m with the added prefix + """ + if m == values.unset: + return {} + + def flatten_dict(d, result=None, prv_keys=None): + if result is None: + result = {} + + if prv_keys is None: + prv_keys = [] + + for k, v in d.items(): + if isinstance(v, dict): + flatten_dict(v, result, prv_keys + [k]) + else: + result[".".join(prv_keys + [k])] = v + + return result + + if isinstance(m, dict): + flattened = flatten_dict(m) + return {"{}.{}".format(prefix, k): v for k, v in flattened.items()} + + return {} + + +def boolean_to_string(bool_or_str): + if bool_or_str == values.unset: + return bool_or_str + + if bool_or_str is None: + return bool_or_str + + if isinstance(bool_or_str, str): + return bool_or_str.lower() + + return "true" if bool_or_str else "false" + + +def object(obj): + """ + Return a jsonified string represenation of obj if obj is jsonifiable else + return obj untouched + """ + if isinstance(obj, dict) or isinstance(obj, list): + return json.dumps(obj) + return obj + + +def map(lst, serialize_func): + """ + Applies serialize_func to every element in lst + """ + if not isinstance(lst, list): + return lst + return [serialize_func(e) for e in lst] diff --git a/venv/Lib/site-packages/twilio/base/values.py b/venv/Lib/site-packages/twilio/base/values.py new file mode 100644 index 00000000..16032b11 --- /dev/null +++ b/venv/Lib/site-packages/twilio/base/values.py @@ -0,0 +1,13 @@ +from typing import Dict + +unset = object() + + +def of(d: Dict[str, object]) -> Dict[str, object]: + """ + Remove unset values from a dict. + + :param d: A dict to strip. + :return A dict with unset values removed. + """ + return {k: v for k, v in d.items() if v != unset} diff --git a/venv/Lib/site-packages/twilio/base/version.py b/venv/Lib/site-packages/twilio/base/version.py new file mode 100644 index 00000000..ed7e86f4 --- /dev/null +++ b/venv/Lib/site-packages/twilio/base/version.py @@ -0,0 +1,489 @@ +import json +from typing import Any, AsyncIterator, Dict, Iterator, Optional, Tuple + +from twilio.base import values +from twilio.base.domain import Domain +from twilio.base.exceptions import TwilioRestException +from twilio.base.page import Page +from twilio.http.response import Response + + +class Version(object): + """ + Represents an API version. + """ + + def __init__(self, domain: Domain, version: str): + self.domain = domain + self.version = version + + def absolute_url(self, uri: str) -> str: + """ + Turns a relative uri into an absolute url. + """ + return self.domain.absolute_url(self.relative_uri(uri)) + + def relative_uri(self, uri: str) -> str: + """ + Turns a relative uri into a versioned relative uri. + """ + return "{}/{}".format(self.version.strip("/"), uri.strip("/")) + + def request( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: + """ + Make an HTTP request. + """ + url = self.relative_uri(uri) + return self.domain.request( + method, + url, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + async def request_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: + """ + Make an asynchronous HTTP request + """ + url = self.relative_uri(uri) + return await self.domain.request_async( + method, + url, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + @classmethod + def exception( + cls, method: str, uri: str, response: Response, message: str + ) -> TwilioRestException: + """ + Wraps an exceptional response in a `TwilioRestException`. + """ + # noinspection PyBroadException + try: + error_payload = json.loads(response.text) + if "message" in error_payload: + message = "{}: {}".format(message, error_payload["message"]) + details = error_payload.get("details") + code = error_payload.get("code", response.status_code) + return TwilioRestException( + response.status_code, uri, message, code, method, details + ) + except Exception: + return TwilioRestException( + response.status_code, uri, message, response.status_code, method + ) + + def _parse_fetch(self, method: str, uri: str, response: Response) -> Any: + """ + Parses fetch response JSON + """ + # Note that 3XX response codes are allowed for fetches. + if response.status_code < 200 or response.status_code >= 400: + raise self.exception(method, uri, response, "Unable to fetch record") + + return json.loads(response.text) + + def fetch( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Any: + """ + Fetch a resource instance. + """ + response = self.request( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + return self._parse_fetch(method, uri, response) + + async def fetch_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Any: + """ + Asynchronously fetch a resource instance. + """ + response = await self.request_async( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + return self._parse_fetch(method, uri, response) + + def _parse_update(self, method: str, uri: str, response: Response) -> Any: + """ + Parses update response JSON + """ + if response.status_code < 200 or response.status_code >= 300: + raise self.exception(method, uri, response, "Unable to update record") + + return json.loads(response.text) + + def update( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Any: + """ + Update a resource instance. + """ + response = self.request( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + return self._parse_update(method, uri, response) + + async def update_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Any: + """ + Asynchronously update a resource instance. + """ + response = await self.request_async( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + return self._parse_update(method, uri, response) + + def _parse_delete(self, method: str, uri: str, response: Response) -> bool: + """ + Parses delete response JSON + """ + if response.status_code < 200 or response.status_code >= 300: + raise self.exception(method, uri, response, "Unable to delete record") + + return response.status_code == 204 + + def delete( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> bool: + """ + Delete a resource. + """ + response = self.request( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + return self._parse_delete(method, uri, response) + + async def delete_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> bool: + """ + Asynchronously delete a resource. + """ + response = await self.request_async( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + return self._parse_delete(method, uri, response) + + def read_limits( + self, limit: Optional[int] = None, page_size: Optional[int] = None + ) -> Dict[str, object]: + """ + Takes a limit on the max number of records to read and a max page_size + and calculates the max number of pages to read. + + :param limit: Max number of records to read. + :param page_size: Max page size. + :return A dictionary of paging limits. + """ + if limit is not None and page_size is None: + page_size = limit + + return { + "limit": limit or values.unset, + "page_size": page_size or values.unset, + } + + def page( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: + """ + Makes an HTTP request. + """ + return self.request( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + async def page_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: + """ + Makes an asynchronous HTTP request. + """ + return await self.request_async( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + def stream( + self, + page: Optional[Page], + limit: Optional[int] = None, + page_limit: Optional[int] = None, + ) -> Iterator[Any]: + """ + Generates records one a time from a page, stopping at prescribed limits. + + :param page: The page to stream. + :param limit: The max number of records to read. + :param page_limit: The max number of pages to read. + """ + current_record = 1 + current_page = 1 + + while page is not None: + for record in page: + yield record + current_record += 1 + if limit and limit is not values.unset and limit < current_record: + return + + current_page += 1 + if ( + page_limit + and page_limit is not values.unset + and page_limit < current_page + ): + return + + page = page.next_page() + + async def stream_async( + self, + page: Optional[Page], + limit: Optional[int] = None, + page_limit: Optional[int] = None, + ) -> AsyncIterator[Any]: + """ + Generates records one a time from a page, stopping at prescribed limits. + + :param page: The page to stream. + :param limit: The max number of records to read. + :param page_limit: The max number of pages to read. + """ + current_record = 1 + current_page = 1 + + while page is not None: + for record in page: + yield record + current_record += 1 + if limit and limit is not values.unset and limit < current_record: + return + + current_page += 1 + if ( + page_limit + and page_limit is not values.unset + and page_limit < current_page + ): + return + + page = await page.next_page_async() + + def _parse_create(self, method: str, uri: str, response: Response) -> Any: + """ + Parse create response JSON + """ + if response.status_code < 200 or response.status_code >= 300: + raise self.exception(method, uri, response, "Unable to create record") + + return json.loads(response.text) + + def create( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Any: + """ + Create a resource instance. + """ + response = self.request( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + return self._parse_create(method, uri, response) + + async def create_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Any: + """ + Asynchronously create a resource instance. + """ + response = await self.request_async( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + return self._parse_create(method, uri, response) diff --git a/venv/Lib/site-packages/twilio/credential/__init__.py b/venv/Lib/site-packages/twilio/credential/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/venv/Lib/site-packages/twilio/credential/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/credential/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..58130f53 Binary files /dev/null and b/venv/Lib/site-packages/twilio/credential/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/credential/__pycache__/client_credential_provider.cpython-312.pyc b/venv/Lib/site-packages/twilio/credential/__pycache__/client_credential_provider.cpython-312.pyc new file mode 100644 index 00000000..31a956b1 Binary files /dev/null and b/venv/Lib/site-packages/twilio/credential/__pycache__/client_credential_provider.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/credential/__pycache__/credential_provider.cpython-312.pyc b/venv/Lib/site-packages/twilio/credential/__pycache__/credential_provider.cpython-312.pyc new file mode 100644 index 00000000..be723eff Binary files /dev/null and b/venv/Lib/site-packages/twilio/credential/__pycache__/credential_provider.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/credential/__pycache__/orgs_credential_provider.cpython-312.pyc b/venv/Lib/site-packages/twilio/credential/__pycache__/orgs_credential_provider.cpython-312.pyc new file mode 100644 index 00000000..1bbd2e7e Binary files /dev/null and b/venv/Lib/site-packages/twilio/credential/__pycache__/orgs_credential_provider.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/credential/client_credential_provider.py b/venv/Lib/site-packages/twilio/credential/client_credential_provider.py new file mode 100644 index 00000000..656d4463 --- /dev/null +++ b/venv/Lib/site-packages/twilio/credential/client_credential_provider.py @@ -0,0 +1,28 @@ +from twilio.http.client_token_manager import ClientTokenManager +from twilio.base.exceptions import TwilioException +from twilio.credential.credential_provider import CredentialProvider +from twilio.auth_strategy.auth_type import AuthType +from twilio.auth_strategy.token_auth_strategy import TokenAuthStrategy + + +class ClientCredentialProvider(CredentialProvider): + def __init__(self, client_id: str, client_secret: str, token_manager=None): + super().__init__(AuthType.CLIENT_CREDENTIALS) + + if client_id is None or client_secret is None: + raise TwilioException("Client id and Client secret are mandatory") + + self.grant_type = "client_credentials" + self.client_id = client_id + self.client_secret = client_secret + self.token_manager = token_manager + self.auth_strategy = None + + def to_auth_strategy(self): + if self.token_manager is None: + self.token_manager = ClientTokenManager( + self.grant_type, self.client_id, self.client_secret + ) + if self.auth_strategy is None: + self.auth_strategy = TokenAuthStrategy(self.token_manager) + return self.auth_strategy diff --git a/venv/Lib/site-packages/twilio/credential/credential_provider.py b/venv/Lib/site-packages/twilio/credential/credential_provider.py new file mode 100644 index 00000000..72aafeed --- /dev/null +++ b/venv/Lib/site-packages/twilio/credential/credential_provider.py @@ -0,0 +1,13 @@ +from twilio.auth_strategy.auth_type import AuthType + + +class CredentialProvider: + def __init__(self, auth_type: AuthType): + self._auth_type = auth_type + + @property + def auth_type(self) -> AuthType: + return self._auth_type + + def to_auth_strategy(self): + raise NotImplementedError("Subclasses must implement this method") diff --git a/venv/Lib/site-packages/twilio/credential/orgs_credential_provider.py b/venv/Lib/site-packages/twilio/credential/orgs_credential_provider.py new file mode 100644 index 00000000..e623f523 --- /dev/null +++ b/venv/Lib/site-packages/twilio/credential/orgs_credential_provider.py @@ -0,0 +1,28 @@ +from twilio.http.orgs_token_manager import OrgTokenManager +from twilio.base.exceptions import TwilioException +from twilio.credential.credential_provider import CredentialProvider +from twilio.auth_strategy.auth_type import AuthType +from twilio.auth_strategy.token_auth_strategy import TokenAuthStrategy + + +class OrgsCredentialProvider(CredentialProvider): + def __init__(self, client_id: str, client_secret: str, token_manager=None): + super().__init__(AuthType.CLIENT_CREDENTIALS) + + if client_id is None or client_secret is None: + raise TwilioException("Client id and Client secret are mandatory") + + self.grant_type = "client_credentials" + self.client_id = client_id + self.client_secret = client_secret + self.token_manager = token_manager + self.auth_strategy = None + + def to_auth_strategy(self): + if self.token_manager is None: + self.token_manager = OrgTokenManager( + self.grant_type, self.client_id, self.client_secret + ) + if self.auth_strategy is None: + self.auth_strategy = TokenAuthStrategy(self.token_manager) + return self.auth_strategy diff --git a/venv/Lib/site-packages/twilio/http/__init__.py b/venv/Lib/site-packages/twilio/http/__init__.py new file mode 100644 index 00000000..3e248270 --- /dev/null +++ b/venv/Lib/site-packages/twilio/http/__init__.py @@ -0,0 +1,104 @@ +from logging import Logger +from typing import Any, Dict, Optional, Tuple +from urllib.parse import urlencode + +from requests import Response + +from twilio.base.exceptions import TwilioException +from twilio.http.request import Request as TwilioRequest +from twilio.http.response import Response as TwilioResponse + + +class HttpClient(object): + def __init__(self, logger: Logger, is_async: bool, timeout: Optional[float] = None): + """ + Constructor for the abstract HTTP client + + :param logger + :param is_async: Whether the client supports async request calls. + :param timeout: Timeout for the requests. + Timeout should never be zero (0) or less. + """ + self.logger = logger + self.is_async = is_async + + if timeout is not None and timeout <= 0: + raise ValueError(timeout) + self.timeout = timeout + + self._test_only_last_request: Optional[TwilioRequest] = None + self._test_only_last_response: Optional[TwilioResponse] = None + + """ + An abstract class representing an HTTP client. + """ + + def request( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> TwilioResponse: + """ + Make an HTTP request. + """ + raise TwilioException("HttpClient is an abstract class") + + def log_request(self, kwargs: Dict[str, Any]) -> None: + """ + Logs the HTTP request + """ + self.logger.info("-- BEGIN Twilio API Request --") + + if kwargs["params"]: + self.logger.info( + "{} Request: {}?{}".format( + kwargs["method"], kwargs["url"], urlencode(kwargs["params"]) + ) + ) + self.logger.info("Query Params: {}".format(kwargs["params"])) + else: + self.logger.info("{} Request: {}".format(kwargs["method"], kwargs["url"])) + + if kwargs["headers"]: + self.logger.info("Headers:") + for key, value in kwargs["headers"].items(): + # Do not log authorization headers + if "authorization" not in key.lower(): + self.logger.info("{} : {}".format(key, value)) + + self.logger.info("-- END Twilio API Request --") + + def log_response(self, status_code: int, response: Response) -> None: + """ + Logs the HTTP response + """ + self.logger.info("Response Status Code: {}".format(status_code)) + self.logger.info("Response Headers: {}".format(response.headers)) + + +class AsyncHttpClient(HttpClient): + """ + An abstract class representing an asynchronous HTTP client. + """ + + async def request( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> TwilioResponse: + """ + Make an asynchronous HTTP request. + """ + raise TwilioException("AsyncHttpClient is an abstract class") diff --git a/venv/Lib/site-packages/twilio/http/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/http/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..c01cec1a Binary files /dev/null and b/venv/Lib/site-packages/twilio/http/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/http/__pycache__/async_http_client.cpython-312.pyc b/venv/Lib/site-packages/twilio/http/__pycache__/async_http_client.cpython-312.pyc new file mode 100644 index 00000000..dcaf5b81 Binary files /dev/null and b/venv/Lib/site-packages/twilio/http/__pycache__/async_http_client.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/http/__pycache__/client_token_manager.cpython-312.pyc b/venv/Lib/site-packages/twilio/http/__pycache__/client_token_manager.cpython-312.pyc new file mode 100644 index 00000000..bfe10a24 Binary files /dev/null and b/venv/Lib/site-packages/twilio/http/__pycache__/client_token_manager.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/http/__pycache__/http_client.cpython-312.pyc b/venv/Lib/site-packages/twilio/http/__pycache__/http_client.cpython-312.pyc new file mode 100644 index 00000000..ffcfa0ee Binary files /dev/null and b/venv/Lib/site-packages/twilio/http/__pycache__/http_client.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/http/__pycache__/orgs_token_manager.cpython-312.pyc b/venv/Lib/site-packages/twilio/http/__pycache__/orgs_token_manager.cpython-312.pyc new file mode 100644 index 00000000..9da20314 Binary files /dev/null and b/venv/Lib/site-packages/twilio/http/__pycache__/orgs_token_manager.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/http/__pycache__/request.cpython-312.pyc b/venv/Lib/site-packages/twilio/http/__pycache__/request.cpython-312.pyc new file mode 100644 index 00000000..3269e48e Binary files /dev/null and b/venv/Lib/site-packages/twilio/http/__pycache__/request.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/http/__pycache__/response.cpython-312.pyc b/venv/Lib/site-packages/twilio/http/__pycache__/response.cpython-312.pyc new file mode 100644 index 00000000..ebfe3098 Binary files /dev/null and b/venv/Lib/site-packages/twilio/http/__pycache__/response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/http/__pycache__/token_manager.cpython-312.pyc b/venv/Lib/site-packages/twilio/http/__pycache__/token_manager.cpython-312.pyc new file mode 100644 index 00000000..b217865a Binary files /dev/null and b/venv/Lib/site-packages/twilio/http/__pycache__/token_manager.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/http/__pycache__/validation_client.cpython-312.pyc b/venv/Lib/site-packages/twilio/http/__pycache__/validation_client.cpython-312.pyc new file mode 100644 index 00000000..37f23efa Binary files /dev/null and b/venv/Lib/site-packages/twilio/http/__pycache__/validation_client.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/http/async_http_client.py b/venv/Lib/site-packages/twilio/http/async_http_client.py new file mode 100644 index 00000000..ecd5d4de --- /dev/null +++ b/venv/Lib/site-packages/twilio/http/async_http_client.py @@ -0,0 +1,135 @@ +import logging +from typing import Dict, Optional, Tuple + +from aiohttp import BasicAuth, ClientSession +from aiohttp_retry import ExponentialRetry, RetryClient + +from twilio.http import AsyncHttpClient +from twilio.http.request import Request as TwilioRequest +from twilio.http.response import Response + +_logger = logging.getLogger("twilio.async_http_client") + + +class AsyncTwilioHttpClient(AsyncHttpClient): + """ + General purpose asynchronous HTTP Client for interacting with the Twilio API + """ + + def __init__( + self, + pool_connections: bool = True, + trace_configs=None, + timeout: Optional[float] = None, + logger: logging.Logger = _logger, + proxy_url: Optional[str] = None, + max_retries: Optional[int] = None, + ): + """ + Constructor for the AsyncTwilioHttpClient + + :param pool_connections: Creates a client session for making requests from. + :param trace_configs: Configuration used to trace request lifecycle events. See aiohttp library TraceConfig + documentation for more info. + :param timeout: Timeout for the requests (seconds) + :param logger + :param proxy_url: Proxy URL + :param max_retries: Maximum number of retries each request should attempt + """ + super().__init__(logger, True, timeout) + self.proxy_url = proxy_url + self.trace_configs = trace_configs + self.session = ( + ClientSession(trace_configs=self.trace_configs) + if pool_connections + else None + ) + if max_retries is not None: + retry_options = ExponentialRetry(attempts=max_retries) + self.session = RetryClient( + client_session=self.session, retry_options=retry_options + ) + + async def request( + self, + method: str, + url: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: + """ + Make an asynchronous HTTP Request with parameters provided. + + :param method: The HTTP method to use + :param url: The URL to request + :param params: Query parameters to append to the URL + :param data: Parameters to go in the body of the HTTP request + :param headers: HTTP Headers to send with the request + :param auth: Basic Auth arguments (username, password entries) + :param timeout: Socket/Read timeout for the request. Overrides the timeout if set on the client. + :param allow_redirects: Whether or not to allow redirects + See the requests documentation for explanation of all these parameters + + :return: An http response + """ + if timeout is not None and timeout <= 0: + raise ValueError(timeout) + + basic_auth = None + if auth is not None: + basic_auth = BasicAuth(login=auth[0], password=auth[1]) + + kwargs = { + "method": method.upper(), + "url": url, + "params": params, + "data": data, + "headers": headers, + "auth": basic_auth, + "timeout": timeout, + "allow_redirects": allow_redirects, + } + + self.log_request(kwargs) + self._test_only_last_response = None + + temp = False + session = None + if self.session: + session = self.session + else: + session = ClientSession() + temp = True + self._test_only_last_request = TwilioRequest(**kwargs) + response = await session.request(**kwargs) + self.log_response(response.status, response) + self._test_only_last_response = Response( + response.status, await response.text(), response.headers + ) + if temp: + await session.close() + return self._test_only_last_response + + async def close(self): + """ + Closes the HTTP client session + """ + if self.session: + await self.session.close() + + async def __aenter__(self): + """ + Async context manager setup + """ + return self + + async def __aexit__(self, *excinfo): + """ + Async context manager exit + """ + if self.session: + await self.session.close() diff --git a/venv/Lib/site-packages/twilio/http/client_token_manager.py b/venv/Lib/site-packages/twilio/http/client_token_manager.py new file mode 100644 index 00000000..0d42428a --- /dev/null +++ b/venv/Lib/site-packages/twilio/http/client_token_manager.py @@ -0,0 +1,41 @@ +from twilio.http.token_manager import TokenManager +from twilio.rest import Client + + +class ClientTokenManager(TokenManager): + """ + Client Token Manager + """ + + def __init__( + self, + grant_type: str, + client_id: str, + client_secret: str, + code: str = None, + redirect_uri: str = None, + audience: str = None, + refreshToken: str = None, + scope: str = None, + ): + self.grant_type = grant_type + self.client_id = client_id + self.client_secret = client_secret + self.code = code + self.redirect_uri = redirect_uri + self.audience = audience + self.refreshToken = refreshToken + self.scope = scope + self.client = Client() + + def fetch_access_token(self): + token_instance = self.client.iam.v1.token.create( + grant_type=self.grant_type, + client_id=self.client_id, + client_secret=self.client_secret, + code=self.code, + redirect_uri=self.redirect_uri, + audience=self.audience, + scope=self.scope, + ) + return token_instance.access_token diff --git a/venv/Lib/site-packages/twilio/http/http_client.py b/venv/Lib/site-packages/twilio/http/http_client.py new file mode 100644 index 00000000..2f2d3635 --- /dev/null +++ b/venv/Lib/site-packages/twilio/http/http_client.py @@ -0,0 +1,119 @@ +import os +import logging +from typing import Dict, Optional, Tuple + +from requests import Request, Session, hooks +from requests.adapters import HTTPAdapter + +from twilio.http import HttpClient +from twilio.http.request import Request as TwilioRequest +from twilio.http.response import Response + +_logger = logging.getLogger("twilio.http_client") + + +class TwilioHttpClient(HttpClient): + """ + General purpose HTTP Client for interacting with the Twilio API + """ + + def __init__( + self, + pool_connections: bool = True, + request_hooks: Optional[Dict[str, object]] = None, + timeout: Optional[float] = None, + logger: logging.Logger = _logger, + proxy: Optional[Dict[str, str]] = None, + max_retries: Optional[int] = None, + ): + """ + Constructor for the TwilioHttpClient + :param pool_connections + :param request_hooks + :param timeout: Timeout for the requests. + Timeout should never be zero (0) or less + :param logger + :param proxy: Http proxy for the requests session + :param max_retries: Maximum number of retries each request should attempt + """ + super().__init__(logger, False, timeout) + self.session = Session() if pool_connections else None + if self.session and max_retries is not None: + self.session.mount("https://", HTTPAdapter(max_retries=max_retries)) + elif self.session is not None: + self.session.mount( + "https://", HTTPAdapter(pool_maxsize=min(32, os.cpu_count() + 4)) + ) + self.request_hooks = request_hooks or hooks.default_hooks() + self.proxy = proxy if proxy else {} + + def request( + self, + method: str, + url: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: + """ + Make an HTTP Request with parameters provided. + + :param method: The HTTP method to use + :param url: The URL to request + :param params: Query parameters to append to the URL + :param data: Parameters to go in the body of the HTTP request + :param headers: HTTP Headers to send with the request + :param auth: Basic Auth arguments + :param timeout: Socket/Read timeout for the request + :param allow_redirects: Whether to allow redirects + See the requests documentation for explanation of all these parameters + + :return: An HTTP response + """ + if timeout is None: + timeout = self.timeout + elif timeout <= 0: + raise ValueError(timeout) + + kwargs = { + "method": method.upper(), + "url": url, + "params": params, + "headers": headers, + "auth": auth, + "hooks": self.request_hooks, + } + if headers and headers.get("Content-Type") == "application/json": + kwargs["json"] = data + elif headers and headers.get("Content-Type") == "application/scim+json": + kwargs["json"] = data + else: + kwargs["data"] = data + self.log_request(kwargs) + self._test_only_last_response = None + session = self.session or Session() + request = Request(**kwargs) + self._test_only_last_request = TwilioRequest(**kwargs) + + prepped_request = session.prepare_request(request) + + settings = session.merge_environment_settings( + prepped_request.url, self.proxy, None, None, None + ) + response = session.send( + prepped_request, + allow_redirects=allow_redirects, + timeout=timeout, + **settings, + ) + + self.log_response(response.status_code, response) + + self._test_only_last_response = Response( + int(response.status_code), response.text, response.headers + ) + + return self._test_only_last_response diff --git a/venv/Lib/site-packages/twilio/http/orgs_token_manager.py b/venv/Lib/site-packages/twilio/http/orgs_token_manager.py new file mode 100644 index 00000000..76fad521 --- /dev/null +++ b/venv/Lib/site-packages/twilio/http/orgs_token_manager.py @@ -0,0 +1,41 @@ +from twilio.http.token_manager import TokenManager +from twilio.rest import Client + + +class OrgTokenManager(TokenManager): + """ + Orgs Token Manager + """ + + def __init__( + self, + grant_type: str, + client_id: str, + client_secret: str, + code: str = None, + redirect_uri: str = None, + audience: str = None, + refreshToken: str = None, + scope: str = None, + ): + self.grant_type = grant_type + self.client_id = client_id + self.client_secret = client_secret + self.code = code + self.redirect_uri = redirect_uri + self.audience = audience + self.refreshToken = refreshToken + self.scope = scope + self.client = Client() + + def fetch_access_token(self): + token_instance = self.client.iam.v1.token.create( + grant_type=self.grant_type, + client_id=self.client_id, + client_secret=self.client_secret, + code=self.code, + redirect_uri=self.redirect_uri, + audience=self.audience, + scope=self.scope, + ) + return token_instance.access_token diff --git a/venv/Lib/site-packages/twilio/http/request.py b/venv/Lib/site-packages/twilio/http/request.py new file mode 100644 index 00000000..e75cf12b --- /dev/null +++ b/venv/Lib/site-packages/twilio/http/request.py @@ -0,0 +1,91 @@ +from enum import Enum +from typing import Any, Dict, Tuple, Union +from urllib.parse import urlencode + + +class Match(Enum): + ANY = "*" + + +class Request(object): + """ + An HTTP request. + """ + + def __init__( + self, + method: Union[str, Match] = Match.ANY, + url: Union[str, Match] = Match.ANY, + auth: Union[Tuple[str, str], Match] = Match.ANY, + params: Union[Dict[str, str], Match] = Match.ANY, + data: Union[Dict[str, str], Match] = Match.ANY, + headers: Union[Dict[str, str], Match] = Match.ANY, + **kwargs: Any + ): + self.method = method + if method and method is not Match.ANY: + self.method = method.upper() + self.url = url + self.auth = auth + self.params = params + self.data = data + self.headers = headers + + @classmethod + def attribute_equal(cls, lhs, rhs) -> bool: + if lhs == Match.ANY or rhs == Match.ANY: + # ANY matches everything + return True + + lhs = lhs or None + rhs = rhs or None + + return lhs == rhs + + def __eq__(self, other) -> bool: + if not isinstance(other, Request): + return False + + return ( + self.attribute_equal(self.method, other.method) + and self.attribute_equal(self.url, other.url) + and self.attribute_equal(self.auth, other.auth) + and self.attribute_equal(self.params, other.params) + and self.attribute_equal(self.data, other.data) + and self.attribute_equal(self.headers, other.headers) + ) + + def __str__(self) -> str: + auth = "" + if self.auth and self.auth != Match.ANY: + auth = "{} ".format(self.auth) + + params = "" + if self.params and self.params != Match.ANY: + params = "?{}".format(urlencode(self.params, doseq=True)) + + data = "" + if self.data and self.data != Match.ANY: + if self.method == "GET": + data = "\n -G" + data += "\n{}".format( + "\n".join(' -d "{}={}"'.format(k, v) for k, v in self.data.items()) + ) + + headers = "" + if self.headers and self.headers != Match.ANY: + headers = "\n{}".format( + "\n".join(' -H "{}: {}"'.format(k, v) for k, v in self.headers.items()) + ) + + return "{auth}{method} {url}{params}{data}{headers}".format( + auth=auth, + method=self.method, + url=self.url, + params=params, + data=data, + headers=headers, + ) + + def __repr__(self) -> str: + return str(self) diff --git a/venv/Lib/site-packages/twilio/http/response.py b/venv/Lib/site-packages/twilio/http/response.py new file mode 100644 index 00000000..af5a3b17 --- /dev/null +++ b/venv/Lib/site-packages/twilio/http/response.py @@ -0,0 +1,22 @@ +from typing import Any, Optional + + +class Response(object): + def __init__( + self, + status_code: int, + text: str, + headers: Optional[Any] = None, + ): + self.content = text + self.headers = headers + self.cached = False + self.status_code = status_code + self.ok = self.status_code < 400 + + @property + def text(self) -> str: + return self.content + + def __repr__(self) -> str: + return "HTTP {} {}".format(self.status_code, self.content) diff --git a/venv/Lib/site-packages/twilio/http/token_manager.py b/venv/Lib/site-packages/twilio/http/token_manager.py new file mode 100644 index 00000000..28cc7310 --- /dev/null +++ b/venv/Lib/site-packages/twilio/http/token_manager.py @@ -0,0 +1,7 @@ +from twilio.base.version import Version + + +class TokenManager: + + def fetch_access_token(self, version: Version): + pass diff --git a/venv/Lib/site-packages/twilio/http/validation_client.py b/venv/Lib/site-packages/twilio/http/validation_client.py new file mode 100644 index 00000000..1a4a83f0 --- /dev/null +++ b/venv/Lib/site-packages/twilio/http/validation_client.py @@ -0,0 +1,138 @@ +from collections import namedtuple + +from requests import Request, Session + +from twilio.base.exceptions import TwilioRestException +from urllib.parse import urlparse +from twilio.http import HttpClient +from twilio.http.response import Response +from twilio.jwt.validation import ClientValidationJwt + + +ValidationPayload = namedtuple( + "ValidationPayload", + ["method", "path", "query_string", "all_headers", "signed_headers", "body"], +) + + +class ValidationClient(HttpClient): + __SIGNED_HEADERS = ["authorization", "host"] + + def __init__( + self, + account_sid, + api_key_sid, + credential_sid, + private_key, + pool_connections=True, + ): + """ + Build a ValidationClient which signs requests with private_key and allows Twilio to + validate request has not been tampered with. + + :param str account_sid: A Twilio Account Sid starting with 'AC' + :param str api_key_sid: A Twilio API Key Sid starting with 'SK' + :param str credential_sid: A Credential Sid starting with 'CR', + corresponds to public key Twilio will use to verify the JWT. + :param str private_key: The private key used to sign the Client Validation JWT. + """ + self.account_sid = account_sid + self.credential_sid = credential_sid + self.api_key_sid = api_key_sid + self.private_key = private_key + self.session = Session() if pool_connections else None + + def request( + self, + method, + url, + params=None, + data=None, + headers=None, + auth=None, + timeout=None, + allow_redirects=False, + ): + """ + Make a signed HTTP Request + + :param str method: The HTTP method to use + :param str url: The URL to request + :param dict params: Query parameters to append to the URL + :param dict data: Parameters to go in the body of the HTTP request + :param dict headers: HTTP Headers to send with the request + :param tuple auth: Basic Auth arguments + :param float timeout: Socket/Read timeout for the request + :param boolean allow_redirects: Whether or not to allow redirects + See the requests documentation for explanation of all these parameters + + :return: An http response + :rtype: A :class:`Response ` object + """ + session = self.session or Session() + request = Request( + method.upper(), url, params=params, data=data, headers=headers, auth=auth + ) + prepared_request = session.prepare_request(request) + + if ( + "Host" not in prepared_request.headers + and "host" not in prepared_request.headers + ): + prepared_request.headers["Host"] = self._get_host(prepared_request) + + validation_payload = self._build_validation_payload(prepared_request) + jwt = ClientValidationJwt( + self.account_sid, + self.api_key_sid, + self.credential_sid, + self.private_key, + validation_payload, + ) + prepared_request.headers["Twilio-Client-Validation"] = jwt.to_jwt() + + response = session.send( + prepared_request, + allow_redirects=allow_redirects, + timeout=timeout, + ) + + return Response(int(response.status_code), response.text) + + def _build_validation_payload(self, request): + """ + Extract relevant information from request to build a ClientValidationJWT + :param PreparedRequest request: request we will extract information from. + :return: ValidationPayload + """ + parsed = urlparse(request.url) + path = parsed.path + query_string = parsed.query or "" + + return ValidationPayload( + method=request.method, + path=path, + query_string=query_string, + all_headers=request.headers, + signed_headers=ValidationClient.__SIGNED_HEADERS, + body=request.body or "", + ) + + def _get_host(self, request): + """Pull the Host out of the request""" + parsed = urlparse(request.url) + return str(parsed.netloc) + + def validate_ssl_certificate(self, client): + """ + Validate that a request to the new SSL certificate is successful + :return: null on success, raise TwilioRestException if the request fails + """ + response = client.request("GET", "https://tls-test.twilio.com:443") + + if response.status_code < 200 or response.status_code >= 300: + raise TwilioRestException( + response.status_code, + "https://tls-test.twilio.com:443", + "Failed to validate SSL certificate", + ) diff --git a/venv/Lib/site-packages/twilio/jwt/__init__.py b/venv/Lib/site-packages/twilio/jwt/__init__.py new file mode 100644 index 00000000..7a51ea70 --- /dev/null +++ b/venv/Lib/site-packages/twilio/jwt/__init__.py @@ -0,0 +1,161 @@ +import jwt as jwt_lib +import time + + +__all__ = ["Jwt", "JwtDecodeError"] + + +class JwtDecodeError(Exception): + pass + + +class Jwt(object): + """Base class for building a Json Web Token""" + + GENERATE = object() + ALGORITHM = "HS256" + + def __init__( + self, + secret_key, + issuer, + subject=None, + algorithm=None, + nbf=GENERATE, + ttl=3600, + valid_until=None, + ): + self.secret_key = secret_key + """:type str: The secret used to encode the JWT""" + self.issuer = issuer + """:type str: The issuer of this JWT""" + self.subject = subject + """:type str: The subject of this JWT, omitted from payload by default""" + self.algorithm = algorithm or self.ALGORITHM + """:type str: The algorithm used to encode the JWT, defaults to 'HS256'""" + self.nbf = nbf + """:type int: Time in secs since epoch before which this JWT is invalid. Defaults to now.""" + self.ttl = ttl + """:type int: Time to live of the JWT in seconds, defaults to 1 hour""" + self.valid_until = valid_until + """:type int: Time in secs since epoch this JWT is valid for. Overrides ttl if provided.""" + + self.__decoded_payload = None + self.__decoded_headers = None + + def _generate_payload(self): + """:rtype: dict the payload of the JWT to send""" + raise NotImplementedError("Subclass must provide a payload.") + + def _generate_headers(self): + """:rtype dict: Additional headers to include in the JWT, defaults to an empty dict""" + return {} + + @classmethod + def _from_jwt(cls, headers, payload, key=None): + """ + Class specific implementation of from_jwt which should take jwt components and return + and instance of this Class with jwt information loaded. + :return: Jwt object containing the headers, payload and key + """ + jwt = Jwt( + secret_key=key, + issuer=payload.get("iss", None), + subject=payload.get("sub", None), + algorithm=headers.get("alg", None), + valid_until=payload.get("exp", None), + nbf=payload.get("nbf", None), + ) + jwt.__decoded_payload = payload + jwt.__decoded_headers = headers + return jwt + + @property + def payload(self): + if self.__decoded_payload: + return self.__decoded_payload + + payload = self._generate_payload().copy() + payload["iss"] = self.issuer + payload["exp"] = int(time.time()) + self.ttl + if self.nbf is not None: + if self.nbf == self.GENERATE: + payload["nbf"] = int(time.time()) + else: + payload["nbf"] = self.nbf + if self.valid_until: + payload["exp"] = self.valid_until + if self.subject: + payload["sub"] = self.subject + + return payload + + @property + def headers(self): + if self.__decoded_headers: + return self.__decoded_headers + + headers = self._generate_headers().copy() + headers["typ"] = "JWT" + headers["alg"] = self.algorithm + return headers + + def to_jwt(self, ttl=None): + """ + Encode this JWT object into a JWT string + :param int ttl: override the ttl configured in the constructor + :rtype: str The JWT string + """ + + if not self.secret_key: + raise ValueError("JWT does not have a signing key configured.") + + headers = self.headers.copy() + + payload = self.payload.copy() + if ttl: + payload["exp"] = int(time.time()) + ttl + + return jwt_lib.encode( + payload, self.secret_key, algorithm=self.algorithm, headers=headers + ) + + @classmethod + def from_jwt(cls, jwt, key=""): + """ + Decode a JWT string into a Jwt object + :param str jwt: JWT string + :param Optional[str] key: key used to verify JWT signature, if not provided then validation + is skipped. + :raises JwtDecodeError if decoding JWT fails for any reason. + :return: A DecodedJwt object containing the jwt information. + """ + verify = True if key else False + + try: + headers = jwt_lib.get_unverified_header(jwt) + + alg = headers.get("alg") + if alg != cls.ALGORITHM: + raise ValueError( + f"Incorrect decoding algorithm {alg}, " + f"expecting {cls.ALGORITHM}." + ) + + payload = jwt_lib.decode( + jwt, + key, + algorithms=[cls.ALGORITHM], + options={ + "verify_signature": verify, + "verify_exp": True, + "verify_nbf": True, + }, + ) + except Exception as e: + raise JwtDecodeError(getattr(e, "message", str(e))) + + return cls._from_jwt(headers, payload, key) + + def __str__(self): + return "".format(self.to_jwt()) diff --git a/venv/Lib/site-packages/twilio/jwt/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/jwt/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..b45af854 Binary files /dev/null and b/venv/Lib/site-packages/twilio/jwt/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/jwt/access_token/__init__.py b/venv/Lib/site-packages/twilio/jwt/access_token/__init__.py new file mode 100644 index 00000000..764b2a02 --- /dev/null +++ b/venv/Lib/site-packages/twilio/jwt/access_token/__init__.py @@ -0,0 +1,81 @@ +import time + +from twilio.jwt import Jwt + + +class AccessTokenGrant(object): + """A Grant giving access to a Twilio Resource""" + + @property + def key(self): + """:rtype str Grant's twilio specific key""" + raise NotImplementedError("Grant must have a key property.") + + def to_payload(self): + """:return: dict something""" + raise NotImplementedError("Grant must implement to_payload.") + + def __str__(self): + return "<{} {}>".format(self.__class__.__name__, self.to_payload()) + + +class AccessToken(Jwt): + """Access Token containing one or more AccessTokenGrants used to access Twilio Resources""" + + ALGORITHM = "HS256" + + def __init__( + self, + account_sid, + signing_key_sid, + secret, + grants=None, + identity=None, + nbf=Jwt.GENERATE, + ttl=3600, + valid_until=None, + region=None, + ): + grants = grants or [] + if any(not isinstance(g, AccessTokenGrant) for g in grants): + raise ValueError("Grants must be instances of AccessTokenGrant.") + + self.account_sid = account_sid + self.signing_key_sid = signing_key_sid + self.identity = identity + self.region = region + self.grants = grants + super(AccessToken, self).__init__( + secret_key=secret, + algorithm=self.ALGORITHM, + issuer=signing_key_sid, + subject=self.account_sid, + nbf=nbf, + ttl=ttl, + valid_until=valid_until, + ) + + def add_grant(self, grant): + """Add a grant to this AccessToken""" + if not isinstance(grant, AccessTokenGrant): + raise ValueError("Grant must be an instance of AccessTokenGrant.") + self.grants.append(grant) + + def _generate_headers(self): + headers = {"cty": "twilio-fpa;v=1"} + if self.region and isinstance(self.region, str): + headers["twr"] = self.region + return headers + + def _generate_payload(self): + now = int(time.time()) + payload = { + "jti": "{}-{}".format(self.signing_key_sid, now), + "grants": {grant.key: grant.to_payload() for grant in self.grants}, + } + if self.identity: + payload["grants"]["identity"] = self.identity + return payload + + def __str__(self): + return "<{} {}>".format(self.__class__.__name__, self.to_jwt()) diff --git a/venv/Lib/site-packages/twilio/jwt/access_token/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/jwt/access_token/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..258b6d35 Binary files /dev/null and b/venv/Lib/site-packages/twilio/jwt/access_token/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/jwt/access_token/__pycache__/grants.cpython-312.pyc b/venv/Lib/site-packages/twilio/jwt/access_token/__pycache__/grants.cpython-312.pyc new file mode 100644 index 00000000..c2aa5411 Binary files /dev/null and b/venv/Lib/site-packages/twilio/jwt/access_token/__pycache__/grants.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/jwt/access_token/grants.py b/venv/Lib/site-packages/twilio/jwt/access_token/grants.py new file mode 100644 index 00000000..16d19aa3 --- /dev/null +++ b/venv/Lib/site-packages/twilio/jwt/access_token/grants.py @@ -0,0 +1,183 @@ +from twilio.jwt.access_token import AccessTokenGrant +import warnings +import functools + + +def deprecated(func): + """This is a decorator which can be used to mark functions + as deprecated. It will result in a warning being emitted + when the function is used.""" + + @functools.wraps(func) + def new_func(*args, **kwargs): + warnings.simplefilter("always", DeprecationWarning) + warnings.warn( + "Call to deprecated function {}.".format(func.__name__), + category=DeprecationWarning, + stacklevel=2, + ) + warnings.simplefilter("default", DeprecationWarning) + return func(*args, **kwargs) + + return new_func + + +class ChatGrant(AccessTokenGrant): + """Grant to access Twilio Chat""" + + def __init__( + self, + service_sid=None, + endpoint_id=None, + deployment_role_sid=None, + push_credential_sid=None, + ): + self.service_sid = service_sid + self.endpoint_id = endpoint_id + self.deployment_role_sid = deployment_role_sid + self.push_credential_sid = push_credential_sid + + @property + def key(self): + return "chat" + + def to_payload(self): + grant = {} + if self.service_sid: + grant["service_sid"] = self.service_sid + if self.endpoint_id: + grant["endpoint_id"] = self.endpoint_id + if self.deployment_role_sid: + grant["deployment_role_sid"] = self.deployment_role_sid + if self.push_credential_sid: + grant["push_credential_sid"] = self.push_credential_sid + + return grant + + +class SyncGrant(AccessTokenGrant): + """Grant to access Twilio Sync""" + + def __init__(self, service_sid=None, endpoint_id=None): + self.service_sid = service_sid + self.endpoint_id = endpoint_id + + @property + def key(self): + return "data_sync" + + def to_payload(self): + grant = {} + if self.service_sid: + grant["service_sid"] = self.service_sid + if self.endpoint_id: + grant["endpoint_id"] = self.endpoint_id + + return grant + + +class VoiceGrant(AccessTokenGrant): + """Grant to access Twilio Programmable Voice""" + + def __init__( + self, + incoming_allow=None, + outgoing_application_sid=None, + outgoing_application_params=None, + push_credential_sid=None, + endpoint_id=None, + ): + self.incoming_allow = incoming_allow + """ :type : bool """ + self.outgoing_application_sid = outgoing_application_sid + """ :type : str """ + self.outgoing_application_params = outgoing_application_params + """ :type : dict """ + self.push_credential_sid = push_credential_sid + """ :type : str """ + self.endpoint_id = endpoint_id + """ :type : str """ + + @property + def key(self): + return "voice" + + def to_payload(self): + grant = {} + if self.incoming_allow is True: + grant["incoming"] = {} + grant["incoming"]["allow"] = True + + if self.outgoing_application_sid: + grant["outgoing"] = {} + grant["outgoing"]["application_sid"] = self.outgoing_application_sid + + if self.outgoing_application_params: + grant["outgoing"]["params"] = self.outgoing_application_params + + if self.push_credential_sid: + grant["push_credential_sid"] = self.push_credential_sid + + if self.endpoint_id: + grant["endpoint_id"] = self.endpoint_id + + return grant + + +class VideoGrant(AccessTokenGrant): + """Grant to access Twilio Video""" + + def __init__(self, room=None): + self.room = room + + @property + def key(self): + return "video" + + def to_payload(self): + grant = {} + if self.room: + grant["room"] = self.room + + return grant + + +class TaskRouterGrant(AccessTokenGrant): + """Grant to access Twilio TaskRouter""" + + def __init__(self, workspace_sid=None, worker_sid=None, role=None): + self.workspace_sid = workspace_sid + self.worker_sid = worker_sid + self.role = role + + @property + def key(self): + return "task_router" + + def to_payload(self): + grant = {} + if self.workspace_sid: + grant["workspace_sid"] = self.workspace_sid + if self.worker_sid: + grant["worker_sid"] = self.worker_sid + if self.role: + grant["role"] = self.role + + return grant + + +class PlaybackGrant(AccessTokenGrant): + """Grant to access Twilio Live stream""" + + def __init__(self, grant=None): + """Initialize a PlaybackGrant with a grant retrieved from the Twilio API.""" + self.grant = grant + + @property + def key(self): + """Return the grant's key.""" + return "player" + + def to_payload(self): + """Return the grant.""" + return self.grant diff --git a/venv/Lib/site-packages/twilio/jwt/client/__init__.py b/venv/Lib/site-packages/twilio/jwt/client/__init__.py new file mode 100644 index 00000000..d5c38c47 --- /dev/null +++ b/venv/Lib/site-packages/twilio/jwt/client/__init__.py @@ -0,0 +1,117 @@ +from twilio.jwt import Jwt + +from urllib.parse import urlencode + + +class ClientCapabilityToken(Jwt): + """A token to control permissions with Twilio Client""" + + ALGORITHM = "HS256" + + def __init__( + self, + account_sid, + auth_token, + nbf=Jwt.GENERATE, + ttl=3600, + valid_until=None, + **kwargs + ): + """ + :param str account_sid: The account sid to which this token is granted access. + :param str auth_token: The secret key used to sign the token. Note, this auth token is not + visible to the user of the token. + :param int nbf: Time in secs from epic before which this token is considered invalid. + :param int ttl: the amount of time in seconds from generation that this token is valid for. + :param kwargs: + + + :returns: A new CapabilityToken with zero permissions + """ + super(ClientCapabilityToken, self).__init__( + algorithm=self.ALGORITHM, + secret_key=auth_token, + issuer=account_sid, + nbf=nbf, + ttl=ttl, + valid_until=None, + ) + + self.account_sid = account_sid + self.auth_token = auth_token + self.client_name = None + self.capabilities = {} + + if "allow_client_outgoing" in kwargs: + self.allow_client_outgoing(**kwargs["allow_client_outgoing"]) + if "allow_client_incoming" in kwargs: + self.allow_client_incoming(**kwargs["allow_client_incoming"]) + if "allow_event_stream" in kwargs: + self.allow_event_stream(**kwargs["allow_event_stream"]) + + def allow_client_outgoing(self, application_sid, **kwargs): + """ + Allow the user of this token to make outgoing connections. Keyword arguments are passed + to the application. + + :param str application_sid: Application to contact + """ + scope = ScopeURI("client", "outgoing", {"appSid": application_sid}) + if kwargs: + scope.add_param("appParams", urlencode(kwargs, doseq=True)) + + self.capabilities["outgoing"] = scope + + def allow_client_incoming(self, client_name): + """ + Allow the user of this token to accept incoming connections. + + :param str client_name: Client name to accept calls from + """ + self.client_name = client_name + self.capabilities["incoming"] = ScopeURI( + "client", "incoming", {"clientName": client_name} + ) + + def allow_event_stream(self, **kwargs): + """ + Allow the user of this token to access their event stream. + """ + scope = ScopeURI("stream", "subscribe", {"path": "/2010-04-01/Events"}) + if kwargs: + scope.add_param("params", urlencode(kwargs, doseq=True)) + + self.capabilities["events"] = scope + + def _generate_payload(self): + if "outgoing" in self.capabilities and self.client_name is not None: + self.capabilities["outgoing"].add_param("clientName", self.client_name) + + scope_uris = [ + scope_uri.to_payload() for scope_uri in self.capabilities.values() + ] + return {"scope": " ".join(scope_uris)} + + +class ScopeURI(object): + """A single capability granted to Twilio Client and scoped to a service""" + + def __init__(self, service, privilege, params=None): + self.service = service + self.privilege = privilege + self.params = params or {} + + def add_param(self, key, value): + self.params[key] = value + + def to_payload(self): + if self.params: + sorted_params = sorted([(k, v) for k, v in self.params.items()]) + encoded_params = urlencode(sorted_params) + param_string = "?{}".format(encoded_params) + else: + param_string = "" + return "scope:{}:{}{}".format(self.service, self.privilege, param_string) + + def __str__(self): + return "".format(self.to_payload()) diff --git a/venv/Lib/site-packages/twilio/jwt/client/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/jwt/client/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..5efe8cda Binary files /dev/null and b/venv/Lib/site-packages/twilio/jwt/client/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/jwt/taskrouter/__init__.py b/venv/Lib/site-packages/twilio/jwt/taskrouter/__init__.py new file mode 100644 index 00000000..5a01560d --- /dev/null +++ b/venv/Lib/site-packages/twilio/jwt/taskrouter/__init__.py @@ -0,0 +1,142 @@ +from twilio.jwt import Jwt + + +class TaskRouterCapabilityToken(Jwt): + VERSION = "v1" + DOMAIN = "https://taskrouter.twilio.com" + EVENTS_BASE_URL = "https://event-bridge.twilio.com/v1/wschannels" + ALGORITHM = "HS256" + + def __init__(self, account_sid, auth_token, workspace_sid, channel_id, **kwargs): + """ + :param str account_sid: Twilio account sid + :param str auth_token: Twilio auth token used to sign the JWT + :param str workspace_sid: TaskRouter workspace sid + :param str channel_id: TaskRouter channel sid + :param kwargs: + :param bool allow_web_sockets: shortcut to calling allow_web_sockets, defaults to True + :param bool allow_fetch_self: shortcut to calling allow_fetch_self, defaults to True + :param bool allow_update_self: shortcut to calling allow_update_self, defaults to False + :param bool allow_delete_self: shortcut to calling allow_delete_self, defaults to False + :param bool allow_fetch_subresources: shortcut to calling allow_fetch_subresources, + defaults to False + :param bool allow_update_subresources: shortcut to calling allow_update_subresources, + defaults to False + :param bool allow_delete_subresources: shortcut to calling allow_delete_subresources, + defaults to False + :returns a new TaskRouterCapabilityToken with capabilities set depending on kwargs. + """ + super(TaskRouterCapabilityToken, self).__init__( + secret_key=auth_token, + issuer=account_sid, + algorithm=self.ALGORITHM, + nbf=kwargs.get("nbf", Jwt.GENERATE), + ttl=kwargs.get("ttl", 3600), + valid_until=kwargs.get("valid_until", None), + ) + + self._validate_inputs(account_sid, workspace_sid, channel_id) + + self.account_sid = account_sid + self.auth_token = auth_token + self.workspace_sid = workspace_sid + self.channel_id = channel_id + self.policies = [] + + if kwargs.get("allow_web_sockets", True): + self.allow_web_sockets() + if kwargs.get("allow_fetch_self", True): + self.allow_fetch_self() + if kwargs.get("allow_update_self", False): + self.allow_update_self() + if kwargs.get("allow_delete_self", False): + self.allow_delete_self() + if kwargs.get("allow_fetch_subresources", False): + self.allow_fetch_subresources() + if kwargs.get("allow_delete_subresources", False): + self.allow_delete_subresources() + if kwargs.get("allow_update_subresources", False): + self.allow_update_subresources() + + @property + def workspace_url(self): + return "{}/{}/Workspaces/{}".format( + self.DOMAIN, self.VERSION, self.workspace_sid + ) + + @property + def resource_url(self): + raise NotImplementedError("Subclass must set its specific resource_url.") + + @property + def channel_prefix(self): + raise NotImplementedError( + "Subclass must set its specific channel_id sid prefix." + ) + + def allow_fetch_self(self): + self._make_policy(self.resource_url, "GET", True) + + def allow_update_self(self): + self._make_policy(self.resource_url, "POST", True) + + def allow_delete_self(self): + self._make_policy(self.resource_url, "DELETE", True) + + def allow_fetch_subresources(self): + self._make_policy(self.resource_url + "/**", "GET", True) + + def allow_update_subresources(self): + self._make_policy(self.resource_url + "/**", "POST", True) + + def allow_delete_subresources(self): + self._make_policy(self.resource_url + "/**", "DELETE", True) + + def allow_web_sockets(self, channel_id=None): + channel_id = channel_id or self.channel_id + web_socket_url = "{}/{}/{}".format( + self.EVENTS_BASE_URL, self.account_sid, channel_id + ) + self._make_policy(web_socket_url, "GET", True) + self._make_policy(web_socket_url, "POST", True) + + def _generate_payload(self): + payload = { + "account_sid": self.account_sid, + "workspace_sid": self.workspace_sid, + "channel": self.channel_id, + "version": self.VERSION, + "friendly_name": self.channel_id, + "policies": self.policies, + } + + if self.channel_id.startswith("WK"): + payload["worker_sid"] = self.channel_id + elif self.channel_id.startswith("WQ"): + payload["taskqueue_sid"] = self.channel_id + + return payload + + def _make_policy(self, url, method, allowed, query_filter=None, post_filter=None): + self.policies.append( + { + "url": url, + "method": method.upper(), + "allow": allowed, + "query_filter": query_filter or {}, + "post_filter": post_filter or {}, + } + ) + + def _validate_inputs(self, account_sid, workspace_sid, channel_id): + if not account_sid or not account_sid.startswith("AC"): + raise ValueError("Invalid account sid provided {}".format(account_sid)) + + if not workspace_sid or not workspace_sid.startswith("WS"): + raise ValueError("Invalid workspace sid provided {}".format(workspace_sid)) + + if not channel_id or not channel_id.startswith(self.channel_prefix): + raise ValueError("Invalid channel id provided {}".format(channel_id)) + + def __str__(self): + return "".format(self.to_jwt()) diff --git a/venv/Lib/site-packages/twilio/jwt/taskrouter/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/jwt/taskrouter/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..5a37d506 Binary files /dev/null and b/venv/Lib/site-packages/twilio/jwt/taskrouter/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/jwt/taskrouter/__pycache__/capabilities.cpython-312.pyc b/venv/Lib/site-packages/twilio/jwt/taskrouter/__pycache__/capabilities.cpython-312.pyc new file mode 100644 index 00000000..c0e6ec99 Binary files /dev/null and b/venv/Lib/site-packages/twilio/jwt/taskrouter/__pycache__/capabilities.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/jwt/taskrouter/capabilities.py b/venv/Lib/site-packages/twilio/jwt/taskrouter/capabilities.py new file mode 100644 index 00000000..468a0270 --- /dev/null +++ b/venv/Lib/site-packages/twilio/jwt/taskrouter/capabilities.py @@ -0,0 +1,116 @@ +from twilio.jwt.taskrouter import TaskRouterCapabilityToken + + +class WorkerCapabilityToken(TaskRouterCapabilityToken): + def __init__( + self, account_sid, auth_token, workspace_sid, worker_sid, ttl=3600, **kwargs + ): + """ + :param kwargs: + All kwarg parameters supported by TaskRouterCapabilityToken + :param bool allow_fetch_activities: shortcut to calling allow_fetch_activities, + defaults to True + :param bool allow_fetch_reservations: shortcut to calling allow_fetch_reservations, + defaults to True + :param bool allow_fetch_worker_reservations: shortcut to calling allow_fetch_worker_reservations, + defaults to True + :param bool allow_update_activities: shortcut to calling allow_update_activities, + defaults to False + :param bool allow_update_reservations: shortcut to calling allow_update_reservations, + defaults to False + """ + super(WorkerCapabilityToken, self).__init__( + account_sid=account_sid, + auth_token=auth_token, + workspace_sid=workspace_sid, + channel_id=worker_sid, + ttl=ttl, + **kwargs + ) + + if kwargs.get("allow_fetch_activities", True): + self.allow_fetch_activities() + if kwargs.get("allow_fetch_reservations", True): + self.allow_fetch_reservations() + if kwargs.get("allow_fetch_worker_reservations", True): + self.allow_fetch_worker_reservations() + if kwargs.get("allow_update_activities", False): + self.allow_update_activities() + if kwargs.get("allow_update_reservations", False): + self.allow_update_reservations() + + @property + def resource_url(self): + return "{}/Workers/{}".format(self.workspace_url, self.channel_id) + + @property + def channel_prefix(self): + return "WK" + + def allow_fetch_activities(self): + self._make_policy(self.workspace_url + "/Activities", "GET", True) + + def allow_fetch_reservations(self): + self._make_policy(self.workspace_url + "/Tasks/**", "GET", True) + + def allow_fetch_worker_reservations(self): + self._make_policy(self.resource_url + "/Reservations/**", "GET", True) + + def allow_update_activities(self): + post_filter = {"ActivitySid": {"required": True}} + self._make_policy(self.resource_url, "POST", True, post_filter=post_filter) + + def allow_update_reservations(self): + self._make_policy(self.workspace_url + "/Tasks/**", "POST", True) + self._make_policy(self.resource_url + "/Reservations/**", "POST", True) + + def __str__(self): + return "".format(self.to_jwt()) + + +class TaskQueueCapabilityToken(TaskRouterCapabilityToken): + def __init__( + self, account_sid, auth_token, workspace_sid, task_queue_sid, ttl=3600, **kwargs + ): + super(TaskQueueCapabilityToken, self).__init__( + account_sid=account_sid, + auth_token=auth_token, + workspace_sid=workspace_sid, + channel_id=task_queue_sid, + ttl=ttl, + **kwargs + ) + + @property + def resource_url(self): + return "{}/TaskQueues/{}".format(self.workspace_url, self.channel_id) + + @property + def channel_prefix(self): + return "WQ" + + def __str__(self): + return "".format(self.to_jwt()) + + +class WorkspaceCapabilityToken(TaskRouterCapabilityToken): + def __init__(self, account_sid, auth_token, workspace_sid, ttl=3600, **kwargs): + super(WorkspaceCapabilityToken, self).__init__( + account_sid=account_sid, + auth_token=auth_token, + workspace_sid=workspace_sid, + channel_id=workspace_sid, + ttl=ttl, + **kwargs + ) + + @property + def resource_url(self): + return self.workspace_url + + @property + def channel_prefix(self): + return "WS" + + def __str__(self): + return "".format(self.to_jwt()) diff --git a/venv/Lib/site-packages/twilio/jwt/validation/__init__.py b/venv/Lib/site-packages/twilio/jwt/validation/__init__.py new file mode 100644 index 00000000..837d6196 --- /dev/null +++ b/venv/Lib/site-packages/twilio/jwt/validation/__init__.py @@ -0,0 +1,92 @@ +from hashlib import sha256 + +from twilio.jwt import Jwt + + +class ClientValidationJwt(Jwt): + """A JWT included on requests so that Twilio can verify request authenticity""" + + __CTY = "twilio-pkrv;v=1" + ALGORITHM = "RS256" + + def __init__( + self, account_sid, api_key_sid, credential_sid, private_key, validation_payload + ): + """ + Create a new ClientValidationJwt + :param str account_sid: A Twilio Account Sid starting with 'AC' + :param str api_key_sid: A Twilio API Key Sid starting with 'SK' + :param str credential_sid: A Credential Sid starting with 'CR', + public key Twilio will use to verify the JWT. + :param str private_key: The private key used to sign the JWT. + :param ValidationPayload validation_payload: information from the request to sign + """ + super(ClientValidationJwt, self).__init__( + secret_key=private_key, + issuer=api_key_sid, + subject=account_sid, + algorithm=self.ALGORITHM, + ttl=300, # 5 minute ttl + ) + self.credential_sid = credential_sid + self.validation_payload = validation_payload + + def _generate_headers(self): + return {"cty": ClientValidationJwt.__CTY, "kid": self.credential_sid} + + def _generate_payload(self): + # Lowercase header keys, combine and sort headers with list values + all_headers = { + k.lower(): self._sort_and_join(v, ",") + for k, v in self.validation_payload.all_headers.items() + } + # Names of headers we are signing in the jwt + signed_headers = sorted(self.validation_payload.signed_headers) + + # Stringify headers, only include headers in signed_headers + headers_str = [ + "{}:{}".format(h, all_headers[h]) + for h in signed_headers + if h in all_headers + ] + headers_str = "\n".join(headers_str) + + # Sort query string parameters + query_string = self.validation_payload.query_string.split("&") + query_string = self._sort_and_join(query_string, "&") + + req_body_hash = self._hash(self.validation_payload.body) or "" + + signed_headers_str = ";".join(signed_headers) + + signed_payload = [ + self.validation_payload.method, + self.validation_payload.path, + query_string, + ] + + if headers_str: + signed_payload.append(headers_str) + signed_payload.append("") + signed_payload.append(signed_headers_str) + signed_payload.append(req_body_hash) + + signed_payload = "\n".join(signed_payload) + + return {"hrh": signed_headers_str, "rqh": self._hash(signed_payload)} + + @classmethod + def _sort_and_join(cls, values, joiner): + if isinstance(values, str): + return values + return joiner.join(sorted(values)) + + @classmethod + def _hash(cls, input_str): + if not input_str: + return input_str + + if not isinstance(input_str, bytes): + input_str = input_str.encode("utf-8") + + return sha256(input_str).hexdigest() diff --git a/venv/Lib/site-packages/twilio/jwt/validation/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/jwt/validation/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..f3986565 Binary files /dev/null and b/venv/Lib/site-packages/twilio/jwt/validation/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/request_validator.py b/venv/Lib/site-packages/twilio/request_validator.py new file mode 100644 index 00000000..f7a0db36 --- /dev/null +++ b/venv/Lib/site-packages/twilio/request_validator.py @@ -0,0 +1,137 @@ +import base64 +import hmac +from hashlib import sha1, sha256 + +from urllib.parse import urlparse, parse_qs + + +def compare(string1, string2): + """Compare two strings while protecting against timing attacks + + :param str string1: the first string + :param str string2: the second string + + :returns: True if the strings are equal, False if not + :rtype: :obj:`bool` + """ + if len(string1) != len(string2): + return False + result = True + for c1, c2 in zip(string1, string2): + result &= c1 == c2 + + return result + + +def remove_port(uri): + """Remove the port number from a URI + + :param uri: parsed URI that Twilio requested on your server + + :returns: full URI without a port number + :rtype: str + """ + if not uri.port: + return uri.geturl() + + new_netloc = uri.netloc.split(":")[0] + new_uri = uri._replace(netloc=new_netloc) + + return new_uri.geturl() + + +def add_port(uri): + """Add the port number to a URI + + :param uri: parsed URI that Twilio requested on your server + + :returns: full URI with a port number + :rtype: str + """ + if uri.port: + return uri.geturl() + + port = 443 if uri.scheme == "https" else 80 + new_netloc = uri.netloc + ":" + str(port) + new_uri = uri._replace(netloc=new_netloc) + + return new_uri.geturl() + + +class RequestValidator(object): + def __init__(self, token): + self.token = token.encode("utf-8") + + def compute_signature(self, uri, params): + """Compute the signature for a given request + + :param uri: full URI that Twilio requested on your server + :param params: post vars that Twilio sent with the request + + :returns: The computed signature + """ + s = uri + if params: + for param_name in sorted(set(params)): + values = self.get_values(params, param_name) + + for value in sorted(set(values)): + s += param_name + value + + # compute signature and compare signatures + mac = hmac.new(self.token, s.encode("utf-8"), sha1) + computed = base64.b64encode(mac.digest()) + computed = computed.decode("utf-8") + + return computed.strip() + + def get_values(self, param_dict, param_name): + try: + # Support MultiDict used by Flask. + return param_dict.getall(param_name) + except AttributeError: + try: + # Support QueryDict used by Django. + return param_dict.getlist(param_name) + except AttributeError: + # Fallback to a standard dict. + return [param_dict[param_name]] + + def compute_hash(self, body): + computed = sha256(body.encode("utf-8")).hexdigest() + + return computed.strip() + + def validate(self, uri, params, signature): + """Validate a request from Twilio + + :param uri: full URI that Twilio requested on your server + :param params: dictionary of POST variables or string of POST body for JSON requests + :param signature: expected signature in HTTP X-Twilio-Signature header + + :returns: True if the request passes validation, False if not + """ + if params is None: + params = {} + + parsed_uri = urlparse(uri) + uri_with_port = add_port(parsed_uri) + uri_without_port = remove_port(parsed_uri) + + valid_body_hash = True # May not receive body hash, so default succeed + + query = parse_qs(parsed_uri.query) + if "bodySHA256" in query and isinstance(params, str): + valid_body_hash = compare(self.compute_hash(params), query["bodySHA256"][0]) + params = {} + + # check signature of uri with and without port, + # since sig generation on back end is inconsistent + valid_signature = compare( + self.compute_signature(uri_without_port, params), signature + ) + valid_signature_with_port = compare( + self.compute_signature(uri_with_port, params), signature + ) + + return valid_body_hash and (valid_signature or valid_signature_with_port) diff --git a/venv/Lib/site-packages/twilio/rest/__init__.py b/venv/Lib/site-packages/twilio/rest/__init__.py new file mode 100644 index 00000000..dc774118 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/__init__.py @@ -0,0 +1,772 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import TYPE_CHECKING, Optional + +from twilio.base.client_base import ClientBase + +if TYPE_CHECKING: + from twilio.rest.accounts import Accounts + from twilio.rest.api import Api + from twilio.rest.assistants import Assistants + from twilio.rest.bulkexports import Bulkexports + from twilio.rest.chat import Chat + from twilio.rest.content import Content + from twilio.rest.conversations import Conversations + from twilio.rest.events import Events + from twilio.rest.flex_api import FlexApi + from twilio.rest.frontline_api import FrontlineApi + from twilio.rest.preview_iam import PreviewIam + from twilio.rest.iam import Iam + from twilio.rest.insights import Insights + from twilio.rest.intelligence import Intelligence + from twilio.rest.ip_messaging import IpMessaging + from twilio.rest.knowledge import Knowledge + from twilio.rest.lookups import Lookups + from twilio.rest.marketplace import Marketplace + from twilio.rest.messaging import Messaging + from twilio.rest.microvisor import Microvisor + from twilio.rest.monitor import Monitor + from twilio.rest.notify import Notify + from twilio.rest.numbers import Numbers + from twilio.rest.oauth import Oauth + from twilio.rest.preview import Preview + from twilio.rest.pricing import Pricing + from twilio.rest.proxy import Proxy + from twilio.rest.routes import Routes + from twilio.rest.serverless import Serverless + from twilio.rest.studio import Studio + from twilio.rest.supersim import Supersim + from twilio.rest.sync import Sync + from twilio.rest.taskrouter import Taskrouter + from twilio.rest.trunking import Trunking + from twilio.rest.trusthub import Trusthub + from twilio.rest.verify import Verify + from twilio.rest.video import Video + from twilio.rest.voice import Voice + from twilio.rest.wireless import Wireless + from twilio.rest.api.v2010.account.address import AddressList + from twilio.rest.api.v2010.account.application import ApplicationList + from twilio.rest.api.v2010.account.authorized_connect_app import ( + AuthorizedConnectAppList, + ) + from twilio.rest.api.v2010.account.available_phone_number_country import ( + AvailablePhoneNumberCountryList, + ) + from twilio.rest.api.v2010.account.balance import BalanceList + from twilio.rest.api.v2010.account.call import CallList + from twilio.rest.api.v2010.account.conference import ConferenceList + from twilio.rest.api.v2010.account.connect_app import ConnectAppList + from twilio.rest.api.v2010.account.incoming_phone_number import ( + IncomingPhoneNumberList, + ) + from twilio.rest.api.v2010.account.key import KeyList + from twilio.rest.api.v2010.account.new_key import NewKeyList + from twilio.rest.api.v2010.account.message import MessageList + from twilio.rest.api.v2010.account.signing_key import SigningKeyList + from twilio.rest.api.v2010.account.new_signing_key import NewSigningKeyList + from twilio.rest.api.v2010.account.notification import NotificationList + from twilio.rest.api.v2010.account.outgoing_caller_id import OutgoingCallerIdList + from twilio.rest.api.v2010.account.validation_request import ValidationRequestList + from twilio.rest.api.v2010.account.queue import QueueList + from twilio.rest.api.v2010.account.recording import RecordingList + from twilio.rest.api.v2010.account.short_code import ShortCodeList + from twilio.rest.api.v2010.account.sip import SipList + from twilio.rest.api.v2010.account.token import TokenList + from twilio.rest.api.v2010.account.transcription import TranscriptionList + from twilio.rest.api.v2010.account.usage import UsageList + + +class Client(ClientBase): + """A client for accessing the Twilio API.""" + + def __init__( + self, + username=None, + password=None, + account_sid=None, + region=None, + http_client=None, + environment=None, + edge=None, + user_agent_extensions=None, + credential_provider=None, + ): + """ + Initializes the Twilio Client + + :param str username: Username to authenticate with, either account_sid or api_key + :param str password: Password to authenticate with, auth_token (if using account_sid) or api_secret (if using api_key) + :param str account_sid: Account SID, required if using api_key to authenticate. + :param str region: Twilio Region to make requests to, defaults to 'us1' if an edge is provided + :param HttpClient http_client: HttpClient, defaults to TwilioHttpClient + :param dict environment: Environment to look for auth details, defaults to os.environ + :param str edge: Twilio Edge to make requests to, defaults to None + :param list[str] user_agent_extensions: Additions to the user agent string + + :returns: Twilio Client + :rtype: twilio.rest.Client + """ + super().__init__( + username, + password, + account_sid, + region, + http_client, + environment, + edge, + user_agent_extensions, + credential_provider, + ) + + # Domains + self._accounts: Optional["Accounts"] = None + self._api: Optional["Api"] = None + self._assistants: Optional["Assistants"] = None + self._bulkexports: Optional["Bulkexports"] = None + self._chat: Optional["Chat"] = None + self._content: Optional["Content"] = None + self._conversations: Optional["Conversations"] = None + self._events: Optional["Events"] = None + self._flex_api: Optional["FlexApi"] = None + self._frontline_api: Optional["FrontlineApi"] = None + self._preview_iam: Optional["PreviewIam"] = None + self._iam: Optional["Iam"] = None + self._insights: Optional["Insights"] = None + self._intelligence: Optional["Intelligence"] = None + self._ip_messaging: Optional["IpMessaging"] = None + self._knowledge: Optional["Knowledge"] = None + self._lookups: Optional["Lookups"] = None + self._marketplace: Optional["Marketplace"] = None + self._messaging: Optional["Messaging"] = None + self._microvisor: Optional["Microvisor"] = None + self._monitor: Optional["Monitor"] = None + self._notify: Optional["Notify"] = None + self._numbers: Optional["Numbers"] = None + self._oauth: Optional["Oauth"] = None + self._preview: Optional["Preview"] = None + self._pricing: Optional["Pricing"] = None + self._proxy: Optional["Proxy"] = None + self._routes: Optional["Routes"] = None + self._serverless: Optional["Serverless"] = None + self._studio: Optional["Studio"] = None + self._supersim: Optional["Supersim"] = None + self._sync: Optional["Sync"] = None + self._taskrouter: Optional["Taskrouter"] = None + self._trunking: Optional["Trunking"] = None + self._trusthub: Optional["Trusthub"] = None + self._verify: Optional["Verify"] = None + self._video: Optional["Video"] = None + self._voice: Optional["Voice"] = None + self._wireless: Optional["Wireless"] = None + + @property + def accounts(self) -> "Accounts": + """ + Access the Accounts Twilio Domain + + :returns: Accounts Twilio Domain + """ + if self._accounts is None: + from twilio.rest.accounts import Accounts + + self._accounts = Accounts(self) + return self._accounts + + @property + def api(self) -> "Api": + """ + Access the Api Twilio Domain + + :returns: Api Twilio Domain + """ + if self._api is None: + from twilio.rest.api import Api + + self._api = Api(self) + return self._api + + @property + def assistants(self) -> "Assistants": + """ + Access the Assistants Twilio Domain + + :returns: Assistants Twilio Domain + """ + if self._assistants is None: + from twilio.rest.assistants import Assistants + + self._assistants = Assistants(self) + return self._assistants + + @property + def bulkexports(self) -> "Bulkexports": + """ + Access the Bulkexports Twilio Domain + + :returns: Bulkexports Twilio Domain + """ + if self._bulkexports is None: + from twilio.rest.bulkexports import Bulkexports + + self._bulkexports = Bulkexports(self) + return self._bulkexports + + @property + def chat(self) -> "Chat": + """ + Access the Chat Twilio Domain + + :returns: Chat Twilio Domain + """ + if self._chat is None: + from twilio.rest.chat import Chat + + self._chat = Chat(self) + return self._chat + + @property + def content(self) -> "Content": + """ + Access the Content Twilio Domain + + :returns: Content Twilio Domain + """ + if self._content is None: + from twilio.rest.content import Content + + self._content = Content(self) + return self._content + + @property + def conversations(self) -> "Conversations": + """ + Access the Conversations Twilio Domain + + :returns: Conversations Twilio Domain + """ + if self._conversations is None: + from twilio.rest.conversations import Conversations + + self._conversations = Conversations(self) + return self._conversations + + @property + def events(self) -> "Events": + """ + Access the Events Twilio Domain + + :returns: Events Twilio Domain + """ + if self._events is None: + from twilio.rest.events import Events + + self._events = Events(self) + return self._events + + @property + def flex_api(self) -> "FlexApi": + """ + Access the FlexApi Twilio Domain + + :returns: FlexApi Twilio Domain + """ + if self._flex_api is None: + from twilio.rest.flex_api import FlexApi + + self._flex_api = FlexApi(self) + return self._flex_api + + @property + def frontline_api(self) -> "FrontlineApi": + """ + Access the FrontlineApi Twilio Domain + + :returns: FrontlineApi Twilio Domain + """ + if self._frontline_api is None: + from twilio.rest.frontline_api import FrontlineApi + + self._frontline_api = FrontlineApi(self) + return self._frontline_api + + @property + def preview_iam(self) -> "PreviewIam": + """ + Access the PreviewIam Twilio Domain + + :returns: PreviewIam Twilio Domain + """ + if self._preview_iam is None: + from twilio.rest.preview_iam import PreviewIam + + self._preview_iam = PreviewIam(self) + return self._preview_iam + + @property + def iam(self) -> "Iam": + """ + Access the Iam Twilio Domain + + :returns: Iam Twilio Domain + """ + if self._iam is None: + from twilio.rest.iam import Iam + + self._iam = Iam(self) + return self._iam + + @property + def insights(self) -> "Insights": + """ + Access the Insights Twilio Domain + + :returns: Insights Twilio Domain + """ + if self._insights is None: + from twilio.rest.insights import Insights + + self._insights = Insights(self) + return self._insights + + @property + def intelligence(self) -> "Intelligence": + """ + Access the Intelligence Twilio Domain + + :returns: Intelligence Twilio Domain + """ + if self._intelligence is None: + from twilio.rest.intelligence import Intelligence + + self._intelligence = Intelligence(self) + return self._intelligence + + @property + def ip_messaging(self) -> "IpMessaging": + """ + Access the IpMessaging Twilio Domain + + :returns: IpMessaging Twilio Domain + """ + if self._ip_messaging is None: + from twilio.rest.ip_messaging import IpMessaging + + self._ip_messaging = IpMessaging(self) + return self._ip_messaging + + @property + def knowledge(self) -> "Knowledge": + """ + Access the Knowledge Twilio Domain + + :returns: Knowledge Twilio Domain + """ + if self._knowledge is None: + from twilio.rest.knowledge import Knowledge + + self._knowledge = Knowledge(self) + return self._knowledge + + @property + def lookups(self) -> "Lookups": + """ + Access the Lookups Twilio Domain + + :returns: Lookups Twilio Domain + """ + if self._lookups is None: + from twilio.rest.lookups import Lookups + + self._lookups = Lookups(self) + return self._lookups + + @property + def marketplace(self) -> "Marketplace": + """ + Access the Marketplace Twilio Domain + + :returns: Marketplace Twilio Domain + """ + if self._marketplace is None: + from twilio.rest.marketplace import Marketplace + + self._marketplace = Marketplace(self) + return self._marketplace + + @property + def messaging(self) -> "Messaging": + """ + Access the Messaging Twilio Domain + + :returns: Messaging Twilio Domain + """ + if self._messaging is None: + from twilio.rest.messaging import Messaging + + self._messaging = Messaging(self) + return self._messaging + + @property + def microvisor(self) -> "Microvisor": + """ + Access the Microvisor Twilio Domain + + :returns: Microvisor Twilio Domain + """ + if self._microvisor is None: + from twilio.rest.microvisor import Microvisor + + self._microvisor = Microvisor(self) + return self._microvisor + + @property + def monitor(self) -> "Monitor": + """ + Access the Monitor Twilio Domain + + :returns: Monitor Twilio Domain + """ + if self._monitor is None: + from twilio.rest.monitor import Monitor + + self._monitor = Monitor(self) + return self._monitor + + @property + def notify(self) -> "Notify": + """ + Access the Notify Twilio Domain + + :returns: Notify Twilio Domain + """ + if self._notify is None: + from twilio.rest.notify import Notify + + self._notify = Notify(self) + return self._notify + + @property + def numbers(self) -> "Numbers": + """ + Access the Numbers Twilio Domain + + :returns: Numbers Twilio Domain + """ + if self._numbers is None: + from twilio.rest.numbers import Numbers + + self._numbers = Numbers(self) + return self._numbers + + @property + def oauth(self) -> "Oauth": + """ + Access the Oauth Twilio Domain + + :returns: Oauth Twilio Domain + """ + if self._oauth is None: + from twilio.rest.oauth import Oauth + + self._oauth = Oauth(self) + return self._oauth + + @property + def preview(self) -> "Preview": + """ + Access the Preview Twilio Domain + + :returns: Preview Twilio Domain + """ + if self._preview is None: + from twilio.rest.preview import Preview + + self._preview = Preview(self) + return self._preview + + @property + def pricing(self) -> "Pricing": + """ + Access the Pricing Twilio Domain + + :returns: Pricing Twilio Domain + """ + if self._pricing is None: + from twilio.rest.pricing import Pricing + + self._pricing = Pricing(self) + return self._pricing + + @property + def proxy(self) -> "Proxy": + """ + Access the Proxy Twilio Domain + + :returns: Proxy Twilio Domain + """ + if self._proxy is None: + from twilio.rest.proxy import Proxy + + self._proxy = Proxy(self) + return self._proxy + + @property + def routes(self) -> "Routes": + """ + Access the Routes Twilio Domain + + :returns: Routes Twilio Domain + """ + if self._routes is None: + from twilio.rest.routes import Routes + + self._routes = Routes(self) + return self._routes + + @property + def serverless(self) -> "Serverless": + """ + Access the Serverless Twilio Domain + + :returns: Serverless Twilio Domain + """ + if self._serverless is None: + from twilio.rest.serverless import Serverless + + self._serverless = Serverless(self) + return self._serverless + + @property + def studio(self) -> "Studio": + """ + Access the Studio Twilio Domain + + :returns: Studio Twilio Domain + """ + if self._studio is None: + from twilio.rest.studio import Studio + + self._studio = Studio(self) + return self._studio + + @property + def supersim(self) -> "Supersim": + """ + Access the Supersim Twilio Domain + + :returns: Supersim Twilio Domain + """ + if self._supersim is None: + from twilio.rest.supersim import Supersim + + self._supersim = Supersim(self) + return self._supersim + + @property + def sync(self) -> "Sync": + """ + Access the Sync Twilio Domain + + :returns: Sync Twilio Domain + """ + if self._sync is None: + from twilio.rest.sync import Sync + + self._sync = Sync(self) + return self._sync + + @property + def taskrouter(self) -> "Taskrouter": + """ + Access the Taskrouter Twilio Domain + + :returns: Taskrouter Twilio Domain + """ + if self._taskrouter is None: + from twilio.rest.taskrouter import Taskrouter + + self._taskrouter = Taskrouter(self) + return self._taskrouter + + @property + def trunking(self) -> "Trunking": + """ + Access the Trunking Twilio Domain + + :returns: Trunking Twilio Domain + """ + if self._trunking is None: + from twilio.rest.trunking import Trunking + + self._trunking = Trunking(self) + return self._trunking + + @property + def trusthub(self) -> "Trusthub": + """ + Access the Trusthub Twilio Domain + + :returns: Trusthub Twilio Domain + """ + if self._trusthub is None: + from twilio.rest.trusthub import Trusthub + + self._trusthub = Trusthub(self) + return self._trusthub + + @property + def verify(self) -> "Verify": + """ + Access the Verify Twilio Domain + + :returns: Verify Twilio Domain + """ + if self._verify is None: + from twilio.rest.verify import Verify + + self._verify = Verify(self) + return self._verify + + @property + def video(self) -> "Video": + """ + Access the Video Twilio Domain + + :returns: Video Twilio Domain + """ + if self._video is None: + from twilio.rest.video import Video + + self._video = Video(self) + return self._video + + @property + def voice(self) -> "Voice": + """ + Access the Voice Twilio Domain + + :returns: Voice Twilio Domain + """ + if self._voice is None: + from twilio.rest.voice import Voice + + self._voice = Voice(self) + return self._voice + + @property + def wireless(self) -> "Wireless": + """ + Access the Wireless Twilio Domain + + :returns: Wireless Twilio Domain + """ + if self._wireless is None: + from twilio.rest.wireless import Wireless + + self._wireless = Wireless(self) + return self._wireless + + @property + def addresses(self) -> "AddressList": + return self.api.account.addresses + + @property + def applications(self) -> "ApplicationList": + return self.api.account.applications + + @property + def authorized_connect_apps(self) -> "AuthorizedConnectAppList": + return self.api.account.authorized_connect_apps + + @property + def available_phone_numbers(self) -> "AvailablePhoneNumberCountryList": + return self.api.account.available_phone_numbers + + @property + def balance(self) -> "BalanceList": + return self.api.account.balance + + @property + def calls(self) -> "CallList": + return self.api.account.calls + + @property + def conferences(self) -> "ConferenceList": + return self.api.account.conferences + + @property + def connect_apps(self) -> "ConnectAppList": + return self.api.account.connect_apps + + @property + def incoming_phone_numbers(self) -> "IncomingPhoneNumberList": + return self.api.account.incoming_phone_numbers + + @property + def keys(self) -> "KeyList": + return self.api.account.keys + + @property + def new_keys(self) -> "NewKeyList": + return self.api.account.new_keys + + @property + def messages(self) -> "MessageList": + return self.api.account.messages + + @property + def signing_keys(self) -> "SigningKeyList": + return self.api.account.signing_keys + + @property + def new_signing_keys(self) -> "NewSigningKeyList": + return self.api.account.new_signing_keys + + @property + def notifications(self) -> "NotificationList": + return self.api.account.notifications + + @property + def outgoing_caller_ids(self) -> "OutgoingCallerIdList": + return self.api.account.outgoing_caller_ids + + @property + def validation_requests(self) -> "ValidationRequestList": + return self.api.account.validation_requests + + @property + def queues(self) -> "QueueList": + return self.api.account.queues + + @property + def recordings(self) -> "RecordingList": + return self.api.account.recordings + + @property + def short_codes(self) -> "ShortCodeList": + return self.api.account.short_codes + + @property + def sip(self) -> "SipList": + return self.api.account.sip + + @property + def tokens(self) -> "TokenList": + return self.api.account.tokens + + @property + def transcriptions(self) -> "TranscriptionList": + return self.api.account.transcriptions + + @property + def usage(self) -> "UsageList": + return self.api.account.usage diff --git a/venv/Lib/site-packages/twilio/rest/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..5d1fc5c3 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/accounts/AccountsBase.py b/venv/Lib/site-packages/twilio/rest/accounts/AccountsBase.py new file mode 100644 index 00000000..e9ac0d58 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/accounts/AccountsBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.accounts.v1 import V1 + + +class AccountsBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Accounts Domain + + :returns: Domain for Accounts + """ + super().__init__(twilio, "https://accounts.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Accounts + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/accounts/__init__.py b/venv/Lib/site-packages/twilio/rest/accounts/__init__.py new file mode 100644 index 00000000..e2275aea --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/accounts/__init__.py @@ -0,0 +1,35 @@ +from warnings import warn + +from twilio.rest.accounts.AccountsBase import AccountsBase +from twilio.rest.accounts.v1.auth_token_promotion import AuthTokenPromotionList +from twilio.rest.accounts.v1.credential import CredentialList +from twilio.rest.accounts.v1.secondary_auth_token import SecondaryAuthTokenList + + +class Accounts(AccountsBase): + @property + def auth_token_promotion(self) -> AuthTokenPromotionList: + warn( + "auth_token_promotion is deprecated. Use v1.auth_token_promotion instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.auth_token_promotion + + @property + def credentials(self) -> CredentialList: + warn( + "credentials is deprecated. Use v1.credentials instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.credentials + + @property + def secondary_auth_token(self) -> SecondaryAuthTokenList: + warn( + "secondary_auth_token is deprecated. Use v1.secondary_auth_token instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.secondary_auth_token diff --git a/venv/Lib/site-packages/twilio/rest/accounts/__pycache__/AccountsBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/accounts/__pycache__/AccountsBase.cpython-312.pyc new file mode 100644 index 00000000..7a2a3229 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/accounts/__pycache__/AccountsBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/accounts/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/accounts/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..e0340a0c Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/accounts/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/accounts/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/accounts/v1/__init__.py new file mode 100644 index 00000000..6f5012d0 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/accounts/v1/__init__.py @@ -0,0 +1,83 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Accounts + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.accounts.v1.auth_token_promotion import AuthTokenPromotionList +from twilio.rest.accounts.v1.bulk_consents import BulkConsentsList +from twilio.rest.accounts.v1.bulk_contacts import BulkContactsList +from twilio.rest.accounts.v1.credential import CredentialList +from twilio.rest.accounts.v1.safelist import SafelistList +from twilio.rest.accounts.v1.secondary_auth_token import SecondaryAuthTokenList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Accounts + + :param domain: The Twilio.accounts domain + """ + super().__init__(domain, "v1") + self._auth_token_promotion: Optional[AuthTokenPromotionList] = None + self._bulk_consents: Optional[BulkConsentsList] = None + self._bulk_contacts: Optional[BulkContactsList] = None + self._credentials: Optional[CredentialList] = None + self._safelist: Optional[SafelistList] = None + self._secondary_auth_token: Optional[SecondaryAuthTokenList] = None + + @property + def auth_token_promotion(self) -> AuthTokenPromotionList: + if self._auth_token_promotion is None: + self._auth_token_promotion = AuthTokenPromotionList(self) + return self._auth_token_promotion + + @property + def bulk_consents(self) -> BulkConsentsList: + if self._bulk_consents is None: + self._bulk_consents = BulkConsentsList(self) + return self._bulk_consents + + @property + def bulk_contacts(self) -> BulkContactsList: + if self._bulk_contacts is None: + self._bulk_contacts = BulkContactsList(self) + return self._bulk_contacts + + @property + def credentials(self) -> CredentialList: + if self._credentials is None: + self._credentials = CredentialList(self) + return self._credentials + + @property + def safelist(self) -> SafelistList: + if self._safelist is None: + self._safelist = SafelistList(self) + return self._safelist + + @property + def secondary_auth_token(self) -> SecondaryAuthTokenList: + if self._secondary_auth_token is None: + self._secondary_auth_token = SecondaryAuthTokenList(self) + return self._secondary_auth_token + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/accounts/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/accounts/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..54d27eee Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/accounts/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/accounts/v1/__pycache__/auth_token_promotion.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/accounts/v1/__pycache__/auth_token_promotion.cpython-312.pyc new file mode 100644 index 00000000..b69eacf2 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/accounts/v1/__pycache__/auth_token_promotion.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/accounts/v1/__pycache__/bulk_consents.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/accounts/v1/__pycache__/bulk_consents.cpython-312.pyc new file mode 100644 index 00000000..82885b82 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/accounts/v1/__pycache__/bulk_consents.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/accounts/v1/__pycache__/bulk_contacts.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/accounts/v1/__pycache__/bulk_contacts.cpython-312.pyc new file mode 100644 index 00000000..17a7d28c Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/accounts/v1/__pycache__/bulk_contacts.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/accounts/v1/__pycache__/safelist.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/accounts/v1/__pycache__/safelist.cpython-312.pyc new file mode 100644 index 00000000..a68abf84 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/accounts/v1/__pycache__/safelist.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/accounts/v1/__pycache__/secondary_auth_token.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/accounts/v1/__pycache__/secondary_auth_token.cpython-312.pyc new file mode 100644 index 00000000..c807318a Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/accounts/v1/__pycache__/secondary_auth_token.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/accounts/v1/auth_token_promotion.py b/venv/Lib/site-packages/twilio/rest/accounts/v1/auth_token_promotion.py new file mode 100644 index 00000000..8580538a --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/accounts/v1/auth_token_promotion.py @@ -0,0 +1,181 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Accounts + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class AuthTokenPromotionInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the secondary Auth Token was created for. + :ivar auth_token: The promoted Auth Token that must be used to authenticate future API requests. + :ivar date_created: The date and time in UTC when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The URI for this resource, relative to `https://accounts.twilio.com` + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.auth_token: Optional[str] = payload.get("auth_token") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._context: Optional[AuthTokenPromotionContext] = None + + @property + def _proxy(self) -> "AuthTokenPromotionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AuthTokenPromotionContext for this AuthTokenPromotionInstance + """ + if self._context is None: + self._context = AuthTokenPromotionContext( + self._version, + ) + return self._context + + def update(self) -> "AuthTokenPromotionInstance": + """ + Update the AuthTokenPromotionInstance + + + :returns: The updated AuthTokenPromotionInstance + """ + return self._proxy.update() + + async def update_async(self) -> "AuthTokenPromotionInstance": + """ + Asynchronous coroutine to update the AuthTokenPromotionInstance + + + :returns: The updated AuthTokenPromotionInstance + """ + return await self._proxy.update_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class AuthTokenPromotionContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the AuthTokenPromotionContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/AuthTokens/Promote" + + def update(self) -> AuthTokenPromotionInstance: + """ + Update the AuthTokenPromotionInstance + + + :returns: The updated AuthTokenPromotionInstance + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthTokenPromotionInstance(self._version, payload) + + async def update_async(self) -> AuthTokenPromotionInstance: + """ + Asynchronous coroutine to update the AuthTokenPromotionInstance + + + :returns: The updated AuthTokenPromotionInstance + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthTokenPromotionInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class AuthTokenPromotionList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AuthTokenPromotionList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> AuthTokenPromotionContext: + """ + Constructs a AuthTokenPromotionContext + + """ + return AuthTokenPromotionContext(self._version) + + def __call__(self) -> AuthTokenPromotionContext: + """ + Constructs a AuthTokenPromotionContext + + """ + return AuthTokenPromotionContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/accounts/v1/bulk_consents.py b/venv/Lib/site-packages/twilio/rest/accounts/v1/bulk_consents.py new file mode 100644 index 00000000..9e242552 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/accounts/v1/bulk_consents.py @@ -0,0 +1,114 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Accounts + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional +from twilio.base import serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class BulkConsentsInstance(InstanceResource): + """ + :ivar items: A list of objects where each object represents the result of processing a `correlation_id`. Each object contains the following fields: `correlation_id`, a unique 32-character UUID that maps the response to the original request; `error_code`, an integer where 0 indicates success and any non-zero value represents an error; and `error_messages`, an array of strings describing specific validation errors encountered. If the request is successful, the error_messages array will be empty. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.items: Optional[Dict[str, object]] = payload.get("items") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class BulkConsentsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the BulkConsentsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Consents/Bulk" + + def create(self, items: List[object]) -> BulkConsentsInstance: + """ + Create the BulkConsentsInstance + + :param items: This is a list of objects that describes a contact's opt-in status. Each object contains the following fields: `contact_id`, which must be a string representing phone number in [E.164 format](https://www.twilio.com/docs/glossary/what-e164); `correlation_id`, a unique 32-character UUID used to uniquely map the request item with the response item; `sender_id`, which can be either a valid messaging service SID or a from phone number; `status`, a string representing the consent status. Can be one of [`opt-in`, `opt-out`]; `source`, a string indicating the medium through which the consent was collected. Can be one of [`website`, `offline`, `opt-in-message`, `opt-out-message`, `others`]; `date_of_consent`, an optional datetime string field in ISO-8601 format that captures the exact date and time when the user gave or revoked consent. If not provided, it will be empty. + + :returns: The created BulkConsentsInstance + """ + + data = values.of( + { + "Items": serialize.map(items, lambda e: serialize.object(e)), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BulkConsentsInstance(self._version, payload) + + async def create_async(self, items: List[object]) -> BulkConsentsInstance: + """ + Asynchronously create the BulkConsentsInstance + + :param items: This is a list of objects that describes a contact's opt-in status. Each object contains the following fields: `contact_id`, which must be a string representing phone number in [E.164 format](https://www.twilio.com/docs/glossary/what-e164); `correlation_id`, a unique 32-character UUID used to uniquely map the request item with the response item; `sender_id`, which can be either a valid messaging service SID or a from phone number; `status`, a string representing the consent status. Can be one of [`opt-in`, `opt-out`]; `source`, a string indicating the medium through which the consent was collected. Can be one of [`website`, `offline`, `opt-in-message`, `opt-out-message`, `others`]; `date_of_consent`, an optional datetime string field in ISO-8601 format that captures the exact date and time when the user gave or revoked consent. If not provided, it will be empty. + + :returns: The created BulkConsentsInstance + """ + + data = values.of( + { + "Items": serialize.map(items, lambda e: serialize.object(e)), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BulkConsentsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/accounts/v1/bulk_contacts.py b/venv/Lib/site-packages/twilio/rest/accounts/v1/bulk_contacts.py new file mode 100644 index 00000000..17b6da33 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/accounts/v1/bulk_contacts.py @@ -0,0 +1,114 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Accounts + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional +from twilio.base import serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class BulkContactsInstance(InstanceResource): + """ + :ivar items: A list of objects where each object represents the result of processing a `correlation_id`. Each object contains the following fields: `correlation_id`, a unique 32-character UUID that maps the response to the original request; `error_code`, an integer where 0 indicates success and any non-zero value represents an error; and `error_messages`, an array of strings describing specific validation errors encountered. If the request is successful, the error_messages array will be empty. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.items: Optional[Dict[str, object]] = payload.get("items") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class BulkContactsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the BulkContactsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Contacts/Bulk" + + def create(self, items: List[object]) -> BulkContactsInstance: + """ + Create the BulkContactsInstance + + :param items: A list of objects where each object represents a contact's details. Each object includes the following fields: `contact_id`, which must be a string representing phone number in [E.164 format](https://www.twilio.com/docs/glossary/what-e164); `correlation_id`, a unique 32-character UUID that maps the response to the original request; `country_iso_code`, a string representing the country using the ISO format (e.g., US for the United States); and `zip_code`, a string representing the postal code. + + :returns: The created BulkContactsInstance + """ + + data = values.of( + { + "Items": serialize.map(items, lambda e: serialize.object(e)), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BulkContactsInstance(self._version, payload) + + async def create_async(self, items: List[object]) -> BulkContactsInstance: + """ + Asynchronously create the BulkContactsInstance + + :param items: A list of objects where each object represents a contact's details. Each object includes the following fields: `contact_id`, which must be a string representing phone number in [E.164 format](https://www.twilio.com/docs/glossary/what-e164); `correlation_id`, a unique 32-character UUID that maps the response to the original request; `country_iso_code`, a string representing the country using the ISO format (e.g., US for the United States); and `zip_code`, a string representing the postal code. + + :returns: The created BulkContactsInstance + """ + + data = values.of( + { + "Items": serialize.map(items, lambda e: serialize.object(e)), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BulkContactsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/accounts/v1/credential/__init__.py b/venv/Lib/site-packages/twilio/rest/accounts/v1/credential/__init__.py new file mode 100644 index 00000000..e9c4653f --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/accounts/v1/credential/__init__.py @@ -0,0 +1,65 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Accounts + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.accounts.v1.credential.aws import AwsList +from twilio.rest.accounts.v1.credential.public_key import PublicKeyList + + +class CredentialList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CredentialList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Credentials" + + self._aws: Optional[AwsList] = None + self._public_key: Optional[PublicKeyList] = None + + @property + def aws(self) -> AwsList: + """ + Access the aws + """ + if self._aws is None: + self._aws = AwsList(self._version) + return self._aws + + @property + def public_key(self) -> PublicKeyList: + """ + Access the public_key + """ + if self._public_key is None: + self._public_key = PublicKeyList(self._version) + return self._public_key + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/accounts/v1/credential/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/accounts/v1/credential/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..e5474e48 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/accounts/v1/credential/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/accounts/v1/credential/__pycache__/aws.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/accounts/v1/credential/__pycache__/aws.cpython-312.pyc new file mode 100644 index 00000000..a8c5b0fc Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/accounts/v1/credential/__pycache__/aws.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/accounts/v1/credential/__pycache__/public_key.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/accounts/v1/credential/__pycache__/public_key.cpython-312.pyc new file mode 100644 index 00000000..b1f319c0 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/accounts/v1/credential/__pycache__/public_key.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/accounts/v1/credential/aws.py b/venv/Lib/site-packages/twilio/rest/accounts/v1/credential/aws.py new file mode 100644 index 00000000..ba5335ac --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/accounts/v1/credential/aws.py @@ -0,0 +1,609 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Accounts + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AwsInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the AWS resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AWS resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The URI for this resource, relative to `https://accounts.twilio.com` + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[AwsContext] = None + + @property + def _proxy(self) -> "AwsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AwsContext for this AwsInstance + """ + if self._context is None: + self._context = AwsContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AwsInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AwsInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AwsInstance": + """ + Fetch the AwsInstance + + + :returns: The fetched AwsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AwsInstance": + """ + Asynchronous coroutine to fetch the AwsInstance + + + :returns: The fetched AwsInstance + """ + return await self._proxy.fetch_async() + + def update(self, friendly_name: Union[str, object] = values.unset) -> "AwsInstance": + """ + Update the AwsInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated AwsInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "AwsInstance": + """ + Asynchronous coroutine to update the AwsInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated AwsInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AwsContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the AwsContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the AWS resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/AWS/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the AwsInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AwsInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AwsInstance: + """ + Fetch the AwsInstance + + + :returns: The fetched AwsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AwsInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AwsInstance: + """ + Asynchronous coroutine to fetch the AwsInstance + + + :returns: The fetched AwsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AwsInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update(self, friendly_name: Union[str, object] = values.unset) -> AwsInstance: + """ + Update the AwsInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated AwsInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AwsInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> AwsInstance: + """ + Asynchronous coroutine to update the AwsInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated AwsInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AwsInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AwsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AwsInstance: + """ + Build an instance of AwsInstance + + :param payload: Payload response from the API + """ + return AwsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AwsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AwsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Credentials/AWS" + + def create( + self, + credentials: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> AwsInstance: + """ + Create the AwsInstance + + :param credentials: A string that contains the AWS access credentials in the format `:`. For example, `AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY` + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param account_sid: The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request. + + :returns: The created AwsInstance + """ + + data = values.of( + { + "Credentials": credentials, + "FriendlyName": friendly_name, + "AccountSid": account_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AwsInstance(self._version, payload) + + async def create_async( + self, + credentials: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> AwsInstance: + """ + Asynchronously create the AwsInstance + + :param credentials: A string that contains the AWS access credentials in the format `:`. For example, `AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY` + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param account_sid: The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request. + + :returns: The created AwsInstance + """ + + data = values.of( + { + "Credentials": credentials, + "FriendlyName": friendly_name, + "AccountSid": account_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AwsInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AwsInstance]: + """ + Streams AwsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AwsInstance]: + """ + Asynchronously streams AwsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AwsInstance]: + """ + Lists AwsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AwsInstance]: + """ + Asynchronously lists AwsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AwsPage: + """ + Retrieve a single page of AwsInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AwsInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AwsPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AwsPage: + """ + Asynchronously retrieve a single page of AwsInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AwsInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AwsPage(self._version, response) + + def get_page(self, target_url: str) -> AwsPage: + """ + Retrieve a specific page of AwsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AwsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AwsPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AwsPage: + """ + Asynchronously retrieve a specific page of AwsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AwsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AwsPage(self._version, response) + + def get(self, sid: str) -> AwsContext: + """ + Constructs a AwsContext + + :param sid: The Twilio-provided string that uniquely identifies the AWS resource to update. + """ + return AwsContext(self._version, sid=sid) + + def __call__(self, sid: str) -> AwsContext: + """ + Constructs a AwsContext + + :param sid: The Twilio-provided string that uniquely identifies the AWS resource to update. + """ + return AwsContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/accounts/v1/credential/public_key.py b/venv/Lib/site-packages/twilio/rest/accounts/v1/credential/public_key.py new file mode 100644 index 00000000..c2b4f9bb --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/accounts/v1/credential/public_key.py @@ -0,0 +1,613 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Accounts + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class PublicKeyInstance(InstanceResource): + """ + :ivar sid: The unique string that that we created to identify the PublicKey resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Credential that the PublicKey resource belongs to. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The URI for this resource, relative to `https://accounts.twilio.com` + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[PublicKeyContext] = None + + @property + def _proxy(self) -> "PublicKeyContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PublicKeyContext for this PublicKeyInstance + """ + if self._context is None: + self._context = PublicKeyContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the PublicKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PublicKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "PublicKeyInstance": + """ + Fetch the PublicKeyInstance + + + :returns: The fetched PublicKeyInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PublicKeyInstance": + """ + Asynchronous coroutine to fetch the PublicKeyInstance + + + :returns: The fetched PublicKeyInstance + """ + return await self._proxy.fetch_async() + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> "PublicKeyInstance": + """ + Update the PublicKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated PublicKeyInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "PublicKeyInstance": + """ + Asynchronous coroutine to update the PublicKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated PublicKeyInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PublicKeyContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the PublicKeyContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the PublicKey resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/PublicKeys/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the PublicKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PublicKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> PublicKeyInstance: + """ + Fetch the PublicKeyInstance + + + :returns: The fetched PublicKeyInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PublicKeyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> PublicKeyInstance: + """ + Asynchronous coroutine to fetch the PublicKeyInstance + + + :returns: The fetched PublicKeyInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PublicKeyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> PublicKeyInstance: + """ + Update the PublicKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated PublicKeyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PublicKeyInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> PublicKeyInstance: + """ + Asynchronous coroutine to update the PublicKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated PublicKeyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PublicKeyInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PublicKeyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PublicKeyInstance: + """ + Build an instance of PublicKeyInstance + + :param payload: Payload response from the API + """ + return PublicKeyInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class PublicKeyList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PublicKeyList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Credentials/PublicKeys" + + def create( + self, + public_key: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> PublicKeyInstance: + """ + Create the PublicKeyInstance + + :param public_key: A URL encoded representation of the public key. For example, `-----BEGIN PUBLIC KEY-----MIIBIjANB.pa9xQIDAQAB-----END PUBLIC KEY-----` + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param account_sid: The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request + + :returns: The created PublicKeyInstance + """ + + data = values.of( + { + "PublicKey": public_key, + "FriendlyName": friendly_name, + "AccountSid": account_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PublicKeyInstance(self._version, payload) + + async def create_async( + self, + public_key: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> PublicKeyInstance: + """ + Asynchronously create the PublicKeyInstance + + :param public_key: A URL encoded representation of the public key. For example, `-----BEGIN PUBLIC KEY-----MIIBIjANB.pa9xQIDAQAB-----END PUBLIC KEY-----` + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param account_sid: The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request + + :returns: The created PublicKeyInstance + """ + + data = values.of( + { + "PublicKey": public_key, + "FriendlyName": friendly_name, + "AccountSid": account_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PublicKeyInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PublicKeyInstance]: + """ + Streams PublicKeyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PublicKeyInstance]: + """ + Asynchronously streams PublicKeyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PublicKeyInstance]: + """ + Lists PublicKeyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PublicKeyInstance]: + """ + Asynchronously lists PublicKeyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PublicKeyPage: + """ + Retrieve a single page of PublicKeyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PublicKeyInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PublicKeyPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PublicKeyPage: + """ + Asynchronously retrieve a single page of PublicKeyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PublicKeyInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PublicKeyPage(self._version, response) + + def get_page(self, target_url: str) -> PublicKeyPage: + """ + Retrieve a specific page of PublicKeyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PublicKeyInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PublicKeyPage(self._version, response) + + async def get_page_async(self, target_url: str) -> PublicKeyPage: + """ + Asynchronously retrieve a specific page of PublicKeyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PublicKeyInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PublicKeyPage(self._version, response) + + def get(self, sid: str) -> PublicKeyContext: + """ + Constructs a PublicKeyContext + + :param sid: The Twilio-provided string that uniquely identifies the PublicKey resource to update. + """ + return PublicKeyContext(self._version, sid=sid) + + def __call__(self, sid: str) -> PublicKeyContext: + """ + Constructs a PublicKeyContext + + :param sid: The Twilio-provided string that uniquely identifies the PublicKey resource to update. + """ + return PublicKeyContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/accounts/v1/safelist.py b/venv/Lib/site-packages/twilio/rest/accounts/v1/safelist.py new file mode 100644 index 00000000..be8fe416 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/accounts/v1/safelist.py @@ -0,0 +1,204 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Accounts + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class SafelistInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the SafeList resource. + :ivar phone_number: The phone number or phone number 1k prefix in SafeList. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.phone_number: Optional[str] = payload.get("phone_number") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class SafelistList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SafelistList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/SafeList/Numbers" + + def create(self, phone_number: str) -> SafelistInstance: + """ + Create the SafelistInstance + + :param phone_number: The phone number or phone number 1k prefix to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + + :returns: The created SafelistInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SafelistInstance(self._version, payload) + + async def create_async(self, phone_number: str) -> SafelistInstance: + """ + Asynchronously create the SafelistInstance + + :param phone_number: The phone number or phone number 1k prefix to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + + :returns: The created SafelistInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SafelistInstance(self._version, payload) + + def delete(self, phone_number: Union[str, object] = values.unset) -> bool: + """ + Asynchronously delete the SafelistInstance + + :param phone_number: The phone number or phone number 1k prefix to be removed from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :returns: True if delete succeeds, False otherwise + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + params = values.of( + { + "PhoneNumber": phone_number, + } + ) + return self._version.delete( + method="DELETE", uri=self._uri, headers=headers, params=params + ) + + async def delete_async( + self, phone_number: Union[str, object] = values.unset + ) -> bool: + """ + Asynchronously delete the SafelistInstance + + :param phone_number: The phone number or phone number 1k prefix to be removed from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :returns: True if delete succeeds, False otherwise + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + params = values.of( + { + "PhoneNumber": phone_number, + } + ) + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers, params=params + ) + + def fetch( + self, phone_number: Union[str, object] = values.unset + ) -> SafelistInstance: + """ + Asynchronously fetch the SafelistInstance + + :param phone_number: The phone number or phone number 1k prefix to be fetched from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :returns: The fetched SafelistInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "PhoneNumber": phone_number, + } + ) + + payload = self._version.fetch( + method="GET", uri=self._uri, headers=headers, params=params + ) + + return SafelistInstance(self._version, payload) + + async def fetch_async( + self, phone_number: Union[str, object] = values.unset + ) -> SafelistInstance: + """ + Asynchronously fetch the SafelistInstance + + :param phone_number: The phone number or phone number 1k prefix to be fetched from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :returns: The fetched SafelistInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "PhoneNumber": phone_number, + } + ) + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers, params=params + ) + + return SafelistInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/accounts/v1/secondary_auth_token.py b/venv/Lib/site-packages/twilio/rest/accounts/v1/secondary_auth_token.py new file mode 100644 index 00000000..f5e2b5c1 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/accounts/v1/secondary_auth_token.py @@ -0,0 +1,215 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Accounts + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class SecondaryAuthTokenInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the secondary Auth Token was created for. + :ivar date_created: The date and time in UTC when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in UTC when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar secondary_auth_token: The generated secondary Auth Token that can be used to authenticate future API requests. + :ivar url: The URI for this resource, relative to `https://accounts.twilio.com` + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.secondary_auth_token: Optional[str] = payload.get("secondary_auth_token") + self.url: Optional[str] = payload.get("url") + + self._context: Optional[SecondaryAuthTokenContext] = None + + @property + def _proxy(self) -> "SecondaryAuthTokenContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SecondaryAuthTokenContext for this SecondaryAuthTokenInstance + """ + if self._context is None: + self._context = SecondaryAuthTokenContext( + self._version, + ) + return self._context + + def create(self) -> "SecondaryAuthTokenInstance": + """ + Create the SecondaryAuthTokenInstance + + + :returns: The created SecondaryAuthTokenInstance + """ + return self._proxy.create() + + async def create_async(self) -> "SecondaryAuthTokenInstance": + """ + Asynchronous coroutine to create the SecondaryAuthTokenInstance + + + :returns: The created SecondaryAuthTokenInstance + """ + return await self._proxy.create_async() + + def delete(self) -> bool: + """ + Deletes the SecondaryAuthTokenInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SecondaryAuthTokenInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class SecondaryAuthTokenContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the SecondaryAuthTokenContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/AuthTokens/Secondary" + + def create(self) -> SecondaryAuthTokenInstance: + """ + Create the SecondaryAuthTokenInstance + + + :returns: The created SecondaryAuthTokenInstance + """ + data = values.of({}) + + payload = self._version.create(method="POST", uri=self._uri, data=data) + + return SecondaryAuthTokenInstance(self._version, payload) + + async def create_async(self) -> SecondaryAuthTokenInstance: + """ + Asynchronous coroutine to create the SecondaryAuthTokenInstance + + + :returns: The created SecondaryAuthTokenInstance + """ + data = values.of({}) + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data + ) + + return SecondaryAuthTokenInstance(self._version, payload) + + def delete(self) -> bool: + """ + Deletes the SecondaryAuthTokenInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SecondaryAuthTokenInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class SecondaryAuthTokenList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SecondaryAuthTokenList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> SecondaryAuthTokenContext: + """ + Constructs a SecondaryAuthTokenContext + + """ + return SecondaryAuthTokenContext(self._version) + + def __call__(self) -> SecondaryAuthTokenContext: + """ + Constructs a SecondaryAuthTokenContext + + """ + return SecondaryAuthTokenContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/ApiBase.py b/venv/Lib/site-packages/twilio/rest/api/ApiBase.py new file mode 100644 index 00000000..e53535ab --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/ApiBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.api.v2010 import V2010 + + +class ApiBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Api Domain + + :returns: Domain for Api + """ + super().__init__(twilio, "https://api.twilio.com") + self._v2010: Optional[V2010] = None + + @property + def v2010(self) -> V2010: + """ + :returns: Versions v2010 of Api + """ + if self._v2010 is None: + self._v2010 = V2010(self) + return self._v2010 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/__init__.py b/venv/Lib/site-packages/twilio/rest/api/__init__.py new file mode 100644 index 00000000..08d5885c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/__init__.py @@ -0,0 +1,258 @@ +from warnings import warn + +from twilio.rest.api.ApiBase import ApiBase +from twilio.rest.api.v2010.account import AccountContext, AccountList +from twilio.rest.api.v2010.account.address import AddressList +from twilio.rest.api.v2010.account.application import ApplicationList +from twilio.rest.api.v2010.account.authorized_connect_app import ( + AuthorizedConnectAppList, +) +from twilio.rest.api.v2010.account.available_phone_number_country import ( + AvailablePhoneNumberCountryList, +) +from twilio.rest.api.v2010.account.balance import BalanceList +from twilio.rest.api.v2010.account.call import CallList +from twilio.rest.api.v2010.account.conference import ConferenceList +from twilio.rest.api.v2010.account.connect_app import ConnectAppList +from twilio.rest.api.v2010.account.incoming_phone_number import IncomingPhoneNumberList +from twilio.rest.api.v2010.account.key import KeyList +from twilio.rest.api.v2010.account.message import MessageList +from twilio.rest.api.v2010.account.new_key import NewKeyList +from twilio.rest.api.v2010.account.new_signing_key import NewSigningKeyList +from twilio.rest.api.v2010.account.notification import NotificationList +from twilio.rest.api.v2010.account.outgoing_caller_id import OutgoingCallerIdList +from twilio.rest.api.v2010.account.queue import QueueList +from twilio.rest.api.v2010.account.recording import RecordingList +from twilio.rest.api.v2010.account.short_code import ShortCodeList +from twilio.rest.api.v2010.account.signing_key import SigningKeyList +from twilio.rest.api.v2010.account.sip import SipList +from twilio.rest.api.v2010.account.token import TokenList +from twilio.rest.api.v2010.account.transcription import TranscriptionList +from twilio.rest.api.v2010.account.usage import UsageList +from twilio.rest.api.v2010.account.validation_request import ValidationRequestList + + +class Api(ApiBase): + @property + def account(self) -> AccountContext: + return self.v2010.account + + @property + def accounts(self) -> AccountList: + return self.v2010.accounts + + @property + def addresses(self) -> AddressList: + warn( + "addresses is deprecated. Use account.addresses instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.addresses + + @property + def applications(self) -> ApplicationList: + warn( + "applications is deprecated. Use account.applications instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.applications + + @property + def authorized_connect_apps(self) -> AuthorizedConnectAppList: + warn( + "authorized_connect_apps is deprecated. Use account.authorized_connect_apps instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.authorized_connect_apps + + @property + def available_phone_numbers(self) -> AvailablePhoneNumberCountryList: + warn( + "available_phone_numbers is deprecated. Use account.available_phone_numbers instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.available_phone_numbers + + @property + def balance(self) -> BalanceList: + warn( + "balance is deprecated. Use account.balance instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.balance + + @property + def calls(self) -> CallList: + warn( + "calls is deprecated. Use account.calls instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.calls + + @property + def conferences(self) -> ConferenceList: + warn( + "conferences is deprecated. Use account.conferences instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.conferences + + @property + def connect_apps(self) -> ConnectAppList: + warn( + "connect_apps is deprecated. Use account.connect_apps instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.connect_apps + + @property + def incoming_phone_numbers(self) -> IncomingPhoneNumberList: + warn( + "incoming_phone_numbers is deprecated. Use account.incoming_phone_numbers instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.incoming_phone_numbers + + @property + def keys(self) -> KeyList: + warn( + "keys is deprecated. Use account.keys instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.keys + + @property + def messages(self) -> MessageList: + warn( + "messages is deprecated. Use account.messages instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.messages + + @property + def new_keys(self) -> NewKeyList: + warn( + "new_keys is deprecated. Use account.new_keys instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.new_keys + + @property + def new_signing_keys(self) -> NewSigningKeyList: + warn( + "new_signing_keys is deprecated. Use account.new_signing_keys instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.new_signing_keys + + @property + def notifications(self) -> NotificationList: + warn( + "notifications is deprecated. Use account.notifications instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.notifications + + @property + def outgoing_caller_ids(self) -> OutgoingCallerIdList: + warn( + "outgoing_caller_ids is deprecated. Use account.outgoing_caller_ids instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.outgoing_caller_ids + + @property + def queues(self) -> QueueList: + warn( + "queues is deprecated. Use account.queues instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.queues + + @property + def recordings(self) -> RecordingList: + warn( + "recordings is deprecated. Use account.recordings instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.recordings + + @property + def signing_keys(self) -> SigningKeyList: + warn( + "signing_keys is deprecated. Use account.signing_keys instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.signing_keys + + @property + def sip(self) -> SipList: + warn( + "sip is deprecated. Use account.sip instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.sip + + @property + def short_codes(self) -> ShortCodeList: + warn( + "short_codes is deprecated. Use account.short_codes instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.short_codes + + @property + def tokens(self) -> TokenList: + warn( + "tokens is deprecated. Use account.tokens instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.tokens + + @property + def transcriptions(self) -> TranscriptionList: + warn( + "transcriptions is deprecated. Use account.transcriptions instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.transcriptions + + @property + def usage(self) -> UsageList: + warn( + "usage is deprecated. Use account.usage instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.usage + + @property + def validation_requests(self) -> ValidationRequestList: + warn( + "validation_requests is deprecated. Use account.validation_requests instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.validation_requests diff --git a/venv/Lib/site-packages/twilio/rest/api/__pycache__/ApiBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/__pycache__/ApiBase.cpython-312.pyc new file mode 100644 index 00000000..1eff59a8 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/__pycache__/ApiBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..ec203214 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/__init__.py b/venv/Lib/site-packages/twilio/rest/api/v2010/__init__.py new file mode 100644 index 00000000..2efb4ff3 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/__init__.py @@ -0,0 +1,59 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.api.v2010.account import AccountList +from twilio.rest.api.v2010.account import AccountContext + + +class V2010(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2010 version of Api + + :param domain: The Twilio.api domain + """ + super().__init__(domain, "2010-04-01") + self._accounts: Optional[AccountList] = None + self._account: Optional[AccountContext] = None + + @property + def accounts(self) -> AccountList: + if self._accounts is None: + self._accounts = AccountList(self) + return self._accounts + + @property + def account(self) -> AccountContext: + if self._account is None: + self._account = AccountContext(self, self.domain.twilio.account_sid) + return self._account + + @account.setter + def account(self, value: AccountContext) -> None: + """ + Setter to override account + :param value: value to use as account + """ + self._account = value + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..e626f8e9 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/__init__.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__init__.py new file mode 100644 index 00000000..7c7e2c10 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__init__.py @@ -0,0 +1,1136 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.address import AddressList +from twilio.rest.api.v2010.account.application import ApplicationList +from twilio.rest.api.v2010.account.authorized_connect_app import ( + AuthorizedConnectAppList, +) +from twilio.rest.api.v2010.account.available_phone_number_country import ( + AvailablePhoneNumberCountryList, +) +from twilio.rest.api.v2010.account.balance import BalanceList +from twilio.rest.api.v2010.account.call import CallList +from twilio.rest.api.v2010.account.conference import ConferenceList +from twilio.rest.api.v2010.account.connect_app import ConnectAppList +from twilio.rest.api.v2010.account.incoming_phone_number import IncomingPhoneNumberList +from twilio.rest.api.v2010.account.key import KeyList +from twilio.rest.api.v2010.account.message import MessageList +from twilio.rest.api.v2010.account.new_key import NewKeyList +from twilio.rest.api.v2010.account.new_signing_key import NewSigningKeyList +from twilio.rest.api.v2010.account.notification import NotificationList +from twilio.rest.api.v2010.account.outgoing_caller_id import OutgoingCallerIdList +from twilio.rest.api.v2010.account.queue import QueueList +from twilio.rest.api.v2010.account.recording import RecordingList +from twilio.rest.api.v2010.account.short_code import ShortCodeList +from twilio.rest.api.v2010.account.signing_key import SigningKeyList +from twilio.rest.api.v2010.account.sip import SipList +from twilio.rest.api.v2010.account.token import TokenList +from twilio.rest.api.v2010.account.transcription import TranscriptionList +from twilio.rest.api.v2010.account.usage import UsageList +from twilio.rest.api.v2010.account.validation_request import ValidationRequestList + + +class AccountInstance(InstanceResource): + + class Status(object): + ACTIVE = "active" + SUSPENDED = "suspended" + CLOSED = "closed" + + class Type(object): + TRIAL = "Trial" + FULL = "Full" + + """ + :ivar auth_token: The authorization token for this account. This token should be kept a secret, so no sharing. + :ivar date_created: The date that this account was created, in GMT in RFC 2822 format + :ivar date_updated: The date that this account was last updated, in GMT in RFC 2822 format. + :ivar friendly_name: A human readable description of this account, up to 64 characters long. By default the FriendlyName is your email address. + :ivar owner_account_sid: The unique 34 character id that represents the parent of this account. The OwnerAccountSid of a parent account is it's own sid. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar status: + :ivar subresource_uris: A Map of various subresources available for the given Account Instance + :ivar type: + :ivar uri: The URI for this resource, relative to `https://api.twilio.com` + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.auth_token: Optional[str] = payload.get("auth_token") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.owner_account_sid: Optional[str] = payload.get("owner_account_sid") + self.sid: Optional[str] = payload.get("sid") + self.status: Optional["AccountInstance.Status"] = payload.get("status") + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.type: Optional["AccountInstance.Type"] = payload.get("type") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[AccountContext] = None + + @property + def _proxy(self) -> "AccountContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AccountContext for this AccountInstance + """ + if self._context is None: + self._context = AccountContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "AccountInstance": + """ + Fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AccountInstance": + """ + Asynchronous coroutine to fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> "AccountInstance": + """ + Update the AccountInstance + + :param friendly_name: Update the human-readable description of this Account + :param status: + + :returns: The updated AccountInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + status=status, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> "AccountInstance": + """ + Asynchronous coroutine to update the AccountInstance + + :param friendly_name: Update the human-readable description of this Account + :param status: + + :returns: The updated AccountInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + status=status, + ) + + @property + def addresses(self) -> AddressList: + """ + Access the addresses + """ + return self._proxy.addresses + + @property + def applications(self) -> ApplicationList: + """ + Access the applications + """ + return self._proxy.applications + + @property + def authorized_connect_apps(self) -> AuthorizedConnectAppList: + """ + Access the authorized_connect_apps + """ + return self._proxy.authorized_connect_apps + + @property + def available_phone_numbers(self) -> AvailablePhoneNumberCountryList: + """ + Access the available_phone_numbers + """ + return self._proxy.available_phone_numbers + + @property + def balance(self) -> BalanceList: + """ + Access the balance + """ + return self._proxy.balance + + @property + def calls(self) -> CallList: + """ + Access the calls + """ + return self._proxy.calls + + @property + def conferences(self) -> ConferenceList: + """ + Access the conferences + """ + return self._proxy.conferences + + @property + def connect_apps(self) -> ConnectAppList: + """ + Access the connect_apps + """ + return self._proxy.connect_apps + + @property + def incoming_phone_numbers(self) -> IncomingPhoneNumberList: + """ + Access the incoming_phone_numbers + """ + return self._proxy.incoming_phone_numbers + + @property + def keys(self) -> KeyList: + """ + Access the keys + """ + return self._proxy.keys + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages + + @property + def new_keys(self) -> NewKeyList: + """ + Access the new_keys + """ + return self._proxy.new_keys + + @property + def new_signing_keys(self) -> NewSigningKeyList: + """ + Access the new_signing_keys + """ + return self._proxy.new_signing_keys + + @property + def notifications(self) -> NotificationList: + """ + Access the notifications + """ + return self._proxy.notifications + + @property + def outgoing_caller_ids(self) -> OutgoingCallerIdList: + """ + Access the outgoing_caller_ids + """ + return self._proxy.outgoing_caller_ids + + @property + def queues(self) -> QueueList: + """ + Access the queues + """ + return self._proxy.queues + + @property + def recordings(self) -> RecordingList: + """ + Access the recordings + """ + return self._proxy.recordings + + @property + def short_codes(self) -> ShortCodeList: + """ + Access the short_codes + """ + return self._proxy.short_codes + + @property + def signing_keys(self) -> SigningKeyList: + """ + Access the signing_keys + """ + return self._proxy.signing_keys + + @property + def sip(self) -> SipList: + """ + Access the sip + """ + return self._proxy.sip + + @property + def tokens(self) -> TokenList: + """ + Access the tokens + """ + return self._proxy.tokens + + @property + def transcriptions(self) -> TranscriptionList: + """ + Access the transcriptions + """ + return self._proxy.transcriptions + + @property + def usage(self) -> UsageList: + """ + Access the usage + """ + return self._proxy.usage + + @property + def validation_requests(self) -> ValidationRequestList: + """ + Access the validation_requests + """ + return self._proxy.validation_requests + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AccountContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the AccountContext + + :param version: Version that contains the resource + :param sid: The Account Sid that uniquely identifies the account to update + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Accounts/{sid}.json".format(**self._solution) + + self._addresses: Optional[AddressList] = None + self._applications: Optional[ApplicationList] = None + self._authorized_connect_apps: Optional[AuthorizedConnectAppList] = None + self._available_phone_numbers: Optional[AvailablePhoneNumberCountryList] = None + self._balance: Optional[BalanceList] = None + self._calls: Optional[CallList] = None + self._conferences: Optional[ConferenceList] = None + self._connect_apps: Optional[ConnectAppList] = None + self._incoming_phone_numbers: Optional[IncomingPhoneNumberList] = None + self._keys: Optional[KeyList] = None + self._messages: Optional[MessageList] = None + self._new_keys: Optional[NewKeyList] = None + self._new_signing_keys: Optional[NewSigningKeyList] = None + self._notifications: Optional[NotificationList] = None + self._outgoing_caller_ids: Optional[OutgoingCallerIdList] = None + self._queues: Optional[QueueList] = None + self._recordings: Optional[RecordingList] = None + self._short_codes: Optional[ShortCodeList] = None + self._signing_keys: Optional[SigningKeyList] = None + self._sip: Optional[SipList] = None + self._tokens: Optional[TokenList] = None + self._transcriptions: Optional[TranscriptionList] = None + self._usage: Optional[UsageList] = None + self._validation_requests: Optional[ValidationRequestList] = None + + def fetch(self) -> AccountInstance: + """ + Fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AccountInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AccountInstance: + """ + Asynchronous coroutine to fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AccountInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> AccountInstance: + """ + Update the AccountInstance + + :param friendly_name: Update the human-readable description of this Account + :param status: + + :returns: The updated AccountInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AccountInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> AccountInstance: + """ + Asynchronous coroutine to update the AccountInstance + + :param friendly_name: Update the human-readable description of this Account + :param status: + + :returns: The updated AccountInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AccountInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def addresses(self) -> AddressList: + """ + Access the addresses + """ + if self._addresses is None: + self._addresses = AddressList( + self._version, + self._solution["sid"], + ) + return self._addresses + + @property + def applications(self) -> ApplicationList: + """ + Access the applications + """ + if self._applications is None: + self._applications = ApplicationList( + self._version, + self._solution["sid"], + ) + return self._applications + + @property + def authorized_connect_apps(self) -> AuthorizedConnectAppList: + """ + Access the authorized_connect_apps + """ + if self._authorized_connect_apps is None: + self._authorized_connect_apps = AuthorizedConnectAppList( + self._version, + self._solution["sid"], + ) + return self._authorized_connect_apps + + @property + def available_phone_numbers(self) -> AvailablePhoneNumberCountryList: + """ + Access the available_phone_numbers + """ + if self._available_phone_numbers is None: + self._available_phone_numbers = AvailablePhoneNumberCountryList( + self._version, + self._solution["sid"], + ) + return self._available_phone_numbers + + @property + def balance(self) -> BalanceList: + """ + Access the balance + """ + if self._balance is None: + self._balance = BalanceList( + self._version, + self._solution["sid"], + ) + return self._balance + + @property + def calls(self) -> CallList: + """ + Access the calls + """ + if self._calls is None: + self._calls = CallList( + self._version, + self._solution["sid"], + ) + return self._calls + + @property + def conferences(self) -> ConferenceList: + """ + Access the conferences + """ + if self._conferences is None: + self._conferences = ConferenceList( + self._version, + self._solution["sid"], + ) + return self._conferences + + @property + def connect_apps(self) -> ConnectAppList: + """ + Access the connect_apps + """ + if self._connect_apps is None: + self._connect_apps = ConnectAppList( + self._version, + self._solution["sid"], + ) + return self._connect_apps + + @property + def incoming_phone_numbers(self) -> IncomingPhoneNumberList: + """ + Access the incoming_phone_numbers + """ + if self._incoming_phone_numbers is None: + self._incoming_phone_numbers = IncomingPhoneNumberList( + self._version, + self._solution["sid"], + ) + return self._incoming_phone_numbers + + @property + def keys(self) -> KeyList: + """ + Access the keys + """ + if self._keys is None: + self._keys = KeyList( + self._version, + self._solution["sid"], + ) + return self._keys + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + if self._messages is None: + self._messages = MessageList( + self._version, + self._solution["sid"], + ) + return self._messages + + @property + def new_keys(self) -> NewKeyList: + """ + Access the new_keys + """ + if self._new_keys is None: + self._new_keys = NewKeyList( + self._version, + self._solution["sid"], + ) + return self._new_keys + + @property + def new_signing_keys(self) -> NewSigningKeyList: + """ + Access the new_signing_keys + """ + if self._new_signing_keys is None: + self._new_signing_keys = NewSigningKeyList( + self._version, + self._solution["sid"], + ) + return self._new_signing_keys + + @property + def notifications(self) -> NotificationList: + """ + Access the notifications + """ + if self._notifications is None: + self._notifications = NotificationList( + self._version, + self._solution["sid"], + ) + return self._notifications + + @property + def outgoing_caller_ids(self) -> OutgoingCallerIdList: + """ + Access the outgoing_caller_ids + """ + if self._outgoing_caller_ids is None: + self._outgoing_caller_ids = OutgoingCallerIdList( + self._version, + self._solution["sid"], + ) + return self._outgoing_caller_ids + + @property + def queues(self) -> QueueList: + """ + Access the queues + """ + if self._queues is None: + self._queues = QueueList( + self._version, + self._solution["sid"], + ) + return self._queues + + @property + def recordings(self) -> RecordingList: + """ + Access the recordings + """ + if self._recordings is None: + self._recordings = RecordingList( + self._version, + self._solution["sid"], + ) + return self._recordings + + @property + def short_codes(self) -> ShortCodeList: + """ + Access the short_codes + """ + if self._short_codes is None: + self._short_codes = ShortCodeList( + self._version, + self._solution["sid"], + ) + return self._short_codes + + @property + def signing_keys(self) -> SigningKeyList: + """ + Access the signing_keys + """ + if self._signing_keys is None: + self._signing_keys = SigningKeyList( + self._version, + self._solution["sid"], + ) + return self._signing_keys + + @property + def sip(self) -> SipList: + """ + Access the sip + """ + if self._sip is None: + self._sip = SipList( + self._version, + self._solution["sid"], + ) + return self._sip + + @property + def tokens(self) -> TokenList: + """ + Access the tokens + """ + if self._tokens is None: + self._tokens = TokenList( + self._version, + self._solution["sid"], + ) + return self._tokens + + @property + def transcriptions(self) -> TranscriptionList: + """ + Access the transcriptions + """ + if self._transcriptions is None: + self._transcriptions = TranscriptionList( + self._version, + self._solution["sid"], + ) + return self._transcriptions + + @property + def usage(self) -> UsageList: + """ + Access the usage + """ + if self._usage is None: + self._usage = UsageList( + self._version, + self._solution["sid"], + ) + return self._usage + + @property + def validation_requests(self) -> ValidationRequestList: + """ + Access the validation_requests + """ + if self._validation_requests is None: + self._validation_requests = ValidationRequestList( + self._version, + self._solution["sid"], + ) + return self._validation_requests + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AccountPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AccountInstance: + """ + Build an instance of AccountInstance + + :param payload: Payload response from the API + """ + return AccountInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AccountList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AccountList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Accounts.json" + + def create( + self, friendly_name: Union[str, object] = values.unset + ) -> AccountInstance: + """ + Create the AccountInstance + + :param friendly_name: A human readable description of the account to create, defaults to `SubAccount Created at {YYYY-MM-DD HH:MM meridian}` + + :returns: The created AccountInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AccountInstance(self._version, payload) + + async def create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> AccountInstance: + """ + Asynchronously create the AccountInstance + + :param friendly_name: A human readable description of the account to create, defaults to `SubAccount Created at {YYYY-MM-DD HH:MM meridian}` + + :returns: The created AccountInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AccountInstance(self._version, payload) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AccountInstance]: + """ + Streams AccountInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: Only return the Account resources with friendly names that exactly match this name. + :param "AccountInstance.Status" status: Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + friendly_name=friendly_name, status=status, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AccountInstance]: + """ + Asynchronously streams AccountInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: Only return the Account resources with friendly names that exactly match this name. + :param "AccountInstance.Status" status: Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, status=status, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AccountInstance]: + """ + Lists AccountInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: Only return the Account resources with friendly names that exactly match this name. + :param "AccountInstance.Status" status: Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + friendly_name=friendly_name, + status=status, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AccountInstance]: + """ + Asynchronously lists AccountInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: Only return the Account resources with friendly names that exactly match this name. + :param "AccountInstance.Status" status: Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + status=status, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AccountPage: + """ + Retrieve a single page of AccountInstance records from the API. + Request is executed immediately + + :param friendly_name: Only return the Account resources with friendly names that exactly match this name. + :param status: Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AccountInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AccountPage(self._version, response) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AccountPage: + """ + Asynchronously retrieve a single page of AccountInstance records from the API. + Request is executed immediately + + :param friendly_name: Only return the Account resources with friendly names that exactly match this name. + :param status: Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AccountInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AccountPage(self._version, response) + + def get_page(self, target_url: str) -> AccountPage: + """ + Retrieve a specific page of AccountInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AccountInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AccountPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AccountPage: + """ + Asynchronously retrieve a specific page of AccountInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AccountInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AccountPage(self._version, response) + + def get(self, sid: str) -> AccountContext: + """ + Constructs a AccountContext + + :param sid: The Account Sid that uniquely identifies the account to update + """ + return AccountContext(self._version, sid=sid) + + def __call__(self, sid: str) -> AccountContext: + """ + Constructs a AccountContext + + :param sid: The Account Sid that uniquely identifies the account to update + """ + return AccountContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..946d905b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/application.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/application.cpython-312.pyc new file mode 100644 index 00000000..9af4e1b8 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/application.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/authorized_connect_app.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/authorized_connect_app.cpython-312.pyc new file mode 100644 index 00000000..745150d9 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/authorized_connect_app.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/balance.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/balance.cpython-312.pyc new file mode 100644 index 00000000..2f3f7cd7 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/balance.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/connect_app.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/connect_app.cpython-312.pyc new file mode 100644 index 00000000..3e91c5c4 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/connect_app.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/key.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/key.cpython-312.pyc new file mode 100644 index 00000000..a6549714 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/key.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/new_key.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/new_key.cpython-312.pyc new file mode 100644 index 00000000..a6bf7c8c Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/new_key.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/new_signing_key.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/new_signing_key.cpython-312.pyc new file mode 100644 index 00000000..b5494780 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/new_signing_key.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/notification.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/notification.cpython-312.pyc new file mode 100644 index 00000000..663846ba Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/notification.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/outgoing_caller_id.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/outgoing_caller_id.cpython-312.pyc new file mode 100644 index 00000000..b869c18a Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/outgoing_caller_id.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/short_code.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/short_code.cpython-312.pyc new file mode 100644 index 00000000..74b95bf6 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/short_code.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/signing_key.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/signing_key.cpython-312.pyc new file mode 100644 index 00000000..4bae097a Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/signing_key.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/token.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/token.cpython-312.pyc new file mode 100644 index 00000000..4782c443 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/token.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/transcription.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/transcription.cpython-312.pyc new file mode 100644 index 00000000..d5f7846b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/transcription.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/validation_request.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/validation_request.cpython-312.pyc new file mode 100644 index 00000000..479d5b27 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/__pycache__/validation_request.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/address/__init__.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/address/__init__.py new file mode 100644 index 00000000..77fc702c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/address/__init__.py @@ -0,0 +1,913 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.address.dependent_phone_number import ( + DependentPhoneNumberList, +) + + +class AddressInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that is responsible for the Address resource. + :ivar city: The city in which the address is located. + :ivar customer_name: The name associated with the address.This property has a maximum length of 16 4-byte characters, or 21 3-byte characters. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar iso_country: The ISO country code of the address. + :ivar postal_code: The postal code of the address. + :ivar region: The state or region of the address. + :ivar sid: The unique string that that we created to identify the Address resource. + :ivar street: The number and street address of the address. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar emergency_enabled: Whether emergency calling has been enabled on this number. + :ivar validated: Whether the address has been validated to comply with local regulation. In countries that require valid addresses, an invalid address will not be accepted. `true` indicates the Address has been validated. `false` indicate the country doesn't require validation or the Address is not valid. + :ivar verified: Whether the address has been verified to comply with regulation. In countries that require valid addresses, an invalid address will not be accepted. `true` indicates the Address has been verified. `false` indicate the country doesn't require verified or the Address is not valid. + :ivar street_secondary: The additional number and street address of the address. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.city: Optional[str] = payload.get("city") + self.customer_name: Optional[str] = payload.get("customer_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.iso_country: Optional[str] = payload.get("iso_country") + self.postal_code: Optional[str] = payload.get("postal_code") + self.region: Optional[str] = payload.get("region") + self.sid: Optional[str] = payload.get("sid") + self.street: Optional[str] = payload.get("street") + self.uri: Optional[str] = payload.get("uri") + self.emergency_enabled: Optional[bool] = payload.get("emergency_enabled") + self.validated: Optional[bool] = payload.get("validated") + self.verified: Optional[bool] = payload.get("verified") + self.street_secondary: Optional[str] = payload.get("street_secondary") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[AddressContext] = None + + @property + def _proxy(self) -> "AddressContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AddressContext for this AddressInstance + """ + if self._context is None: + self._context = AddressContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AddressInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AddressInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AddressInstance": + """ + Fetch the AddressInstance + + + :returns: The fetched AddressInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AddressInstance": + """ + Asynchronous coroutine to fetch the AddressInstance + + + :returns: The fetched AddressInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + customer_name: Union[str, object] = values.unset, + street: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> "AddressInstance": + """ + Update the AddressInstance + + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param customer_name: The name to associate with the address. + :param street: The number and street address of the address. + :param city: The city of the address. + :param region: The state or region of the address. + :param postal_code: The postal code of the address. + :param emergency_enabled: Whether to enable emergency calling on the address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: The updated AddressInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + customer_name: Union[str, object] = values.unset, + street: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> "AddressInstance": + """ + Asynchronous coroutine to update the AddressInstance + + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param customer_name: The name to associate with the address. + :param street: The number and street address of the address. + :param city: The city of the address. + :param region: The state or region of the address. + :param postal_code: The postal code of the address. + :param emergency_enabled: Whether to enable emergency calling on the address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: The updated AddressInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) + + @property + def dependent_phone_numbers(self) -> DependentPhoneNumberList: + """ + Access the dependent_phone_numbers + """ + return self._proxy.dependent_phone_numbers + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AddressContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the AddressContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that is responsible for the Address resource to update. + :param sid: The Twilio-provided string that uniquely identifies the Address resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Addresses/{sid}.json".format( + **self._solution + ) + + self._dependent_phone_numbers: Optional[DependentPhoneNumberList] = None + + def delete(self) -> bool: + """ + Deletes the AddressInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AddressInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AddressInstance: + """ + Fetch the AddressInstance + + + :returns: The fetched AddressInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AddressInstance: + """ + Asynchronous coroutine to fetch the AddressInstance + + + :returns: The fetched AddressInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + customer_name: Union[str, object] = values.unset, + street: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> AddressInstance: + """ + Update the AddressInstance + + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param customer_name: The name to associate with the address. + :param street: The number and street address of the address. + :param city: The city of the address. + :param region: The state or region of the address. + :param postal_code: The postal code of the address. + :param emergency_enabled: Whether to enable emergency calling on the address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: The updated AddressInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "CustomerName": customer_name, + "Street": street, + "City": city, + "Region": region, + "PostalCode": postal_code, + "EmergencyEnabled": serialize.boolean_to_string(emergency_enabled), + "AutoCorrectAddress": serialize.boolean_to_string(auto_correct_address), + "StreetSecondary": street_secondary, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + customer_name: Union[str, object] = values.unset, + street: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> AddressInstance: + """ + Asynchronous coroutine to update the AddressInstance + + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param customer_name: The name to associate with the address. + :param street: The number and street address of the address. + :param city: The city of the address. + :param region: The state or region of the address. + :param postal_code: The postal code of the address. + :param emergency_enabled: Whether to enable emergency calling on the address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: The updated AddressInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "CustomerName": customer_name, + "Street": street, + "City": city, + "Region": region, + "PostalCode": postal_code, + "EmergencyEnabled": serialize.boolean_to_string(emergency_enabled), + "AutoCorrectAddress": serialize.boolean_to_string(auto_correct_address), + "StreetSecondary": street_secondary, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + @property + def dependent_phone_numbers(self) -> DependentPhoneNumberList: + """ + Access the dependent_phone_numbers + """ + if self._dependent_phone_numbers is None: + self._dependent_phone_numbers = DependentPhoneNumberList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._dependent_phone_numbers + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AddressPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AddressInstance: + """ + Build an instance of AddressInstance + + :param payload: Payload response from the API + """ + return AddressInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AddressList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the AddressList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that is responsible for the Address resource to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Addresses.json".format(**self._solution) + + def create( + self, + customer_name: str, + street: str, + city: str, + region: str, + postal_code: str, + iso_country: str, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> AddressInstance: + """ + Create the AddressInstance + + :param customer_name: The name to associate with the new address. + :param street: The number and street address of the new address. + :param city: The city of the new address. + :param region: The state or region of the new address. + :param postal_code: The postal code of the new address. + :param iso_country: The ISO country code of the new address. + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long. + :param emergency_enabled: Whether to enable emergency calling on the new address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: The created AddressInstance + """ + + data = values.of( + { + "CustomerName": customer_name, + "Street": street, + "City": city, + "Region": region, + "PostalCode": postal_code, + "IsoCountry": iso_country, + "FriendlyName": friendly_name, + "EmergencyEnabled": serialize.boolean_to_string(emergency_enabled), + "AutoCorrectAddress": serialize.boolean_to_string(auto_correct_address), + "StreetSecondary": street_secondary, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AddressInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, + customer_name: str, + street: str, + city: str, + region: str, + postal_code: str, + iso_country: str, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> AddressInstance: + """ + Asynchronously create the AddressInstance + + :param customer_name: The name to associate with the new address. + :param street: The number and street address of the new address. + :param city: The city of the new address. + :param region: The state or region of the new address. + :param postal_code: The postal code of the new address. + :param iso_country: The ISO country code of the new address. + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long. + :param emergency_enabled: Whether to enable emergency calling on the new address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: The created AddressInstance + """ + + data = values.of( + { + "CustomerName": customer_name, + "Street": street, + "City": city, + "Region": region, + "PostalCode": postal_code, + "IsoCountry": iso_country, + "FriendlyName": friendly_name, + "EmergencyEnabled": serialize.boolean_to_string(emergency_enabled), + "AutoCorrectAddress": serialize.boolean_to_string(auto_correct_address), + "StreetSecondary": street_secondary, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AddressInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + customer_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + iso_country: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AddressInstance]: + """ + Streams AddressInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str customer_name: The `customer_name` of the Address resources to read. + :param str friendly_name: The string that identifies the Address resources to read. + :param bool emergency_enabled: Whether the address can be associated to a number for emergency calling. + :param str iso_country: The ISO country code of the Address resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + customer_name=customer_name, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + iso_country=iso_country, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + customer_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + iso_country: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AddressInstance]: + """ + Asynchronously streams AddressInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str customer_name: The `customer_name` of the Address resources to read. + :param str friendly_name: The string that identifies the Address resources to read. + :param bool emergency_enabled: Whether the address can be associated to a number for emergency calling. + :param str iso_country: The ISO country code of the Address resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + customer_name=customer_name, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + iso_country=iso_country, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + customer_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + iso_country: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AddressInstance]: + """ + Lists AddressInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str customer_name: The `customer_name` of the Address resources to read. + :param str friendly_name: The string that identifies the Address resources to read. + :param bool emergency_enabled: Whether the address can be associated to a number for emergency calling. + :param str iso_country: The ISO country code of the Address resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + customer_name=customer_name, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + iso_country=iso_country, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + customer_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + iso_country: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AddressInstance]: + """ + Asynchronously lists AddressInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str customer_name: The `customer_name` of the Address resources to read. + :param str friendly_name: The string that identifies the Address resources to read. + :param bool emergency_enabled: Whether the address can be associated to a number for emergency calling. + :param str iso_country: The ISO country code of the Address resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + customer_name=customer_name, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + iso_country=iso_country, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + customer_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + iso_country: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AddressPage: + """ + Retrieve a single page of AddressInstance records from the API. + Request is executed immediately + + :param customer_name: The `customer_name` of the Address resources to read. + :param friendly_name: The string that identifies the Address resources to read. + :param emergency_enabled: Whether the address can be associated to a number for emergency calling. + :param iso_country: The ISO country code of the Address resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AddressInstance + """ + data = values.of( + { + "CustomerName": customer_name, + "FriendlyName": friendly_name, + "EmergencyEnabled": serialize.boolean_to_string(emergency_enabled), + "IsoCountry": iso_country, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AddressPage(self._version, response, self._solution) + + async def page_async( + self, + customer_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + iso_country: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AddressPage: + """ + Asynchronously retrieve a single page of AddressInstance records from the API. + Request is executed immediately + + :param customer_name: The `customer_name` of the Address resources to read. + :param friendly_name: The string that identifies the Address resources to read. + :param emergency_enabled: Whether the address can be associated to a number for emergency calling. + :param iso_country: The ISO country code of the Address resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AddressInstance + """ + data = values.of( + { + "CustomerName": customer_name, + "FriendlyName": friendly_name, + "EmergencyEnabled": serialize.boolean_to_string(emergency_enabled), + "IsoCountry": iso_country, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AddressPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AddressPage: + """ + Retrieve a specific page of AddressInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AddressInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AddressPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AddressPage: + """ + Asynchronously retrieve a specific page of AddressInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AddressInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AddressPage(self._version, response, self._solution) + + def get(self, sid: str) -> AddressContext: + """ + Constructs a AddressContext + + :param sid: The Twilio-provided string that uniquely identifies the Address resource to update. + """ + return AddressContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> AddressContext: + """ + Constructs a AddressContext + + :param sid: The Twilio-provided string that uniquely identifies the Address resource to update. + """ + return AddressContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/address/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/address/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..589d1646 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/address/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/address/__pycache__/dependent_phone_number.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/address/__pycache__/dependent_phone_number.cpython-312.pyc new file mode 100644 index 00000000..2e34a8ec Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/address/__pycache__/dependent_phone_number.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/address/dependent_phone_number.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/address/dependent_phone_number.py new file mode 100644 index 00000000..504e69bc --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/address/dependent_phone_number.py @@ -0,0 +1,374 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DependentPhoneNumberInstance(InstanceResource): + + class AddressRequirement(object): + NONE = "none" + ANY = "any" + LOCAL = "local" + FOREIGN = "foreign" + + class EmergencyStatus(object): + ACTIVE = "Active" + INACTIVE = "Inactive" + + """ + :ivar sid: The unique string that that we created to identify the DependentPhoneNumber resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the DependentPhoneNumber resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar voice_url: The URL we call when the phone number receives a call. The `voice_url` will not be used if a `voice_application_sid` or a `trunk_sid` is set. + :ivar voice_method: The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_method: The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_url: The URL that we call when an error occurs retrieving or executing the TwiML requested by `url`. + :ivar voice_caller_id_lookup: Whether we look up the caller's caller-ID name from the CNAM database. Can be: `true` or `false`. Caller ID lookups can cost $0.01 each. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar sms_fallback_method: The HTTP method we use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :ivar sms_fallback_url: The URL that we call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :ivar sms_method: The HTTP method we use to call `sms_url`. Can be: `GET` or `POST`. + :ivar sms_url: The URL we call when the phone number receives an incoming SMS message. + :ivar address_requirements: + :ivar capabilities: The set of Boolean properties that indicates whether a phone number can receive calls or messages. Capabilities are `Voice`, `SMS`, and `MMS` and each capability can be: `true` or `false`. + :ivar status_callback: The URL we call using the `status_callback_method` to send status information to your application. + :ivar status_callback_method: The HTTP method we use to call `status_callback`. Can be: `GET` or `POST`. + :ivar api_version: The API version used to start a new TwiML session. + :ivar sms_application_sid: The SID of the application that handles SMS messages sent to the phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :ivar voice_application_sid: The SID of the application that handles calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :ivar trunk_sid: The SID of the Trunk that handles calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :ivar emergency_status: + :ivar emergency_address_sid: The SID of the emergency address configuration that we use for emergency calling from the phone number. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + address_sid: str, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.phone_number: Optional[str] = payload.get("phone_number") + self.voice_url: Optional[str] = payload.get("voice_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_caller_id_lookup: Optional[bool] = payload.get( + "voice_caller_id_lookup" + ) + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.sms_fallback_method: Optional[str] = payload.get("sms_fallback_method") + self.sms_fallback_url: Optional[str] = payload.get("sms_fallback_url") + self.sms_method: Optional[str] = payload.get("sms_method") + self.sms_url: Optional[str] = payload.get("sms_url") + self.address_requirements: Optional[ + "DependentPhoneNumberInstance.AddressRequirement" + ] = payload.get("address_requirements") + self.capabilities: Optional[Dict[str, object]] = payload.get("capabilities") + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.api_version: Optional[str] = payload.get("api_version") + self.sms_application_sid: Optional[str] = payload.get("sms_application_sid") + self.voice_application_sid: Optional[str] = payload.get("voice_application_sid") + self.trunk_sid: Optional[str] = payload.get("trunk_sid") + self.emergency_status: Optional[ + "DependentPhoneNumberInstance.EmergencyStatus" + ] = payload.get("emergency_status") + self.emergency_address_sid: Optional[str] = payload.get("emergency_address_sid") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "address_sid": address_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DependentPhoneNumberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DependentPhoneNumberInstance: + """ + Build an instance of DependentPhoneNumberInstance + + :param payload: Payload response from the API + """ + return DependentPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + address_sid=self._solution["address_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class DependentPhoneNumberList(ListResource): + + def __init__(self, version: Version, account_sid: str, address_sid: str): + """ + Initialize the DependentPhoneNumberList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the DependentPhoneNumber resources to read. + :param address_sid: The SID of the Address resource associated with the phone number. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "address_sid": address_sid, + } + self._uri = "/Accounts/{account_sid}/Addresses/{address_sid}/DependentPhoneNumbers.json".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DependentPhoneNumberInstance]: + """ + Streams DependentPhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DependentPhoneNumberInstance]: + """ + Asynchronously streams DependentPhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DependentPhoneNumberInstance]: + """ + Lists DependentPhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DependentPhoneNumberInstance]: + """ + Asynchronously lists DependentPhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DependentPhoneNumberPage: + """ + Retrieve a single page of DependentPhoneNumberInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DependentPhoneNumberInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DependentPhoneNumberPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DependentPhoneNumberPage: + """ + Asynchronously retrieve a single page of DependentPhoneNumberInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DependentPhoneNumberInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DependentPhoneNumberPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DependentPhoneNumberPage: + """ + Retrieve a specific page of DependentPhoneNumberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DependentPhoneNumberInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DependentPhoneNumberPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DependentPhoneNumberPage: + """ + Asynchronously retrieve a specific page of DependentPhoneNumberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DependentPhoneNumberInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DependentPhoneNumberPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/application.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/application.py new file mode 100644 index 00000000..555ab72b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/application.py @@ -0,0 +1,984 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ApplicationInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Application resource. + :ivar api_version: The API version used to start a new TwiML session. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar message_status_callback: The URL we call using a POST method to send message status information to your application. + :ivar sid: The unique string that that we created to identify the Application resource. + :ivar sms_fallback_method: The HTTP method we use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :ivar sms_fallback_url: The URL that we call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :ivar sms_method: The HTTP method we use to call `sms_url`. Can be: `GET` or `POST`. + :ivar sms_status_callback: The URL we call using a POST method to send status information to your application about SMS messages that refer to the application. + :ivar sms_url: The URL we call when the phone number receives an incoming SMS message. + :ivar status_callback: The URL we call using the `status_callback_method` to send status information to your application. + :ivar status_callback_method: The HTTP method we use to call `status_callback`. Can be: `GET` or `POST`. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar voice_caller_id_lookup: Whether we look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :ivar voice_fallback_method: The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_url: The URL that we call when an error occurs retrieving or executing the TwiML requested by `url`. + :ivar voice_method: The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + :ivar voice_url: The URL we call when the phone number assigned to this application receives a call. + :ivar public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.message_status_callback: Optional[str] = payload.get( + "message_status_callback" + ) + self.sid: Optional[str] = payload.get("sid") + self.sms_fallback_method: Optional[str] = payload.get("sms_fallback_method") + self.sms_fallback_url: Optional[str] = payload.get("sms_fallback_url") + self.sms_method: Optional[str] = payload.get("sms_method") + self.sms_status_callback: Optional[str] = payload.get("sms_status_callback") + self.sms_url: Optional[str] = payload.get("sms_url") + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.uri: Optional[str] = payload.get("uri") + self.voice_caller_id_lookup: Optional[bool] = payload.get( + "voice_caller_id_lookup" + ) + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_url: Optional[str] = payload.get("voice_url") + self.public_application_connect_enabled: Optional[bool] = payload.get( + "public_application_connect_enabled" + ) + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[ApplicationContext] = None + + @property + def _proxy(self) -> "ApplicationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ApplicationContext for this ApplicationInstance + """ + if self._context is None: + self._context = ApplicationContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ApplicationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ApplicationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ApplicationInstance": + """ + Fetch the ApplicationInstance + + + :returns: The fetched ApplicationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ApplicationInstance": + """ + Asynchronous coroutine to fetch the ApplicationInstance + + + :returns: The fetched ApplicationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> "ApplicationInstance": + """ + Update the ApplicationInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is your account's default API version. + :param voice_url: The URL we should call when the phone number assigned to this application receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. + :param voice_caller_id_lookup: Whether we should look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :param sms_status_callback: Same as message_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. Deprecated, included for backwards compatibility. + :param message_status_callback: The URL we should call using a POST method to send message status information to your application. + :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + + :returns: The updated ApplicationInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + api_version=api_version, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_caller_id_lookup=voice_caller_id_lookup, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + sms_status_callback=sms_status_callback, + message_status_callback=message_status_callback, + public_application_connect_enabled=public_application_connect_enabled, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> "ApplicationInstance": + """ + Asynchronous coroutine to update the ApplicationInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is your account's default API version. + :param voice_url: The URL we should call when the phone number assigned to this application receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. + :param voice_caller_id_lookup: Whether we should look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :param sms_status_callback: Same as message_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. Deprecated, included for backwards compatibility. + :param message_status_callback: The URL we should call using a POST method to send message status information to your application. + :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + + :returns: The updated ApplicationInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + api_version=api_version, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_caller_id_lookup=voice_caller_id_lookup, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + sms_status_callback=sms_status_callback, + message_status_callback=message_status_callback, + public_application_connect_enabled=public_application_connect_enabled, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ApplicationContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the ApplicationContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Application resources to update. + :param sid: The Twilio-provided string that uniquely identifies the Application resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Applications/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the ApplicationInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ApplicationInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ApplicationInstance: + """ + Fetch the ApplicationInstance + + + :returns: The fetched ApplicationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ApplicationInstance: + """ + Asynchronous coroutine to fetch the ApplicationInstance + + + :returns: The fetched ApplicationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> ApplicationInstance: + """ + Update the ApplicationInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is your account's default API version. + :param voice_url: The URL we should call when the phone number assigned to this application receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. + :param voice_caller_id_lookup: Whether we should look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :param sms_status_callback: Same as message_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. Deprecated, included for backwards compatibility. + :param message_status_callback: The URL we should call using a POST method to send message status information to your application. + :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + + :returns: The updated ApplicationInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ApiVersion": api_version, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsStatusCallback": sms_status_callback, + "MessageStatusCallback": message_status_callback, + "PublicApplicationConnectEnabled": serialize.boolean_to_string( + public_application_connect_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> ApplicationInstance: + """ + Asynchronous coroutine to update the ApplicationInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is your account's default API version. + :param voice_url: The URL we should call when the phone number assigned to this application receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. + :param voice_caller_id_lookup: Whether we should look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :param sms_status_callback: Same as message_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. Deprecated, included for backwards compatibility. + :param message_status_callback: The URL we should call using a POST method to send message status information to your application. + :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + + :returns: The updated ApplicationInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ApiVersion": api_version, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsStatusCallback": sms_status_callback, + "MessageStatusCallback": message_status_callback, + "PublicApplicationConnectEnabled": serialize.boolean_to_string( + public_application_connect_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ApplicationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ApplicationInstance: + """ + Build an instance of ApplicationInstance + + :param payload: Payload response from the API + """ + return ApplicationInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ApplicationList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the ApplicationList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Application resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Applications.json".format(**self._solution) + + def create( + self, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> ApplicationInstance: + """ + Create the ApplicationInstance + + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is the account's default API version. + :param voice_url: The URL we should call when the phone number assigned to this application receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. + :param voice_caller_id_lookup: Whether we should look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :param sms_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. + :param message_status_callback: The URL we should call using a POST method to send message status information to your application. + :param friendly_name: A descriptive string that you create to describe the new application. It can be up to 64 characters long. + :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + + :returns: The created ApplicationInstance + """ + + data = values.of( + { + "ApiVersion": api_version, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsStatusCallback": sms_status_callback, + "MessageStatusCallback": message_status_callback, + "FriendlyName": friendly_name, + "PublicApplicationConnectEnabled": serialize.boolean_to_string( + public_application_connect_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ApplicationInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> ApplicationInstance: + """ + Asynchronously create the ApplicationInstance + + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is the account's default API version. + :param voice_url: The URL we should call when the phone number assigned to this application receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. + :param voice_caller_id_lookup: Whether we should look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :param sms_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. + :param message_status_callback: The URL we should call using a POST method to send message status information to your application. + :param friendly_name: A descriptive string that you create to describe the new application. It can be up to 64 characters long. + :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + + :returns: The created ApplicationInstance + """ + + data = values.of( + { + "ApiVersion": api_version, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsStatusCallback": sms_status_callback, + "MessageStatusCallback": message_status_callback, + "FriendlyName": friendly_name, + "PublicApplicationConnectEnabled": serialize.boolean_to_string( + public_application_connect_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ApplicationInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ApplicationInstance]: + """ + Streams ApplicationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The string that identifies the Application resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(friendly_name=friendly_name, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ApplicationInstance]: + """ + Asynchronously streams ApplicationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The string that identifies the Application resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ApplicationInstance]: + """ + Lists ApplicationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The string that identifies the Application resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ApplicationInstance]: + """ + Asynchronously lists ApplicationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The string that identifies the Application resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApplicationPage: + """ + Retrieve a single page of ApplicationInstance records from the API. + Request is executed immediately + + :param friendly_name: The string that identifies the Application resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ApplicationInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ApplicationPage(self._version, response, self._solution) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApplicationPage: + """ + Asynchronously retrieve a single page of ApplicationInstance records from the API. + Request is executed immediately + + :param friendly_name: The string that identifies the Application resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ApplicationInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ApplicationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ApplicationPage: + """ + Retrieve a specific page of ApplicationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ApplicationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ApplicationPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ApplicationPage: + """ + Asynchronously retrieve a specific page of ApplicationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ApplicationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ApplicationPage(self._version, response, self._solution) + + def get(self, sid: str) -> ApplicationContext: + """ + Constructs a ApplicationContext + + :param sid: The Twilio-provided string that uniquely identifies the Application resource to update. + """ + return ApplicationContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ApplicationContext: + """ + Constructs a ApplicationContext + + :param sid: The Twilio-provided string that uniquely identifies the Application resource to update. + """ + return ApplicationContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/authorized_connect_app.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/authorized_connect_app.py new file mode 100644 index 00000000..cceb694c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/authorized_connect_app.py @@ -0,0 +1,458 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AuthorizedConnectAppInstance(InstanceResource): + + class Permission(object): + GET_ALL = "get-all" + POST_ALL = "post-all" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AuthorizedConnectApp resource. + :ivar connect_app_company_name: The company name set for the Connect App. + :ivar connect_app_description: A detailed description of the Connect App. + :ivar connect_app_friendly_name: The name of the Connect App. + :ivar connect_app_homepage_url: The public URL for the Connect App. + :ivar connect_app_sid: The SID that we assigned to the Connect App. + :ivar permissions: The set of permissions that you authorized for the Connect App. Can be: `get-all` or `post-all`. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + connect_app_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.connect_app_company_name: Optional[str] = payload.get( + "connect_app_company_name" + ) + self.connect_app_description: Optional[str] = payload.get( + "connect_app_description" + ) + self.connect_app_friendly_name: Optional[str] = payload.get( + "connect_app_friendly_name" + ) + self.connect_app_homepage_url: Optional[str] = payload.get( + "connect_app_homepage_url" + ) + self.connect_app_sid: Optional[str] = payload.get("connect_app_sid") + self.permissions: Optional[List["AuthorizedConnectAppInstance.Permission"]] = ( + payload.get("permissions") + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "connect_app_sid": connect_app_sid or self.connect_app_sid, + } + self._context: Optional[AuthorizedConnectAppContext] = None + + @property + def _proxy(self) -> "AuthorizedConnectAppContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AuthorizedConnectAppContext for this AuthorizedConnectAppInstance + """ + if self._context is None: + self._context = AuthorizedConnectAppContext( + self._version, + account_sid=self._solution["account_sid"], + connect_app_sid=self._solution["connect_app_sid"], + ) + return self._context + + def fetch(self) -> "AuthorizedConnectAppInstance": + """ + Fetch the AuthorizedConnectAppInstance + + + :returns: The fetched AuthorizedConnectAppInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AuthorizedConnectAppInstance": + """ + Asynchronous coroutine to fetch the AuthorizedConnectAppInstance + + + :returns: The fetched AuthorizedConnectAppInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AuthorizedConnectAppContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, connect_app_sid: str): + """ + Initialize the AuthorizedConnectAppContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AuthorizedConnectApp resource to fetch. + :param connect_app_sid: The SID of the Connect App to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "connect_app_sid": connect_app_sid, + } + self._uri = "/Accounts/{account_sid}/AuthorizedConnectApps/{connect_app_sid}.json".format( + **self._solution + ) + + def fetch(self) -> AuthorizedConnectAppInstance: + """ + Fetch the AuthorizedConnectAppInstance + + + :returns: The fetched AuthorizedConnectAppInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AuthorizedConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + connect_app_sid=self._solution["connect_app_sid"], + ) + + async def fetch_async(self) -> AuthorizedConnectAppInstance: + """ + Asynchronous coroutine to fetch the AuthorizedConnectAppInstance + + + :returns: The fetched AuthorizedConnectAppInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AuthorizedConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + connect_app_sid=self._solution["connect_app_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AuthorizedConnectAppPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AuthorizedConnectAppInstance: + """ + Build an instance of AuthorizedConnectAppInstance + + :param payload: Payload response from the API + """ + return AuthorizedConnectAppInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AuthorizedConnectAppList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the AuthorizedConnectAppList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AuthorizedConnectApp resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/AuthorizedConnectApps.json".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AuthorizedConnectAppInstance]: + """ + Streams AuthorizedConnectAppInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AuthorizedConnectAppInstance]: + """ + Asynchronously streams AuthorizedConnectAppInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthorizedConnectAppInstance]: + """ + Lists AuthorizedConnectAppInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthorizedConnectAppInstance]: + """ + Asynchronously lists AuthorizedConnectAppInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AuthorizedConnectAppPage: + """ + Retrieve a single page of AuthorizedConnectAppInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AuthorizedConnectAppInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthorizedConnectAppPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AuthorizedConnectAppPage: + """ + Asynchronously retrieve a single page of AuthorizedConnectAppInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AuthorizedConnectAppInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthorizedConnectAppPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AuthorizedConnectAppPage: + """ + Retrieve a specific page of AuthorizedConnectAppInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthorizedConnectAppInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AuthorizedConnectAppPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AuthorizedConnectAppPage: + """ + Asynchronously retrieve a specific page of AuthorizedConnectAppInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthorizedConnectAppInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AuthorizedConnectAppPage(self._version, response, self._solution) + + def get(self, connect_app_sid: str) -> AuthorizedConnectAppContext: + """ + Constructs a AuthorizedConnectAppContext + + :param connect_app_sid: The SID of the Connect App to fetch. + """ + return AuthorizedConnectAppContext( + self._version, + account_sid=self._solution["account_sid"], + connect_app_sid=connect_app_sid, + ) + + def __call__(self, connect_app_sid: str) -> AuthorizedConnectAppContext: + """ + Constructs a AuthorizedConnectAppContext + + :param connect_app_sid: The SID of the Connect App to fetch. + """ + return AuthorizedConnectAppContext( + self._version, + account_sid=self._solution["account_sid"], + connect_app_sid=connect_app_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__init__.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__init__.py new file mode 100644 index 00000000..fc2a6f06 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__init__.py @@ -0,0 +1,612 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.available_phone_number_country.local import LocalList +from twilio.rest.api.v2010.account.available_phone_number_country.machine_to_machine import ( + MachineToMachineList, +) +from twilio.rest.api.v2010.account.available_phone_number_country.mobile import ( + MobileList, +) +from twilio.rest.api.v2010.account.available_phone_number_country.national import ( + NationalList, +) +from twilio.rest.api.v2010.account.available_phone_number_country.shared_cost import ( + SharedCostList, +) +from twilio.rest.api.v2010.account.available_phone_number_country.toll_free import ( + TollFreeList, +) +from twilio.rest.api.v2010.account.available_phone_number_country.voip import VoipList + + +class AvailablePhoneNumberCountryInstance(InstanceResource): + """ + :ivar country_code: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country. + :ivar country: The name of the country. + :ivar uri: The URI of the Country resource, relative to `https://api.twilio.com`. + :ivar beta: Whether all phone numbers available in the country are new to the Twilio platform. `true` if they are and `false` if all numbers are not in the Twilio Phone Number Beta program. + :ivar subresource_uris: A list of related AvailablePhoneNumber resources identified by their URIs relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + country_code: Optional[str] = None, + ): + super().__init__(version) + + self.country_code: Optional[str] = payload.get("country_code") + self.country: Optional[str] = payload.get("country") + self.uri: Optional[str] = payload.get("uri") + self.beta: Optional[bool] = payload.get("beta") + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + + self._solution = { + "account_sid": account_sid, + "country_code": country_code or self.country_code, + } + self._context: Optional[AvailablePhoneNumberCountryContext] = None + + @property + def _proxy(self) -> "AvailablePhoneNumberCountryContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AvailablePhoneNumberCountryContext for this AvailablePhoneNumberCountryInstance + """ + if self._context is None: + self._context = AvailablePhoneNumberCountryContext( + self._version, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + return self._context + + def fetch(self) -> "AvailablePhoneNumberCountryInstance": + """ + Fetch the AvailablePhoneNumberCountryInstance + + + :returns: The fetched AvailablePhoneNumberCountryInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AvailablePhoneNumberCountryInstance": + """ + Asynchronous coroutine to fetch the AvailablePhoneNumberCountryInstance + + + :returns: The fetched AvailablePhoneNumberCountryInstance + """ + return await self._proxy.fetch_async() + + @property + def local(self) -> LocalList: + """ + Access the local + """ + return self._proxy.local + + @property + def machine_to_machine(self) -> MachineToMachineList: + """ + Access the machine_to_machine + """ + return self._proxy.machine_to_machine + + @property + def mobile(self) -> MobileList: + """ + Access the mobile + """ + return self._proxy.mobile + + @property + def national(self) -> NationalList: + """ + Access the national + """ + return self._proxy.national + + @property + def shared_cost(self) -> SharedCostList: + """ + Access the shared_cost + """ + return self._proxy.shared_cost + + @property + def toll_free(self) -> TollFreeList: + """ + Access the toll_free + """ + return self._proxy.toll_free + + @property + def voip(self) -> VoipList: + """ + Access the voip + """ + return self._proxy.voip + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class AvailablePhoneNumberCountryContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, country_code: str): + """ + Initialize the AvailablePhoneNumberCountryContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) requesting the available phone number Country resource. + :param country_code: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country to fetch available phone number information about. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + self._uri = ( + "/Accounts/{account_sid}/AvailablePhoneNumbers/{country_code}.json".format( + **self._solution + ) + ) + + self._local: Optional[LocalList] = None + self._machine_to_machine: Optional[MachineToMachineList] = None + self._mobile: Optional[MobileList] = None + self._national: Optional[NationalList] = None + self._shared_cost: Optional[SharedCostList] = None + self._toll_free: Optional[TollFreeList] = None + self._voip: Optional[VoipList] = None + + def fetch(self) -> AvailablePhoneNumberCountryInstance: + """ + Fetch the AvailablePhoneNumberCountryInstance + + + :returns: The fetched AvailablePhoneNumberCountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AvailablePhoneNumberCountryInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + + async def fetch_async(self) -> AvailablePhoneNumberCountryInstance: + """ + Asynchronous coroutine to fetch the AvailablePhoneNumberCountryInstance + + + :returns: The fetched AvailablePhoneNumberCountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AvailablePhoneNumberCountryInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + + @property + def local(self) -> LocalList: + """ + Access the local + """ + if self._local is None: + self._local = LocalList( + self._version, + self._solution["account_sid"], + self._solution["country_code"], + ) + return self._local + + @property + def machine_to_machine(self) -> MachineToMachineList: + """ + Access the machine_to_machine + """ + if self._machine_to_machine is None: + self._machine_to_machine = MachineToMachineList( + self._version, + self._solution["account_sid"], + self._solution["country_code"], + ) + return self._machine_to_machine + + @property + def mobile(self) -> MobileList: + """ + Access the mobile + """ + if self._mobile is None: + self._mobile = MobileList( + self._version, + self._solution["account_sid"], + self._solution["country_code"], + ) + return self._mobile + + @property + def national(self) -> NationalList: + """ + Access the national + """ + if self._national is None: + self._national = NationalList( + self._version, + self._solution["account_sid"], + self._solution["country_code"], + ) + return self._national + + @property + def shared_cost(self) -> SharedCostList: + """ + Access the shared_cost + """ + if self._shared_cost is None: + self._shared_cost = SharedCostList( + self._version, + self._solution["account_sid"], + self._solution["country_code"], + ) + return self._shared_cost + + @property + def toll_free(self) -> TollFreeList: + """ + Access the toll_free + """ + if self._toll_free is None: + self._toll_free = TollFreeList( + self._version, + self._solution["account_sid"], + self._solution["country_code"], + ) + return self._toll_free + + @property + def voip(self) -> VoipList: + """ + Access the voip + """ + if self._voip is None: + self._voip = VoipList( + self._version, + self._solution["account_sid"], + self._solution["country_code"], + ) + return self._voip + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class AvailablePhoneNumberCountryPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> AvailablePhoneNumberCountryInstance: + """ + Build an instance of AvailablePhoneNumberCountryInstance + + :param payload: Payload response from the API + """ + return AvailablePhoneNumberCountryInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AvailablePhoneNumberCountryList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the AvailablePhoneNumberCountryList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) requesting the available phone number Country resources. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/AvailablePhoneNumbers.json".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AvailablePhoneNumberCountryInstance]: + """ + Streams AvailablePhoneNumberCountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AvailablePhoneNumberCountryInstance]: + """ + Asynchronously streams AvailablePhoneNumberCountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailablePhoneNumberCountryInstance]: + """ + Lists AvailablePhoneNumberCountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailablePhoneNumberCountryInstance]: + """ + Asynchronously lists AvailablePhoneNumberCountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AvailablePhoneNumberCountryPage: + """ + Retrieve a single page of AvailablePhoneNumberCountryInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AvailablePhoneNumberCountryInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailablePhoneNumberCountryPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AvailablePhoneNumberCountryPage: + """ + Asynchronously retrieve a single page of AvailablePhoneNumberCountryInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AvailablePhoneNumberCountryInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailablePhoneNumberCountryPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AvailablePhoneNumberCountryPage: + """ + Retrieve a specific page of AvailablePhoneNumberCountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailablePhoneNumberCountryInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AvailablePhoneNumberCountryPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AvailablePhoneNumberCountryPage: + """ + Asynchronously retrieve a specific page of AvailablePhoneNumberCountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailablePhoneNumberCountryInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AvailablePhoneNumberCountryPage(self._version, response, self._solution) + + def get(self, country_code: str) -> AvailablePhoneNumberCountryContext: + """ + Constructs a AvailablePhoneNumberCountryContext + + :param country_code: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country to fetch available phone number information about. + """ + return AvailablePhoneNumberCountryContext( + self._version, + account_sid=self._solution["account_sid"], + country_code=country_code, + ) + + def __call__(self, country_code: str) -> AvailablePhoneNumberCountryContext: + """ + Constructs a AvailablePhoneNumberCountryContext + + :param country_code: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country to fetch available phone number information about. + """ + return AvailablePhoneNumberCountryContext( + self._version, + account_sid=self._solution["account_sid"], + country_code=country_code, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..2760af69 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/local.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/local.cpython-312.pyc new file mode 100644 index 00000000..f1dadf36 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/local.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/machine_to_machine.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/machine_to_machine.cpython-312.pyc new file mode 100644 index 00000000..e97b523d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/machine_to_machine.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/mobile.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/mobile.cpython-312.pyc new file mode 100644 index 00000000..c8f30665 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/mobile.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/national.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/national.cpython-312.pyc new file mode 100644 index 00000000..4205f515 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/national.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/shared_cost.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/shared_cost.cpython-312.pyc new file mode 100644 index 00000000..cf71637e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/shared_cost.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/toll_free.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/toll_free.cpython-312.pyc new file mode 100644 index 00000000..b0b85e3f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/toll_free.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/voip.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/voip.cpython-312.pyc new file mode 100644 index 00000000..cd145b76 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/__pycache__/voip.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/local.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/local.py new file mode 100644 index 00000000..4f0b2e79 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/local.py @@ -0,0 +1,664 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class LocalInstance(InstanceResource): + """ + :ivar friendly_name: A formatted version of the phone number. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar lata: The [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) of this phone number. Available for only phone numbers from the US and Canada. + :ivar locality: The locality or city of this phone number's location. + :ivar rate_center: The [rate center](https://en.wikipedia.org/wiki/Telephone_exchange) of this phone number. Available for only phone numbers from the US and Canada. + :ivar latitude: The latitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar longitude: The longitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar region: The two-letter state or province abbreviation of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar postal_code: The postal or ZIP code of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of this phone number. + :ivar address_requirements: The type of [Address](https://www.twilio.com/docs/usage/api/address) resource the phone number requires. Can be: `none`, `any`, `local`, or `foreign`. `none` means no address is required. `any` means an address is required, but it can be anywhere in the world. `local` means an address in the phone number's country is required. `foreign` means an address outside of the phone number's country is required. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + country_code: str, + ): + super().__init__(version) + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.phone_number: Optional[str] = payload.get("phone_number") + self.lata: Optional[str] = payload.get("lata") + self.locality: Optional[str] = payload.get("locality") + self.rate_center: Optional[str] = payload.get("rate_center") + self.latitude: Optional[float] = deserialize.decimal(payload.get("latitude")) + self.longitude: Optional[float] = deserialize.decimal(payload.get("longitude")) + self.region: Optional[str] = payload.get("region") + self.postal_code: Optional[str] = payload.get("postal_code") + self.iso_country: Optional[str] = payload.get("iso_country") + self.address_requirements: Optional[str] = payload.get("address_requirements") + self.beta: Optional[bool] = payload.get("beta") + self.capabilities: Optional[str] = payload.get("capabilities") + + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class LocalPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> LocalInstance: + """ + Build an instance of LocalInstance + + :param payload: Payload response from the API + """ + return LocalInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class LocalList(ListResource): + + def __init__(self, version: Version, account_sid: str, country_code: str): + """ + Initialize the LocalList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) requesting the AvailablePhoneNumber resources. + :param country_code: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country from which to read phone numbers. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + self._uri = "/Accounts/{account_sid}/AvailablePhoneNumbers/{country_code}/Local.json".format( + **self._solution + ) + + def stream( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[LocalInstance]: + """ + Streams LocalInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-number-pattern) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-character-pattern). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[LocalInstance]: + """ + Asynchronously streams LocalInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-number-pattern) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-character-pattern). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[LocalInstance]: + """ + Lists LocalInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-number-pattern) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-character-pattern). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[LocalInstance]: + """ + Asynchronously lists LocalInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-number-pattern) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-character-pattern). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> LocalPage: + """ + Retrieve a single page of LocalInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-number-pattern) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-character-pattern). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of LocalInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LocalPage(self._version, response, self._solution) + + async def page_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> LocalPage: + """ + Asynchronously retrieve a single page of LocalInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-number-pattern) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-character-pattern). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of LocalInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LocalPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> LocalPage: + """ + Retrieve a specific page of LocalInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of LocalInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return LocalPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> LocalPage: + """ + Asynchronously retrieve a specific page of LocalInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of LocalInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return LocalPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/machine_to_machine.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/machine_to_machine.py new file mode 100644 index 00000000..5695c917 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/machine_to_machine.py @@ -0,0 +1,664 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MachineToMachineInstance(InstanceResource): + """ + :ivar friendly_name: A formatted version of the phone number. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar lata: The [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) of this phone number. Available for only phone numbers from the US and Canada. + :ivar locality: The locality or city of this phone number's location. + :ivar rate_center: The [rate center](https://en.wikipedia.org/wiki/Telephone_exchange) of this phone number. Available for only phone numbers from the US and Canada. + :ivar latitude: The latitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar longitude: The longitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar region: The two-letter state or province abbreviation of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar postal_code: The postal or ZIP code of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of this phone number. + :ivar address_requirements: The type of [Address](https://www.twilio.com/docs/usage/api/address) resource the phone number requires. Can be: `none`, `any`, `local`, or `foreign`. `none` means no address is required. `any` means an address is required, but it can be anywhere in the world. `local` means an address in the phone number's country is required. `foreign` means an address outside of the phone number's country is required. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + country_code: str, + ): + super().__init__(version) + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.phone_number: Optional[str] = payload.get("phone_number") + self.lata: Optional[str] = payload.get("lata") + self.locality: Optional[str] = payload.get("locality") + self.rate_center: Optional[str] = payload.get("rate_center") + self.latitude: Optional[float] = deserialize.decimal(payload.get("latitude")) + self.longitude: Optional[float] = deserialize.decimal(payload.get("longitude")) + self.region: Optional[str] = payload.get("region") + self.postal_code: Optional[str] = payload.get("postal_code") + self.iso_country: Optional[str] = payload.get("iso_country") + self.address_requirements: Optional[str] = payload.get("address_requirements") + self.beta: Optional[bool] = payload.get("beta") + self.capabilities: Optional[str] = payload.get("capabilities") + + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MachineToMachinePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MachineToMachineInstance: + """ + Build an instance of MachineToMachineInstance + + :param payload: Payload response from the API + """ + return MachineToMachineInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MachineToMachineList(ListResource): + + def __init__(self, version: Version, account_sid: str, country_code: str): + """ + Initialize the MachineToMachineList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) requesting the AvailablePhoneNumber resources. + :param country_code: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country from which to read phone numbers. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + self._uri = "/Accounts/{account_sid}/AvailablePhoneNumbers/{country_code}/MachineToMachine.json".format( + **self._solution + ) + + def stream( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MachineToMachineInstance]: + """ + Streams MachineToMachineInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MachineToMachineInstance]: + """ + Asynchronously streams MachineToMachineInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MachineToMachineInstance]: + """ + Lists MachineToMachineInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MachineToMachineInstance]: + """ + Asynchronously lists MachineToMachineInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MachineToMachinePage: + """ + Retrieve a single page of MachineToMachineInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MachineToMachineInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MachineToMachinePage(self._version, response, self._solution) + + async def page_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MachineToMachinePage: + """ + Asynchronously retrieve a single page of MachineToMachineInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MachineToMachineInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MachineToMachinePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MachineToMachinePage: + """ + Retrieve a specific page of MachineToMachineInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MachineToMachineInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MachineToMachinePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MachineToMachinePage: + """ + Asynchronously retrieve a specific page of MachineToMachineInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MachineToMachineInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MachineToMachinePage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/mobile.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/mobile.py new file mode 100644 index 00000000..2382155e --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/mobile.py @@ -0,0 +1,664 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MobileInstance(InstanceResource): + """ + :ivar friendly_name: A formatted version of the phone number. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar lata: The [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) of this phone number. Available for only phone numbers from the US and Canada. + :ivar locality: The locality or city of this phone number's location. + :ivar rate_center: The [rate center](https://en.wikipedia.org/wiki/Telephone_exchange) of this phone number. Available for only phone numbers from the US and Canada. + :ivar latitude: The latitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar longitude: The longitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar region: The two-letter state or province abbreviation of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar postal_code: The postal or ZIP code of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of this phone number. + :ivar address_requirements: The type of [Address](https://www.twilio.com/docs/usage/api/address) resource the phone number requires. Can be: `none`, `any`, `local`, or `foreign`. `none` means no address is required. `any` means an address is required, but it can be anywhere in the world. `local` means an address in the phone number's country is required. `foreign` means an address outside of the phone number's country is required. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + country_code: str, + ): + super().__init__(version) + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.phone_number: Optional[str] = payload.get("phone_number") + self.lata: Optional[str] = payload.get("lata") + self.locality: Optional[str] = payload.get("locality") + self.rate_center: Optional[str] = payload.get("rate_center") + self.latitude: Optional[float] = deserialize.decimal(payload.get("latitude")) + self.longitude: Optional[float] = deserialize.decimal(payload.get("longitude")) + self.region: Optional[str] = payload.get("region") + self.postal_code: Optional[str] = payload.get("postal_code") + self.iso_country: Optional[str] = payload.get("iso_country") + self.address_requirements: Optional[str] = payload.get("address_requirements") + self.beta: Optional[bool] = payload.get("beta") + self.capabilities: Optional[str] = payload.get("capabilities") + + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MobilePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MobileInstance: + """ + Build an instance of MobileInstance + + :param payload: Payload response from the API + """ + return MobileInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MobileList(ListResource): + + def __init__(self, version: Version, account_sid: str, country_code: str): + """ + Initialize the MobileList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) requesting the AvailablePhoneNumber resources. + :param country_code: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country from which to read phone numbers. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + self._uri = "/Accounts/{account_sid}/AvailablePhoneNumbers/{country_code}/Mobile.json".format( + **self._solution + ) + + def stream( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MobileInstance]: + """ + Streams MobileInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MobileInstance]: + """ + Asynchronously streams MobileInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MobileInstance]: + """ + Lists MobileInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MobileInstance]: + """ + Asynchronously lists MobileInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MobilePage: + """ + Retrieve a single page of MobileInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MobileInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MobilePage(self._version, response, self._solution) + + async def page_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MobilePage: + """ + Asynchronously retrieve a single page of MobileInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MobileInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MobilePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MobilePage: + """ + Retrieve a specific page of MobileInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MobileInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MobilePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MobilePage: + """ + Asynchronously retrieve a specific page of MobileInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MobileInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MobilePage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/national.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/national.py new file mode 100644 index 00000000..a5e92642 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/national.py @@ -0,0 +1,664 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class NationalInstance(InstanceResource): + """ + :ivar friendly_name: A formatted version of the phone number. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar lata: The [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) of this phone number. Available for only phone numbers from the US and Canada. + :ivar locality: The locality or city of this phone number's location. + :ivar rate_center: The [rate center](https://en.wikipedia.org/wiki/Telephone_exchange) of this phone number. Available for only phone numbers from the US and Canada. + :ivar latitude: The latitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar longitude: The longitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar region: The two-letter state or province abbreviation of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar postal_code: The postal or ZIP code of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of this phone number. + :ivar address_requirements: The type of [Address](https://www.twilio.com/docs/usage/api/address) resource the phone number requires. Can be: `none`, `any`, `local`, or `foreign`. `none` means no address is required. `any` means an address is required, but it can be anywhere in the world. `local` means an address in the phone number's country is required. `foreign` means an address outside of the phone number's country is required. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + country_code: str, + ): + super().__init__(version) + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.phone_number: Optional[str] = payload.get("phone_number") + self.lata: Optional[str] = payload.get("lata") + self.locality: Optional[str] = payload.get("locality") + self.rate_center: Optional[str] = payload.get("rate_center") + self.latitude: Optional[float] = deserialize.decimal(payload.get("latitude")) + self.longitude: Optional[float] = deserialize.decimal(payload.get("longitude")) + self.region: Optional[str] = payload.get("region") + self.postal_code: Optional[str] = payload.get("postal_code") + self.iso_country: Optional[str] = payload.get("iso_country") + self.address_requirements: Optional[str] = payload.get("address_requirements") + self.beta: Optional[bool] = payload.get("beta") + self.capabilities: Optional[str] = payload.get("capabilities") + + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NationalPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> NationalInstance: + """ + Build an instance of NationalInstance + + :param payload: Payload response from the API + """ + return NationalInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class NationalList(ListResource): + + def __init__(self, version: Version, account_sid: str, country_code: str): + """ + Initialize the NationalList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) requesting the AvailablePhoneNumber resources. + :param country_code: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country from which to read phone numbers. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + self._uri = "/Accounts/{account_sid}/AvailablePhoneNumbers/{country_code}/National.json".format( + **self._solution + ) + + def stream( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[NationalInstance]: + """ + Streams NationalInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[NationalInstance]: + """ + Asynchronously streams NationalInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NationalInstance]: + """ + Lists NationalInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NationalInstance]: + """ + Asynchronously lists NationalInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NationalPage: + """ + Retrieve a single page of NationalInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NationalInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NationalPage(self._version, response, self._solution) + + async def page_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NationalPage: + """ + Asynchronously retrieve a single page of NationalInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NationalInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NationalPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> NationalPage: + """ + Retrieve a specific page of NationalInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NationalInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return NationalPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> NationalPage: + """ + Asynchronously retrieve a specific page of NationalInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NationalInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return NationalPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/shared_cost.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/shared_cost.py new file mode 100644 index 00000000..3a9c02ba --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/shared_cost.py @@ -0,0 +1,664 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SharedCostInstance(InstanceResource): + """ + :ivar friendly_name: A formatted version of the phone number. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar lata: The [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) of this phone number. Available for only phone numbers from the US and Canada. + :ivar locality: The locality or city of this phone number's location. + :ivar rate_center: The [rate center](https://en.wikipedia.org/wiki/Telephone_exchange) of this phone number. Available for only phone numbers from the US and Canada. + :ivar latitude: The latitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar longitude: The longitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar region: The two-letter state or province abbreviation of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar postal_code: The postal or ZIP code of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of this phone number. + :ivar address_requirements: The type of [Address](https://www.twilio.com/docs/usage/api/address) resource the phone number requires. Can be: `none`, `any`, `local`, or `foreign`. `none` means no address is required. `any` means an address is required, but it can be anywhere in the world. `local` means an address in the phone number's country is required. `foreign` means an address outside of the phone number's country is required. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + country_code: str, + ): + super().__init__(version) + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.phone_number: Optional[str] = payload.get("phone_number") + self.lata: Optional[str] = payload.get("lata") + self.locality: Optional[str] = payload.get("locality") + self.rate_center: Optional[str] = payload.get("rate_center") + self.latitude: Optional[float] = deserialize.decimal(payload.get("latitude")) + self.longitude: Optional[float] = deserialize.decimal(payload.get("longitude")) + self.region: Optional[str] = payload.get("region") + self.postal_code: Optional[str] = payload.get("postal_code") + self.iso_country: Optional[str] = payload.get("iso_country") + self.address_requirements: Optional[str] = payload.get("address_requirements") + self.beta: Optional[bool] = payload.get("beta") + self.capabilities: Optional[str] = payload.get("capabilities") + + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SharedCostPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SharedCostInstance: + """ + Build an instance of SharedCostInstance + + :param payload: Payload response from the API + """ + return SharedCostInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SharedCostList(ListResource): + + def __init__(self, version: Version, account_sid: str, country_code: str): + """ + Initialize the SharedCostList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) requesting the AvailablePhoneNumber resources. + :param country_code: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country from which to read phone numbers. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + self._uri = "/Accounts/{account_sid}/AvailablePhoneNumbers/{country_code}/SharedCost.json".format( + **self._solution + ) + + def stream( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SharedCostInstance]: + """ + Streams SharedCostInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SharedCostInstance]: + """ + Asynchronously streams SharedCostInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SharedCostInstance]: + """ + Lists SharedCostInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SharedCostInstance]: + """ + Asynchronously lists SharedCostInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SharedCostPage: + """ + Retrieve a single page of SharedCostInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SharedCostInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SharedCostPage(self._version, response, self._solution) + + async def page_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SharedCostPage: + """ + Asynchronously retrieve a single page of SharedCostInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SharedCostInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SharedCostPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SharedCostPage: + """ + Retrieve a specific page of SharedCostInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SharedCostInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SharedCostPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SharedCostPage: + """ + Asynchronously retrieve a specific page of SharedCostInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SharedCostInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SharedCostPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/toll_free.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/toll_free.py new file mode 100644 index 00000000..de4a2d98 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/toll_free.py @@ -0,0 +1,664 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TollFreeInstance(InstanceResource): + """ + :ivar friendly_name: A formatted version of the phone number. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar lata: The [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) of this phone number. Available for only phone numbers from the US and Canada. + :ivar locality: The locality or city of this phone number's location. + :ivar rate_center: The [rate center](https://en.wikipedia.org/wiki/Telephone_exchange) of this phone number. Available for only phone numbers from the US and Canada. + :ivar latitude: The latitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar longitude: The longitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar region: The two-letter state or province abbreviation of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar postal_code: The postal or ZIP code of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of this phone number. + :ivar address_requirements: The type of [Address](https://www.twilio.com/docs/usage/api/address) resource the phone number requires. Can be: `none`, `any`, `local`, or `foreign`. `none` means no address is required. `any` means an address is required, but it can be anywhere in the world. `local` means an address in the phone number's country is required. `foreign` means an address outside of the phone number's country is required. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + country_code: str, + ): + super().__init__(version) + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.phone_number: Optional[str] = payload.get("phone_number") + self.lata: Optional[str] = payload.get("lata") + self.locality: Optional[str] = payload.get("locality") + self.rate_center: Optional[str] = payload.get("rate_center") + self.latitude: Optional[float] = deserialize.decimal(payload.get("latitude")) + self.longitude: Optional[float] = deserialize.decimal(payload.get("longitude")) + self.region: Optional[str] = payload.get("region") + self.postal_code: Optional[str] = payload.get("postal_code") + self.iso_country: Optional[str] = payload.get("iso_country") + self.address_requirements: Optional[str] = payload.get("address_requirements") + self.beta: Optional[bool] = payload.get("beta") + self.capabilities: Optional[str] = payload.get("capabilities") + + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TollFreePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TollFreeInstance: + """ + Build an instance of TollFreeInstance + + :param payload: Payload response from the API + """ + return TollFreeInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TollFreeList(ListResource): + + def __init__(self, version: Version, account_sid: str, country_code: str): + """ + Initialize the TollFreeList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) requesting the AvailablePhoneNumber resources. + :param country_code: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country from which to read phone numbers. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + self._uri = "/Accounts/{account_sid}/AvailablePhoneNumbers/{country_code}/TollFree.json".format( + **self._solution + ) + + def stream( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TollFreeInstance]: + """ + Streams TollFreeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TollFreeInstance]: + """ + Asynchronously streams TollFreeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TollFreeInstance]: + """ + Lists TollFreeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TollFreeInstance]: + """ + Asynchronously lists TollFreeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TollFreePage: + """ + Retrieve a single page of TollFreeInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TollFreeInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TollFreePage(self._version, response, self._solution) + + async def page_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TollFreePage: + """ + Asynchronously retrieve a single page of TollFreeInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TollFreeInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TollFreePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> TollFreePage: + """ + Retrieve a specific page of TollFreeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TollFreeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TollFreePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> TollFreePage: + """ + Asynchronously retrieve a specific page of TollFreeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TollFreeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TollFreePage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/voip.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/voip.py new file mode 100644 index 00000000..9ebfae53 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/available_phone_number_country/voip.py @@ -0,0 +1,664 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class VoipInstance(InstanceResource): + """ + :ivar friendly_name: A formatted version of the phone number. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar lata: The [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) of this phone number. Available for only phone numbers from the US and Canada. + :ivar locality: The locality or city of this phone number's location. + :ivar rate_center: The [rate center](https://en.wikipedia.org/wiki/Telephone_exchange) of this phone number. Available for only phone numbers from the US and Canada. + :ivar latitude: The latitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar longitude: The longitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar region: The two-letter state or province abbreviation of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar postal_code: The postal or ZIP code of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of this phone number. + :ivar address_requirements: The type of [Address](https://www.twilio.com/docs/usage/api/address) resource the phone number requires. Can be: `none`, `any`, `local`, or `foreign`. `none` means no address is required. `any` means an address is required, but it can be anywhere in the world. `local` means an address in the phone number's country is required. `foreign` means an address outside of the phone number's country is required. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + country_code: str, + ): + super().__init__(version) + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.phone_number: Optional[str] = payload.get("phone_number") + self.lata: Optional[str] = payload.get("lata") + self.locality: Optional[str] = payload.get("locality") + self.rate_center: Optional[str] = payload.get("rate_center") + self.latitude: Optional[float] = deserialize.decimal(payload.get("latitude")) + self.longitude: Optional[float] = deserialize.decimal(payload.get("longitude")) + self.region: Optional[str] = payload.get("region") + self.postal_code: Optional[str] = payload.get("postal_code") + self.iso_country: Optional[str] = payload.get("iso_country") + self.address_requirements: Optional[str] = payload.get("address_requirements") + self.beta: Optional[bool] = payload.get("beta") + self.capabilities: Optional[str] = payload.get("capabilities") + + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class VoipPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> VoipInstance: + """ + Build an instance of VoipInstance + + :param payload: Payload response from the API + """ + return VoipInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class VoipList(ListResource): + + def __init__(self, version: Version, account_sid: str, country_code: str): + """ + Initialize the VoipList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) requesting the AvailablePhoneNumber resources. + :param country_code: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country from which to read phone numbers. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + self._uri = "/Accounts/{account_sid}/AvailablePhoneNumbers/{country_code}/Voip.json".format( + **self._solution + ) + + def stream( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[VoipInstance]: + """ + Streams VoipInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[VoipInstance]: + """ + Asynchronously streams VoipInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[VoipInstance]: + """ + Lists VoipInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[VoipInstance]: + """ + Asynchronously lists VoipInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> VoipPage: + """ + Retrieve a single page of VoipInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of VoipInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return VoipPage(self._version, response, self._solution) + + async def page_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> VoipPage: + """ + Asynchronously retrieve a single page of VoipInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of VoipInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return VoipPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> VoipPage: + """ + Retrieve a specific page of VoipInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of VoipInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return VoipPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> VoipPage: + """ + Asynchronously retrieve a specific page of VoipInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of VoipInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return VoipPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/balance.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/balance.py new file mode 100644 index 00000000..66bb91e9 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/balance.py @@ -0,0 +1,111 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class BalanceInstance(InstanceResource): + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar balance: The balance of the Account, in units specified by the unit parameter. Balance changes may not be reflected immediately. Child accounts do not contain balance information + :ivar currency: The units of currency for the account balance + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.balance: Optional[str] = payload.get("balance") + self.currency: Optional[str] = payload.get("currency") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BalanceList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the BalanceList + + :param version: Version that contains the resource + :param account_sid: The unique SID identifier of the Account. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Balance.json".format(**self._solution) + + def fetch(self) -> BalanceInstance: + """ + Asynchronously fetch the BalanceInstance + + + :returns: The fetched BalanceInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return BalanceInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def fetch_async(self) -> BalanceInstance: + """ + Asynchronously fetch the BalanceInstance + + + :returns: The fetched BalanceInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return BalanceInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__init__.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__init__.py new file mode 100644 index 00000000..f7756c40 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__init__.py @@ -0,0 +1,1400 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.call.event import EventList +from twilio.rest.api.v2010.account.call.notification import NotificationList +from twilio.rest.api.v2010.account.call.payment import PaymentList +from twilio.rest.api.v2010.account.call.recording import RecordingList +from twilio.rest.api.v2010.account.call.siprec import SiprecList +from twilio.rest.api.v2010.account.call.stream import StreamList +from twilio.rest.api.v2010.account.call.transcription import TranscriptionList +from twilio.rest.api.v2010.account.call.user_defined_message import ( + UserDefinedMessageList, +) +from twilio.rest.api.v2010.account.call.user_defined_message_subscription import ( + UserDefinedMessageSubscriptionList, +) + + +class CallInstance(InstanceResource): + + class Status(object): + QUEUED = "queued" + RINGING = "ringing" + IN_PROGRESS = "in-progress" + COMPLETED = "completed" + BUSY = "busy" + FAILED = "failed" + NO_ANSWER = "no-answer" + CANCELED = "canceled" + + class UpdateStatus(object): + CANCELED = "canceled" + COMPLETED = "completed" + + """ + :ivar sid: The unique string that we created to identify this Call resource. + :ivar date_created: The date and time in UTC that this resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in UTC that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar parent_call_sid: The SID that identifies the call that created this leg. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Call resource. + :ivar to: The phone number, SIP address, Client identifier or SIM SID that received this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). SIP addresses are formatted as `name@company.com`. Client identifiers are formatted `client:name`. SIM SIDs are formatted as `sim:sid`. + :ivar to_formatted: The phone number, SIP address or Client identifier that received this call. Formatted for display. Non-North American phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +442071838750). + :ivar _from: The phone number, SIP address, Client identifier or SIM SID that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). SIP addresses are formatted as `name@company.com`. Client identifiers are formatted `client:name`. SIM SIDs are formatted as `sim:sid`. + :ivar from_formatted: The calling phone number, SIP address, or Client identifier formatted for display. Non-North American phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +442071838750). + :ivar phone_number_sid: If the call was inbound, this is the SID of the IncomingPhoneNumber resource that received the call. If the call was outbound, it is the SID of the OutgoingCallerId resource from which the call was placed. + :ivar status: + :ivar start_time: The start time of the call, given as UTC in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. Empty if the call has not yet been dialed. + :ivar end_time: The time the call ended, given as UTC in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. Empty if the call did not complete successfully. + :ivar duration: The length of the call in seconds. This value is empty for busy, failed, unanswered, or ongoing calls. + :ivar price: The charge for this call, in the currency associated with the account. Populated after the call is completed. May not be immediately available. The price associated with a call only reflects the charge for connectivity. Charges for other call-related features such as Answering Machine Detection, Text-To-Speech, and SIP REFER are not included in this value. + :ivar price_unit: The currency in which `Price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g., `USD`, `EUR`, `JPY`). Always capitalized for calls. + :ivar direction: A string describing the direction of the call. Can be: `inbound` for inbound calls, `outbound-api` for calls initiated via the REST API or `outbound-dial` for calls initiated by a `` verb. Using [Elastic SIP Trunking](https://www.twilio.com/docs/sip-trunking), the values can be [`trunking-terminating`](https://www.twilio.com/docs/sip-trunking#termination) for outgoing calls from your communications infrastructure to the PSTN or [`trunking-originating`](https://www.twilio.com/docs/sip-trunking#origination) for incoming calls to your communications infrastructure from the PSTN. + :ivar answered_by: Either `human` or `machine` if this call was initiated with answering machine detection. Empty otherwise. + :ivar api_version: The API version used to create the call. + :ivar forwarded_from: The forwarding phone number if this call was an incoming call forwarded from another number (depends on carrier supporting forwarding). Otherwise, empty. + :ivar group_sid: The Group SID associated with this call. If no Group is associated with the call, the field is empty. + :ivar caller_name: The caller's name if this call was an incoming call to a phone number with caller ID Lookup enabled. Otherwise, empty. + :ivar queue_time: The wait time in milliseconds before the call is placed. + :ivar trunk_sid: The unique identifier of the trunk resource that was used for this call. The field is empty if the call was not made using a SIP trunk or if the call is not terminated. + :ivar uri: The URI of this resource, relative to `https://api.twilio.com`. + :ivar subresource_uris: A list of subresources available to this call, identified by their URIs relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.parent_call_sid: Optional[str] = payload.get("parent_call_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.to: Optional[str] = payload.get("to") + self.to_formatted: Optional[str] = payload.get("to_formatted") + self._from: Optional[str] = payload.get("from") + self.from_formatted: Optional[str] = payload.get("from_formatted") + self.phone_number_sid: Optional[str] = payload.get("phone_number_sid") + self.status: Optional["CallInstance.Status"] = payload.get("status") + self.start_time: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("end_time") + ) + self.duration: Optional[str] = payload.get("duration") + self.price: Optional[str] = payload.get("price") + self.price_unit: Optional[str] = payload.get("price_unit") + self.direction: Optional[str] = payload.get("direction") + self.answered_by: Optional[str] = payload.get("answered_by") + self.api_version: Optional[str] = payload.get("api_version") + self.forwarded_from: Optional[str] = payload.get("forwarded_from") + self.group_sid: Optional[str] = payload.get("group_sid") + self.caller_name: Optional[str] = payload.get("caller_name") + self.queue_time: Optional[str] = payload.get("queue_time") + self.trunk_sid: Optional[str] = payload.get("trunk_sid") + self.uri: Optional[str] = payload.get("uri") + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[CallContext] = None + + @property + def _proxy(self) -> "CallContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CallContext for this CallInstance + """ + if self._context is None: + self._context = CallContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CallInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CallInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CallInstance": + """ + Fetch the CallInstance + + + :returns: The fetched CallInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CallInstance": + """ + Asynchronous coroutine to fetch the CallInstance + + + :returns: The fetched CallInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + url: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + status: Union["CallInstance.UpdateStatus", object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + ) -> "CallInstance": + """ + Update the CallInstance + + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param method: The HTTP method we should use when calling the `url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status: + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_method: The HTTP method we should use when requesting the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url. Twiml and url parameters are mutually exclusive + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + + :returns: The updated CallInstance + """ + return self._proxy.update( + url=url, + method=method, + status=status, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + twiml=twiml, + time_limit=time_limit, + ) + + async def update_async( + self, + url: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + status: Union["CallInstance.UpdateStatus", object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + ) -> "CallInstance": + """ + Asynchronous coroutine to update the CallInstance + + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param method: The HTTP method we should use when calling the `url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status: + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_method: The HTTP method we should use when requesting the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url. Twiml and url parameters are mutually exclusive + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + + :returns: The updated CallInstance + """ + return await self._proxy.update_async( + url=url, + method=method, + status=status, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + twiml=twiml, + time_limit=time_limit, + ) + + @property + def events(self) -> EventList: + """ + Access the events + """ + return self._proxy.events + + @property + def notifications(self) -> NotificationList: + """ + Access the notifications + """ + return self._proxy.notifications + + @property + def payments(self) -> PaymentList: + """ + Access the payments + """ + return self._proxy.payments + + @property + def recordings(self) -> RecordingList: + """ + Access the recordings + """ + return self._proxy.recordings + + @property + def siprec(self) -> SiprecList: + """ + Access the siprec + """ + return self._proxy.siprec + + @property + def streams(self) -> StreamList: + """ + Access the streams + """ + return self._proxy.streams + + @property + def transcriptions(self) -> TranscriptionList: + """ + Access the transcriptions + """ + return self._proxy.transcriptions + + @property + def user_defined_messages(self) -> UserDefinedMessageList: + """ + Access the user_defined_messages + """ + return self._proxy.user_defined_messages + + @property + def user_defined_message_subscriptions(self) -> UserDefinedMessageSubscriptionList: + """ + Access the user_defined_message_subscriptions + """ + return self._proxy.user_defined_message_subscriptions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CallContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the CallContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Call resource(s) to update. + :param sid: The Twilio-provided string that uniquely identifies the Call resource to update + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Calls/{sid}.json".format(**self._solution) + + self._events: Optional[EventList] = None + self._notifications: Optional[NotificationList] = None + self._payments: Optional[PaymentList] = None + self._recordings: Optional[RecordingList] = None + self._siprec: Optional[SiprecList] = None + self._streams: Optional[StreamList] = None + self._transcriptions: Optional[TranscriptionList] = None + self._user_defined_messages: Optional[UserDefinedMessageList] = None + self._user_defined_message_subscriptions: Optional[ + UserDefinedMessageSubscriptionList + ] = None + + def delete(self) -> bool: + """ + Deletes the CallInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CallInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CallInstance: + """ + Fetch the CallInstance + + + :returns: The fetched CallInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CallInstance: + """ + Asynchronous coroutine to fetch the CallInstance + + + :returns: The fetched CallInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + url: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + status: Union["CallInstance.UpdateStatus", object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + ) -> CallInstance: + """ + Update the CallInstance + + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param method: The HTTP method we should use when calling the `url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status: + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_method: The HTTP method we should use when requesting the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url. Twiml and url parameters are mutually exclusive + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + + :returns: The updated CallInstance + """ + + data = values.of( + { + "Url": url, + "Method": method, + "Status": status, + "FallbackUrl": fallback_url, + "FallbackMethod": fallback_method, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Twiml": twiml, + "TimeLimit": time_limit, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + url: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + status: Union["CallInstance.UpdateStatus", object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + ) -> CallInstance: + """ + Asynchronous coroutine to update the CallInstance + + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param method: The HTTP method we should use when calling the `url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status: + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_method: The HTTP method we should use when requesting the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url. Twiml and url parameters are mutually exclusive + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + + :returns: The updated CallInstance + """ + + data = values.of( + { + "Url": url, + "Method": method, + "Status": status, + "FallbackUrl": fallback_url, + "FallbackMethod": fallback_method, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Twiml": twiml, + "TimeLimit": time_limit, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + @property + def events(self) -> EventList: + """ + Access the events + """ + if self._events is None: + self._events = EventList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._events + + @property + def notifications(self) -> NotificationList: + """ + Access the notifications + """ + if self._notifications is None: + self._notifications = NotificationList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._notifications + + @property + def payments(self) -> PaymentList: + """ + Access the payments + """ + if self._payments is None: + self._payments = PaymentList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._payments + + @property + def recordings(self) -> RecordingList: + """ + Access the recordings + """ + if self._recordings is None: + self._recordings = RecordingList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._recordings + + @property + def siprec(self) -> SiprecList: + """ + Access the siprec + """ + if self._siprec is None: + self._siprec = SiprecList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._siprec + + @property + def streams(self) -> StreamList: + """ + Access the streams + """ + if self._streams is None: + self._streams = StreamList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._streams + + @property + def transcriptions(self) -> TranscriptionList: + """ + Access the transcriptions + """ + if self._transcriptions is None: + self._transcriptions = TranscriptionList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._transcriptions + + @property + def user_defined_messages(self) -> UserDefinedMessageList: + """ + Access the user_defined_messages + """ + if self._user_defined_messages is None: + self._user_defined_messages = UserDefinedMessageList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._user_defined_messages + + @property + def user_defined_message_subscriptions(self) -> UserDefinedMessageSubscriptionList: + """ + Access the user_defined_message_subscriptions + """ + if self._user_defined_message_subscriptions is None: + self._user_defined_message_subscriptions = ( + UserDefinedMessageSubscriptionList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + ) + return self._user_defined_message_subscriptions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CallPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CallInstance: + """ + Build an instance of CallInstance + + :param payload: Payload response from the API + """ + return CallInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CallList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the CallList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Call resource(s) to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Calls.json".format(**self._solution) + + def create( + self, + to: str, + from_: str, + method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_event: Union[List[str], object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + send_digits: Union[str, object] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + machine_detection: Union[str, object] = values.unset, + machine_detection_timeout: Union[int, object] = values.unset, + recording_status_callback_event: Union[List[str], object] = values.unset, + trim: Union[str, object] = values.unset, + caller_id: Union[str, object] = values.unset, + machine_detection_speech_threshold: Union[int, object] = values.unset, + machine_detection_speech_end_threshold: Union[int, object] = values.unset, + machine_detection_silence_timeout: Union[int, object] = values.unset, + async_amd: Union[str, object] = values.unset, + async_amd_status_callback: Union[str, object] = values.unset, + async_amd_status_callback_method: Union[str, object] = values.unset, + byoc: Union[str, object] = values.unset, + call_reason: Union[str, object] = values.unset, + call_token: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + url: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + ) -> CallInstance: + """ + Create the CallInstance + + :param to: The phone number, SIP address, or client identifier to call. + :param from_: The phone number or client identifier to use as the caller id. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `From` must also be a phone number. + :param method: The HTTP method we should use when calling the `url` parameter's value. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_event: The call progress events that we will send to the `status_callback` URL. Can be: `initiated`, `ringing`, `answered`, and `completed`. If no event is specified, we send the `completed` status. If you want to receive multiple events, specify each one in a separate `status_callback_event` parameter. See the code sample for [monitoring call progress](https://www.twilio.com/docs/voice/api/call-resource?code-sample=code-create-a-call-resource-and-specify-a-statuscallbackevent&code-sdk-version=json). If an `application_sid` is present, this parameter is ignored. + :param status_callback_method: The HTTP method we should use when calling the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param send_digits: The string of keys to dial after connecting to the number, with a maximum length of 32 digits. Valid digits in the string include any digit (`0`-`9`), '`A`', '`B`', '`C`', '`D`', '`#`', and '`*`'. You can also use '`w`' to insert a half-second pause and '`W`' to insert a one-second pause. For example, to pause for one second after connecting and then dial extension 1234 followed by the # key, set this parameter to `W1234#`. Be sure to URL-encode this string because the '`#`' character has special meaning in a URL. If both `SendDigits` and `MachineDetection` parameters are provided, then `MachineDetection` will be ignored. + :param timeout: The integer number of seconds that we should allow the phone to ring before assuming there is no answer. The default is `60` seconds and the maximum is `600` seconds. For some call flows, we will add a 5-second buffer to the timeout value you provide. For this reason, a timeout value of 10 seconds could result in an actual timeout closer to 15 seconds. You can set this to a short time, such as `15` seconds, to hang up before reaching an answering machine or voicemail. + :param record: Whether to record the call. Can be `true` to record the phone call, or `false` to not. The default is `false`. The `recording_url` is sent to the `status_callback` URL. + :param recording_channels: The number of channels in the final recording. Can be: `mono` or `dual`. The default is `mono`. `mono` records both legs of the call in a single channel of the recording file. `dual` records each leg to a separate channel of the recording file. The first channel of a dual-channel recording contains the parent call and the second channel contains the child call. + :param recording_status_callback: The URL that we call when the recording is available to be accessed. + :param recording_status_callback_method: The HTTP method we should use when calling the `recording_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param sip_auth_username: The username used to authenticate the caller making a SIP call. + :param sip_auth_password: The password required to authenticate the user account specified in `sip_auth_username`. + :param machine_detection: Whether to detect if a human, answering machine, or fax has picked up the call. Can be: `Enable` or `DetectMessageEnd`. Use `Enable` if you would like us to return `AnsweredBy` as soon as the called party is identified. Use `DetectMessageEnd`, if you would like to leave a message on an answering machine. If `send_digits` is provided, this parameter is ignored. For more information, see [Answering Machine Detection](https://www.twilio.com/docs/voice/answering-machine-detection). + :param machine_detection_timeout: The number of seconds that we should attempt to detect an answering machine before timing out and sending a voice request with `AnsweredBy` of `unknown`. The default timeout is 30 seconds. + :param recording_status_callback_event: The recording status events that will trigger calls to the URL specified in `recording_status_callback`. Can be: `in-progress`, `completed` and `absent`. Defaults to `completed`. Separate multiple values with a space. + :param trim: Whether to trim any leading and trailing silence from the recording. Can be: `trim-silence` or `do-not-trim` and the default is `trim-silence`. + :param caller_id: The phone number, SIP address, or Client identifier that made this call. Phone numbers are in [E.164 format](https://wwnw.twilio.com/docs/glossary/what-e164) (e.g., +16175551212). SIP addresses are formatted as `name@company.com`. + :param machine_detection_speech_threshold: The number of milliseconds that is used as the measuring stick for the length of the speech activity, where durations lower than this value will be interpreted as a human and longer than this value as a machine. Possible Values: 1000-6000. Default: 2400. + :param machine_detection_speech_end_threshold: The number of milliseconds of silence after speech activity at which point the speech activity is considered complete. Possible Values: 500-5000. Default: 1200. + :param machine_detection_silence_timeout: The number of milliseconds of initial silence after which an `unknown` AnsweredBy result will be returned. Possible Values: 2000-10000. Default: 5000. + :param async_amd: Select whether to perform answering machine detection in the background. Default, blocks the execution of the call until Answering Machine Detection is completed. Can be: `true` or `false`. + :param async_amd_status_callback: The URL that we should call using the `async_amd_status_callback_method` to notify customer application whether the call was answered by human, machine or fax. + :param async_amd_status_callback_method: The HTTP method we should use when calling the `async_amd_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param byoc: The SID of a BYOC (Bring Your Own Carrier) trunk to route this call with. Note that `byoc` is only meaningful when `to` is a phone number; it will otherwise be ignored. (Beta) + :param call_reason: The Reason for the outgoing call. Use it to specify the purpose of the call that is presented on the called party's phone. (Branded Calls Beta) + :param call_token: A token string needed to invoke a forwarded call. A call_token is generated when an incoming call is received on a Twilio number. Pass an incoming call's call_token value to a forwarded call via the call_token parameter when creating a new call. A forwarded call should bear the same CallerID of the original incoming call. + :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is generated from Twilio. `both` records the audio that is received and generated by Twilio. + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url parameter. If both `twiml` and `url` are provided then `twiml` parameter will be ignored. Max 4000 characters. + :param application_sid: The SID of the Application resource that will handle the call, if the call will be handled by an application. + + :returns: The created CallInstance + """ + + data = values.of( + { + "To": to, + "From": from_, + "Method": method, + "FallbackUrl": fallback_url, + "FallbackMethod": fallback_method, + "StatusCallback": status_callback, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "StatusCallbackMethod": status_callback_method, + "SendDigits": send_digits, + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "MachineDetection": machine_detection, + "MachineDetectionTimeout": machine_detection_timeout, + "RecordingStatusCallbackEvent": serialize.map( + recording_status_callback_event, lambda e: e + ), + "Trim": trim, + "CallerId": caller_id, + "MachineDetectionSpeechThreshold": machine_detection_speech_threshold, + "MachineDetectionSpeechEndThreshold": machine_detection_speech_end_threshold, + "MachineDetectionSilenceTimeout": machine_detection_silence_timeout, + "AsyncAmd": async_amd, + "AsyncAmdStatusCallback": async_amd_status_callback, + "AsyncAmdStatusCallbackMethod": async_amd_status_callback_method, + "Byoc": byoc, + "CallReason": call_reason, + "CallToken": call_token, + "RecordingTrack": recording_track, + "TimeLimit": time_limit, + "Url": url, + "Twiml": twiml, + "ApplicationSid": application_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CallInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, + to: str, + from_: str, + method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_event: Union[List[str], object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + send_digits: Union[str, object] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + machine_detection: Union[str, object] = values.unset, + machine_detection_timeout: Union[int, object] = values.unset, + recording_status_callback_event: Union[List[str], object] = values.unset, + trim: Union[str, object] = values.unset, + caller_id: Union[str, object] = values.unset, + machine_detection_speech_threshold: Union[int, object] = values.unset, + machine_detection_speech_end_threshold: Union[int, object] = values.unset, + machine_detection_silence_timeout: Union[int, object] = values.unset, + async_amd: Union[str, object] = values.unset, + async_amd_status_callback: Union[str, object] = values.unset, + async_amd_status_callback_method: Union[str, object] = values.unset, + byoc: Union[str, object] = values.unset, + call_reason: Union[str, object] = values.unset, + call_token: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + url: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + ) -> CallInstance: + """ + Asynchronously create the CallInstance + + :param to: The phone number, SIP address, or client identifier to call. + :param from_: The phone number or client identifier to use as the caller id. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `From` must also be a phone number. + :param method: The HTTP method we should use when calling the `url` parameter's value. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_event: The call progress events that we will send to the `status_callback` URL. Can be: `initiated`, `ringing`, `answered`, and `completed`. If no event is specified, we send the `completed` status. If you want to receive multiple events, specify each one in a separate `status_callback_event` parameter. See the code sample for [monitoring call progress](https://www.twilio.com/docs/voice/api/call-resource?code-sample=code-create-a-call-resource-and-specify-a-statuscallbackevent&code-sdk-version=json). If an `application_sid` is present, this parameter is ignored. + :param status_callback_method: The HTTP method we should use when calling the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param send_digits: The string of keys to dial after connecting to the number, with a maximum length of 32 digits. Valid digits in the string include any digit (`0`-`9`), '`A`', '`B`', '`C`', '`D`', '`#`', and '`*`'. You can also use '`w`' to insert a half-second pause and '`W`' to insert a one-second pause. For example, to pause for one second after connecting and then dial extension 1234 followed by the # key, set this parameter to `W1234#`. Be sure to URL-encode this string because the '`#`' character has special meaning in a URL. If both `SendDigits` and `MachineDetection` parameters are provided, then `MachineDetection` will be ignored. + :param timeout: The integer number of seconds that we should allow the phone to ring before assuming there is no answer. The default is `60` seconds and the maximum is `600` seconds. For some call flows, we will add a 5-second buffer to the timeout value you provide. For this reason, a timeout value of 10 seconds could result in an actual timeout closer to 15 seconds. You can set this to a short time, such as `15` seconds, to hang up before reaching an answering machine or voicemail. + :param record: Whether to record the call. Can be `true` to record the phone call, or `false` to not. The default is `false`. The `recording_url` is sent to the `status_callback` URL. + :param recording_channels: The number of channels in the final recording. Can be: `mono` or `dual`. The default is `mono`. `mono` records both legs of the call in a single channel of the recording file. `dual` records each leg to a separate channel of the recording file. The first channel of a dual-channel recording contains the parent call and the second channel contains the child call. + :param recording_status_callback: The URL that we call when the recording is available to be accessed. + :param recording_status_callback_method: The HTTP method we should use when calling the `recording_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param sip_auth_username: The username used to authenticate the caller making a SIP call. + :param sip_auth_password: The password required to authenticate the user account specified in `sip_auth_username`. + :param machine_detection: Whether to detect if a human, answering machine, or fax has picked up the call. Can be: `Enable` or `DetectMessageEnd`. Use `Enable` if you would like us to return `AnsweredBy` as soon as the called party is identified. Use `DetectMessageEnd`, if you would like to leave a message on an answering machine. If `send_digits` is provided, this parameter is ignored. For more information, see [Answering Machine Detection](https://www.twilio.com/docs/voice/answering-machine-detection). + :param machine_detection_timeout: The number of seconds that we should attempt to detect an answering machine before timing out and sending a voice request with `AnsweredBy` of `unknown`. The default timeout is 30 seconds. + :param recording_status_callback_event: The recording status events that will trigger calls to the URL specified in `recording_status_callback`. Can be: `in-progress`, `completed` and `absent`. Defaults to `completed`. Separate multiple values with a space. + :param trim: Whether to trim any leading and trailing silence from the recording. Can be: `trim-silence` or `do-not-trim` and the default is `trim-silence`. + :param caller_id: The phone number, SIP address, or Client identifier that made this call. Phone numbers are in [E.164 format](https://wwnw.twilio.com/docs/glossary/what-e164) (e.g., +16175551212). SIP addresses are formatted as `name@company.com`. + :param machine_detection_speech_threshold: The number of milliseconds that is used as the measuring stick for the length of the speech activity, where durations lower than this value will be interpreted as a human and longer than this value as a machine. Possible Values: 1000-6000. Default: 2400. + :param machine_detection_speech_end_threshold: The number of milliseconds of silence after speech activity at which point the speech activity is considered complete. Possible Values: 500-5000. Default: 1200. + :param machine_detection_silence_timeout: The number of milliseconds of initial silence after which an `unknown` AnsweredBy result will be returned. Possible Values: 2000-10000. Default: 5000. + :param async_amd: Select whether to perform answering machine detection in the background. Default, blocks the execution of the call until Answering Machine Detection is completed. Can be: `true` or `false`. + :param async_amd_status_callback: The URL that we should call using the `async_amd_status_callback_method` to notify customer application whether the call was answered by human, machine or fax. + :param async_amd_status_callback_method: The HTTP method we should use when calling the `async_amd_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param byoc: The SID of a BYOC (Bring Your Own Carrier) trunk to route this call with. Note that `byoc` is only meaningful when `to` is a phone number; it will otherwise be ignored. (Beta) + :param call_reason: The Reason for the outgoing call. Use it to specify the purpose of the call that is presented on the called party's phone. (Branded Calls Beta) + :param call_token: A token string needed to invoke a forwarded call. A call_token is generated when an incoming call is received on a Twilio number. Pass an incoming call's call_token value to a forwarded call via the call_token parameter when creating a new call. A forwarded call should bear the same CallerID of the original incoming call. + :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is generated from Twilio. `both` records the audio that is received and generated by Twilio. + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url parameter. If both `twiml` and `url` are provided then `twiml` parameter will be ignored. Max 4000 characters. + :param application_sid: The SID of the Application resource that will handle the call, if the call will be handled by an application. + + :returns: The created CallInstance + """ + + data = values.of( + { + "To": to, + "From": from_, + "Method": method, + "FallbackUrl": fallback_url, + "FallbackMethod": fallback_method, + "StatusCallback": status_callback, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "StatusCallbackMethod": status_callback_method, + "SendDigits": send_digits, + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "MachineDetection": machine_detection, + "MachineDetectionTimeout": machine_detection_timeout, + "RecordingStatusCallbackEvent": serialize.map( + recording_status_callback_event, lambda e: e + ), + "Trim": trim, + "CallerId": caller_id, + "MachineDetectionSpeechThreshold": machine_detection_speech_threshold, + "MachineDetectionSpeechEndThreshold": machine_detection_speech_end_threshold, + "MachineDetectionSilenceTimeout": machine_detection_silence_timeout, + "AsyncAmd": async_amd, + "AsyncAmdStatusCallback": async_amd_status_callback, + "AsyncAmdStatusCallbackMethod": async_amd_status_callback_method, + "Byoc": byoc, + "CallReason": call_reason, + "CallToken": call_token, + "RecordingTrack": recording_track, + "TimeLimit": time_limit, + "Url": url, + "Twiml": twiml, + "ApplicationSid": application_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CallInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + parent_call_sid: Union[str, object] = values.unset, + status: Union["CallInstance.Status", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + start_time_before: Union[datetime, object] = values.unset, + start_time_after: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + end_time_before: Union[datetime, object] = values.unset, + end_time_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CallInstance]: + """ + Streams CallInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str to: Only show calls made to this phone number, SIP address, Client identifier or SIM SID. + :param str from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. + :param str parent_call_sid: Only include calls spawned by calls with this SID. + :param "CallInstance.Status" status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. + :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param datetime start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param datetime start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param datetime end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param datetime end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + to=to, + from_=from_, + parent_call_sid=parent_call_sid, + status=status, + start_time=start_time, + start_time_before=start_time_before, + start_time_after=start_time_after, + end_time=end_time, + end_time_before=end_time_before, + end_time_after=end_time_after, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + parent_call_sid: Union[str, object] = values.unset, + status: Union["CallInstance.Status", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + start_time_before: Union[datetime, object] = values.unset, + start_time_after: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + end_time_before: Union[datetime, object] = values.unset, + end_time_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CallInstance]: + """ + Asynchronously streams CallInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str to: Only show calls made to this phone number, SIP address, Client identifier or SIM SID. + :param str from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. + :param str parent_call_sid: Only include calls spawned by calls with this SID. + :param "CallInstance.Status" status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. + :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param datetime start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param datetime start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param datetime end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param datetime end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + to=to, + from_=from_, + parent_call_sid=parent_call_sid, + status=status, + start_time=start_time, + start_time_before=start_time_before, + start_time_after=start_time_after, + end_time=end_time, + end_time_before=end_time_before, + end_time_after=end_time_after, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + parent_call_sid: Union[str, object] = values.unset, + status: Union["CallInstance.Status", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + start_time_before: Union[datetime, object] = values.unset, + start_time_after: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + end_time_before: Union[datetime, object] = values.unset, + end_time_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CallInstance]: + """ + Lists CallInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str to: Only show calls made to this phone number, SIP address, Client identifier or SIM SID. + :param str from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. + :param str parent_call_sid: Only include calls spawned by calls with this SID. + :param "CallInstance.Status" status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. + :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param datetime start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param datetime start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param datetime end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param datetime end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + to=to, + from_=from_, + parent_call_sid=parent_call_sid, + status=status, + start_time=start_time, + start_time_before=start_time_before, + start_time_after=start_time_after, + end_time=end_time, + end_time_before=end_time_before, + end_time_after=end_time_after, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + parent_call_sid: Union[str, object] = values.unset, + status: Union["CallInstance.Status", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + start_time_before: Union[datetime, object] = values.unset, + start_time_after: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + end_time_before: Union[datetime, object] = values.unset, + end_time_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CallInstance]: + """ + Asynchronously lists CallInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str to: Only show calls made to this phone number, SIP address, Client identifier or SIM SID. + :param str from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. + :param str parent_call_sid: Only include calls spawned by calls with this SID. + :param "CallInstance.Status" status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. + :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param datetime start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param datetime start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param datetime end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param datetime end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + to=to, + from_=from_, + parent_call_sid=parent_call_sid, + status=status, + start_time=start_time, + start_time_before=start_time_before, + start_time_after=start_time_after, + end_time=end_time, + end_time_before=end_time_before, + end_time_after=end_time_after, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + parent_call_sid: Union[str, object] = values.unset, + status: Union["CallInstance.Status", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + start_time_before: Union[datetime, object] = values.unset, + start_time_after: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + end_time_before: Union[datetime, object] = values.unset, + end_time_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CallPage: + """ + Retrieve a single page of CallInstance records from the API. + Request is executed immediately + + :param to: Only show calls made to this phone number, SIP address, Client identifier or SIM SID. + :param from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. + :param parent_call_sid: Only include calls spawned by calls with this SID. + :param status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. + :param start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CallInstance + """ + data = values.of( + { + "To": to, + "From": from_, + "ParentCallSid": parent_call_sid, + "Status": status, + "StartTime": serialize.iso8601_datetime(start_time), + "StartTime<": serialize.iso8601_datetime(start_time_before), + "StartTime>": serialize.iso8601_datetime(start_time_after), + "EndTime": serialize.iso8601_datetime(end_time), + "EndTime<": serialize.iso8601_datetime(end_time_before), + "EndTime>": serialize.iso8601_datetime(end_time_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CallPage(self._version, response, self._solution) + + async def page_async( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + parent_call_sid: Union[str, object] = values.unset, + status: Union["CallInstance.Status", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + start_time_before: Union[datetime, object] = values.unset, + start_time_after: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + end_time_before: Union[datetime, object] = values.unset, + end_time_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CallPage: + """ + Asynchronously retrieve a single page of CallInstance records from the API. + Request is executed immediately + + :param to: Only show calls made to this phone number, SIP address, Client identifier or SIM SID. + :param from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. + :param parent_call_sid: Only include calls spawned by calls with this SID. + :param status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. + :param start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CallInstance + """ + data = values.of( + { + "To": to, + "From": from_, + "ParentCallSid": parent_call_sid, + "Status": status, + "StartTime": serialize.iso8601_datetime(start_time), + "StartTime<": serialize.iso8601_datetime(start_time_before), + "StartTime>": serialize.iso8601_datetime(start_time_after), + "EndTime": serialize.iso8601_datetime(end_time), + "EndTime<": serialize.iso8601_datetime(end_time_before), + "EndTime>": serialize.iso8601_datetime(end_time_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CallPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> CallPage: + """ + Retrieve a specific page of CallInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CallInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CallPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> CallPage: + """ + Asynchronously retrieve a specific page of CallInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CallInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CallPage(self._version, response, self._solution) + + def get(self, sid: str) -> CallContext: + """ + Constructs a CallContext + + :param sid: The Twilio-provided string that uniquely identifies the Call resource to update + """ + return CallContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> CallContext: + """ + Constructs a CallContext + + :param sid: The Twilio-provided string that uniquely identifies the Call resource to update + """ + return CallContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..3efe3da2 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/event.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/event.cpython-312.pyc new file mode 100644 index 00000000..6e119f6c Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/notification.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/notification.cpython-312.pyc new file mode 100644 index 00000000..ccea5435 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/notification.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/payment.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/payment.cpython-312.pyc new file mode 100644 index 00000000..9e5cacb3 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/payment.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/recording.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/recording.cpython-312.pyc new file mode 100644 index 00000000..14d687fb Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/recording.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/siprec.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/siprec.cpython-312.pyc new file mode 100644 index 00000000..29b58d66 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/siprec.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/stream.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/stream.cpython-312.pyc new file mode 100644 index 00000000..28a88f21 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/stream.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/transcription.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/transcription.cpython-312.pyc new file mode 100644 index 00000000..514066de Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/transcription.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/user_defined_message.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/user_defined_message.cpython-312.pyc new file mode 100644 index 00000000..b9863eb9 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/user_defined_message.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/user_defined_message_subscription.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/user_defined_message_subscription.cpython-312.pyc new file mode 100644 index 00000000..b02ba873 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/__pycache__/user_defined_message_subscription.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/event.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/event.py new file mode 100644 index 00000000..80eb8aa8 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/event.py @@ -0,0 +1,298 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class EventInstance(InstanceResource): + """ + :ivar request: Contains a dictionary representing the request of the call. + :ivar response: Contains a dictionary representing the call response, including a list of the call events. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], account_sid: str, call_sid: str + ): + super().__init__(version) + + self.request: Optional[Dict[str, object]] = payload.get("request") + self.response: Optional[Dict[str, object]] = payload.get("response") + + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EventPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EventInstance: + """ + Build an instance of EventInstance + + :param payload: Payload response from the API + """ + return EventInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class EventList(ListResource): + + def __init__(self, version: Version, account_sid: str, call_sid: str): + """ + Initialize the EventList + + :param version: Version that contains the resource + :param account_sid: The unique SID identifier of the Account. + :param call_sid: The unique SID identifier of the Call. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + self._uri = "/Accounts/{account_sid}/Calls/{call_sid}/Events.json".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EventInstance]: + """ + Streams EventInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EventInstance]: + """ + Asynchronously streams EventInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventInstance]: + """ + Lists EventInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventInstance]: + """ + Asynchronously lists EventInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EventPage: + """ + Retrieve a single page of EventInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EventInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EventPage: + """ + Asynchronously retrieve a single page of EventInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EventInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> EventPage: + """ + Retrieve a specific page of EventInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EventInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EventPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> EventPage: + """ + Asynchronously retrieve a specific page of EventInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EventInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EventPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/notification.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/notification.py new file mode 100644 index 00000000..fd9e8c0d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/notification.py @@ -0,0 +1,562 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class NotificationInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Call Notification resource. + :ivar api_version: The API version used to create the Call Notification resource. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Call Notification resource is associated with. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar error_code: A unique error code for the error condition that is described in our [Error Dictionary](https://www.twilio.com/docs/api/errors). + :ivar log: An integer log level that corresponds to the type of notification: `0` is ERROR, `1` is WARNING. + :ivar message_date: The date the notification was actually generated in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. Message buffering can cause this value to differ from `date_created`. + :ivar message_text: The text of the notification. + :ivar more_info: The URL for more information about the error condition. This value is a page in our [Error Dictionary](https://www.twilio.com/docs/api/errors). + :ivar request_method: The HTTP method used to generate the notification. If the notification was generated during a phone call, this is the HTTP Method used to request the resource on your server. If the notification was generated by your use of our REST API, this is the HTTP method used to call the resource on our servers. + :ivar request_url: The URL of the resource that generated the notification. If the notification was generated during a phone call, this is the URL of the resource on your server that caused the notification. If the notification was generated by your use of our REST API, this is the URL of the resource you called. + :ivar request_variables: The HTTP GET or POST variables we sent to your server. However, if the notification was generated by our REST API, this contains the HTTP POST or PUT variables you sent to our API. + :ivar response_body: The HTTP body returned by your server. + :ivar response_headers: The HTTP headers returned by your server. + :ivar sid: The unique string that that we created to identify the Call Notification resource. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + call_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.call_sid: Optional[str] = payload.get("call_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.error_code: Optional[str] = payload.get("error_code") + self.log: Optional[str] = payload.get("log") + self.message_date: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("message_date") + ) + self.message_text: Optional[str] = payload.get("message_text") + self.more_info: Optional[str] = payload.get("more_info") + self.request_method: Optional[str] = payload.get("request_method") + self.request_url: Optional[str] = payload.get("request_url") + self.request_variables: Optional[str] = payload.get("request_variables") + self.response_body: Optional[str] = payload.get("response_body") + self.response_headers: Optional[str] = payload.get("response_headers") + self.sid: Optional[str] = payload.get("sid") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid or self.sid, + } + self._context: Optional[NotificationContext] = None + + @property + def _proxy(self) -> "NotificationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: NotificationContext for this NotificationInstance + """ + if self._context is None: + self._context = NotificationContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "NotificationInstance": + """ + Fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "NotificationInstance": + """ + Asynchronous coroutine to fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NotificationContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): + """ + Initialize the NotificationContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Call Notification resource to fetch. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the Call Notification resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Call Notification resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid, + } + self._uri = ( + "/Accounts/{account_sid}/Calls/{call_sid}/Notifications/{sid}.json".format( + **self._solution + ) + ) + + def fetch(self) -> NotificationInstance: + """ + Fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> NotificationInstance: + """ + Asynchronous coroutine to fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NotificationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> NotificationInstance: + """ + Build an instance of NotificationInstance + + :param payload: Payload response from the API + """ + return NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class NotificationList(ListResource): + + def __init__(self, version: Version, account_sid: str, call_sid: str): + """ + Initialize the NotificationList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Call Notification resources to read. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the Call Notification resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + self._uri = ( + "/Accounts/{account_sid}/Calls/{call_sid}/Notifications.json".format( + **self._solution + ) + ) + + def stream( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[NotificationInstance]: + """ + Streams NotificationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[NotificationInstance]: + """ + Asynchronously streams NotificationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NotificationInstance]: + """ + Lists NotificationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NotificationInstance]: + """ + Asynchronously lists NotificationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NotificationPage: + """ + Retrieve a single page of NotificationInstance records from the API. + Request is executed immediately + + :param log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NotificationInstance + """ + data = values.of( + { + "Log": log, + "MessageDate": serialize.iso8601_date(message_date), + "MessageDate<": serialize.iso8601_date(message_date_before), + "MessageDate>": serialize.iso8601_date(message_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NotificationPage(self._version, response, self._solution) + + async def page_async( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NotificationPage: + """ + Asynchronously retrieve a single page of NotificationInstance records from the API. + Request is executed immediately + + :param log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NotificationInstance + """ + data = values.of( + { + "Log": log, + "MessageDate": serialize.iso8601_date(message_date), + "MessageDate<": serialize.iso8601_date(message_date_before), + "MessageDate>": serialize.iso8601_date(message_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NotificationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> NotificationPage: + """ + Retrieve a specific page of NotificationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NotificationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return NotificationPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> NotificationPage: + """ + Asynchronously retrieve a specific page of NotificationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NotificationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return NotificationPage(self._version, response, self._solution) + + def get(self, sid: str) -> NotificationContext: + """ + Constructs a NotificationContext + + :param sid: The Twilio-provided string that uniquely identifies the Call Notification resource to fetch. + """ + return NotificationContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> NotificationContext: + """ + Constructs a NotificationContext + + :param sid: The Twilio-provided string that uniquely identifies the Call Notification resource to fetch. + """ + return NotificationContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/payment.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/payment.py new file mode 100644 index 00000000..0f918609 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/payment.py @@ -0,0 +1,503 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PaymentInstance(InstanceResource): + + class BankAccountType(object): + CONSUMER_CHECKING = "consumer-checking" + CONSUMER_SAVINGS = "consumer-savings" + COMMERCIAL_CHECKING = "commercial-checking" + + class Capture(object): + PAYMENT_CARD_NUMBER = "payment-card-number" + EXPIRATION_DATE = "expiration-date" + SECURITY_CODE = "security-code" + POSTAL_CODE = "postal-code" + BANK_ROUTING_NUMBER = "bank-routing-number" + BANK_ACCOUNT_NUMBER = "bank-account-number" + + class PaymentMethod(object): + CREDIT_CARD = "credit-card" + ACH_DEBIT = "ach-debit" + + class Status(object): + COMPLETE = "complete" + CANCEL = "cancel" + + class TokenType(object): + ONE_TIME = "one-time" + REUSABLE = "reusable" + PAYMENT_METHOD = "payment-method" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Payments resource is associated with. This will refer to the call sid that is producing the payment card (credit/ACH) information thru DTMF. + :ivar sid: The SID of the Payments resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + call_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.call_sid: Optional[str] = payload.get("call_sid") + self.sid: Optional[str] = payload.get("sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid or self.sid, + } + self._context: Optional[PaymentContext] = None + + @property + def _proxy(self) -> "PaymentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PaymentContext for this PaymentInstance + """ + if self._context is None: + self._context = PaymentContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return self._context + + def update( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> "PaymentInstance": + """ + Update the PaymentInstance + + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [Update](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-update) and [Complete/Cancel](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-cancelcomplete) POST requests. + :param capture: + :param status: + + :returns: The updated PaymentInstance + """ + return self._proxy.update( + idempotency_key=idempotency_key, + status_callback=status_callback, + capture=capture, + status=status, + ) + + async def update_async( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> "PaymentInstance": + """ + Asynchronous coroutine to update the PaymentInstance + + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [Update](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-update) and [Complete/Cancel](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-cancelcomplete) POST requests. + :param capture: + :param status: + + :returns: The updated PaymentInstance + """ + return await self._proxy.update_async( + idempotency_key=idempotency_key, + status_callback=status_callback, + capture=capture, + status=status, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PaymentContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): + """ + Initialize the PaymentContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that will update the resource. + :param call_sid: The SID of the call that will update the resource. This should be the same call sid that was used to create payments resource. + :param sid: The SID of Payments session that needs to be updated. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid, + } + self._uri = ( + "/Accounts/{account_sid}/Calls/{call_sid}/Payments/{sid}.json".format( + **self._solution + ) + ) + + def update( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> PaymentInstance: + """ + Update the PaymentInstance + + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [Update](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-update) and [Complete/Cancel](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-cancelcomplete) POST requests. + :param capture: + :param status: + + :returns: The updated PaymentInstance + """ + + data = values.of( + { + "IdempotencyKey": idempotency_key, + "StatusCallback": status_callback, + "Capture": capture, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PaymentInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> PaymentInstance: + """ + Asynchronous coroutine to update the PaymentInstance + + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [Update](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-update) and [Complete/Cancel](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-cancelcomplete) POST requests. + :param capture: + :param status: + + :returns: The updated PaymentInstance + """ + + data = values.of( + { + "IdempotencyKey": idempotency_key, + "StatusCallback": status_callback, + "Capture": capture, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PaymentInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PaymentList(ListResource): + + def __init__(self, version: Version, account_sid: str, call_sid: str): + """ + Initialize the PaymentList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that will create the resource. + :param call_sid: The SID of the call that will create the resource. Call leg associated with this sid is expected to provide payment information thru DTMF. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + self._uri = "/Accounts/{account_sid}/Calls/{call_sid}/Payments.json".format( + **self._solution + ) + + def create( + self, + idempotency_key: str, + status_callback: str, + bank_account_type: Union[ + "PaymentInstance.BankAccountType", object + ] = values.unset, + charge_amount: Union[float, object] = values.unset, + currency: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + input: Union[str, object] = values.unset, + min_postal_code_length: Union[int, object] = values.unset, + parameter: Union[object, object] = values.unset, + payment_connector: Union[str, object] = values.unset, + payment_method: Union["PaymentInstance.PaymentMethod", object] = values.unset, + postal_code: Union[bool, object] = values.unset, + security_code: Union[bool, object] = values.unset, + timeout: Union[int, object] = values.unset, + token_type: Union["PaymentInstance.TokenType", object] = values.unset, + valid_card_types: Union[str, object] = values.unset, + ) -> PaymentInstance: + """ + Create the PaymentInstance + + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [expected StatusCallback values](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback) + :param bank_account_type: + :param charge_amount: A positive decimal value less than 1,000,000 to charge against the credit card or bank account. Default currency can be overwritten with `currency` field. Leave blank or set to 0 to tokenize. + :param currency: The currency of the `charge_amount`, formatted as [ISO 4127](http://www.iso.org/iso/home/standards/currency_codes.htm) format. The default value is `USD` and all values allowed from the Pay Connector are accepted. + :param description: The description can be used to provide more details regarding the transaction. This information is submitted along with the payment details to the Payment Connector which are then posted on the transactions. + :param input: A list of inputs that should be accepted. Currently only `dtmf` is supported. All digits captured during a pay session are redacted from the logs. + :param min_postal_code_length: A positive integer that is used to validate the length of the `PostalCode` inputted by the user. User must enter this many digits. + :param parameter: A single-level JSON object used to pass custom parameters to payment processors. (Required for ACH payments). The information that has to be included here depends on the Connector. [Read more](https://www.twilio.com/console/voice/pay-connectors). + :param payment_connector: This is the unique name corresponding to the Pay Connector installed in the Twilio Add-ons. Learn more about [ Connectors](https://www.twilio.com/console/voice/pay-connectors). The default value is `Default`. + :param payment_method: + :param postal_code: Indicates whether the credit card postal code (zip code) is a required piece of payment information that must be provided by the caller. The default is `true`. + :param security_code: Indicates whether the credit card security code is a required piece of payment information that must be provided by the caller. The default is `true`. + :param timeout: The number of seconds that should wait for the caller to press a digit between each subsequent digit, after the first one, before moving on to validate the digits captured. The default is `5`, maximum is `600`. + :param token_type: + :param valid_card_types: Credit card types separated by space that Pay should accept. The default value is `visa mastercard amex` + + :returns: The created PaymentInstance + """ + + data = values.of( + { + "IdempotencyKey": idempotency_key, + "StatusCallback": status_callback, + "BankAccountType": bank_account_type, + "ChargeAmount": charge_amount, + "Currency": currency, + "Description": description, + "Input": input, + "MinPostalCodeLength": min_postal_code_length, + "Parameter": serialize.object(parameter), + "PaymentConnector": payment_connector, + "PaymentMethod": payment_method, + "PostalCode": serialize.boolean_to_string(postal_code), + "SecurityCode": serialize.boolean_to_string(security_code), + "Timeout": timeout, + "TokenType": token_type, + "ValidCardTypes": valid_card_types, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PaymentInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + async def create_async( + self, + idempotency_key: str, + status_callback: str, + bank_account_type: Union[ + "PaymentInstance.BankAccountType", object + ] = values.unset, + charge_amount: Union[float, object] = values.unset, + currency: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + input: Union[str, object] = values.unset, + min_postal_code_length: Union[int, object] = values.unset, + parameter: Union[object, object] = values.unset, + payment_connector: Union[str, object] = values.unset, + payment_method: Union["PaymentInstance.PaymentMethod", object] = values.unset, + postal_code: Union[bool, object] = values.unset, + security_code: Union[bool, object] = values.unset, + timeout: Union[int, object] = values.unset, + token_type: Union["PaymentInstance.TokenType", object] = values.unset, + valid_card_types: Union[str, object] = values.unset, + ) -> PaymentInstance: + """ + Asynchronously create the PaymentInstance + + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [expected StatusCallback values](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback) + :param bank_account_type: + :param charge_amount: A positive decimal value less than 1,000,000 to charge against the credit card or bank account. Default currency can be overwritten with `currency` field. Leave blank or set to 0 to tokenize. + :param currency: The currency of the `charge_amount`, formatted as [ISO 4127](http://www.iso.org/iso/home/standards/currency_codes.htm) format. The default value is `USD` and all values allowed from the Pay Connector are accepted. + :param description: The description can be used to provide more details regarding the transaction. This information is submitted along with the payment details to the Payment Connector which are then posted on the transactions. + :param input: A list of inputs that should be accepted. Currently only `dtmf` is supported. All digits captured during a pay session are redacted from the logs. + :param min_postal_code_length: A positive integer that is used to validate the length of the `PostalCode` inputted by the user. User must enter this many digits. + :param parameter: A single-level JSON object used to pass custom parameters to payment processors. (Required for ACH payments). The information that has to be included here depends on the Connector. [Read more](https://www.twilio.com/console/voice/pay-connectors). + :param payment_connector: This is the unique name corresponding to the Pay Connector installed in the Twilio Add-ons. Learn more about [ Connectors](https://www.twilio.com/console/voice/pay-connectors). The default value is `Default`. + :param payment_method: + :param postal_code: Indicates whether the credit card postal code (zip code) is a required piece of payment information that must be provided by the caller. The default is `true`. + :param security_code: Indicates whether the credit card security code is a required piece of payment information that must be provided by the caller. The default is `true`. + :param timeout: The number of seconds that should wait for the caller to press a digit between each subsequent digit, after the first one, before moving on to validate the digits captured. The default is `5`, maximum is `600`. + :param token_type: + :param valid_card_types: Credit card types separated by space that Pay should accept. The default value is `visa mastercard amex` + + :returns: The created PaymentInstance + """ + + data = values.of( + { + "IdempotencyKey": idempotency_key, + "StatusCallback": status_callback, + "BankAccountType": bank_account_type, + "ChargeAmount": charge_amount, + "Currency": currency, + "Description": description, + "Input": input, + "MinPostalCodeLength": min_postal_code_length, + "Parameter": serialize.object(parameter), + "PaymentConnector": payment_connector, + "PaymentMethod": payment_method, + "PostalCode": serialize.boolean_to_string(postal_code), + "SecurityCode": serialize.boolean_to_string(security_code), + "Timeout": timeout, + "TokenType": token_type, + "ValidCardTypes": valid_card_types, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PaymentInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def get(self, sid: str) -> PaymentContext: + """ + Constructs a PaymentContext + + :param sid: The SID of Payments session that needs to be updated. + """ + return PaymentContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> PaymentContext: + """ + Constructs a PaymentContext + + :param sid: The SID of Payments session that needs to be updated. + """ + return PaymentContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/recording.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/recording.py new file mode 100644 index 00000000..5b93ec6c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/recording.py @@ -0,0 +1,822 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RecordingInstance(InstanceResource): + + class Source(object): + DIALVERB = "DialVerb" + CONFERENCE = "Conference" + OUTBOUNDAPI = "OutboundAPI" + TRUNKING = "Trunking" + RECORDVERB = "RecordVerb" + STARTCALLRECORDINGAPI = "StartCallRecordingAPI" + STARTCONFERENCERECORDINGAPI = "StartConferenceRecordingAPI" + + class Status(object): + IN_PROGRESS = "in-progress" + PAUSED = "paused" + STOPPED = "stopped" + PROCESSING = "processing" + COMPLETED = "completed" + ABSENT = "absent" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording resource. + :ivar api_version: The API version used to make the recording. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Recording resource is associated with. + :ivar conference_sid: The Conference SID that identifies the conference associated with the recording, if a conference recording. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar start_time: The start time of the recording in GMT and in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar duration: The length of the recording in seconds. + :ivar sid: The unique string that that we created to identify the Recording resource. + :ivar price: The one-time cost of creating the recording in the `price_unit` currency. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar encryption_details: How to decrypt the recording if it was encrypted using [Call Recording Encryption](https://www.twilio.com/docs/voice/tutorials/voice-recording-encryption) feature. + :ivar price_unit: The currency used in the `price` property. Example: `USD`. + :ivar status: + :ivar channels: The number of channels in the final recording file. Can be: `1`, or `2`. Separating a two leg call into two separate channels of the recording file is supported in [Dial](https://www.twilio.com/docs/voice/twiml/dial#attributes-record) and [Outbound Rest API](https://www.twilio.com/docs/voice/make-calls) record options. + :ivar source: + :ivar error_code: The error code that describes why the recording is `absent`. The error code is described in our [Error Dictionary](https://www.twilio.com/docs/api/errors). This value is null if the recording `status` is not `absent`. + :ivar track: The recorded track. Can be: `inbound`, `outbound`, or `both`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + call_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.call_sid: Optional[str] = payload.get("call_sid") + self.conference_sid: Optional[str] = payload.get("conference_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.start_time: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("start_time") + ) + self.duration: Optional[str] = payload.get("duration") + self.sid: Optional[str] = payload.get("sid") + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.uri: Optional[str] = payload.get("uri") + self.encryption_details: Optional[Dict[str, object]] = payload.get( + "encryption_details" + ) + self.price_unit: Optional[str] = payload.get("price_unit") + self.status: Optional["RecordingInstance.Status"] = payload.get("status") + self.channels: Optional[int] = deserialize.integer(payload.get("channels")) + self.source: Optional["RecordingInstance.Source"] = payload.get("source") + self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) + self.track: Optional[str] = payload.get("track") + + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid or self.sid, + } + self._context: Optional[RecordingContext] = None + + @property + def _proxy(self) -> "RecordingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RecordingContext for this RecordingInstance + """ + if self._context is None: + self._context = RecordingContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RecordingInstance": + """ + Fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RecordingInstance": + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> "RecordingInstance": + """ + Update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance + """ + return self._proxy.update( + status=status, + pause_behavior=pause_behavior, + ) + + async def update_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> "RecordingInstance": + """ + Asynchronous coroutine to update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance + """ + return await self._proxy.update_async( + status=status, + pause_behavior=pause_behavior, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RecordingContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): + """ + Initialize the RecordingContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording resource to update. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resource to update. + :param sid: The Twilio-provided string that uniquely identifies the Recording resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid, + } + self._uri = ( + "/Accounts/{account_sid}/Calls/{call_sid}/Recordings/{sid}.json".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RecordingInstance: + """ + Fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RecordingInstance: + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> RecordingInstance: + """ + Update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance + """ + + data = values.of( + { + "Status": status, + "PauseBehavior": pause_behavior, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> RecordingInstance: + """ + Asynchronous coroutine to update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance + """ + + data = values.of( + { + "Status": status, + "PauseBehavior": pause_behavior, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RecordingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RecordingInstance: + """ + Build an instance of RecordingInstance + + :param payload: Payload response from the API + """ + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RecordingList(ListResource): + + def __init__(self, version: Version, account_sid: str, call_sid: str): + """ + Initialize the RecordingList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording resources to read. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + self._uri = "/Accounts/{account_sid}/Calls/{call_sid}/Recordings.json".format( + **self._solution + ) + + def create( + self, + recording_status_callback_event: Union[List[str], object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + ) -> RecordingInstance: + """ + Create the RecordingInstance + + :param recording_status_callback_event: The recording status events on which we should call the `recording_status_callback` URL. Can be: `in-progress`, `completed` and `absent` and the default is `completed`. Separate multiple event values with a space. + :param recording_status_callback: The URL we should call using the `recording_status_callback_method` on each recording event specified in `recording_status_callback_event`. For more information, see [RecordingStatusCallback parameters](https://www.twilio.com/docs/voice/api/recording#recordingstatuscallback). + :param recording_status_callback_method: The HTTP method we should use to call `recording_status_callback`. Can be: `GET` or `POST` and the default is `POST`. + :param trim: Whether to trim any leading and trailing silence in the recording. Can be: `trim-silence` or `do-not-trim` and the default is `do-not-trim`. `trim-silence` trims the silence from the beginning and end of the recording and `do-not-trim` does not. + :param recording_channels: The number of channels used in the recording. Can be: `mono` or `dual` and the default is `mono`. `mono` records all parties of the call into one channel. `dual` records each party of a 2-party call into separate channels. + :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is generated from Twilio. `both` records the audio that is received and generated by Twilio. + + :returns: The created RecordingInstance + """ + + data = values.of( + { + "RecordingStatusCallbackEvent": serialize.map( + recording_status_callback_event, lambda e: e + ), + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "Trim": trim, + "RecordingChannels": recording_channels, + "RecordingTrack": recording_track, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + async def create_async( + self, + recording_status_callback_event: Union[List[str], object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + ) -> RecordingInstance: + """ + Asynchronously create the RecordingInstance + + :param recording_status_callback_event: The recording status events on which we should call the `recording_status_callback` URL. Can be: `in-progress`, `completed` and `absent` and the default is `completed`. Separate multiple event values with a space. + :param recording_status_callback: The URL we should call using the `recording_status_callback_method` on each recording event specified in `recording_status_callback_event`. For more information, see [RecordingStatusCallback parameters](https://www.twilio.com/docs/voice/api/recording#recordingstatuscallback). + :param recording_status_callback_method: The HTTP method we should use to call `recording_status_callback`. Can be: `GET` or `POST` and the default is `POST`. + :param trim: Whether to trim any leading and trailing silence in the recording. Can be: `trim-silence` or `do-not-trim` and the default is `do-not-trim`. `trim-silence` trims the silence from the beginning and end of the recording and `do-not-trim` does not. + :param recording_channels: The number of channels used in the recording. Can be: `mono` or `dual` and the default is `mono`. `mono` records all parties of the call into one channel. `dual` records each party of a 2-party call into separate channels. + :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is generated from Twilio. `both` records the audio that is received and generated by Twilio. + + :returns: The created RecordingInstance + """ + + data = values.of( + { + "RecordingStatusCallbackEvent": serialize.map( + recording_status_callback_event, lambda e: e + ), + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "Trim": trim, + "RecordingChannels": recording_channels, + "RecordingTrack": recording_track, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def stream( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RecordingInstance]: + """ + Streams RecordingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RecordingInstance]: + """ + Asynchronously streams RecordingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RecordingInstance]: + """ + Lists RecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RecordingInstance]: + """ + Asynchronously lists RecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RecordingPage: + """ + Retrieve a single page of RecordingInstance records from the API. + Request is executed immediately + + :param date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordingInstance + """ + data = values.of( + { + "DateCreated": serialize.iso8601_date(date_created), + "DateCreated<": serialize.iso8601_date(date_created_before), + "DateCreated>": serialize.iso8601_date(date_created_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordingPage(self._version, response, self._solution) + + async def page_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RecordingPage: + """ + Asynchronously retrieve a single page of RecordingInstance records from the API. + Request is executed immediately + + :param date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordingInstance + """ + data = values.of( + { + "DateCreated": serialize.iso8601_date(date_created), + "DateCreated<": serialize.iso8601_date(date_created_before), + "DateCreated>": serialize.iso8601_date(date_created_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RecordingPage: + """ + Retrieve a specific page of RecordingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RecordingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RecordingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RecordingPage: + """ + Asynchronously retrieve a specific page of RecordingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RecordingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RecordingPage(self._version, response, self._solution) + + def get(self, sid: str) -> RecordingContext: + """ + Constructs a RecordingContext + + :param sid: The Twilio-provided string that uniquely identifies the Recording resource to update. + """ + return RecordingContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> RecordingContext: + """ + Constructs a RecordingContext + + :param sid: The Twilio-provided string that uniquely identifies the Recording resource to update. + """ + return RecordingContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/siprec.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/siprec.py new file mode 100644 index 00000000..d808331c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/siprec.py @@ -0,0 +1,1561 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class SiprecInstance(InstanceResource): + + class Status(object): + IN_PROGRESS = "in-progress" + STOPPED = "stopped" + + class Track(object): + INBOUND_TRACK = "inbound_track" + OUTBOUND_TRACK = "outbound_track" + BOTH_TRACKS = "both_tracks" + + class UpdateStatus(object): + STOPPED = "stopped" + + """ + :ivar sid: The SID of the Siprec resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Siprec resource. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Siprec resource is associated with. + :ivar name: The user-specified name of this Siprec, if one was given when the Siprec was created. This may be used to stop the Siprec. + :ivar status: + :ivar date_updated: The date and time in GMT that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + call_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.call_sid: Optional[str] = payload.get("call_sid") + self.name: Optional[str] = payload.get("name") + self.status: Optional["SiprecInstance.Status"] = payload.get("status") + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid or self.sid, + } + self._context: Optional[SiprecContext] = None + + @property + def _proxy(self) -> "SiprecContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SiprecContext for this SiprecInstance + """ + if self._context is None: + self._context = SiprecContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return self._context + + def update(self, status: "SiprecInstance.UpdateStatus") -> "SiprecInstance": + """ + Update the SiprecInstance + + :param status: + + :returns: The updated SiprecInstance + """ + return self._proxy.update( + status=status, + ) + + async def update_async( + self, status: "SiprecInstance.UpdateStatus" + ) -> "SiprecInstance": + """ + Asynchronous coroutine to update the SiprecInstance + + :param status: + + :returns: The updated SiprecInstance + """ + return await self._proxy.update_async( + status=status, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SiprecContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): + """ + Initialize the SiprecContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Siprec resource. + :param call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Siprec resource is associated with. + :param sid: The SID of the Siprec resource, or the `name` used when creating the resource + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Calls/{call_sid}/Siprec/{sid}.json".format( + **self._solution + ) + + def update(self, status: "SiprecInstance.UpdateStatus") -> SiprecInstance: + """ + Update the SiprecInstance + + :param status: + + :returns: The updated SiprecInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SiprecInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, status: "SiprecInstance.UpdateStatus" + ) -> SiprecInstance: + """ + Asynchronous coroutine to update the SiprecInstance + + :param status: + + :returns: The updated SiprecInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SiprecInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SiprecList(ListResource): + + def __init__(self, version: Version, account_sid: str, call_sid: str): + """ + Initialize the SiprecList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Siprec resource. + :param call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Siprec resource is associated with. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + self._uri = "/Accounts/{account_sid}/Calls/{call_sid}/Siprec.json".format( + **self._solution + ) + + def create( + self, + name: Union[str, object] = values.unset, + connector_name: Union[str, object] = values.unset, + track: Union["SiprecInstance.Track", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + parameter1_name: Union[str, object] = values.unset, + parameter1_value: Union[str, object] = values.unset, + parameter2_name: Union[str, object] = values.unset, + parameter2_value: Union[str, object] = values.unset, + parameter3_name: Union[str, object] = values.unset, + parameter3_value: Union[str, object] = values.unset, + parameter4_name: Union[str, object] = values.unset, + parameter4_value: Union[str, object] = values.unset, + parameter5_name: Union[str, object] = values.unset, + parameter5_value: Union[str, object] = values.unset, + parameter6_name: Union[str, object] = values.unset, + parameter6_value: Union[str, object] = values.unset, + parameter7_name: Union[str, object] = values.unset, + parameter7_value: Union[str, object] = values.unset, + parameter8_name: Union[str, object] = values.unset, + parameter8_value: Union[str, object] = values.unset, + parameter9_name: Union[str, object] = values.unset, + parameter9_value: Union[str, object] = values.unset, + parameter10_name: Union[str, object] = values.unset, + parameter10_value: Union[str, object] = values.unset, + parameter11_name: Union[str, object] = values.unset, + parameter11_value: Union[str, object] = values.unset, + parameter12_name: Union[str, object] = values.unset, + parameter12_value: Union[str, object] = values.unset, + parameter13_name: Union[str, object] = values.unset, + parameter13_value: Union[str, object] = values.unset, + parameter14_name: Union[str, object] = values.unset, + parameter14_value: Union[str, object] = values.unset, + parameter15_name: Union[str, object] = values.unset, + parameter15_value: Union[str, object] = values.unset, + parameter16_name: Union[str, object] = values.unset, + parameter16_value: Union[str, object] = values.unset, + parameter17_name: Union[str, object] = values.unset, + parameter17_value: Union[str, object] = values.unset, + parameter18_name: Union[str, object] = values.unset, + parameter18_value: Union[str, object] = values.unset, + parameter19_name: Union[str, object] = values.unset, + parameter19_value: Union[str, object] = values.unset, + parameter20_name: Union[str, object] = values.unset, + parameter20_value: Union[str, object] = values.unset, + parameter21_name: Union[str, object] = values.unset, + parameter21_value: Union[str, object] = values.unset, + parameter22_name: Union[str, object] = values.unset, + parameter22_value: Union[str, object] = values.unset, + parameter23_name: Union[str, object] = values.unset, + parameter23_value: Union[str, object] = values.unset, + parameter24_name: Union[str, object] = values.unset, + parameter24_value: Union[str, object] = values.unset, + parameter25_name: Union[str, object] = values.unset, + parameter25_value: Union[str, object] = values.unset, + parameter26_name: Union[str, object] = values.unset, + parameter26_value: Union[str, object] = values.unset, + parameter27_name: Union[str, object] = values.unset, + parameter27_value: Union[str, object] = values.unset, + parameter28_name: Union[str, object] = values.unset, + parameter28_value: Union[str, object] = values.unset, + parameter29_name: Union[str, object] = values.unset, + parameter29_value: Union[str, object] = values.unset, + parameter30_name: Union[str, object] = values.unset, + parameter30_value: Union[str, object] = values.unset, + parameter31_name: Union[str, object] = values.unset, + parameter31_value: Union[str, object] = values.unset, + parameter32_name: Union[str, object] = values.unset, + parameter32_value: Union[str, object] = values.unset, + parameter33_name: Union[str, object] = values.unset, + parameter33_value: Union[str, object] = values.unset, + parameter34_name: Union[str, object] = values.unset, + parameter34_value: Union[str, object] = values.unset, + parameter35_name: Union[str, object] = values.unset, + parameter35_value: Union[str, object] = values.unset, + parameter36_name: Union[str, object] = values.unset, + parameter36_value: Union[str, object] = values.unset, + parameter37_name: Union[str, object] = values.unset, + parameter37_value: Union[str, object] = values.unset, + parameter38_name: Union[str, object] = values.unset, + parameter38_value: Union[str, object] = values.unset, + parameter39_name: Union[str, object] = values.unset, + parameter39_value: Union[str, object] = values.unset, + parameter40_name: Union[str, object] = values.unset, + parameter40_value: Union[str, object] = values.unset, + parameter41_name: Union[str, object] = values.unset, + parameter41_value: Union[str, object] = values.unset, + parameter42_name: Union[str, object] = values.unset, + parameter42_value: Union[str, object] = values.unset, + parameter43_name: Union[str, object] = values.unset, + parameter43_value: Union[str, object] = values.unset, + parameter44_name: Union[str, object] = values.unset, + parameter44_value: Union[str, object] = values.unset, + parameter45_name: Union[str, object] = values.unset, + parameter45_value: Union[str, object] = values.unset, + parameter46_name: Union[str, object] = values.unset, + parameter46_value: Union[str, object] = values.unset, + parameter47_name: Union[str, object] = values.unset, + parameter47_value: Union[str, object] = values.unset, + parameter48_name: Union[str, object] = values.unset, + parameter48_value: Union[str, object] = values.unset, + parameter49_name: Union[str, object] = values.unset, + parameter49_value: Union[str, object] = values.unset, + parameter50_name: Union[str, object] = values.unset, + parameter50_value: Union[str, object] = values.unset, + parameter51_name: Union[str, object] = values.unset, + parameter51_value: Union[str, object] = values.unset, + parameter52_name: Union[str, object] = values.unset, + parameter52_value: Union[str, object] = values.unset, + parameter53_name: Union[str, object] = values.unset, + parameter53_value: Union[str, object] = values.unset, + parameter54_name: Union[str, object] = values.unset, + parameter54_value: Union[str, object] = values.unset, + parameter55_name: Union[str, object] = values.unset, + parameter55_value: Union[str, object] = values.unset, + parameter56_name: Union[str, object] = values.unset, + parameter56_value: Union[str, object] = values.unset, + parameter57_name: Union[str, object] = values.unset, + parameter57_value: Union[str, object] = values.unset, + parameter58_name: Union[str, object] = values.unset, + parameter58_value: Union[str, object] = values.unset, + parameter59_name: Union[str, object] = values.unset, + parameter59_value: Union[str, object] = values.unset, + parameter60_name: Union[str, object] = values.unset, + parameter60_value: Union[str, object] = values.unset, + parameter61_name: Union[str, object] = values.unset, + parameter61_value: Union[str, object] = values.unset, + parameter62_name: Union[str, object] = values.unset, + parameter62_value: Union[str, object] = values.unset, + parameter63_name: Union[str, object] = values.unset, + parameter63_value: Union[str, object] = values.unset, + parameter64_name: Union[str, object] = values.unset, + parameter64_value: Union[str, object] = values.unset, + parameter65_name: Union[str, object] = values.unset, + parameter65_value: Union[str, object] = values.unset, + parameter66_name: Union[str, object] = values.unset, + parameter66_value: Union[str, object] = values.unset, + parameter67_name: Union[str, object] = values.unset, + parameter67_value: Union[str, object] = values.unset, + parameter68_name: Union[str, object] = values.unset, + parameter68_value: Union[str, object] = values.unset, + parameter69_name: Union[str, object] = values.unset, + parameter69_value: Union[str, object] = values.unset, + parameter70_name: Union[str, object] = values.unset, + parameter70_value: Union[str, object] = values.unset, + parameter71_name: Union[str, object] = values.unset, + parameter71_value: Union[str, object] = values.unset, + parameter72_name: Union[str, object] = values.unset, + parameter72_value: Union[str, object] = values.unset, + parameter73_name: Union[str, object] = values.unset, + parameter73_value: Union[str, object] = values.unset, + parameter74_name: Union[str, object] = values.unset, + parameter74_value: Union[str, object] = values.unset, + parameter75_name: Union[str, object] = values.unset, + parameter75_value: Union[str, object] = values.unset, + parameter76_name: Union[str, object] = values.unset, + parameter76_value: Union[str, object] = values.unset, + parameter77_name: Union[str, object] = values.unset, + parameter77_value: Union[str, object] = values.unset, + parameter78_name: Union[str, object] = values.unset, + parameter78_value: Union[str, object] = values.unset, + parameter79_name: Union[str, object] = values.unset, + parameter79_value: Union[str, object] = values.unset, + parameter80_name: Union[str, object] = values.unset, + parameter80_value: Union[str, object] = values.unset, + parameter81_name: Union[str, object] = values.unset, + parameter81_value: Union[str, object] = values.unset, + parameter82_name: Union[str, object] = values.unset, + parameter82_value: Union[str, object] = values.unset, + parameter83_name: Union[str, object] = values.unset, + parameter83_value: Union[str, object] = values.unset, + parameter84_name: Union[str, object] = values.unset, + parameter84_value: Union[str, object] = values.unset, + parameter85_name: Union[str, object] = values.unset, + parameter85_value: Union[str, object] = values.unset, + parameter86_name: Union[str, object] = values.unset, + parameter86_value: Union[str, object] = values.unset, + parameter87_name: Union[str, object] = values.unset, + parameter87_value: Union[str, object] = values.unset, + parameter88_name: Union[str, object] = values.unset, + parameter88_value: Union[str, object] = values.unset, + parameter89_name: Union[str, object] = values.unset, + parameter89_value: Union[str, object] = values.unset, + parameter90_name: Union[str, object] = values.unset, + parameter90_value: Union[str, object] = values.unset, + parameter91_name: Union[str, object] = values.unset, + parameter91_value: Union[str, object] = values.unset, + parameter92_name: Union[str, object] = values.unset, + parameter92_value: Union[str, object] = values.unset, + parameter93_name: Union[str, object] = values.unset, + parameter93_value: Union[str, object] = values.unset, + parameter94_name: Union[str, object] = values.unset, + parameter94_value: Union[str, object] = values.unset, + parameter95_name: Union[str, object] = values.unset, + parameter95_value: Union[str, object] = values.unset, + parameter96_name: Union[str, object] = values.unset, + parameter96_value: Union[str, object] = values.unset, + parameter97_name: Union[str, object] = values.unset, + parameter97_value: Union[str, object] = values.unset, + parameter98_name: Union[str, object] = values.unset, + parameter98_value: Union[str, object] = values.unset, + parameter99_name: Union[str, object] = values.unset, + parameter99_value: Union[str, object] = values.unset, + ) -> SiprecInstance: + """ + Create the SiprecInstance + + :param name: The user-specified name of this Siprec, if one was given when the Siprec was created. This may be used to stop the Siprec. + :param connector_name: Unique name used when configuring the connector via Marketplace Add-on. + :param track: + :param status_callback: Absolute URL of the status callback. + :param status_callback_method: The http method for the status_callback (one of GET, POST). + :param parameter1_name: Parameter name + :param parameter1_value: Parameter value + :param parameter2_name: Parameter name + :param parameter2_value: Parameter value + :param parameter3_name: Parameter name + :param parameter3_value: Parameter value + :param parameter4_name: Parameter name + :param parameter4_value: Parameter value + :param parameter5_name: Parameter name + :param parameter5_value: Parameter value + :param parameter6_name: Parameter name + :param parameter6_value: Parameter value + :param parameter7_name: Parameter name + :param parameter7_value: Parameter value + :param parameter8_name: Parameter name + :param parameter8_value: Parameter value + :param parameter9_name: Parameter name + :param parameter9_value: Parameter value + :param parameter10_name: Parameter name + :param parameter10_value: Parameter value + :param parameter11_name: Parameter name + :param parameter11_value: Parameter value + :param parameter12_name: Parameter name + :param parameter12_value: Parameter value + :param parameter13_name: Parameter name + :param parameter13_value: Parameter value + :param parameter14_name: Parameter name + :param parameter14_value: Parameter value + :param parameter15_name: Parameter name + :param parameter15_value: Parameter value + :param parameter16_name: Parameter name + :param parameter16_value: Parameter value + :param parameter17_name: Parameter name + :param parameter17_value: Parameter value + :param parameter18_name: Parameter name + :param parameter18_value: Parameter value + :param parameter19_name: Parameter name + :param parameter19_value: Parameter value + :param parameter20_name: Parameter name + :param parameter20_value: Parameter value + :param parameter21_name: Parameter name + :param parameter21_value: Parameter value + :param parameter22_name: Parameter name + :param parameter22_value: Parameter value + :param parameter23_name: Parameter name + :param parameter23_value: Parameter value + :param parameter24_name: Parameter name + :param parameter24_value: Parameter value + :param parameter25_name: Parameter name + :param parameter25_value: Parameter value + :param parameter26_name: Parameter name + :param parameter26_value: Parameter value + :param parameter27_name: Parameter name + :param parameter27_value: Parameter value + :param parameter28_name: Parameter name + :param parameter28_value: Parameter value + :param parameter29_name: Parameter name + :param parameter29_value: Parameter value + :param parameter30_name: Parameter name + :param parameter30_value: Parameter value + :param parameter31_name: Parameter name + :param parameter31_value: Parameter value + :param parameter32_name: Parameter name + :param parameter32_value: Parameter value + :param parameter33_name: Parameter name + :param parameter33_value: Parameter value + :param parameter34_name: Parameter name + :param parameter34_value: Parameter value + :param parameter35_name: Parameter name + :param parameter35_value: Parameter value + :param parameter36_name: Parameter name + :param parameter36_value: Parameter value + :param parameter37_name: Parameter name + :param parameter37_value: Parameter value + :param parameter38_name: Parameter name + :param parameter38_value: Parameter value + :param parameter39_name: Parameter name + :param parameter39_value: Parameter value + :param parameter40_name: Parameter name + :param parameter40_value: Parameter value + :param parameter41_name: Parameter name + :param parameter41_value: Parameter value + :param parameter42_name: Parameter name + :param parameter42_value: Parameter value + :param parameter43_name: Parameter name + :param parameter43_value: Parameter value + :param parameter44_name: Parameter name + :param parameter44_value: Parameter value + :param parameter45_name: Parameter name + :param parameter45_value: Parameter value + :param parameter46_name: Parameter name + :param parameter46_value: Parameter value + :param parameter47_name: Parameter name + :param parameter47_value: Parameter value + :param parameter48_name: Parameter name + :param parameter48_value: Parameter value + :param parameter49_name: Parameter name + :param parameter49_value: Parameter value + :param parameter50_name: Parameter name + :param parameter50_value: Parameter value + :param parameter51_name: Parameter name + :param parameter51_value: Parameter value + :param parameter52_name: Parameter name + :param parameter52_value: Parameter value + :param parameter53_name: Parameter name + :param parameter53_value: Parameter value + :param parameter54_name: Parameter name + :param parameter54_value: Parameter value + :param parameter55_name: Parameter name + :param parameter55_value: Parameter value + :param parameter56_name: Parameter name + :param parameter56_value: Parameter value + :param parameter57_name: Parameter name + :param parameter57_value: Parameter value + :param parameter58_name: Parameter name + :param parameter58_value: Parameter value + :param parameter59_name: Parameter name + :param parameter59_value: Parameter value + :param parameter60_name: Parameter name + :param parameter60_value: Parameter value + :param parameter61_name: Parameter name + :param parameter61_value: Parameter value + :param parameter62_name: Parameter name + :param parameter62_value: Parameter value + :param parameter63_name: Parameter name + :param parameter63_value: Parameter value + :param parameter64_name: Parameter name + :param parameter64_value: Parameter value + :param parameter65_name: Parameter name + :param parameter65_value: Parameter value + :param parameter66_name: Parameter name + :param parameter66_value: Parameter value + :param parameter67_name: Parameter name + :param parameter67_value: Parameter value + :param parameter68_name: Parameter name + :param parameter68_value: Parameter value + :param parameter69_name: Parameter name + :param parameter69_value: Parameter value + :param parameter70_name: Parameter name + :param parameter70_value: Parameter value + :param parameter71_name: Parameter name + :param parameter71_value: Parameter value + :param parameter72_name: Parameter name + :param parameter72_value: Parameter value + :param parameter73_name: Parameter name + :param parameter73_value: Parameter value + :param parameter74_name: Parameter name + :param parameter74_value: Parameter value + :param parameter75_name: Parameter name + :param parameter75_value: Parameter value + :param parameter76_name: Parameter name + :param parameter76_value: Parameter value + :param parameter77_name: Parameter name + :param parameter77_value: Parameter value + :param parameter78_name: Parameter name + :param parameter78_value: Parameter value + :param parameter79_name: Parameter name + :param parameter79_value: Parameter value + :param parameter80_name: Parameter name + :param parameter80_value: Parameter value + :param parameter81_name: Parameter name + :param parameter81_value: Parameter value + :param parameter82_name: Parameter name + :param parameter82_value: Parameter value + :param parameter83_name: Parameter name + :param parameter83_value: Parameter value + :param parameter84_name: Parameter name + :param parameter84_value: Parameter value + :param parameter85_name: Parameter name + :param parameter85_value: Parameter value + :param parameter86_name: Parameter name + :param parameter86_value: Parameter value + :param parameter87_name: Parameter name + :param parameter87_value: Parameter value + :param parameter88_name: Parameter name + :param parameter88_value: Parameter value + :param parameter89_name: Parameter name + :param parameter89_value: Parameter value + :param parameter90_name: Parameter name + :param parameter90_value: Parameter value + :param parameter91_name: Parameter name + :param parameter91_value: Parameter value + :param parameter92_name: Parameter name + :param parameter92_value: Parameter value + :param parameter93_name: Parameter name + :param parameter93_value: Parameter value + :param parameter94_name: Parameter name + :param parameter94_value: Parameter value + :param parameter95_name: Parameter name + :param parameter95_value: Parameter value + :param parameter96_name: Parameter name + :param parameter96_value: Parameter value + :param parameter97_name: Parameter name + :param parameter97_value: Parameter value + :param parameter98_name: Parameter name + :param parameter98_value: Parameter value + :param parameter99_name: Parameter name + :param parameter99_value: Parameter value + + :returns: The created SiprecInstance + """ + + data = values.of( + { + "Name": name, + "ConnectorName": connector_name, + "Track": track, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Parameter1.Name": parameter1_name, + "Parameter1.Value": parameter1_value, + "Parameter2.Name": parameter2_name, + "Parameter2.Value": parameter2_value, + "Parameter3.Name": parameter3_name, + "Parameter3.Value": parameter3_value, + "Parameter4.Name": parameter4_name, + "Parameter4.Value": parameter4_value, + "Parameter5.Name": parameter5_name, + "Parameter5.Value": parameter5_value, + "Parameter6.Name": parameter6_name, + "Parameter6.Value": parameter6_value, + "Parameter7.Name": parameter7_name, + "Parameter7.Value": parameter7_value, + "Parameter8.Name": parameter8_name, + "Parameter8.Value": parameter8_value, + "Parameter9.Name": parameter9_name, + "Parameter9.Value": parameter9_value, + "Parameter10.Name": parameter10_name, + "Parameter10.Value": parameter10_value, + "Parameter11.Name": parameter11_name, + "Parameter11.Value": parameter11_value, + "Parameter12.Name": parameter12_name, + "Parameter12.Value": parameter12_value, + "Parameter13.Name": parameter13_name, + "Parameter13.Value": parameter13_value, + "Parameter14.Name": parameter14_name, + "Parameter14.Value": parameter14_value, + "Parameter15.Name": parameter15_name, + "Parameter15.Value": parameter15_value, + "Parameter16.Name": parameter16_name, + "Parameter16.Value": parameter16_value, + "Parameter17.Name": parameter17_name, + "Parameter17.Value": parameter17_value, + "Parameter18.Name": parameter18_name, + "Parameter18.Value": parameter18_value, + "Parameter19.Name": parameter19_name, + "Parameter19.Value": parameter19_value, + "Parameter20.Name": parameter20_name, + "Parameter20.Value": parameter20_value, + "Parameter21.Name": parameter21_name, + "Parameter21.Value": parameter21_value, + "Parameter22.Name": parameter22_name, + "Parameter22.Value": parameter22_value, + "Parameter23.Name": parameter23_name, + "Parameter23.Value": parameter23_value, + "Parameter24.Name": parameter24_name, + "Parameter24.Value": parameter24_value, + "Parameter25.Name": parameter25_name, + "Parameter25.Value": parameter25_value, + "Parameter26.Name": parameter26_name, + "Parameter26.Value": parameter26_value, + "Parameter27.Name": parameter27_name, + "Parameter27.Value": parameter27_value, + "Parameter28.Name": parameter28_name, + "Parameter28.Value": parameter28_value, + "Parameter29.Name": parameter29_name, + "Parameter29.Value": parameter29_value, + "Parameter30.Name": parameter30_name, + "Parameter30.Value": parameter30_value, + "Parameter31.Name": parameter31_name, + "Parameter31.Value": parameter31_value, + "Parameter32.Name": parameter32_name, + "Parameter32.Value": parameter32_value, + "Parameter33.Name": parameter33_name, + "Parameter33.Value": parameter33_value, + "Parameter34.Name": parameter34_name, + "Parameter34.Value": parameter34_value, + "Parameter35.Name": parameter35_name, + "Parameter35.Value": parameter35_value, + "Parameter36.Name": parameter36_name, + "Parameter36.Value": parameter36_value, + "Parameter37.Name": parameter37_name, + "Parameter37.Value": parameter37_value, + "Parameter38.Name": parameter38_name, + "Parameter38.Value": parameter38_value, + "Parameter39.Name": parameter39_name, + "Parameter39.Value": parameter39_value, + "Parameter40.Name": parameter40_name, + "Parameter40.Value": parameter40_value, + "Parameter41.Name": parameter41_name, + "Parameter41.Value": parameter41_value, + "Parameter42.Name": parameter42_name, + "Parameter42.Value": parameter42_value, + "Parameter43.Name": parameter43_name, + "Parameter43.Value": parameter43_value, + "Parameter44.Name": parameter44_name, + "Parameter44.Value": parameter44_value, + "Parameter45.Name": parameter45_name, + "Parameter45.Value": parameter45_value, + "Parameter46.Name": parameter46_name, + "Parameter46.Value": parameter46_value, + "Parameter47.Name": parameter47_name, + "Parameter47.Value": parameter47_value, + "Parameter48.Name": parameter48_name, + "Parameter48.Value": parameter48_value, + "Parameter49.Name": parameter49_name, + "Parameter49.Value": parameter49_value, + "Parameter50.Name": parameter50_name, + "Parameter50.Value": parameter50_value, + "Parameter51.Name": parameter51_name, + "Parameter51.Value": parameter51_value, + "Parameter52.Name": parameter52_name, + "Parameter52.Value": parameter52_value, + "Parameter53.Name": parameter53_name, + "Parameter53.Value": parameter53_value, + "Parameter54.Name": parameter54_name, + "Parameter54.Value": parameter54_value, + "Parameter55.Name": parameter55_name, + "Parameter55.Value": parameter55_value, + "Parameter56.Name": parameter56_name, + "Parameter56.Value": parameter56_value, + "Parameter57.Name": parameter57_name, + "Parameter57.Value": parameter57_value, + "Parameter58.Name": parameter58_name, + "Parameter58.Value": parameter58_value, + "Parameter59.Name": parameter59_name, + "Parameter59.Value": parameter59_value, + "Parameter60.Name": parameter60_name, + "Parameter60.Value": parameter60_value, + "Parameter61.Name": parameter61_name, + "Parameter61.Value": parameter61_value, + "Parameter62.Name": parameter62_name, + "Parameter62.Value": parameter62_value, + "Parameter63.Name": parameter63_name, + "Parameter63.Value": parameter63_value, + "Parameter64.Name": parameter64_name, + "Parameter64.Value": parameter64_value, + "Parameter65.Name": parameter65_name, + "Parameter65.Value": parameter65_value, + "Parameter66.Name": parameter66_name, + "Parameter66.Value": parameter66_value, + "Parameter67.Name": parameter67_name, + "Parameter67.Value": parameter67_value, + "Parameter68.Name": parameter68_name, + "Parameter68.Value": parameter68_value, + "Parameter69.Name": parameter69_name, + "Parameter69.Value": parameter69_value, + "Parameter70.Name": parameter70_name, + "Parameter70.Value": parameter70_value, + "Parameter71.Name": parameter71_name, + "Parameter71.Value": parameter71_value, + "Parameter72.Name": parameter72_name, + "Parameter72.Value": parameter72_value, + "Parameter73.Name": parameter73_name, + "Parameter73.Value": parameter73_value, + "Parameter74.Name": parameter74_name, + "Parameter74.Value": parameter74_value, + "Parameter75.Name": parameter75_name, + "Parameter75.Value": parameter75_value, + "Parameter76.Name": parameter76_name, + "Parameter76.Value": parameter76_value, + "Parameter77.Name": parameter77_name, + "Parameter77.Value": parameter77_value, + "Parameter78.Name": parameter78_name, + "Parameter78.Value": parameter78_value, + "Parameter79.Name": parameter79_name, + "Parameter79.Value": parameter79_value, + "Parameter80.Name": parameter80_name, + "Parameter80.Value": parameter80_value, + "Parameter81.Name": parameter81_name, + "Parameter81.Value": parameter81_value, + "Parameter82.Name": parameter82_name, + "Parameter82.Value": parameter82_value, + "Parameter83.Name": parameter83_name, + "Parameter83.Value": parameter83_value, + "Parameter84.Name": parameter84_name, + "Parameter84.Value": parameter84_value, + "Parameter85.Name": parameter85_name, + "Parameter85.Value": parameter85_value, + "Parameter86.Name": parameter86_name, + "Parameter86.Value": parameter86_value, + "Parameter87.Name": parameter87_name, + "Parameter87.Value": parameter87_value, + "Parameter88.Name": parameter88_name, + "Parameter88.Value": parameter88_value, + "Parameter89.Name": parameter89_name, + "Parameter89.Value": parameter89_value, + "Parameter90.Name": parameter90_name, + "Parameter90.Value": parameter90_value, + "Parameter91.Name": parameter91_name, + "Parameter91.Value": parameter91_value, + "Parameter92.Name": parameter92_name, + "Parameter92.Value": parameter92_value, + "Parameter93.Name": parameter93_name, + "Parameter93.Value": parameter93_value, + "Parameter94.Name": parameter94_name, + "Parameter94.Value": parameter94_value, + "Parameter95.Name": parameter95_name, + "Parameter95.Value": parameter95_value, + "Parameter96.Name": parameter96_name, + "Parameter96.Value": parameter96_value, + "Parameter97.Name": parameter97_name, + "Parameter97.Value": parameter97_value, + "Parameter98.Name": parameter98_name, + "Parameter98.Value": parameter98_value, + "Parameter99.Name": parameter99_name, + "Parameter99.Value": parameter99_value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SiprecInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + async def create_async( + self, + name: Union[str, object] = values.unset, + connector_name: Union[str, object] = values.unset, + track: Union["SiprecInstance.Track", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + parameter1_name: Union[str, object] = values.unset, + parameter1_value: Union[str, object] = values.unset, + parameter2_name: Union[str, object] = values.unset, + parameter2_value: Union[str, object] = values.unset, + parameter3_name: Union[str, object] = values.unset, + parameter3_value: Union[str, object] = values.unset, + parameter4_name: Union[str, object] = values.unset, + parameter4_value: Union[str, object] = values.unset, + parameter5_name: Union[str, object] = values.unset, + parameter5_value: Union[str, object] = values.unset, + parameter6_name: Union[str, object] = values.unset, + parameter6_value: Union[str, object] = values.unset, + parameter7_name: Union[str, object] = values.unset, + parameter7_value: Union[str, object] = values.unset, + parameter8_name: Union[str, object] = values.unset, + parameter8_value: Union[str, object] = values.unset, + parameter9_name: Union[str, object] = values.unset, + parameter9_value: Union[str, object] = values.unset, + parameter10_name: Union[str, object] = values.unset, + parameter10_value: Union[str, object] = values.unset, + parameter11_name: Union[str, object] = values.unset, + parameter11_value: Union[str, object] = values.unset, + parameter12_name: Union[str, object] = values.unset, + parameter12_value: Union[str, object] = values.unset, + parameter13_name: Union[str, object] = values.unset, + parameter13_value: Union[str, object] = values.unset, + parameter14_name: Union[str, object] = values.unset, + parameter14_value: Union[str, object] = values.unset, + parameter15_name: Union[str, object] = values.unset, + parameter15_value: Union[str, object] = values.unset, + parameter16_name: Union[str, object] = values.unset, + parameter16_value: Union[str, object] = values.unset, + parameter17_name: Union[str, object] = values.unset, + parameter17_value: Union[str, object] = values.unset, + parameter18_name: Union[str, object] = values.unset, + parameter18_value: Union[str, object] = values.unset, + parameter19_name: Union[str, object] = values.unset, + parameter19_value: Union[str, object] = values.unset, + parameter20_name: Union[str, object] = values.unset, + parameter20_value: Union[str, object] = values.unset, + parameter21_name: Union[str, object] = values.unset, + parameter21_value: Union[str, object] = values.unset, + parameter22_name: Union[str, object] = values.unset, + parameter22_value: Union[str, object] = values.unset, + parameter23_name: Union[str, object] = values.unset, + parameter23_value: Union[str, object] = values.unset, + parameter24_name: Union[str, object] = values.unset, + parameter24_value: Union[str, object] = values.unset, + parameter25_name: Union[str, object] = values.unset, + parameter25_value: Union[str, object] = values.unset, + parameter26_name: Union[str, object] = values.unset, + parameter26_value: Union[str, object] = values.unset, + parameter27_name: Union[str, object] = values.unset, + parameter27_value: Union[str, object] = values.unset, + parameter28_name: Union[str, object] = values.unset, + parameter28_value: Union[str, object] = values.unset, + parameter29_name: Union[str, object] = values.unset, + parameter29_value: Union[str, object] = values.unset, + parameter30_name: Union[str, object] = values.unset, + parameter30_value: Union[str, object] = values.unset, + parameter31_name: Union[str, object] = values.unset, + parameter31_value: Union[str, object] = values.unset, + parameter32_name: Union[str, object] = values.unset, + parameter32_value: Union[str, object] = values.unset, + parameter33_name: Union[str, object] = values.unset, + parameter33_value: Union[str, object] = values.unset, + parameter34_name: Union[str, object] = values.unset, + parameter34_value: Union[str, object] = values.unset, + parameter35_name: Union[str, object] = values.unset, + parameter35_value: Union[str, object] = values.unset, + parameter36_name: Union[str, object] = values.unset, + parameter36_value: Union[str, object] = values.unset, + parameter37_name: Union[str, object] = values.unset, + parameter37_value: Union[str, object] = values.unset, + parameter38_name: Union[str, object] = values.unset, + parameter38_value: Union[str, object] = values.unset, + parameter39_name: Union[str, object] = values.unset, + parameter39_value: Union[str, object] = values.unset, + parameter40_name: Union[str, object] = values.unset, + parameter40_value: Union[str, object] = values.unset, + parameter41_name: Union[str, object] = values.unset, + parameter41_value: Union[str, object] = values.unset, + parameter42_name: Union[str, object] = values.unset, + parameter42_value: Union[str, object] = values.unset, + parameter43_name: Union[str, object] = values.unset, + parameter43_value: Union[str, object] = values.unset, + parameter44_name: Union[str, object] = values.unset, + parameter44_value: Union[str, object] = values.unset, + parameter45_name: Union[str, object] = values.unset, + parameter45_value: Union[str, object] = values.unset, + parameter46_name: Union[str, object] = values.unset, + parameter46_value: Union[str, object] = values.unset, + parameter47_name: Union[str, object] = values.unset, + parameter47_value: Union[str, object] = values.unset, + parameter48_name: Union[str, object] = values.unset, + parameter48_value: Union[str, object] = values.unset, + parameter49_name: Union[str, object] = values.unset, + parameter49_value: Union[str, object] = values.unset, + parameter50_name: Union[str, object] = values.unset, + parameter50_value: Union[str, object] = values.unset, + parameter51_name: Union[str, object] = values.unset, + parameter51_value: Union[str, object] = values.unset, + parameter52_name: Union[str, object] = values.unset, + parameter52_value: Union[str, object] = values.unset, + parameter53_name: Union[str, object] = values.unset, + parameter53_value: Union[str, object] = values.unset, + parameter54_name: Union[str, object] = values.unset, + parameter54_value: Union[str, object] = values.unset, + parameter55_name: Union[str, object] = values.unset, + parameter55_value: Union[str, object] = values.unset, + parameter56_name: Union[str, object] = values.unset, + parameter56_value: Union[str, object] = values.unset, + parameter57_name: Union[str, object] = values.unset, + parameter57_value: Union[str, object] = values.unset, + parameter58_name: Union[str, object] = values.unset, + parameter58_value: Union[str, object] = values.unset, + parameter59_name: Union[str, object] = values.unset, + parameter59_value: Union[str, object] = values.unset, + parameter60_name: Union[str, object] = values.unset, + parameter60_value: Union[str, object] = values.unset, + parameter61_name: Union[str, object] = values.unset, + parameter61_value: Union[str, object] = values.unset, + parameter62_name: Union[str, object] = values.unset, + parameter62_value: Union[str, object] = values.unset, + parameter63_name: Union[str, object] = values.unset, + parameter63_value: Union[str, object] = values.unset, + parameter64_name: Union[str, object] = values.unset, + parameter64_value: Union[str, object] = values.unset, + parameter65_name: Union[str, object] = values.unset, + parameter65_value: Union[str, object] = values.unset, + parameter66_name: Union[str, object] = values.unset, + parameter66_value: Union[str, object] = values.unset, + parameter67_name: Union[str, object] = values.unset, + parameter67_value: Union[str, object] = values.unset, + parameter68_name: Union[str, object] = values.unset, + parameter68_value: Union[str, object] = values.unset, + parameter69_name: Union[str, object] = values.unset, + parameter69_value: Union[str, object] = values.unset, + parameter70_name: Union[str, object] = values.unset, + parameter70_value: Union[str, object] = values.unset, + parameter71_name: Union[str, object] = values.unset, + parameter71_value: Union[str, object] = values.unset, + parameter72_name: Union[str, object] = values.unset, + parameter72_value: Union[str, object] = values.unset, + parameter73_name: Union[str, object] = values.unset, + parameter73_value: Union[str, object] = values.unset, + parameter74_name: Union[str, object] = values.unset, + parameter74_value: Union[str, object] = values.unset, + parameter75_name: Union[str, object] = values.unset, + parameter75_value: Union[str, object] = values.unset, + parameter76_name: Union[str, object] = values.unset, + parameter76_value: Union[str, object] = values.unset, + parameter77_name: Union[str, object] = values.unset, + parameter77_value: Union[str, object] = values.unset, + parameter78_name: Union[str, object] = values.unset, + parameter78_value: Union[str, object] = values.unset, + parameter79_name: Union[str, object] = values.unset, + parameter79_value: Union[str, object] = values.unset, + parameter80_name: Union[str, object] = values.unset, + parameter80_value: Union[str, object] = values.unset, + parameter81_name: Union[str, object] = values.unset, + parameter81_value: Union[str, object] = values.unset, + parameter82_name: Union[str, object] = values.unset, + parameter82_value: Union[str, object] = values.unset, + parameter83_name: Union[str, object] = values.unset, + parameter83_value: Union[str, object] = values.unset, + parameter84_name: Union[str, object] = values.unset, + parameter84_value: Union[str, object] = values.unset, + parameter85_name: Union[str, object] = values.unset, + parameter85_value: Union[str, object] = values.unset, + parameter86_name: Union[str, object] = values.unset, + parameter86_value: Union[str, object] = values.unset, + parameter87_name: Union[str, object] = values.unset, + parameter87_value: Union[str, object] = values.unset, + parameter88_name: Union[str, object] = values.unset, + parameter88_value: Union[str, object] = values.unset, + parameter89_name: Union[str, object] = values.unset, + parameter89_value: Union[str, object] = values.unset, + parameter90_name: Union[str, object] = values.unset, + parameter90_value: Union[str, object] = values.unset, + parameter91_name: Union[str, object] = values.unset, + parameter91_value: Union[str, object] = values.unset, + parameter92_name: Union[str, object] = values.unset, + parameter92_value: Union[str, object] = values.unset, + parameter93_name: Union[str, object] = values.unset, + parameter93_value: Union[str, object] = values.unset, + parameter94_name: Union[str, object] = values.unset, + parameter94_value: Union[str, object] = values.unset, + parameter95_name: Union[str, object] = values.unset, + parameter95_value: Union[str, object] = values.unset, + parameter96_name: Union[str, object] = values.unset, + parameter96_value: Union[str, object] = values.unset, + parameter97_name: Union[str, object] = values.unset, + parameter97_value: Union[str, object] = values.unset, + parameter98_name: Union[str, object] = values.unset, + parameter98_value: Union[str, object] = values.unset, + parameter99_name: Union[str, object] = values.unset, + parameter99_value: Union[str, object] = values.unset, + ) -> SiprecInstance: + """ + Asynchronously create the SiprecInstance + + :param name: The user-specified name of this Siprec, if one was given when the Siprec was created. This may be used to stop the Siprec. + :param connector_name: Unique name used when configuring the connector via Marketplace Add-on. + :param track: + :param status_callback: Absolute URL of the status callback. + :param status_callback_method: The http method for the status_callback (one of GET, POST). + :param parameter1_name: Parameter name + :param parameter1_value: Parameter value + :param parameter2_name: Parameter name + :param parameter2_value: Parameter value + :param parameter3_name: Parameter name + :param parameter3_value: Parameter value + :param parameter4_name: Parameter name + :param parameter4_value: Parameter value + :param parameter5_name: Parameter name + :param parameter5_value: Parameter value + :param parameter6_name: Parameter name + :param parameter6_value: Parameter value + :param parameter7_name: Parameter name + :param parameter7_value: Parameter value + :param parameter8_name: Parameter name + :param parameter8_value: Parameter value + :param parameter9_name: Parameter name + :param parameter9_value: Parameter value + :param parameter10_name: Parameter name + :param parameter10_value: Parameter value + :param parameter11_name: Parameter name + :param parameter11_value: Parameter value + :param parameter12_name: Parameter name + :param parameter12_value: Parameter value + :param parameter13_name: Parameter name + :param parameter13_value: Parameter value + :param parameter14_name: Parameter name + :param parameter14_value: Parameter value + :param parameter15_name: Parameter name + :param parameter15_value: Parameter value + :param parameter16_name: Parameter name + :param parameter16_value: Parameter value + :param parameter17_name: Parameter name + :param parameter17_value: Parameter value + :param parameter18_name: Parameter name + :param parameter18_value: Parameter value + :param parameter19_name: Parameter name + :param parameter19_value: Parameter value + :param parameter20_name: Parameter name + :param parameter20_value: Parameter value + :param parameter21_name: Parameter name + :param parameter21_value: Parameter value + :param parameter22_name: Parameter name + :param parameter22_value: Parameter value + :param parameter23_name: Parameter name + :param parameter23_value: Parameter value + :param parameter24_name: Parameter name + :param parameter24_value: Parameter value + :param parameter25_name: Parameter name + :param parameter25_value: Parameter value + :param parameter26_name: Parameter name + :param parameter26_value: Parameter value + :param parameter27_name: Parameter name + :param parameter27_value: Parameter value + :param parameter28_name: Parameter name + :param parameter28_value: Parameter value + :param parameter29_name: Parameter name + :param parameter29_value: Parameter value + :param parameter30_name: Parameter name + :param parameter30_value: Parameter value + :param parameter31_name: Parameter name + :param parameter31_value: Parameter value + :param parameter32_name: Parameter name + :param parameter32_value: Parameter value + :param parameter33_name: Parameter name + :param parameter33_value: Parameter value + :param parameter34_name: Parameter name + :param parameter34_value: Parameter value + :param parameter35_name: Parameter name + :param parameter35_value: Parameter value + :param parameter36_name: Parameter name + :param parameter36_value: Parameter value + :param parameter37_name: Parameter name + :param parameter37_value: Parameter value + :param parameter38_name: Parameter name + :param parameter38_value: Parameter value + :param parameter39_name: Parameter name + :param parameter39_value: Parameter value + :param parameter40_name: Parameter name + :param parameter40_value: Parameter value + :param parameter41_name: Parameter name + :param parameter41_value: Parameter value + :param parameter42_name: Parameter name + :param parameter42_value: Parameter value + :param parameter43_name: Parameter name + :param parameter43_value: Parameter value + :param parameter44_name: Parameter name + :param parameter44_value: Parameter value + :param parameter45_name: Parameter name + :param parameter45_value: Parameter value + :param parameter46_name: Parameter name + :param parameter46_value: Parameter value + :param parameter47_name: Parameter name + :param parameter47_value: Parameter value + :param parameter48_name: Parameter name + :param parameter48_value: Parameter value + :param parameter49_name: Parameter name + :param parameter49_value: Parameter value + :param parameter50_name: Parameter name + :param parameter50_value: Parameter value + :param parameter51_name: Parameter name + :param parameter51_value: Parameter value + :param parameter52_name: Parameter name + :param parameter52_value: Parameter value + :param parameter53_name: Parameter name + :param parameter53_value: Parameter value + :param parameter54_name: Parameter name + :param parameter54_value: Parameter value + :param parameter55_name: Parameter name + :param parameter55_value: Parameter value + :param parameter56_name: Parameter name + :param parameter56_value: Parameter value + :param parameter57_name: Parameter name + :param parameter57_value: Parameter value + :param parameter58_name: Parameter name + :param parameter58_value: Parameter value + :param parameter59_name: Parameter name + :param parameter59_value: Parameter value + :param parameter60_name: Parameter name + :param parameter60_value: Parameter value + :param parameter61_name: Parameter name + :param parameter61_value: Parameter value + :param parameter62_name: Parameter name + :param parameter62_value: Parameter value + :param parameter63_name: Parameter name + :param parameter63_value: Parameter value + :param parameter64_name: Parameter name + :param parameter64_value: Parameter value + :param parameter65_name: Parameter name + :param parameter65_value: Parameter value + :param parameter66_name: Parameter name + :param parameter66_value: Parameter value + :param parameter67_name: Parameter name + :param parameter67_value: Parameter value + :param parameter68_name: Parameter name + :param parameter68_value: Parameter value + :param parameter69_name: Parameter name + :param parameter69_value: Parameter value + :param parameter70_name: Parameter name + :param parameter70_value: Parameter value + :param parameter71_name: Parameter name + :param parameter71_value: Parameter value + :param parameter72_name: Parameter name + :param parameter72_value: Parameter value + :param parameter73_name: Parameter name + :param parameter73_value: Parameter value + :param parameter74_name: Parameter name + :param parameter74_value: Parameter value + :param parameter75_name: Parameter name + :param parameter75_value: Parameter value + :param parameter76_name: Parameter name + :param parameter76_value: Parameter value + :param parameter77_name: Parameter name + :param parameter77_value: Parameter value + :param parameter78_name: Parameter name + :param parameter78_value: Parameter value + :param parameter79_name: Parameter name + :param parameter79_value: Parameter value + :param parameter80_name: Parameter name + :param parameter80_value: Parameter value + :param parameter81_name: Parameter name + :param parameter81_value: Parameter value + :param parameter82_name: Parameter name + :param parameter82_value: Parameter value + :param parameter83_name: Parameter name + :param parameter83_value: Parameter value + :param parameter84_name: Parameter name + :param parameter84_value: Parameter value + :param parameter85_name: Parameter name + :param parameter85_value: Parameter value + :param parameter86_name: Parameter name + :param parameter86_value: Parameter value + :param parameter87_name: Parameter name + :param parameter87_value: Parameter value + :param parameter88_name: Parameter name + :param parameter88_value: Parameter value + :param parameter89_name: Parameter name + :param parameter89_value: Parameter value + :param parameter90_name: Parameter name + :param parameter90_value: Parameter value + :param parameter91_name: Parameter name + :param parameter91_value: Parameter value + :param parameter92_name: Parameter name + :param parameter92_value: Parameter value + :param parameter93_name: Parameter name + :param parameter93_value: Parameter value + :param parameter94_name: Parameter name + :param parameter94_value: Parameter value + :param parameter95_name: Parameter name + :param parameter95_value: Parameter value + :param parameter96_name: Parameter name + :param parameter96_value: Parameter value + :param parameter97_name: Parameter name + :param parameter97_value: Parameter value + :param parameter98_name: Parameter name + :param parameter98_value: Parameter value + :param parameter99_name: Parameter name + :param parameter99_value: Parameter value + + :returns: The created SiprecInstance + """ + + data = values.of( + { + "Name": name, + "ConnectorName": connector_name, + "Track": track, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Parameter1.Name": parameter1_name, + "Parameter1.Value": parameter1_value, + "Parameter2.Name": parameter2_name, + "Parameter2.Value": parameter2_value, + "Parameter3.Name": parameter3_name, + "Parameter3.Value": parameter3_value, + "Parameter4.Name": parameter4_name, + "Parameter4.Value": parameter4_value, + "Parameter5.Name": parameter5_name, + "Parameter5.Value": parameter5_value, + "Parameter6.Name": parameter6_name, + "Parameter6.Value": parameter6_value, + "Parameter7.Name": parameter7_name, + "Parameter7.Value": parameter7_value, + "Parameter8.Name": parameter8_name, + "Parameter8.Value": parameter8_value, + "Parameter9.Name": parameter9_name, + "Parameter9.Value": parameter9_value, + "Parameter10.Name": parameter10_name, + "Parameter10.Value": parameter10_value, + "Parameter11.Name": parameter11_name, + "Parameter11.Value": parameter11_value, + "Parameter12.Name": parameter12_name, + "Parameter12.Value": parameter12_value, + "Parameter13.Name": parameter13_name, + "Parameter13.Value": parameter13_value, + "Parameter14.Name": parameter14_name, + "Parameter14.Value": parameter14_value, + "Parameter15.Name": parameter15_name, + "Parameter15.Value": parameter15_value, + "Parameter16.Name": parameter16_name, + "Parameter16.Value": parameter16_value, + "Parameter17.Name": parameter17_name, + "Parameter17.Value": parameter17_value, + "Parameter18.Name": parameter18_name, + "Parameter18.Value": parameter18_value, + "Parameter19.Name": parameter19_name, + "Parameter19.Value": parameter19_value, + "Parameter20.Name": parameter20_name, + "Parameter20.Value": parameter20_value, + "Parameter21.Name": parameter21_name, + "Parameter21.Value": parameter21_value, + "Parameter22.Name": parameter22_name, + "Parameter22.Value": parameter22_value, + "Parameter23.Name": parameter23_name, + "Parameter23.Value": parameter23_value, + "Parameter24.Name": parameter24_name, + "Parameter24.Value": parameter24_value, + "Parameter25.Name": parameter25_name, + "Parameter25.Value": parameter25_value, + "Parameter26.Name": parameter26_name, + "Parameter26.Value": parameter26_value, + "Parameter27.Name": parameter27_name, + "Parameter27.Value": parameter27_value, + "Parameter28.Name": parameter28_name, + "Parameter28.Value": parameter28_value, + "Parameter29.Name": parameter29_name, + "Parameter29.Value": parameter29_value, + "Parameter30.Name": parameter30_name, + "Parameter30.Value": parameter30_value, + "Parameter31.Name": parameter31_name, + "Parameter31.Value": parameter31_value, + "Parameter32.Name": parameter32_name, + "Parameter32.Value": parameter32_value, + "Parameter33.Name": parameter33_name, + "Parameter33.Value": parameter33_value, + "Parameter34.Name": parameter34_name, + "Parameter34.Value": parameter34_value, + "Parameter35.Name": parameter35_name, + "Parameter35.Value": parameter35_value, + "Parameter36.Name": parameter36_name, + "Parameter36.Value": parameter36_value, + "Parameter37.Name": parameter37_name, + "Parameter37.Value": parameter37_value, + "Parameter38.Name": parameter38_name, + "Parameter38.Value": parameter38_value, + "Parameter39.Name": parameter39_name, + "Parameter39.Value": parameter39_value, + "Parameter40.Name": parameter40_name, + "Parameter40.Value": parameter40_value, + "Parameter41.Name": parameter41_name, + "Parameter41.Value": parameter41_value, + "Parameter42.Name": parameter42_name, + "Parameter42.Value": parameter42_value, + "Parameter43.Name": parameter43_name, + "Parameter43.Value": parameter43_value, + "Parameter44.Name": parameter44_name, + "Parameter44.Value": parameter44_value, + "Parameter45.Name": parameter45_name, + "Parameter45.Value": parameter45_value, + "Parameter46.Name": parameter46_name, + "Parameter46.Value": parameter46_value, + "Parameter47.Name": parameter47_name, + "Parameter47.Value": parameter47_value, + "Parameter48.Name": parameter48_name, + "Parameter48.Value": parameter48_value, + "Parameter49.Name": parameter49_name, + "Parameter49.Value": parameter49_value, + "Parameter50.Name": parameter50_name, + "Parameter50.Value": parameter50_value, + "Parameter51.Name": parameter51_name, + "Parameter51.Value": parameter51_value, + "Parameter52.Name": parameter52_name, + "Parameter52.Value": parameter52_value, + "Parameter53.Name": parameter53_name, + "Parameter53.Value": parameter53_value, + "Parameter54.Name": parameter54_name, + "Parameter54.Value": parameter54_value, + "Parameter55.Name": parameter55_name, + "Parameter55.Value": parameter55_value, + "Parameter56.Name": parameter56_name, + "Parameter56.Value": parameter56_value, + "Parameter57.Name": parameter57_name, + "Parameter57.Value": parameter57_value, + "Parameter58.Name": parameter58_name, + "Parameter58.Value": parameter58_value, + "Parameter59.Name": parameter59_name, + "Parameter59.Value": parameter59_value, + "Parameter60.Name": parameter60_name, + "Parameter60.Value": parameter60_value, + "Parameter61.Name": parameter61_name, + "Parameter61.Value": parameter61_value, + "Parameter62.Name": parameter62_name, + "Parameter62.Value": parameter62_value, + "Parameter63.Name": parameter63_name, + "Parameter63.Value": parameter63_value, + "Parameter64.Name": parameter64_name, + "Parameter64.Value": parameter64_value, + "Parameter65.Name": parameter65_name, + "Parameter65.Value": parameter65_value, + "Parameter66.Name": parameter66_name, + "Parameter66.Value": parameter66_value, + "Parameter67.Name": parameter67_name, + "Parameter67.Value": parameter67_value, + "Parameter68.Name": parameter68_name, + "Parameter68.Value": parameter68_value, + "Parameter69.Name": parameter69_name, + "Parameter69.Value": parameter69_value, + "Parameter70.Name": parameter70_name, + "Parameter70.Value": parameter70_value, + "Parameter71.Name": parameter71_name, + "Parameter71.Value": parameter71_value, + "Parameter72.Name": parameter72_name, + "Parameter72.Value": parameter72_value, + "Parameter73.Name": parameter73_name, + "Parameter73.Value": parameter73_value, + "Parameter74.Name": parameter74_name, + "Parameter74.Value": parameter74_value, + "Parameter75.Name": parameter75_name, + "Parameter75.Value": parameter75_value, + "Parameter76.Name": parameter76_name, + "Parameter76.Value": parameter76_value, + "Parameter77.Name": parameter77_name, + "Parameter77.Value": parameter77_value, + "Parameter78.Name": parameter78_name, + "Parameter78.Value": parameter78_value, + "Parameter79.Name": parameter79_name, + "Parameter79.Value": parameter79_value, + "Parameter80.Name": parameter80_name, + "Parameter80.Value": parameter80_value, + "Parameter81.Name": parameter81_name, + "Parameter81.Value": parameter81_value, + "Parameter82.Name": parameter82_name, + "Parameter82.Value": parameter82_value, + "Parameter83.Name": parameter83_name, + "Parameter83.Value": parameter83_value, + "Parameter84.Name": parameter84_name, + "Parameter84.Value": parameter84_value, + "Parameter85.Name": parameter85_name, + "Parameter85.Value": parameter85_value, + "Parameter86.Name": parameter86_name, + "Parameter86.Value": parameter86_value, + "Parameter87.Name": parameter87_name, + "Parameter87.Value": parameter87_value, + "Parameter88.Name": parameter88_name, + "Parameter88.Value": parameter88_value, + "Parameter89.Name": parameter89_name, + "Parameter89.Value": parameter89_value, + "Parameter90.Name": parameter90_name, + "Parameter90.Value": parameter90_value, + "Parameter91.Name": parameter91_name, + "Parameter91.Value": parameter91_value, + "Parameter92.Name": parameter92_name, + "Parameter92.Value": parameter92_value, + "Parameter93.Name": parameter93_name, + "Parameter93.Value": parameter93_value, + "Parameter94.Name": parameter94_name, + "Parameter94.Value": parameter94_value, + "Parameter95.Name": parameter95_name, + "Parameter95.Value": parameter95_value, + "Parameter96.Name": parameter96_name, + "Parameter96.Value": parameter96_value, + "Parameter97.Name": parameter97_name, + "Parameter97.Value": parameter97_value, + "Parameter98.Name": parameter98_name, + "Parameter98.Value": parameter98_value, + "Parameter99.Name": parameter99_name, + "Parameter99.Value": parameter99_value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SiprecInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def get(self, sid: str) -> SiprecContext: + """ + Constructs a SiprecContext + + :param sid: The SID of the Siprec resource, or the `name` used when creating the resource + """ + return SiprecContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> SiprecContext: + """ + Constructs a SiprecContext + + :param sid: The SID of the Siprec resource, or the `name` used when creating the resource + """ + return SiprecContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/stream.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/stream.py new file mode 100644 index 00000000..1a506e66 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/stream.py @@ -0,0 +1,1563 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class StreamInstance(InstanceResource): + + class Status(object): + IN_PROGRESS = "in-progress" + STOPPED = "stopped" + + class Track(object): + INBOUND_TRACK = "inbound_track" + OUTBOUND_TRACK = "outbound_track" + BOTH_TRACKS = "both_tracks" + + class UpdateStatus(object): + STOPPED = "stopped" + + """ + :ivar sid: The SID of the Stream resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Stream resource. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Stream resource is associated with. + :ivar name: The user-specified name of this Stream, if one was given when the Stream was created. This can be used to stop the Stream. + :ivar status: + :ivar date_updated: The date and time in GMT that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + call_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.call_sid: Optional[str] = payload.get("call_sid") + self.name: Optional[str] = payload.get("name") + self.status: Optional["StreamInstance.Status"] = payload.get("status") + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid or self.sid, + } + self._context: Optional[StreamContext] = None + + @property + def _proxy(self) -> "StreamContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: StreamContext for this StreamInstance + """ + if self._context is None: + self._context = StreamContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return self._context + + def update(self, status: "StreamInstance.UpdateStatus") -> "StreamInstance": + """ + Update the StreamInstance + + :param status: + + :returns: The updated StreamInstance + """ + return self._proxy.update( + status=status, + ) + + async def update_async( + self, status: "StreamInstance.UpdateStatus" + ) -> "StreamInstance": + """ + Asynchronous coroutine to update the StreamInstance + + :param status: + + :returns: The updated StreamInstance + """ + return await self._proxy.update_async( + status=status, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class StreamContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): + """ + Initialize the StreamContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Stream resource. + :param call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Stream resource is associated with. + :param sid: The SID or the `name` of the Stream resource to be stopped + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid, + } + self._uri = ( + "/Accounts/{account_sid}/Calls/{call_sid}/Streams/{sid}.json".format( + **self._solution + ) + ) + + def update(self, status: "StreamInstance.UpdateStatus") -> StreamInstance: + """ + Update the StreamInstance + + :param status: + + :returns: The updated StreamInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return StreamInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, status: "StreamInstance.UpdateStatus" + ) -> StreamInstance: + """ + Asynchronous coroutine to update the StreamInstance + + :param status: + + :returns: The updated StreamInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return StreamInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class StreamList(ListResource): + + def __init__(self, version: Version, account_sid: str, call_sid: str): + """ + Initialize the StreamList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Stream resource. + :param call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Stream resource is associated with. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + self._uri = "/Accounts/{account_sid}/Calls/{call_sid}/Streams.json".format( + **self._solution + ) + + def create( + self, + url: str, + name: Union[str, object] = values.unset, + track: Union["StreamInstance.Track", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + parameter1_name: Union[str, object] = values.unset, + parameter1_value: Union[str, object] = values.unset, + parameter2_name: Union[str, object] = values.unset, + parameter2_value: Union[str, object] = values.unset, + parameter3_name: Union[str, object] = values.unset, + parameter3_value: Union[str, object] = values.unset, + parameter4_name: Union[str, object] = values.unset, + parameter4_value: Union[str, object] = values.unset, + parameter5_name: Union[str, object] = values.unset, + parameter5_value: Union[str, object] = values.unset, + parameter6_name: Union[str, object] = values.unset, + parameter6_value: Union[str, object] = values.unset, + parameter7_name: Union[str, object] = values.unset, + parameter7_value: Union[str, object] = values.unset, + parameter8_name: Union[str, object] = values.unset, + parameter8_value: Union[str, object] = values.unset, + parameter9_name: Union[str, object] = values.unset, + parameter9_value: Union[str, object] = values.unset, + parameter10_name: Union[str, object] = values.unset, + parameter10_value: Union[str, object] = values.unset, + parameter11_name: Union[str, object] = values.unset, + parameter11_value: Union[str, object] = values.unset, + parameter12_name: Union[str, object] = values.unset, + parameter12_value: Union[str, object] = values.unset, + parameter13_name: Union[str, object] = values.unset, + parameter13_value: Union[str, object] = values.unset, + parameter14_name: Union[str, object] = values.unset, + parameter14_value: Union[str, object] = values.unset, + parameter15_name: Union[str, object] = values.unset, + parameter15_value: Union[str, object] = values.unset, + parameter16_name: Union[str, object] = values.unset, + parameter16_value: Union[str, object] = values.unset, + parameter17_name: Union[str, object] = values.unset, + parameter17_value: Union[str, object] = values.unset, + parameter18_name: Union[str, object] = values.unset, + parameter18_value: Union[str, object] = values.unset, + parameter19_name: Union[str, object] = values.unset, + parameter19_value: Union[str, object] = values.unset, + parameter20_name: Union[str, object] = values.unset, + parameter20_value: Union[str, object] = values.unset, + parameter21_name: Union[str, object] = values.unset, + parameter21_value: Union[str, object] = values.unset, + parameter22_name: Union[str, object] = values.unset, + parameter22_value: Union[str, object] = values.unset, + parameter23_name: Union[str, object] = values.unset, + parameter23_value: Union[str, object] = values.unset, + parameter24_name: Union[str, object] = values.unset, + parameter24_value: Union[str, object] = values.unset, + parameter25_name: Union[str, object] = values.unset, + parameter25_value: Union[str, object] = values.unset, + parameter26_name: Union[str, object] = values.unset, + parameter26_value: Union[str, object] = values.unset, + parameter27_name: Union[str, object] = values.unset, + parameter27_value: Union[str, object] = values.unset, + parameter28_name: Union[str, object] = values.unset, + parameter28_value: Union[str, object] = values.unset, + parameter29_name: Union[str, object] = values.unset, + parameter29_value: Union[str, object] = values.unset, + parameter30_name: Union[str, object] = values.unset, + parameter30_value: Union[str, object] = values.unset, + parameter31_name: Union[str, object] = values.unset, + parameter31_value: Union[str, object] = values.unset, + parameter32_name: Union[str, object] = values.unset, + parameter32_value: Union[str, object] = values.unset, + parameter33_name: Union[str, object] = values.unset, + parameter33_value: Union[str, object] = values.unset, + parameter34_name: Union[str, object] = values.unset, + parameter34_value: Union[str, object] = values.unset, + parameter35_name: Union[str, object] = values.unset, + parameter35_value: Union[str, object] = values.unset, + parameter36_name: Union[str, object] = values.unset, + parameter36_value: Union[str, object] = values.unset, + parameter37_name: Union[str, object] = values.unset, + parameter37_value: Union[str, object] = values.unset, + parameter38_name: Union[str, object] = values.unset, + parameter38_value: Union[str, object] = values.unset, + parameter39_name: Union[str, object] = values.unset, + parameter39_value: Union[str, object] = values.unset, + parameter40_name: Union[str, object] = values.unset, + parameter40_value: Union[str, object] = values.unset, + parameter41_name: Union[str, object] = values.unset, + parameter41_value: Union[str, object] = values.unset, + parameter42_name: Union[str, object] = values.unset, + parameter42_value: Union[str, object] = values.unset, + parameter43_name: Union[str, object] = values.unset, + parameter43_value: Union[str, object] = values.unset, + parameter44_name: Union[str, object] = values.unset, + parameter44_value: Union[str, object] = values.unset, + parameter45_name: Union[str, object] = values.unset, + parameter45_value: Union[str, object] = values.unset, + parameter46_name: Union[str, object] = values.unset, + parameter46_value: Union[str, object] = values.unset, + parameter47_name: Union[str, object] = values.unset, + parameter47_value: Union[str, object] = values.unset, + parameter48_name: Union[str, object] = values.unset, + parameter48_value: Union[str, object] = values.unset, + parameter49_name: Union[str, object] = values.unset, + parameter49_value: Union[str, object] = values.unset, + parameter50_name: Union[str, object] = values.unset, + parameter50_value: Union[str, object] = values.unset, + parameter51_name: Union[str, object] = values.unset, + parameter51_value: Union[str, object] = values.unset, + parameter52_name: Union[str, object] = values.unset, + parameter52_value: Union[str, object] = values.unset, + parameter53_name: Union[str, object] = values.unset, + parameter53_value: Union[str, object] = values.unset, + parameter54_name: Union[str, object] = values.unset, + parameter54_value: Union[str, object] = values.unset, + parameter55_name: Union[str, object] = values.unset, + parameter55_value: Union[str, object] = values.unset, + parameter56_name: Union[str, object] = values.unset, + parameter56_value: Union[str, object] = values.unset, + parameter57_name: Union[str, object] = values.unset, + parameter57_value: Union[str, object] = values.unset, + parameter58_name: Union[str, object] = values.unset, + parameter58_value: Union[str, object] = values.unset, + parameter59_name: Union[str, object] = values.unset, + parameter59_value: Union[str, object] = values.unset, + parameter60_name: Union[str, object] = values.unset, + parameter60_value: Union[str, object] = values.unset, + parameter61_name: Union[str, object] = values.unset, + parameter61_value: Union[str, object] = values.unset, + parameter62_name: Union[str, object] = values.unset, + parameter62_value: Union[str, object] = values.unset, + parameter63_name: Union[str, object] = values.unset, + parameter63_value: Union[str, object] = values.unset, + parameter64_name: Union[str, object] = values.unset, + parameter64_value: Union[str, object] = values.unset, + parameter65_name: Union[str, object] = values.unset, + parameter65_value: Union[str, object] = values.unset, + parameter66_name: Union[str, object] = values.unset, + parameter66_value: Union[str, object] = values.unset, + parameter67_name: Union[str, object] = values.unset, + parameter67_value: Union[str, object] = values.unset, + parameter68_name: Union[str, object] = values.unset, + parameter68_value: Union[str, object] = values.unset, + parameter69_name: Union[str, object] = values.unset, + parameter69_value: Union[str, object] = values.unset, + parameter70_name: Union[str, object] = values.unset, + parameter70_value: Union[str, object] = values.unset, + parameter71_name: Union[str, object] = values.unset, + parameter71_value: Union[str, object] = values.unset, + parameter72_name: Union[str, object] = values.unset, + parameter72_value: Union[str, object] = values.unset, + parameter73_name: Union[str, object] = values.unset, + parameter73_value: Union[str, object] = values.unset, + parameter74_name: Union[str, object] = values.unset, + parameter74_value: Union[str, object] = values.unset, + parameter75_name: Union[str, object] = values.unset, + parameter75_value: Union[str, object] = values.unset, + parameter76_name: Union[str, object] = values.unset, + parameter76_value: Union[str, object] = values.unset, + parameter77_name: Union[str, object] = values.unset, + parameter77_value: Union[str, object] = values.unset, + parameter78_name: Union[str, object] = values.unset, + parameter78_value: Union[str, object] = values.unset, + parameter79_name: Union[str, object] = values.unset, + parameter79_value: Union[str, object] = values.unset, + parameter80_name: Union[str, object] = values.unset, + parameter80_value: Union[str, object] = values.unset, + parameter81_name: Union[str, object] = values.unset, + parameter81_value: Union[str, object] = values.unset, + parameter82_name: Union[str, object] = values.unset, + parameter82_value: Union[str, object] = values.unset, + parameter83_name: Union[str, object] = values.unset, + parameter83_value: Union[str, object] = values.unset, + parameter84_name: Union[str, object] = values.unset, + parameter84_value: Union[str, object] = values.unset, + parameter85_name: Union[str, object] = values.unset, + parameter85_value: Union[str, object] = values.unset, + parameter86_name: Union[str, object] = values.unset, + parameter86_value: Union[str, object] = values.unset, + parameter87_name: Union[str, object] = values.unset, + parameter87_value: Union[str, object] = values.unset, + parameter88_name: Union[str, object] = values.unset, + parameter88_value: Union[str, object] = values.unset, + parameter89_name: Union[str, object] = values.unset, + parameter89_value: Union[str, object] = values.unset, + parameter90_name: Union[str, object] = values.unset, + parameter90_value: Union[str, object] = values.unset, + parameter91_name: Union[str, object] = values.unset, + parameter91_value: Union[str, object] = values.unset, + parameter92_name: Union[str, object] = values.unset, + parameter92_value: Union[str, object] = values.unset, + parameter93_name: Union[str, object] = values.unset, + parameter93_value: Union[str, object] = values.unset, + parameter94_name: Union[str, object] = values.unset, + parameter94_value: Union[str, object] = values.unset, + parameter95_name: Union[str, object] = values.unset, + parameter95_value: Union[str, object] = values.unset, + parameter96_name: Union[str, object] = values.unset, + parameter96_value: Union[str, object] = values.unset, + parameter97_name: Union[str, object] = values.unset, + parameter97_value: Union[str, object] = values.unset, + parameter98_name: Union[str, object] = values.unset, + parameter98_value: Union[str, object] = values.unset, + parameter99_name: Union[str, object] = values.unset, + parameter99_value: Union[str, object] = values.unset, + ) -> StreamInstance: + """ + Create the StreamInstance + + :param url: Relative or absolute URL where WebSocket connection will be established. + :param name: The user-specified name of this Stream, if one was given when the Stream was created. This can be used to stop the Stream. + :param track: + :param status_callback: Absolute URL to which Twilio sends status callback HTTP requests. + :param status_callback_method: The HTTP method Twilio uses when sending `status_callback` requests. Possible values are `GET` and `POST`. Default is `POST`. + :param parameter1_name: Parameter name + :param parameter1_value: Parameter value + :param parameter2_name: Parameter name + :param parameter2_value: Parameter value + :param parameter3_name: Parameter name + :param parameter3_value: Parameter value + :param parameter4_name: Parameter name + :param parameter4_value: Parameter value + :param parameter5_name: Parameter name + :param parameter5_value: Parameter value + :param parameter6_name: Parameter name + :param parameter6_value: Parameter value + :param parameter7_name: Parameter name + :param parameter7_value: Parameter value + :param parameter8_name: Parameter name + :param parameter8_value: Parameter value + :param parameter9_name: Parameter name + :param parameter9_value: Parameter value + :param parameter10_name: Parameter name + :param parameter10_value: Parameter value + :param parameter11_name: Parameter name + :param parameter11_value: Parameter value + :param parameter12_name: Parameter name + :param parameter12_value: Parameter value + :param parameter13_name: Parameter name + :param parameter13_value: Parameter value + :param parameter14_name: Parameter name + :param parameter14_value: Parameter value + :param parameter15_name: Parameter name + :param parameter15_value: Parameter value + :param parameter16_name: Parameter name + :param parameter16_value: Parameter value + :param parameter17_name: Parameter name + :param parameter17_value: Parameter value + :param parameter18_name: Parameter name + :param parameter18_value: Parameter value + :param parameter19_name: Parameter name + :param parameter19_value: Parameter value + :param parameter20_name: Parameter name + :param parameter20_value: Parameter value + :param parameter21_name: Parameter name + :param parameter21_value: Parameter value + :param parameter22_name: Parameter name + :param parameter22_value: Parameter value + :param parameter23_name: Parameter name + :param parameter23_value: Parameter value + :param parameter24_name: Parameter name + :param parameter24_value: Parameter value + :param parameter25_name: Parameter name + :param parameter25_value: Parameter value + :param parameter26_name: Parameter name + :param parameter26_value: Parameter value + :param parameter27_name: Parameter name + :param parameter27_value: Parameter value + :param parameter28_name: Parameter name + :param parameter28_value: Parameter value + :param parameter29_name: Parameter name + :param parameter29_value: Parameter value + :param parameter30_name: Parameter name + :param parameter30_value: Parameter value + :param parameter31_name: Parameter name + :param parameter31_value: Parameter value + :param parameter32_name: Parameter name + :param parameter32_value: Parameter value + :param parameter33_name: Parameter name + :param parameter33_value: Parameter value + :param parameter34_name: Parameter name + :param parameter34_value: Parameter value + :param parameter35_name: Parameter name + :param parameter35_value: Parameter value + :param parameter36_name: Parameter name + :param parameter36_value: Parameter value + :param parameter37_name: Parameter name + :param parameter37_value: Parameter value + :param parameter38_name: Parameter name + :param parameter38_value: Parameter value + :param parameter39_name: Parameter name + :param parameter39_value: Parameter value + :param parameter40_name: Parameter name + :param parameter40_value: Parameter value + :param parameter41_name: Parameter name + :param parameter41_value: Parameter value + :param parameter42_name: Parameter name + :param parameter42_value: Parameter value + :param parameter43_name: Parameter name + :param parameter43_value: Parameter value + :param parameter44_name: Parameter name + :param parameter44_value: Parameter value + :param parameter45_name: Parameter name + :param parameter45_value: Parameter value + :param parameter46_name: Parameter name + :param parameter46_value: Parameter value + :param parameter47_name: Parameter name + :param parameter47_value: Parameter value + :param parameter48_name: Parameter name + :param parameter48_value: Parameter value + :param parameter49_name: Parameter name + :param parameter49_value: Parameter value + :param parameter50_name: Parameter name + :param parameter50_value: Parameter value + :param parameter51_name: Parameter name + :param parameter51_value: Parameter value + :param parameter52_name: Parameter name + :param parameter52_value: Parameter value + :param parameter53_name: Parameter name + :param parameter53_value: Parameter value + :param parameter54_name: Parameter name + :param parameter54_value: Parameter value + :param parameter55_name: Parameter name + :param parameter55_value: Parameter value + :param parameter56_name: Parameter name + :param parameter56_value: Parameter value + :param parameter57_name: Parameter name + :param parameter57_value: Parameter value + :param parameter58_name: Parameter name + :param parameter58_value: Parameter value + :param parameter59_name: Parameter name + :param parameter59_value: Parameter value + :param parameter60_name: Parameter name + :param parameter60_value: Parameter value + :param parameter61_name: Parameter name + :param parameter61_value: Parameter value + :param parameter62_name: Parameter name + :param parameter62_value: Parameter value + :param parameter63_name: Parameter name + :param parameter63_value: Parameter value + :param parameter64_name: Parameter name + :param parameter64_value: Parameter value + :param parameter65_name: Parameter name + :param parameter65_value: Parameter value + :param parameter66_name: Parameter name + :param parameter66_value: Parameter value + :param parameter67_name: Parameter name + :param parameter67_value: Parameter value + :param parameter68_name: Parameter name + :param parameter68_value: Parameter value + :param parameter69_name: Parameter name + :param parameter69_value: Parameter value + :param parameter70_name: Parameter name + :param parameter70_value: Parameter value + :param parameter71_name: Parameter name + :param parameter71_value: Parameter value + :param parameter72_name: Parameter name + :param parameter72_value: Parameter value + :param parameter73_name: Parameter name + :param parameter73_value: Parameter value + :param parameter74_name: Parameter name + :param parameter74_value: Parameter value + :param parameter75_name: Parameter name + :param parameter75_value: Parameter value + :param parameter76_name: Parameter name + :param parameter76_value: Parameter value + :param parameter77_name: Parameter name + :param parameter77_value: Parameter value + :param parameter78_name: Parameter name + :param parameter78_value: Parameter value + :param parameter79_name: Parameter name + :param parameter79_value: Parameter value + :param parameter80_name: Parameter name + :param parameter80_value: Parameter value + :param parameter81_name: Parameter name + :param parameter81_value: Parameter value + :param parameter82_name: Parameter name + :param parameter82_value: Parameter value + :param parameter83_name: Parameter name + :param parameter83_value: Parameter value + :param parameter84_name: Parameter name + :param parameter84_value: Parameter value + :param parameter85_name: Parameter name + :param parameter85_value: Parameter value + :param parameter86_name: Parameter name + :param parameter86_value: Parameter value + :param parameter87_name: Parameter name + :param parameter87_value: Parameter value + :param parameter88_name: Parameter name + :param parameter88_value: Parameter value + :param parameter89_name: Parameter name + :param parameter89_value: Parameter value + :param parameter90_name: Parameter name + :param parameter90_value: Parameter value + :param parameter91_name: Parameter name + :param parameter91_value: Parameter value + :param parameter92_name: Parameter name + :param parameter92_value: Parameter value + :param parameter93_name: Parameter name + :param parameter93_value: Parameter value + :param parameter94_name: Parameter name + :param parameter94_value: Parameter value + :param parameter95_name: Parameter name + :param parameter95_value: Parameter value + :param parameter96_name: Parameter name + :param parameter96_value: Parameter value + :param parameter97_name: Parameter name + :param parameter97_value: Parameter value + :param parameter98_name: Parameter name + :param parameter98_value: Parameter value + :param parameter99_name: Parameter name + :param parameter99_value: Parameter value + + :returns: The created StreamInstance + """ + + data = values.of( + { + "Url": url, + "Name": name, + "Track": track, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Parameter1.Name": parameter1_name, + "Parameter1.Value": parameter1_value, + "Parameter2.Name": parameter2_name, + "Parameter2.Value": parameter2_value, + "Parameter3.Name": parameter3_name, + "Parameter3.Value": parameter3_value, + "Parameter4.Name": parameter4_name, + "Parameter4.Value": parameter4_value, + "Parameter5.Name": parameter5_name, + "Parameter5.Value": parameter5_value, + "Parameter6.Name": parameter6_name, + "Parameter6.Value": parameter6_value, + "Parameter7.Name": parameter7_name, + "Parameter7.Value": parameter7_value, + "Parameter8.Name": parameter8_name, + "Parameter8.Value": parameter8_value, + "Parameter9.Name": parameter9_name, + "Parameter9.Value": parameter9_value, + "Parameter10.Name": parameter10_name, + "Parameter10.Value": parameter10_value, + "Parameter11.Name": parameter11_name, + "Parameter11.Value": parameter11_value, + "Parameter12.Name": parameter12_name, + "Parameter12.Value": parameter12_value, + "Parameter13.Name": parameter13_name, + "Parameter13.Value": parameter13_value, + "Parameter14.Name": parameter14_name, + "Parameter14.Value": parameter14_value, + "Parameter15.Name": parameter15_name, + "Parameter15.Value": parameter15_value, + "Parameter16.Name": parameter16_name, + "Parameter16.Value": parameter16_value, + "Parameter17.Name": parameter17_name, + "Parameter17.Value": parameter17_value, + "Parameter18.Name": parameter18_name, + "Parameter18.Value": parameter18_value, + "Parameter19.Name": parameter19_name, + "Parameter19.Value": parameter19_value, + "Parameter20.Name": parameter20_name, + "Parameter20.Value": parameter20_value, + "Parameter21.Name": parameter21_name, + "Parameter21.Value": parameter21_value, + "Parameter22.Name": parameter22_name, + "Parameter22.Value": parameter22_value, + "Parameter23.Name": parameter23_name, + "Parameter23.Value": parameter23_value, + "Parameter24.Name": parameter24_name, + "Parameter24.Value": parameter24_value, + "Parameter25.Name": parameter25_name, + "Parameter25.Value": parameter25_value, + "Parameter26.Name": parameter26_name, + "Parameter26.Value": parameter26_value, + "Parameter27.Name": parameter27_name, + "Parameter27.Value": parameter27_value, + "Parameter28.Name": parameter28_name, + "Parameter28.Value": parameter28_value, + "Parameter29.Name": parameter29_name, + "Parameter29.Value": parameter29_value, + "Parameter30.Name": parameter30_name, + "Parameter30.Value": parameter30_value, + "Parameter31.Name": parameter31_name, + "Parameter31.Value": parameter31_value, + "Parameter32.Name": parameter32_name, + "Parameter32.Value": parameter32_value, + "Parameter33.Name": parameter33_name, + "Parameter33.Value": parameter33_value, + "Parameter34.Name": parameter34_name, + "Parameter34.Value": parameter34_value, + "Parameter35.Name": parameter35_name, + "Parameter35.Value": parameter35_value, + "Parameter36.Name": parameter36_name, + "Parameter36.Value": parameter36_value, + "Parameter37.Name": parameter37_name, + "Parameter37.Value": parameter37_value, + "Parameter38.Name": parameter38_name, + "Parameter38.Value": parameter38_value, + "Parameter39.Name": parameter39_name, + "Parameter39.Value": parameter39_value, + "Parameter40.Name": parameter40_name, + "Parameter40.Value": parameter40_value, + "Parameter41.Name": parameter41_name, + "Parameter41.Value": parameter41_value, + "Parameter42.Name": parameter42_name, + "Parameter42.Value": parameter42_value, + "Parameter43.Name": parameter43_name, + "Parameter43.Value": parameter43_value, + "Parameter44.Name": parameter44_name, + "Parameter44.Value": parameter44_value, + "Parameter45.Name": parameter45_name, + "Parameter45.Value": parameter45_value, + "Parameter46.Name": parameter46_name, + "Parameter46.Value": parameter46_value, + "Parameter47.Name": parameter47_name, + "Parameter47.Value": parameter47_value, + "Parameter48.Name": parameter48_name, + "Parameter48.Value": parameter48_value, + "Parameter49.Name": parameter49_name, + "Parameter49.Value": parameter49_value, + "Parameter50.Name": parameter50_name, + "Parameter50.Value": parameter50_value, + "Parameter51.Name": parameter51_name, + "Parameter51.Value": parameter51_value, + "Parameter52.Name": parameter52_name, + "Parameter52.Value": parameter52_value, + "Parameter53.Name": parameter53_name, + "Parameter53.Value": parameter53_value, + "Parameter54.Name": parameter54_name, + "Parameter54.Value": parameter54_value, + "Parameter55.Name": parameter55_name, + "Parameter55.Value": parameter55_value, + "Parameter56.Name": parameter56_name, + "Parameter56.Value": parameter56_value, + "Parameter57.Name": parameter57_name, + "Parameter57.Value": parameter57_value, + "Parameter58.Name": parameter58_name, + "Parameter58.Value": parameter58_value, + "Parameter59.Name": parameter59_name, + "Parameter59.Value": parameter59_value, + "Parameter60.Name": parameter60_name, + "Parameter60.Value": parameter60_value, + "Parameter61.Name": parameter61_name, + "Parameter61.Value": parameter61_value, + "Parameter62.Name": parameter62_name, + "Parameter62.Value": parameter62_value, + "Parameter63.Name": parameter63_name, + "Parameter63.Value": parameter63_value, + "Parameter64.Name": parameter64_name, + "Parameter64.Value": parameter64_value, + "Parameter65.Name": parameter65_name, + "Parameter65.Value": parameter65_value, + "Parameter66.Name": parameter66_name, + "Parameter66.Value": parameter66_value, + "Parameter67.Name": parameter67_name, + "Parameter67.Value": parameter67_value, + "Parameter68.Name": parameter68_name, + "Parameter68.Value": parameter68_value, + "Parameter69.Name": parameter69_name, + "Parameter69.Value": parameter69_value, + "Parameter70.Name": parameter70_name, + "Parameter70.Value": parameter70_value, + "Parameter71.Name": parameter71_name, + "Parameter71.Value": parameter71_value, + "Parameter72.Name": parameter72_name, + "Parameter72.Value": parameter72_value, + "Parameter73.Name": parameter73_name, + "Parameter73.Value": parameter73_value, + "Parameter74.Name": parameter74_name, + "Parameter74.Value": parameter74_value, + "Parameter75.Name": parameter75_name, + "Parameter75.Value": parameter75_value, + "Parameter76.Name": parameter76_name, + "Parameter76.Value": parameter76_value, + "Parameter77.Name": parameter77_name, + "Parameter77.Value": parameter77_value, + "Parameter78.Name": parameter78_name, + "Parameter78.Value": parameter78_value, + "Parameter79.Name": parameter79_name, + "Parameter79.Value": parameter79_value, + "Parameter80.Name": parameter80_name, + "Parameter80.Value": parameter80_value, + "Parameter81.Name": parameter81_name, + "Parameter81.Value": parameter81_value, + "Parameter82.Name": parameter82_name, + "Parameter82.Value": parameter82_value, + "Parameter83.Name": parameter83_name, + "Parameter83.Value": parameter83_value, + "Parameter84.Name": parameter84_name, + "Parameter84.Value": parameter84_value, + "Parameter85.Name": parameter85_name, + "Parameter85.Value": parameter85_value, + "Parameter86.Name": parameter86_name, + "Parameter86.Value": parameter86_value, + "Parameter87.Name": parameter87_name, + "Parameter87.Value": parameter87_value, + "Parameter88.Name": parameter88_name, + "Parameter88.Value": parameter88_value, + "Parameter89.Name": parameter89_name, + "Parameter89.Value": parameter89_value, + "Parameter90.Name": parameter90_name, + "Parameter90.Value": parameter90_value, + "Parameter91.Name": parameter91_name, + "Parameter91.Value": parameter91_value, + "Parameter92.Name": parameter92_name, + "Parameter92.Value": parameter92_value, + "Parameter93.Name": parameter93_name, + "Parameter93.Value": parameter93_value, + "Parameter94.Name": parameter94_name, + "Parameter94.Value": parameter94_value, + "Parameter95.Name": parameter95_name, + "Parameter95.Value": parameter95_value, + "Parameter96.Name": parameter96_name, + "Parameter96.Value": parameter96_value, + "Parameter97.Name": parameter97_name, + "Parameter97.Value": parameter97_value, + "Parameter98.Name": parameter98_name, + "Parameter98.Value": parameter98_value, + "Parameter99.Name": parameter99_name, + "Parameter99.Value": parameter99_value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return StreamInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + async def create_async( + self, + url: str, + name: Union[str, object] = values.unset, + track: Union["StreamInstance.Track", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + parameter1_name: Union[str, object] = values.unset, + parameter1_value: Union[str, object] = values.unset, + parameter2_name: Union[str, object] = values.unset, + parameter2_value: Union[str, object] = values.unset, + parameter3_name: Union[str, object] = values.unset, + parameter3_value: Union[str, object] = values.unset, + parameter4_name: Union[str, object] = values.unset, + parameter4_value: Union[str, object] = values.unset, + parameter5_name: Union[str, object] = values.unset, + parameter5_value: Union[str, object] = values.unset, + parameter6_name: Union[str, object] = values.unset, + parameter6_value: Union[str, object] = values.unset, + parameter7_name: Union[str, object] = values.unset, + parameter7_value: Union[str, object] = values.unset, + parameter8_name: Union[str, object] = values.unset, + parameter8_value: Union[str, object] = values.unset, + parameter9_name: Union[str, object] = values.unset, + parameter9_value: Union[str, object] = values.unset, + parameter10_name: Union[str, object] = values.unset, + parameter10_value: Union[str, object] = values.unset, + parameter11_name: Union[str, object] = values.unset, + parameter11_value: Union[str, object] = values.unset, + parameter12_name: Union[str, object] = values.unset, + parameter12_value: Union[str, object] = values.unset, + parameter13_name: Union[str, object] = values.unset, + parameter13_value: Union[str, object] = values.unset, + parameter14_name: Union[str, object] = values.unset, + parameter14_value: Union[str, object] = values.unset, + parameter15_name: Union[str, object] = values.unset, + parameter15_value: Union[str, object] = values.unset, + parameter16_name: Union[str, object] = values.unset, + parameter16_value: Union[str, object] = values.unset, + parameter17_name: Union[str, object] = values.unset, + parameter17_value: Union[str, object] = values.unset, + parameter18_name: Union[str, object] = values.unset, + parameter18_value: Union[str, object] = values.unset, + parameter19_name: Union[str, object] = values.unset, + parameter19_value: Union[str, object] = values.unset, + parameter20_name: Union[str, object] = values.unset, + parameter20_value: Union[str, object] = values.unset, + parameter21_name: Union[str, object] = values.unset, + parameter21_value: Union[str, object] = values.unset, + parameter22_name: Union[str, object] = values.unset, + parameter22_value: Union[str, object] = values.unset, + parameter23_name: Union[str, object] = values.unset, + parameter23_value: Union[str, object] = values.unset, + parameter24_name: Union[str, object] = values.unset, + parameter24_value: Union[str, object] = values.unset, + parameter25_name: Union[str, object] = values.unset, + parameter25_value: Union[str, object] = values.unset, + parameter26_name: Union[str, object] = values.unset, + parameter26_value: Union[str, object] = values.unset, + parameter27_name: Union[str, object] = values.unset, + parameter27_value: Union[str, object] = values.unset, + parameter28_name: Union[str, object] = values.unset, + parameter28_value: Union[str, object] = values.unset, + parameter29_name: Union[str, object] = values.unset, + parameter29_value: Union[str, object] = values.unset, + parameter30_name: Union[str, object] = values.unset, + parameter30_value: Union[str, object] = values.unset, + parameter31_name: Union[str, object] = values.unset, + parameter31_value: Union[str, object] = values.unset, + parameter32_name: Union[str, object] = values.unset, + parameter32_value: Union[str, object] = values.unset, + parameter33_name: Union[str, object] = values.unset, + parameter33_value: Union[str, object] = values.unset, + parameter34_name: Union[str, object] = values.unset, + parameter34_value: Union[str, object] = values.unset, + parameter35_name: Union[str, object] = values.unset, + parameter35_value: Union[str, object] = values.unset, + parameter36_name: Union[str, object] = values.unset, + parameter36_value: Union[str, object] = values.unset, + parameter37_name: Union[str, object] = values.unset, + parameter37_value: Union[str, object] = values.unset, + parameter38_name: Union[str, object] = values.unset, + parameter38_value: Union[str, object] = values.unset, + parameter39_name: Union[str, object] = values.unset, + parameter39_value: Union[str, object] = values.unset, + parameter40_name: Union[str, object] = values.unset, + parameter40_value: Union[str, object] = values.unset, + parameter41_name: Union[str, object] = values.unset, + parameter41_value: Union[str, object] = values.unset, + parameter42_name: Union[str, object] = values.unset, + parameter42_value: Union[str, object] = values.unset, + parameter43_name: Union[str, object] = values.unset, + parameter43_value: Union[str, object] = values.unset, + parameter44_name: Union[str, object] = values.unset, + parameter44_value: Union[str, object] = values.unset, + parameter45_name: Union[str, object] = values.unset, + parameter45_value: Union[str, object] = values.unset, + parameter46_name: Union[str, object] = values.unset, + parameter46_value: Union[str, object] = values.unset, + parameter47_name: Union[str, object] = values.unset, + parameter47_value: Union[str, object] = values.unset, + parameter48_name: Union[str, object] = values.unset, + parameter48_value: Union[str, object] = values.unset, + parameter49_name: Union[str, object] = values.unset, + parameter49_value: Union[str, object] = values.unset, + parameter50_name: Union[str, object] = values.unset, + parameter50_value: Union[str, object] = values.unset, + parameter51_name: Union[str, object] = values.unset, + parameter51_value: Union[str, object] = values.unset, + parameter52_name: Union[str, object] = values.unset, + parameter52_value: Union[str, object] = values.unset, + parameter53_name: Union[str, object] = values.unset, + parameter53_value: Union[str, object] = values.unset, + parameter54_name: Union[str, object] = values.unset, + parameter54_value: Union[str, object] = values.unset, + parameter55_name: Union[str, object] = values.unset, + parameter55_value: Union[str, object] = values.unset, + parameter56_name: Union[str, object] = values.unset, + parameter56_value: Union[str, object] = values.unset, + parameter57_name: Union[str, object] = values.unset, + parameter57_value: Union[str, object] = values.unset, + parameter58_name: Union[str, object] = values.unset, + parameter58_value: Union[str, object] = values.unset, + parameter59_name: Union[str, object] = values.unset, + parameter59_value: Union[str, object] = values.unset, + parameter60_name: Union[str, object] = values.unset, + parameter60_value: Union[str, object] = values.unset, + parameter61_name: Union[str, object] = values.unset, + parameter61_value: Union[str, object] = values.unset, + parameter62_name: Union[str, object] = values.unset, + parameter62_value: Union[str, object] = values.unset, + parameter63_name: Union[str, object] = values.unset, + parameter63_value: Union[str, object] = values.unset, + parameter64_name: Union[str, object] = values.unset, + parameter64_value: Union[str, object] = values.unset, + parameter65_name: Union[str, object] = values.unset, + parameter65_value: Union[str, object] = values.unset, + parameter66_name: Union[str, object] = values.unset, + parameter66_value: Union[str, object] = values.unset, + parameter67_name: Union[str, object] = values.unset, + parameter67_value: Union[str, object] = values.unset, + parameter68_name: Union[str, object] = values.unset, + parameter68_value: Union[str, object] = values.unset, + parameter69_name: Union[str, object] = values.unset, + parameter69_value: Union[str, object] = values.unset, + parameter70_name: Union[str, object] = values.unset, + parameter70_value: Union[str, object] = values.unset, + parameter71_name: Union[str, object] = values.unset, + parameter71_value: Union[str, object] = values.unset, + parameter72_name: Union[str, object] = values.unset, + parameter72_value: Union[str, object] = values.unset, + parameter73_name: Union[str, object] = values.unset, + parameter73_value: Union[str, object] = values.unset, + parameter74_name: Union[str, object] = values.unset, + parameter74_value: Union[str, object] = values.unset, + parameter75_name: Union[str, object] = values.unset, + parameter75_value: Union[str, object] = values.unset, + parameter76_name: Union[str, object] = values.unset, + parameter76_value: Union[str, object] = values.unset, + parameter77_name: Union[str, object] = values.unset, + parameter77_value: Union[str, object] = values.unset, + parameter78_name: Union[str, object] = values.unset, + parameter78_value: Union[str, object] = values.unset, + parameter79_name: Union[str, object] = values.unset, + parameter79_value: Union[str, object] = values.unset, + parameter80_name: Union[str, object] = values.unset, + parameter80_value: Union[str, object] = values.unset, + parameter81_name: Union[str, object] = values.unset, + parameter81_value: Union[str, object] = values.unset, + parameter82_name: Union[str, object] = values.unset, + parameter82_value: Union[str, object] = values.unset, + parameter83_name: Union[str, object] = values.unset, + parameter83_value: Union[str, object] = values.unset, + parameter84_name: Union[str, object] = values.unset, + parameter84_value: Union[str, object] = values.unset, + parameter85_name: Union[str, object] = values.unset, + parameter85_value: Union[str, object] = values.unset, + parameter86_name: Union[str, object] = values.unset, + parameter86_value: Union[str, object] = values.unset, + parameter87_name: Union[str, object] = values.unset, + parameter87_value: Union[str, object] = values.unset, + parameter88_name: Union[str, object] = values.unset, + parameter88_value: Union[str, object] = values.unset, + parameter89_name: Union[str, object] = values.unset, + parameter89_value: Union[str, object] = values.unset, + parameter90_name: Union[str, object] = values.unset, + parameter90_value: Union[str, object] = values.unset, + parameter91_name: Union[str, object] = values.unset, + parameter91_value: Union[str, object] = values.unset, + parameter92_name: Union[str, object] = values.unset, + parameter92_value: Union[str, object] = values.unset, + parameter93_name: Union[str, object] = values.unset, + parameter93_value: Union[str, object] = values.unset, + parameter94_name: Union[str, object] = values.unset, + parameter94_value: Union[str, object] = values.unset, + parameter95_name: Union[str, object] = values.unset, + parameter95_value: Union[str, object] = values.unset, + parameter96_name: Union[str, object] = values.unset, + parameter96_value: Union[str, object] = values.unset, + parameter97_name: Union[str, object] = values.unset, + parameter97_value: Union[str, object] = values.unset, + parameter98_name: Union[str, object] = values.unset, + parameter98_value: Union[str, object] = values.unset, + parameter99_name: Union[str, object] = values.unset, + parameter99_value: Union[str, object] = values.unset, + ) -> StreamInstance: + """ + Asynchronously create the StreamInstance + + :param url: Relative or absolute URL where WebSocket connection will be established. + :param name: The user-specified name of this Stream, if one was given when the Stream was created. This can be used to stop the Stream. + :param track: + :param status_callback: Absolute URL to which Twilio sends status callback HTTP requests. + :param status_callback_method: The HTTP method Twilio uses when sending `status_callback` requests. Possible values are `GET` and `POST`. Default is `POST`. + :param parameter1_name: Parameter name + :param parameter1_value: Parameter value + :param parameter2_name: Parameter name + :param parameter2_value: Parameter value + :param parameter3_name: Parameter name + :param parameter3_value: Parameter value + :param parameter4_name: Parameter name + :param parameter4_value: Parameter value + :param parameter5_name: Parameter name + :param parameter5_value: Parameter value + :param parameter6_name: Parameter name + :param parameter6_value: Parameter value + :param parameter7_name: Parameter name + :param parameter7_value: Parameter value + :param parameter8_name: Parameter name + :param parameter8_value: Parameter value + :param parameter9_name: Parameter name + :param parameter9_value: Parameter value + :param parameter10_name: Parameter name + :param parameter10_value: Parameter value + :param parameter11_name: Parameter name + :param parameter11_value: Parameter value + :param parameter12_name: Parameter name + :param parameter12_value: Parameter value + :param parameter13_name: Parameter name + :param parameter13_value: Parameter value + :param parameter14_name: Parameter name + :param parameter14_value: Parameter value + :param parameter15_name: Parameter name + :param parameter15_value: Parameter value + :param parameter16_name: Parameter name + :param parameter16_value: Parameter value + :param parameter17_name: Parameter name + :param parameter17_value: Parameter value + :param parameter18_name: Parameter name + :param parameter18_value: Parameter value + :param parameter19_name: Parameter name + :param parameter19_value: Parameter value + :param parameter20_name: Parameter name + :param parameter20_value: Parameter value + :param parameter21_name: Parameter name + :param parameter21_value: Parameter value + :param parameter22_name: Parameter name + :param parameter22_value: Parameter value + :param parameter23_name: Parameter name + :param parameter23_value: Parameter value + :param parameter24_name: Parameter name + :param parameter24_value: Parameter value + :param parameter25_name: Parameter name + :param parameter25_value: Parameter value + :param parameter26_name: Parameter name + :param parameter26_value: Parameter value + :param parameter27_name: Parameter name + :param parameter27_value: Parameter value + :param parameter28_name: Parameter name + :param parameter28_value: Parameter value + :param parameter29_name: Parameter name + :param parameter29_value: Parameter value + :param parameter30_name: Parameter name + :param parameter30_value: Parameter value + :param parameter31_name: Parameter name + :param parameter31_value: Parameter value + :param parameter32_name: Parameter name + :param parameter32_value: Parameter value + :param parameter33_name: Parameter name + :param parameter33_value: Parameter value + :param parameter34_name: Parameter name + :param parameter34_value: Parameter value + :param parameter35_name: Parameter name + :param parameter35_value: Parameter value + :param parameter36_name: Parameter name + :param parameter36_value: Parameter value + :param parameter37_name: Parameter name + :param parameter37_value: Parameter value + :param parameter38_name: Parameter name + :param parameter38_value: Parameter value + :param parameter39_name: Parameter name + :param parameter39_value: Parameter value + :param parameter40_name: Parameter name + :param parameter40_value: Parameter value + :param parameter41_name: Parameter name + :param parameter41_value: Parameter value + :param parameter42_name: Parameter name + :param parameter42_value: Parameter value + :param parameter43_name: Parameter name + :param parameter43_value: Parameter value + :param parameter44_name: Parameter name + :param parameter44_value: Parameter value + :param parameter45_name: Parameter name + :param parameter45_value: Parameter value + :param parameter46_name: Parameter name + :param parameter46_value: Parameter value + :param parameter47_name: Parameter name + :param parameter47_value: Parameter value + :param parameter48_name: Parameter name + :param parameter48_value: Parameter value + :param parameter49_name: Parameter name + :param parameter49_value: Parameter value + :param parameter50_name: Parameter name + :param parameter50_value: Parameter value + :param parameter51_name: Parameter name + :param parameter51_value: Parameter value + :param parameter52_name: Parameter name + :param parameter52_value: Parameter value + :param parameter53_name: Parameter name + :param parameter53_value: Parameter value + :param parameter54_name: Parameter name + :param parameter54_value: Parameter value + :param parameter55_name: Parameter name + :param parameter55_value: Parameter value + :param parameter56_name: Parameter name + :param parameter56_value: Parameter value + :param parameter57_name: Parameter name + :param parameter57_value: Parameter value + :param parameter58_name: Parameter name + :param parameter58_value: Parameter value + :param parameter59_name: Parameter name + :param parameter59_value: Parameter value + :param parameter60_name: Parameter name + :param parameter60_value: Parameter value + :param parameter61_name: Parameter name + :param parameter61_value: Parameter value + :param parameter62_name: Parameter name + :param parameter62_value: Parameter value + :param parameter63_name: Parameter name + :param parameter63_value: Parameter value + :param parameter64_name: Parameter name + :param parameter64_value: Parameter value + :param parameter65_name: Parameter name + :param parameter65_value: Parameter value + :param parameter66_name: Parameter name + :param parameter66_value: Parameter value + :param parameter67_name: Parameter name + :param parameter67_value: Parameter value + :param parameter68_name: Parameter name + :param parameter68_value: Parameter value + :param parameter69_name: Parameter name + :param parameter69_value: Parameter value + :param parameter70_name: Parameter name + :param parameter70_value: Parameter value + :param parameter71_name: Parameter name + :param parameter71_value: Parameter value + :param parameter72_name: Parameter name + :param parameter72_value: Parameter value + :param parameter73_name: Parameter name + :param parameter73_value: Parameter value + :param parameter74_name: Parameter name + :param parameter74_value: Parameter value + :param parameter75_name: Parameter name + :param parameter75_value: Parameter value + :param parameter76_name: Parameter name + :param parameter76_value: Parameter value + :param parameter77_name: Parameter name + :param parameter77_value: Parameter value + :param parameter78_name: Parameter name + :param parameter78_value: Parameter value + :param parameter79_name: Parameter name + :param parameter79_value: Parameter value + :param parameter80_name: Parameter name + :param parameter80_value: Parameter value + :param parameter81_name: Parameter name + :param parameter81_value: Parameter value + :param parameter82_name: Parameter name + :param parameter82_value: Parameter value + :param parameter83_name: Parameter name + :param parameter83_value: Parameter value + :param parameter84_name: Parameter name + :param parameter84_value: Parameter value + :param parameter85_name: Parameter name + :param parameter85_value: Parameter value + :param parameter86_name: Parameter name + :param parameter86_value: Parameter value + :param parameter87_name: Parameter name + :param parameter87_value: Parameter value + :param parameter88_name: Parameter name + :param parameter88_value: Parameter value + :param parameter89_name: Parameter name + :param parameter89_value: Parameter value + :param parameter90_name: Parameter name + :param parameter90_value: Parameter value + :param parameter91_name: Parameter name + :param parameter91_value: Parameter value + :param parameter92_name: Parameter name + :param parameter92_value: Parameter value + :param parameter93_name: Parameter name + :param parameter93_value: Parameter value + :param parameter94_name: Parameter name + :param parameter94_value: Parameter value + :param parameter95_name: Parameter name + :param parameter95_value: Parameter value + :param parameter96_name: Parameter name + :param parameter96_value: Parameter value + :param parameter97_name: Parameter name + :param parameter97_value: Parameter value + :param parameter98_name: Parameter name + :param parameter98_value: Parameter value + :param parameter99_name: Parameter name + :param parameter99_value: Parameter value + + :returns: The created StreamInstance + """ + + data = values.of( + { + "Url": url, + "Name": name, + "Track": track, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Parameter1.Name": parameter1_name, + "Parameter1.Value": parameter1_value, + "Parameter2.Name": parameter2_name, + "Parameter2.Value": parameter2_value, + "Parameter3.Name": parameter3_name, + "Parameter3.Value": parameter3_value, + "Parameter4.Name": parameter4_name, + "Parameter4.Value": parameter4_value, + "Parameter5.Name": parameter5_name, + "Parameter5.Value": parameter5_value, + "Parameter6.Name": parameter6_name, + "Parameter6.Value": parameter6_value, + "Parameter7.Name": parameter7_name, + "Parameter7.Value": parameter7_value, + "Parameter8.Name": parameter8_name, + "Parameter8.Value": parameter8_value, + "Parameter9.Name": parameter9_name, + "Parameter9.Value": parameter9_value, + "Parameter10.Name": parameter10_name, + "Parameter10.Value": parameter10_value, + "Parameter11.Name": parameter11_name, + "Parameter11.Value": parameter11_value, + "Parameter12.Name": parameter12_name, + "Parameter12.Value": parameter12_value, + "Parameter13.Name": parameter13_name, + "Parameter13.Value": parameter13_value, + "Parameter14.Name": parameter14_name, + "Parameter14.Value": parameter14_value, + "Parameter15.Name": parameter15_name, + "Parameter15.Value": parameter15_value, + "Parameter16.Name": parameter16_name, + "Parameter16.Value": parameter16_value, + "Parameter17.Name": parameter17_name, + "Parameter17.Value": parameter17_value, + "Parameter18.Name": parameter18_name, + "Parameter18.Value": parameter18_value, + "Parameter19.Name": parameter19_name, + "Parameter19.Value": parameter19_value, + "Parameter20.Name": parameter20_name, + "Parameter20.Value": parameter20_value, + "Parameter21.Name": parameter21_name, + "Parameter21.Value": parameter21_value, + "Parameter22.Name": parameter22_name, + "Parameter22.Value": parameter22_value, + "Parameter23.Name": parameter23_name, + "Parameter23.Value": parameter23_value, + "Parameter24.Name": parameter24_name, + "Parameter24.Value": parameter24_value, + "Parameter25.Name": parameter25_name, + "Parameter25.Value": parameter25_value, + "Parameter26.Name": parameter26_name, + "Parameter26.Value": parameter26_value, + "Parameter27.Name": parameter27_name, + "Parameter27.Value": parameter27_value, + "Parameter28.Name": parameter28_name, + "Parameter28.Value": parameter28_value, + "Parameter29.Name": parameter29_name, + "Parameter29.Value": parameter29_value, + "Parameter30.Name": parameter30_name, + "Parameter30.Value": parameter30_value, + "Parameter31.Name": parameter31_name, + "Parameter31.Value": parameter31_value, + "Parameter32.Name": parameter32_name, + "Parameter32.Value": parameter32_value, + "Parameter33.Name": parameter33_name, + "Parameter33.Value": parameter33_value, + "Parameter34.Name": parameter34_name, + "Parameter34.Value": parameter34_value, + "Parameter35.Name": parameter35_name, + "Parameter35.Value": parameter35_value, + "Parameter36.Name": parameter36_name, + "Parameter36.Value": parameter36_value, + "Parameter37.Name": parameter37_name, + "Parameter37.Value": parameter37_value, + "Parameter38.Name": parameter38_name, + "Parameter38.Value": parameter38_value, + "Parameter39.Name": parameter39_name, + "Parameter39.Value": parameter39_value, + "Parameter40.Name": parameter40_name, + "Parameter40.Value": parameter40_value, + "Parameter41.Name": parameter41_name, + "Parameter41.Value": parameter41_value, + "Parameter42.Name": parameter42_name, + "Parameter42.Value": parameter42_value, + "Parameter43.Name": parameter43_name, + "Parameter43.Value": parameter43_value, + "Parameter44.Name": parameter44_name, + "Parameter44.Value": parameter44_value, + "Parameter45.Name": parameter45_name, + "Parameter45.Value": parameter45_value, + "Parameter46.Name": parameter46_name, + "Parameter46.Value": parameter46_value, + "Parameter47.Name": parameter47_name, + "Parameter47.Value": parameter47_value, + "Parameter48.Name": parameter48_name, + "Parameter48.Value": parameter48_value, + "Parameter49.Name": parameter49_name, + "Parameter49.Value": parameter49_value, + "Parameter50.Name": parameter50_name, + "Parameter50.Value": parameter50_value, + "Parameter51.Name": parameter51_name, + "Parameter51.Value": parameter51_value, + "Parameter52.Name": parameter52_name, + "Parameter52.Value": parameter52_value, + "Parameter53.Name": parameter53_name, + "Parameter53.Value": parameter53_value, + "Parameter54.Name": parameter54_name, + "Parameter54.Value": parameter54_value, + "Parameter55.Name": parameter55_name, + "Parameter55.Value": parameter55_value, + "Parameter56.Name": parameter56_name, + "Parameter56.Value": parameter56_value, + "Parameter57.Name": parameter57_name, + "Parameter57.Value": parameter57_value, + "Parameter58.Name": parameter58_name, + "Parameter58.Value": parameter58_value, + "Parameter59.Name": parameter59_name, + "Parameter59.Value": parameter59_value, + "Parameter60.Name": parameter60_name, + "Parameter60.Value": parameter60_value, + "Parameter61.Name": parameter61_name, + "Parameter61.Value": parameter61_value, + "Parameter62.Name": parameter62_name, + "Parameter62.Value": parameter62_value, + "Parameter63.Name": parameter63_name, + "Parameter63.Value": parameter63_value, + "Parameter64.Name": parameter64_name, + "Parameter64.Value": parameter64_value, + "Parameter65.Name": parameter65_name, + "Parameter65.Value": parameter65_value, + "Parameter66.Name": parameter66_name, + "Parameter66.Value": parameter66_value, + "Parameter67.Name": parameter67_name, + "Parameter67.Value": parameter67_value, + "Parameter68.Name": parameter68_name, + "Parameter68.Value": parameter68_value, + "Parameter69.Name": parameter69_name, + "Parameter69.Value": parameter69_value, + "Parameter70.Name": parameter70_name, + "Parameter70.Value": parameter70_value, + "Parameter71.Name": parameter71_name, + "Parameter71.Value": parameter71_value, + "Parameter72.Name": parameter72_name, + "Parameter72.Value": parameter72_value, + "Parameter73.Name": parameter73_name, + "Parameter73.Value": parameter73_value, + "Parameter74.Name": parameter74_name, + "Parameter74.Value": parameter74_value, + "Parameter75.Name": parameter75_name, + "Parameter75.Value": parameter75_value, + "Parameter76.Name": parameter76_name, + "Parameter76.Value": parameter76_value, + "Parameter77.Name": parameter77_name, + "Parameter77.Value": parameter77_value, + "Parameter78.Name": parameter78_name, + "Parameter78.Value": parameter78_value, + "Parameter79.Name": parameter79_name, + "Parameter79.Value": parameter79_value, + "Parameter80.Name": parameter80_name, + "Parameter80.Value": parameter80_value, + "Parameter81.Name": parameter81_name, + "Parameter81.Value": parameter81_value, + "Parameter82.Name": parameter82_name, + "Parameter82.Value": parameter82_value, + "Parameter83.Name": parameter83_name, + "Parameter83.Value": parameter83_value, + "Parameter84.Name": parameter84_name, + "Parameter84.Value": parameter84_value, + "Parameter85.Name": parameter85_name, + "Parameter85.Value": parameter85_value, + "Parameter86.Name": parameter86_name, + "Parameter86.Value": parameter86_value, + "Parameter87.Name": parameter87_name, + "Parameter87.Value": parameter87_value, + "Parameter88.Name": parameter88_name, + "Parameter88.Value": parameter88_value, + "Parameter89.Name": parameter89_name, + "Parameter89.Value": parameter89_value, + "Parameter90.Name": parameter90_name, + "Parameter90.Value": parameter90_value, + "Parameter91.Name": parameter91_name, + "Parameter91.Value": parameter91_value, + "Parameter92.Name": parameter92_name, + "Parameter92.Value": parameter92_value, + "Parameter93.Name": parameter93_name, + "Parameter93.Value": parameter93_value, + "Parameter94.Name": parameter94_name, + "Parameter94.Value": parameter94_value, + "Parameter95.Name": parameter95_name, + "Parameter95.Value": parameter95_value, + "Parameter96.Name": parameter96_name, + "Parameter96.Value": parameter96_value, + "Parameter97.Name": parameter97_name, + "Parameter97.Value": parameter97_value, + "Parameter98.Name": parameter98_name, + "Parameter98.Value": parameter98_value, + "Parameter99.Name": parameter99_name, + "Parameter99.Value": parameter99_value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return StreamInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def get(self, sid: str) -> StreamContext: + """ + Constructs a StreamContext + + :param sid: The SID or the `name` of the Stream resource to be stopped + """ + return StreamContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> StreamContext: + """ + Constructs a StreamContext + + :param sid: The SID or the `name` of the Stream resource to be stopped + """ + return StreamContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/transcription.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/transcription.py new file mode 100644 index 00000000..4f8f9125 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/transcription.py @@ -0,0 +1,439 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TranscriptionInstance(InstanceResource): + + class Status(object): + IN_PROGRESS = "in-progress" + STOPPED = "stopped" + + class Track(object): + INBOUND_TRACK = "inbound_track" + OUTBOUND_TRACK = "outbound_track" + BOTH_TRACKS = "both_tracks" + + class UpdateStatus(object): + STOPPED = "stopped" + + """ + :ivar sid: The SID of the Transcription resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Transcription resource. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Transcription resource is associated with. + :ivar name: The user-specified name of this Transcription, if one was given when the Transcription was created. This may be used to stop the Transcription. + :ivar status: + :ivar date_updated: The date and time in GMT that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar uri: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + call_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.call_sid: Optional[str] = payload.get("call_sid") + self.name: Optional[str] = payload.get("name") + self.status: Optional["TranscriptionInstance.Status"] = payload.get("status") + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid or self.sid, + } + self._context: Optional[TranscriptionContext] = None + + @property + def _proxy(self) -> "TranscriptionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TranscriptionContext for this TranscriptionInstance + """ + if self._context is None: + self._context = TranscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return self._context + + def update( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> "TranscriptionInstance": + """ + Update the TranscriptionInstance + + :param status: + + :returns: The updated TranscriptionInstance + """ + return self._proxy.update( + status=status, + ) + + async def update_async( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> "TranscriptionInstance": + """ + Asynchronous coroutine to update the TranscriptionInstance + + :param status: + + :returns: The updated TranscriptionInstance + """ + return await self._proxy.update_async( + status=status, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TranscriptionContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): + """ + Initialize the TranscriptionContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Transcription resource. + :param call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Transcription resource is associated with. + :param sid: The SID of the Transcription resource, or the `name` used when creating the resource + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid, + } + self._uri = ( + "/Accounts/{account_sid}/Calls/{call_sid}/Transcriptions/{sid}.json".format( + **self._solution + ) + ) + + def update( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> TranscriptionInstance: + """ + Update the TranscriptionInstance + + :param status: + + :returns: The updated TranscriptionInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> TranscriptionInstance: + """ + Asynchronous coroutine to update the TranscriptionInstance + + :param status: + + :returns: The updated TranscriptionInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TranscriptionList(ListResource): + + def __init__(self, version: Version, account_sid: str, call_sid: str): + """ + Initialize the TranscriptionList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Transcription resource. + :param call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Transcription resource is associated with. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + self._uri = ( + "/Accounts/{account_sid}/Calls/{call_sid}/Transcriptions.json".format( + **self._solution + ) + ) + + def create( + self, + name: Union[str, object] = values.unset, + track: Union["TranscriptionInstance.Track", object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + inbound_track_label: Union[str, object] = values.unset, + outbound_track_label: Union[str, object] = values.unset, + partial_results: Union[bool, object] = values.unset, + language_code: Union[str, object] = values.unset, + transcription_engine: Union[str, object] = values.unset, + profanity_filter: Union[bool, object] = values.unset, + speech_model: Union[str, object] = values.unset, + hints: Union[str, object] = values.unset, + enable_automatic_punctuation: Union[bool, object] = values.unset, + intelligence_service: Union[str, object] = values.unset, + ) -> TranscriptionInstance: + """ + Create the TranscriptionInstance + + :param name: The user-specified name of this Transcription, if one was given when the Transcription was created. This may be used to stop the Transcription. + :param track: + :param status_callback_url: Absolute URL of the status callback. + :param status_callback_method: The http method for the status_callback (one of GET, POST). + :param inbound_track_label: Friendly name given to the Inbound Track + :param outbound_track_label: Friendly name given to the Outbound Track + :param partial_results: Indicates if partial results are going to be sent to the customer + :param language_code: Language code used by the transcription engine, specified in [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) format + :param transcription_engine: Definition of the transcription engine to be used, among those supported by Twilio + :param profanity_filter: indicates if the server will attempt to filter out profanities, replacing all but the initial character in each filtered word with asterisks + :param speech_model: Recognition model used by the transcription engine, among those supported by the provider + :param hints: A Phrase contains words and phrase \\\"hints\\\" so that the speech recognition engine is more likely to recognize them. + :param enable_automatic_punctuation: The provider will add punctuation to recognition result + :param intelligence_service: The SID or unique name of the [Intelligence Service](https://www.twilio.com/docs/conversational-intelligence/api/service-resource) for persisting transcripts and running post-call Language Operators . + + :returns: The created TranscriptionInstance + """ + + data = values.of( + { + "Name": name, + "Track": track, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "InboundTrackLabel": inbound_track_label, + "OutboundTrackLabel": outbound_track_label, + "PartialResults": serialize.boolean_to_string(partial_results), + "LanguageCode": language_code, + "TranscriptionEngine": transcription_engine, + "ProfanityFilter": serialize.boolean_to_string(profanity_filter), + "SpeechModel": speech_model, + "Hints": hints, + "EnableAutomaticPunctuation": serialize.boolean_to_string( + enable_automatic_punctuation + ), + "IntelligenceService": intelligence_service, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + async def create_async( + self, + name: Union[str, object] = values.unset, + track: Union["TranscriptionInstance.Track", object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + inbound_track_label: Union[str, object] = values.unset, + outbound_track_label: Union[str, object] = values.unset, + partial_results: Union[bool, object] = values.unset, + language_code: Union[str, object] = values.unset, + transcription_engine: Union[str, object] = values.unset, + profanity_filter: Union[bool, object] = values.unset, + speech_model: Union[str, object] = values.unset, + hints: Union[str, object] = values.unset, + enable_automatic_punctuation: Union[bool, object] = values.unset, + intelligence_service: Union[str, object] = values.unset, + ) -> TranscriptionInstance: + """ + Asynchronously create the TranscriptionInstance + + :param name: The user-specified name of this Transcription, if one was given when the Transcription was created. This may be used to stop the Transcription. + :param track: + :param status_callback_url: Absolute URL of the status callback. + :param status_callback_method: The http method for the status_callback (one of GET, POST). + :param inbound_track_label: Friendly name given to the Inbound Track + :param outbound_track_label: Friendly name given to the Outbound Track + :param partial_results: Indicates if partial results are going to be sent to the customer + :param language_code: Language code used by the transcription engine, specified in [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) format + :param transcription_engine: Definition of the transcription engine to be used, among those supported by Twilio + :param profanity_filter: indicates if the server will attempt to filter out profanities, replacing all but the initial character in each filtered word with asterisks + :param speech_model: Recognition model used by the transcription engine, among those supported by the provider + :param hints: A Phrase contains words and phrase \\\"hints\\\" so that the speech recognition engine is more likely to recognize them. + :param enable_automatic_punctuation: The provider will add punctuation to recognition result + :param intelligence_service: The SID or unique name of the [Intelligence Service](https://www.twilio.com/docs/conversational-intelligence/api/service-resource) for persisting transcripts and running post-call Language Operators . + + :returns: The created TranscriptionInstance + """ + + data = values.of( + { + "Name": name, + "Track": track, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "InboundTrackLabel": inbound_track_label, + "OutboundTrackLabel": outbound_track_label, + "PartialResults": serialize.boolean_to_string(partial_results), + "LanguageCode": language_code, + "TranscriptionEngine": transcription_engine, + "ProfanityFilter": serialize.boolean_to_string(profanity_filter), + "SpeechModel": speech_model, + "Hints": hints, + "EnableAutomaticPunctuation": serialize.boolean_to_string( + enable_automatic_punctuation + ), + "IntelligenceService": intelligence_service, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def get(self, sid: str) -> TranscriptionContext: + """ + Constructs a TranscriptionContext + + :param sid: The SID of the Transcription resource, or the `name` used when creating the resource + """ + return TranscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> TranscriptionContext: + """ + Constructs a TranscriptionContext + + :param sid: The SID of the Transcription resource, or the `name` used when creating the resource + """ + return TranscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/user_defined_message.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/user_defined_message.py new file mode 100644 index 00000000..bc66f8b8 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/user_defined_message.py @@ -0,0 +1,159 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class UserDefinedMessageInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created User Defined Message. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the User Defined Message is associated with. + :ivar sid: The SID that uniquely identifies this User Defined Message. + :ivar date_created: The date that this User Defined Message was created, given in RFC 2822 format. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], account_sid: str, call_sid: str + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.call_sid: Optional[str] = payload.get("call_sid") + self.sid: Optional[str] = payload.get("sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserDefinedMessageList(ListResource): + + def __init__(self, version: Version, account_sid: str, call_sid: str): + """ + Initialize the UserDefinedMessageList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created User Defined Message. + :param call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the User Defined Message is associated with. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + self._uri = ( + "/Accounts/{account_sid}/Calls/{call_sid}/UserDefinedMessages.json".format( + **self._solution + ) + ) + + def create( + self, content: str, idempotency_key: Union[str, object] = values.unset + ) -> UserDefinedMessageInstance: + """ + Create the UserDefinedMessageInstance + + :param content: The User Defined Message in the form of URL-encoded JSON string. + :param idempotency_key: A unique string value to identify API call. This should be a unique string value per API call and can be a randomly generated. + + :returns: The created UserDefinedMessageInstance + """ + + data = values.of( + { + "Content": content, + "IdempotencyKey": idempotency_key, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserDefinedMessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + async def create_async( + self, content: str, idempotency_key: Union[str, object] = values.unset + ) -> UserDefinedMessageInstance: + """ + Asynchronously create the UserDefinedMessageInstance + + :param content: The User Defined Message in the form of URL-encoded JSON string. + :param idempotency_key: A unique string value to identify API call. This should be a unique string value per API call and can be a randomly generated. + + :returns: The created UserDefinedMessageInstance + """ + + data = values.of( + { + "Content": content, + "IdempotencyKey": idempotency_key, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserDefinedMessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/user_defined_message_subscription.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/user_defined_message_subscription.py new file mode 100644 index 00000000..66923d4b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/call/user_defined_message_subscription.py @@ -0,0 +1,300 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class UserDefinedMessageSubscriptionInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that subscribed to the User Defined Messages. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the User Defined Message Subscription is associated with. This refers to the Call SID that is producing the User Defined Messages. + :ivar sid: The SID that uniquely identifies this User Defined Message Subscription. + :ivar date_created: The date that this User Defined Message Subscription was created, given in RFC 2822 format. + :ivar uri: The URI of the User Defined Message Subscription Resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + call_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.call_sid: Optional[str] = payload.get("call_sid") + self.sid: Optional[str] = payload.get("sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid or self.sid, + } + self._context: Optional[UserDefinedMessageSubscriptionContext] = None + + @property + def _proxy(self) -> "UserDefinedMessageSubscriptionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserDefinedMessageSubscriptionContext for this UserDefinedMessageSubscriptionInstance + """ + if self._context is None: + self._context = UserDefinedMessageSubscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UserDefinedMessageSubscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserDefinedMessageSubscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class UserDefinedMessageSubscriptionContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): + """ + Initialize the UserDefinedMessageSubscriptionContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that subscribed to the User Defined Messages. + :param call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the User Defined Message Subscription is associated with. This refers to the Call SID that is producing the User Defined Messages. + :param sid: The SID that uniquely identifies this User Defined Message Subscription. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Calls/{call_sid}/UserDefinedMessageSubscriptions/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the UserDefinedMessageSubscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserDefinedMessageSubscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class UserDefinedMessageSubscriptionList(ListResource): + + def __init__(self, version: Version, account_sid: str, call_sid: str): + """ + Initialize the UserDefinedMessageSubscriptionList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that subscribed to the User Defined Messages. + :param call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the User Defined Messages subscription is associated with. This refers to the Call SID that is producing the user defined messages. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + self._uri = "/Accounts/{account_sid}/Calls/{call_sid}/UserDefinedMessageSubscriptions.json".format( + **self._solution + ) + + def create( + self, + callback: str, + idempotency_key: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + ) -> UserDefinedMessageSubscriptionInstance: + """ + Create the UserDefinedMessageSubscriptionInstance + + :param callback: The URL we should call using the `method` to send user defined events to your application. URLs must contain a valid hostname (underscores are not permitted). + :param idempotency_key: A unique string value to identify API call. This should be a unique string value per API call and can be a randomly generated. + :param method: The HTTP method Twilio will use when requesting the above `Url`. Either `GET` or `POST`. Default is `POST`. + + :returns: The created UserDefinedMessageSubscriptionInstance + """ + + data = values.of( + { + "Callback": callback, + "IdempotencyKey": idempotency_key, + "Method": method, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserDefinedMessageSubscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + async def create_async( + self, + callback: str, + idempotency_key: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + ) -> UserDefinedMessageSubscriptionInstance: + """ + Asynchronously create the UserDefinedMessageSubscriptionInstance + + :param callback: The URL we should call using the `method` to send user defined events to your application. URLs must contain a valid hostname (underscores are not permitted). + :param idempotency_key: A unique string value to identify API call. This should be a unique string value per API call and can be a randomly generated. + :param method: The HTTP method Twilio will use when requesting the above `Url`. Either `GET` or `POST`. Default is `POST`. + + :returns: The created UserDefinedMessageSubscriptionInstance + """ + + data = values.of( + { + "Callback": callback, + "IdempotencyKey": idempotency_key, + "Method": method, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserDefinedMessageSubscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def get(self, sid: str) -> UserDefinedMessageSubscriptionContext: + """ + Constructs a UserDefinedMessageSubscriptionContext + + :param sid: The SID that uniquely identifies this User Defined Message Subscription. + """ + return UserDefinedMessageSubscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> UserDefinedMessageSubscriptionContext: + """ + Constructs a UserDefinedMessageSubscriptionContext + + :param sid: The SID that uniquely identifies this User Defined Message Subscription. + """ + return UserDefinedMessageSubscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/conference/__init__.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/conference/__init__.py new file mode 100644 index 00000000..672d9d0f --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/conference/__init__.py @@ -0,0 +1,791 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.conference.participant import ParticipantList +from twilio.rest.api.v2010.account.conference.recording import RecordingList + + +class ConferenceInstance(InstanceResource): + + class ReasonConferenceEnded(object): + CONFERENCE_ENDED_VIA_API = "conference-ended-via-api" + PARTICIPANT_WITH_END_CONFERENCE_ON_EXIT_LEFT = ( + "participant-with-end-conference-on-exit-left" + ) + PARTICIPANT_WITH_END_CONFERENCE_ON_EXIT_KICKED = ( + "participant-with-end-conference-on-exit-kicked" + ) + LAST_PARTICIPANT_KICKED = "last-participant-kicked" + LAST_PARTICIPANT_LEFT = "last-participant-left" + + class Status(object): + INIT = "init" + IN_PROGRESS = "in-progress" + COMPLETED = "completed" + + class UpdateStatus(object): + COMPLETED = "completed" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Conference resource. + :ivar date_created: The date and time in UTC that this resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in UTC that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar api_version: The API version used to create this conference. + :ivar friendly_name: A string that you assigned to describe this conference room. Maximum length is 128 characters. + :ivar region: A string that represents the Twilio Region where the conference audio was mixed. May be `us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, and `jp1`. Basic conference audio will always be mixed in `us1`. Global Conference audio will be mixed nearest to the majority of participants. + :ivar sid: The unique, Twilio-provided string used to identify this Conference resource. + :ivar status: + :ivar uri: The URI of this resource, relative to `https://api.twilio.com`. + :ivar subresource_uris: A list of related resources identified by their URIs relative to `https://api.twilio.com`. + :ivar reason_conference_ended: + :ivar call_sid_ending_conference: The call SID that caused the conference to end. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.api_version: Optional[str] = payload.get("api_version") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.region: Optional[str] = payload.get("region") + self.sid: Optional[str] = payload.get("sid") + self.status: Optional["ConferenceInstance.Status"] = payload.get("status") + self.uri: Optional[str] = payload.get("uri") + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.reason_conference_ended: Optional[ + "ConferenceInstance.ReasonConferenceEnded" + ] = payload.get("reason_conference_ended") + self.call_sid_ending_conference: Optional[str] = payload.get( + "call_sid_ending_conference" + ) + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[ConferenceContext] = None + + @property + def _proxy(self) -> "ConferenceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConferenceContext for this ConferenceInstance + """ + if self._context is None: + self._context = ConferenceContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "ConferenceInstance": + """ + Fetch the ConferenceInstance + + + :returns: The fetched ConferenceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConferenceInstance": + """ + Asynchronous coroutine to fetch the ConferenceInstance + + + :returns: The fetched ConferenceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> "ConferenceInstance": + """ + Update the ConferenceInstance + + :param status: + :param announce_url: The URL we should call to announce something into the conference. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method used to call `announce_url`. Can be: `GET` or `POST` and the default is `POST` + + :returns: The updated ConferenceInstance + """ + return self._proxy.update( + status=status, + announce_url=announce_url, + announce_method=announce_method, + ) + + async def update_async( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> "ConferenceInstance": + """ + Asynchronous coroutine to update the ConferenceInstance + + :param status: + :param announce_url: The URL we should call to announce something into the conference. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method used to call `announce_url`. Can be: `GET` or `POST` and the default is `POST` + + :returns: The updated ConferenceInstance + """ + return await self._proxy.update_async( + status=status, + announce_url=announce_url, + announce_method=announce_method, + ) + + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + return self._proxy.participants + + @property + def recordings(self) -> RecordingList: + """ + Access the recordings + """ + return self._proxy.recordings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConferenceContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the ConferenceContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Conference resource(s) to update. + :param sid: The Twilio-provided string that uniquely identifies the Conference resource to update + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Conferences/{sid}.json".format( + **self._solution + ) + + self._participants: Optional[ParticipantList] = None + self._recordings: Optional[RecordingList] = None + + def fetch(self) -> ConferenceInstance: + """ + Fetch the ConferenceInstance + + + :returns: The fetched ConferenceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ConferenceInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ConferenceInstance: + """ + Asynchronous coroutine to fetch the ConferenceInstance + + + :returns: The fetched ConferenceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ConferenceInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> ConferenceInstance: + """ + Update the ConferenceInstance + + :param status: + :param announce_url: The URL we should call to announce something into the conference. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method used to call `announce_url`. Can be: `GET` or `POST` and the default is `POST` + + :returns: The updated ConferenceInstance + """ + + data = values.of( + { + "Status": status, + "AnnounceUrl": announce_url, + "AnnounceMethod": announce_method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConferenceInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> ConferenceInstance: + """ + Asynchronous coroutine to update the ConferenceInstance + + :param status: + :param announce_url: The URL we should call to announce something into the conference. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method used to call `announce_url`. Can be: `GET` or `POST` and the default is `POST` + + :returns: The updated ConferenceInstance + """ + + data = values.of( + { + "Status": status, + "AnnounceUrl": announce_url, + "AnnounceMethod": announce_method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConferenceInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + if self._participants is None: + self._participants = ParticipantList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._participants + + @property + def recordings(self) -> RecordingList: + """ + Access the recordings + """ + if self._recordings is None: + self._recordings = RecordingList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._recordings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConferencePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ConferenceInstance: + """ + Build an instance of ConferenceInstance + + :param payload: Payload response from the API + """ + return ConferenceInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ConferenceList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the ConferenceList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Conference resource(s) to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Conferences.json".format(**self._solution) + + def stream( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + date_updated: Union[date, object] = values.unset, + date_updated_before: Union[date, object] = values.unset, + date_updated_after: Union[date, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union["ConferenceInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConferenceInstance]: + """ + Streams ConferenceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param date date_created: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_before: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_after: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_updated: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_before: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_after: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param str friendly_name: The string that identifies the Conference resources to read. + :param "ConferenceInstance.Status" status: The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + date_updated=date_updated, + date_updated_before=date_updated_before, + date_updated_after=date_updated_after, + friendly_name=friendly_name, + status=status, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + date_updated: Union[date, object] = values.unset, + date_updated_before: Union[date, object] = values.unset, + date_updated_after: Union[date, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union["ConferenceInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConferenceInstance]: + """ + Asynchronously streams ConferenceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param date date_created: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_before: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_after: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_updated: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_before: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_after: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param str friendly_name: The string that identifies the Conference resources to read. + :param "ConferenceInstance.Status" status: The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + date_updated=date_updated, + date_updated_before=date_updated_before, + date_updated_after=date_updated_after, + friendly_name=friendly_name, + status=status, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + date_updated: Union[date, object] = values.unset, + date_updated_before: Union[date, object] = values.unset, + date_updated_after: Union[date, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union["ConferenceInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConferenceInstance]: + """ + Lists ConferenceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param date date_created: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_before: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_after: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_updated: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_before: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_after: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param str friendly_name: The string that identifies the Conference resources to read. + :param "ConferenceInstance.Status" status: The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + date_updated=date_updated, + date_updated_before=date_updated_before, + date_updated_after=date_updated_after, + friendly_name=friendly_name, + status=status, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + date_updated: Union[date, object] = values.unset, + date_updated_before: Union[date, object] = values.unset, + date_updated_after: Union[date, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union["ConferenceInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConferenceInstance]: + """ + Asynchronously lists ConferenceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param date date_created: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_before: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_after: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_updated: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_before: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_after: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param str friendly_name: The string that identifies the Conference resources to read. + :param "ConferenceInstance.Status" status: The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + date_updated=date_updated, + date_updated_before=date_updated_before, + date_updated_after=date_updated_after, + friendly_name=friendly_name, + status=status, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + date_updated: Union[date, object] = values.unset, + date_updated_before: Union[date, object] = values.unset, + date_updated_after: Union[date, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union["ConferenceInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConferencePage: + """ + Retrieve a single page of ConferenceInstance records from the API. + Request is executed immediately + + :param date_created: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date_created_before: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date_created_after: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date_updated: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date_updated_before: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date_updated_after: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param friendly_name: The string that identifies the Conference resources to read. + :param status: The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConferenceInstance + """ + data = values.of( + { + "DateCreated": serialize.iso8601_date(date_created), + "DateCreated<": serialize.iso8601_date(date_created_before), + "DateCreated>": serialize.iso8601_date(date_created_after), + "DateUpdated": serialize.iso8601_date(date_updated), + "DateUpdated<": serialize.iso8601_date(date_updated_before), + "DateUpdated>": serialize.iso8601_date(date_updated_after), + "FriendlyName": friendly_name, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConferencePage(self._version, response, self._solution) + + async def page_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + date_updated: Union[date, object] = values.unset, + date_updated_before: Union[date, object] = values.unset, + date_updated_after: Union[date, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union["ConferenceInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConferencePage: + """ + Asynchronously retrieve a single page of ConferenceInstance records from the API. + Request is executed immediately + + :param date_created: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date_created_before: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date_created_after: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date_updated: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date_updated_before: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date_updated_after: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param friendly_name: The string that identifies the Conference resources to read. + :param status: The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConferenceInstance + """ + data = values.of( + { + "DateCreated": serialize.iso8601_date(date_created), + "DateCreated<": serialize.iso8601_date(date_created_before), + "DateCreated>": serialize.iso8601_date(date_created_after), + "DateUpdated": serialize.iso8601_date(date_updated), + "DateUpdated<": serialize.iso8601_date(date_updated_before), + "DateUpdated>": serialize.iso8601_date(date_updated_after), + "FriendlyName": friendly_name, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConferencePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ConferencePage: + """ + Retrieve a specific page of ConferenceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConferenceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConferencePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ConferencePage: + """ + Asynchronously retrieve a specific page of ConferenceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConferenceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConferencePage(self._version, response, self._solution) + + def get(self, sid: str) -> ConferenceContext: + """ + Constructs a ConferenceContext + + :param sid: The Twilio-provided string that uniquely identifies the Conference resource to update + """ + return ConferenceContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ConferenceContext: + """ + Constructs a ConferenceContext + + :param sid: The Twilio-provided string that uniquely identifies the Conference resource to update + """ + return ConferenceContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/conference/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/conference/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..f47466dc Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/conference/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/conference/__pycache__/participant.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/conference/__pycache__/participant.cpython-312.pyc new file mode 100644 index 00000000..e5829c95 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/conference/__pycache__/participant.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/conference/__pycache__/recording.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/conference/__pycache__/recording.cpython-312.pyc new file mode 100644 index 00000000..5f707b0b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/conference/__pycache__/recording.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/conference/participant.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/conference/participant.py new file mode 100644 index 00000000..3c49e538 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/conference/participant.py @@ -0,0 +1,1201 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ParticipantInstance(InstanceResource): + + class Status(object): + QUEUED = "queued" + CONNECTING = "connecting" + RINGING = "ringing" + CONNECTED = "connected" + COMPLETE = "complete" + FAILED = "failed" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Participant resource. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Participant resource is associated with. + :ivar label: The user-specified label of this participant, if one was given when the participant was created. This may be used to fetch, update or delete the participant. + :ivar call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + :ivar coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :ivar conference_sid: The SID of the conference the participant is in. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar end_conference_on_exit: Whether the conference ends when the participant leaves. Can be: `true` or `false` and the default is `false`. If `true`, the conference ends and all other participants drop out when the participant leaves. + :ivar muted: Whether the participant is muted. Can be `true` or `false`. + :ivar hold: Whether the participant is on hold. Can be `true` or `false`. + :ivar start_conference_on_enter: Whether the conference starts when the participant joins the conference, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :ivar status: + :ivar queue_time: The wait time in milliseconds before participant's call is placed. Only available in the response to a create participant request. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + conference_sid: str, + call_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.call_sid: Optional[str] = payload.get("call_sid") + self.label: Optional[str] = payload.get("label") + self.call_sid_to_coach: Optional[str] = payload.get("call_sid_to_coach") + self.coaching: Optional[bool] = payload.get("coaching") + self.conference_sid: Optional[str] = payload.get("conference_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.end_conference_on_exit: Optional[bool] = payload.get( + "end_conference_on_exit" + ) + self.muted: Optional[bool] = payload.get("muted") + self.hold: Optional[bool] = payload.get("hold") + self.start_conference_on_enter: Optional[bool] = payload.get( + "start_conference_on_enter" + ) + self.status: Optional["ParticipantInstance.Status"] = payload.get("status") + self.queue_time: Optional[str] = payload.get("queue_time") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "conference_sid": conference_sid, + "call_sid": call_sid or self.call_sid, + } + self._context: Optional[ParticipantContext] = None + + @property + def _proxy(self) -> "ParticipantContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ParticipantContext for this ParticipantInstance + """ + if self._context is None: + self._context = ParticipantContext( + self._version, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ParticipantInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ParticipantInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ParticipantInstance": + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ParticipantInstance": + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + hold_url: Union[str, object] = values.unset, + hold_method: Union[str, object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + beep_on_exit: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + ) -> "ParticipantInstance": + """ + Update the ParticipantInstance + + :param muted: Whether the participant should be muted. Can be `true` or `false`. `true` will mute the participant, and `false` will un-mute them. Anything value other than `true` or `false` is interpreted as `false`. + :param hold: Whether the participant should be on hold. Can be: `true` or `false`. `true` puts the participant on hold, and `false` lets them rejoin the conference. + :param hold_url: The URL we call using the `hold_method` for music that plays when the participant is on hold. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param hold_method: The HTTP method we should use to call `hold_url`. Can be: `GET` or `POST` and the default is `GET`. + :param announce_url: The URL we call using the `announce_method` for an announcement to the participant. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method we should use to call `announce_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param beep_on_exit: Whether to play a notification beep to the conference when the participant exits. Can be: `true` or `false`. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + + :returns: The updated ParticipantInstance + """ + return self._proxy.update( + muted=muted, + hold=hold, + hold_url=hold_url, + hold_method=hold_method, + announce_url=announce_url, + announce_method=announce_method, + wait_url=wait_url, + wait_method=wait_method, + beep_on_exit=beep_on_exit, + end_conference_on_exit=end_conference_on_exit, + coaching=coaching, + call_sid_to_coach=call_sid_to_coach, + ) + + async def update_async( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + hold_url: Union[str, object] = values.unset, + hold_method: Union[str, object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + beep_on_exit: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + ) -> "ParticipantInstance": + """ + Asynchronous coroutine to update the ParticipantInstance + + :param muted: Whether the participant should be muted. Can be `true` or `false`. `true` will mute the participant, and `false` will un-mute them. Anything value other than `true` or `false` is interpreted as `false`. + :param hold: Whether the participant should be on hold. Can be: `true` or `false`. `true` puts the participant on hold, and `false` lets them rejoin the conference. + :param hold_url: The URL we call using the `hold_method` for music that plays when the participant is on hold. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param hold_method: The HTTP method we should use to call `hold_url`. Can be: `GET` or `POST` and the default is `GET`. + :param announce_url: The URL we call using the `announce_method` for an announcement to the participant. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method we should use to call `announce_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param beep_on_exit: Whether to play a notification beep to the conference when the participant exits. Can be: `true` or `false`. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + + :returns: The updated ParticipantInstance + """ + return await self._proxy.update_async( + muted=muted, + hold=hold, + hold_url=hold_url, + hold_method=hold_method, + announce_url=announce_url, + announce_method=announce_method, + wait_url=wait_url, + wait_method=wait_method, + beep_on_exit=beep_on_exit, + end_conference_on_exit=end_conference_on_exit, + coaching=coaching, + call_sid_to_coach=call_sid_to_coach, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ParticipantContext(InstanceContext): + + def __init__( + self, version: Version, account_sid: str, conference_sid: str, call_sid: str + ): + """ + Initialize the ParticipantContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Participant resources to update. + :param conference_sid: The SID of the conference with the participant to update. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID or label of the participant to update. Non URL safe characters in a label must be percent encoded, for example, a space character is represented as %20. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "conference_sid": conference_sid, + "call_sid": call_sid, + } + self._uri = "/Accounts/{account_sid}/Conferences/{conference_sid}/Participants/{call_sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the ParticipantInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ParticipantInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) + + async def fetch_async(self) -> ParticipantInstance: + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) + + def update( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + hold_url: Union[str, object] = values.unset, + hold_method: Union[str, object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + beep_on_exit: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Update the ParticipantInstance + + :param muted: Whether the participant should be muted. Can be `true` or `false`. `true` will mute the participant, and `false` will un-mute them. Anything value other than `true` or `false` is interpreted as `false`. + :param hold: Whether the participant should be on hold. Can be: `true` or `false`. `true` puts the participant on hold, and `false` lets them rejoin the conference. + :param hold_url: The URL we call using the `hold_method` for music that plays when the participant is on hold. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param hold_method: The HTTP method we should use to call `hold_url`. Can be: `GET` or `POST` and the default is `GET`. + :param announce_url: The URL we call using the `announce_method` for an announcement to the participant. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method we should use to call `announce_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param beep_on_exit: Whether to play a notification beep to the conference when the participant exits. Can be: `true` or `false`. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + + :returns: The updated ParticipantInstance + """ + + data = values.of( + { + "Muted": serialize.boolean_to_string(muted), + "Hold": serialize.boolean_to_string(hold), + "HoldUrl": hold_url, + "HoldMethod": hold_method, + "AnnounceUrl": announce_url, + "AnnounceMethod": announce_method, + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "BeepOnExit": serialize.boolean_to_string(beep_on_exit), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "Coaching": serialize.boolean_to_string(coaching), + "CallSidToCoach": call_sid_to_coach, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) + + async def update_async( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + hold_url: Union[str, object] = values.unset, + hold_method: Union[str, object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + beep_on_exit: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronous coroutine to update the ParticipantInstance + + :param muted: Whether the participant should be muted. Can be `true` or `false`. `true` will mute the participant, and `false` will un-mute them. Anything value other than `true` or `false` is interpreted as `false`. + :param hold: Whether the participant should be on hold. Can be: `true` or `false`. `true` puts the participant on hold, and `false` lets them rejoin the conference. + :param hold_url: The URL we call using the `hold_method` for music that plays when the participant is on hold. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param hold_method: The HTTP method we should use to call `hold_url`. Can be: `GET` or `POST` and the default is `GET`. + :param announce_url: The URL we call using the `announce_method` for an announcement to the participant. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method we should use to call `announce_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param beep_on_exit: Whether to play a notification beep to the conference when the participant exits. Can be: `true` or `false`. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + + :returns: The updated ParticipantInstance + """ + + data = values.of( + { + "Muted": serialize.boolean_to_string(muted), + "Hold": serialize.boolean_to_string(hold), + "HoldUrl": hold_url, + "HoldMethod": hold_method, + "AnnounceUrl": announce_url, + "AnnounceMethod": announce_method, + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "BeepOnExit": serialize.boolean_to_string(beep_on_exit), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "Coaching": serialize.boolean_to_string(coaching), + "CallSidToCoach": call_sid_to_coach, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ParticipantPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: + """ + Build an instance of ParticipantInstance + + :param payload: Payload response from the API + """ + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ParticipantList(ListResource): + + def __init__(self, version: Version, account_sid: str, conference_sid: str): + """ + Initialize the ParticipantList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Participant resources to read. + :param conference_sid: The SID of the conference with the participants to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "conference_sid": conference_sid, + } + self._uri = "/Accounts/{account_sid}/Conferences/{conference_sid}/Participants.json".format( + **self._solution + ) + + def create( + self, + from_: str, + to: str, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[List[str], object] = values.unset, + label: Union[str, object] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[List[str], object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + recording_status_callback_event: Union[List[str], object] = values.unset, + conference_recording_status_callback_event: Union[ + List[str], object + ] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + byoc: Union[str, object] = values.unset, + caller_id: Union[str, object] = values.unset, + call_reason: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + machine_detection: Union[str, object] = values.unset, + machine_detection_timeout: Union[int, object] = values.unset, + machine_detection_speech_threshold: Union[int, object] = values.unset, + machine_detection_speech_end_threshold: Union[int, object] = values.unset, + machine_detection_silence_timeout: Union[int, object] = values.unset, + amd_status_callback: Union[str, object] = values.unset, + amd_status_callback_method: Union[str, object] = values.unset, + trim: Union[str, object] = values.unset, + call_token: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Create the ParticipantInstance + + :param from_: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `from` must also be a phone number. If `to` is sip address, this value of `from` should be a username portion to be used to populate the P-Asserted-Identity header that is passed to the SIP endpoint. + :param to: The phone number, SIP address, or Client identifier that received this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). SIP addresses are formatted as `sip:name@company.com`. Client identifiers are formatted `client:name`. [Custom parameters](https://www.twilio.com/docs/voice/api/conference-participant-resource#custom-parameters) may also be specified. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` and `POST` and defaults to `POST`. + :param status_callback_event: The conference state changes that should generate a call to `status_callback`. Can be: `initiated`, `ringing`, `answered`, and `completed`. Separate multiple values with a space. The default value is `completed`. + :param label: A label for this participant. If one is supplied, it may subsequently be used to fetch, update or delete the participant. + :param timeout: The number of seconds that we should allow the phone to ring before assuming there is no answer. Can be an integer between `5` and `600`, inclusive. The default value is `60`. We always add a 5-second timeout buffer to outgoing calls, so value of 10 would result in an actual timeout that was closer to 15 seconds. + :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. + :param muted: Whether the agent is muted in the conference. Can be `true` or `false` and the default is `false`. + :param beep: Whether to play a notification beep to the conference when the participant joins. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. Can be: `true` or `false` and defaults to `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_record: Whether to record the conference the participant is joining. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: Whether to trim leading and trailing silence from the conference recording. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference state changes that should generate a call to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `modify`, `speaker`, and `announcement`. Separate multiple values with a space. Defaults to `start end`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param recording_status_callback_event: The recording state changes that should generate a call to `recording_status_callback`. Can be: `started`, `in-progress`, `paused`, `resumed`, `stopped`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `'in-progress completed failed'`. + :param conference_recording_status_callback_event: The conference recording state changes that generate a call to `conference_recording_status_callback`. Can be: `in-progress`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `'in-progress completed failed'` + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + :param jitter_buffer_size: Jitter buffer size for the connecting participant. Twilio will use this setting to apply Jitter Buffer before participant's audio is mixed into the conference. Can be: `off`, `small`, `medium`, and `large`. Default to `large`. + :param byoc: The SID of a BYOC (Bring Your Own Carrier) trunk to route this call with. Note that `byoc` is only meaningful when `to` is a phone number; it will otherwise be ignored. (Beta) + :param caller_id: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `callerId` must also be a phone number. If `to` is sip address, this value of `callerId` should be a username portion to be used to populate the From header that is passed to the SIP endpoint. + :param call_reason: The Reason for the outgoing call. Use it to specify the purpose of the call that is presented on the called party's phone. (Branded Calls Beta) + :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is sent from Twilio. `both` records the audio that is received and sent by Twilio. + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + :param machine_detection: Whether to detect if a human, answering machine, or fax has picked up the call. Can be: `Enable` or `DetectMessageEnd`. Use `Enable` if you would like us to return `AnsweredBy` as soon as the called party is identified. Use `DetectMessageEnd`, if you would like to leave a message on an answering machine. For more information, see [Answering Machine Detection](https://www.twilio.com/docs/voice/answering-machine-detection). + :param machine_detection_timeout: The number of seconds that we should attempt to detect an answering machine before timing out and sending a voice request with `AnsweredBy` of `unknown`. The default timeout is 30 seconds. + :param machine_detection_speech_threshold: The number of milliseconds that is used as the measuring stick for the length of the speech activity, where durations lower than this value will be interpreted as a human and longer than this value as a machine. Possible Values: 1000-6000. Default: 2400. + :param machine_detection_speech_end_threshold: The number of milliseconds of silence after speech activity at which point the speech activity is considered complete. Possible Values: 500-5000. Default: 1200. + :param machine_detection_silence_timeout: The number of milliseconds of initial silence after which an `unknown` AnsweredBy result will be returned. Possible Values: 2000-10000. Default: 5000. + :param amd_status_callback: The URL that we should call using the `amd_status_callback_method` to notify customer application whether the call was answered by human, machine or fax. + :param amd_status_callback_method: The HTTP method we should use when calling the `amd_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param trim: Whether to trim any leading and trailing silence from the participant recording. Can be: `trim-silence` or `do-not-trim` and the default is `trim-silence`. + :param call_token: A token string needed to invoke a forwarded call. A call_token is generated when an incoming call is received on a Twilio number. Pass an incoming call's call_token value to a forwarded call via the call_token parameter when creating a new call. A forwarded call should bear the same CallerID of the original incoming call. + + :returns: The created ParticipantInstance + """ + + data = values.of( + { + "From": from_, + "To": to, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "Label": label, + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "Muted": serialize.boolean_to_string(muted), + "Beep": beep, + "StartConferenceOnEnter": serialize.boolean_to_string( + start_conference_on_enter + ), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "EarlyMedia": serialize.boolean_to_string(early_media), + "MaxParticipants": max_participants, + "ConferenceRecord": conference_record, + "ConferenceTrim": conference_trim, + "ConferenceStatusCallback": conference_status_callback, + "ConferenceStatusCallbackMethod": conference_status_callback_method, + "ConferenceStatusCallbackEvent": serialize.map( + conference_status_callback_event, lambda e: e + ), + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "Region": region, + "ConferenceRecordingStatusCallback": conference_recording_status_callback, + "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, + "RecordingStatusCallbackEvent": serialize.map( + recording_status_callback_event, lambda e: e + ), + "ConferenceRecordingStatusCallbackEvent": serialize.map( + conference_recording_status_callback_event, lambda e: e + ), + "Coaching": serialize.boolean_to_string(coaching), + "CallSidToCoach": call_sid_to_coach, + "JitterBufferSize": jitter_buffer_size, + "Byoc": byoc, + "CallerId": caller_id, + "CallReason": call_reason, + "RecordingTrack": recording_track, + "TimeLimit": time_limit, + "MachineDetection": machine_detection, + "MachineDetectionTimeout": machine_detection_timeout, + "MachineDetectionSpeechThreshold": machine_detection_speech_threshold, + "MachineDetectionSpeechEndThreshold": machine_detection_speech_end_threshold, + "MachineDetectionSilenceTimeout": machine_detection_silence_timeout, + "AmdStatusCallback": amd_status_callback, + "AmdStatusCallbackMethod": amd_status_callback_method, + "Trim": trim, + "CallToken": call_token, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + ) + + async def create_async( + self, + from_: str, + to: str, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[List[str], object] = values.unset, + label: Union[str, object] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[List[str], object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + recording_status_callback_event: Union[List[str], object] = values.unset, + conference_recording_status_callback_event: Union[ + List[str], object + ] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + byoc: Union[str, object] = values.unset, + caller_id: Union[str, object] = values.unset, + call_reason: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + machine_detection: Union[str, object] = values.unset, + machine_detection_timeout: Union[int, object] = values.unset, + machine_detection_speech_threshold: Union[int, object] = values.unset, + machine_detection_speech_end_threshold: Union[int, object] = values.unset, + machine_detection_silence_timeout: Union[int, object] = values.unset, + amd_status_callback: Union[str, object] = values.unset, + amd_status_callback_method: Union[str, object] = values.unset, + trim: Union[str, object] = values.unset, + call_token: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronously create the ParticipantInstance + + :param from_: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `from` must also be a phone number. If `to` is sip address, this value of `from` should be a username portion to be used to populate the P-Asserted-Identity header that is passed to the SIP endpoint. + :param to: The phone number, SIP address, or Client identifier that received this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). SIP addresses are formatted as `sip:name@company.com`. Client identifiers are formatted `client:name`. [Custom parameters](https://www.twilio.com/docs/voice/api/conference-participant-resource#custom-parameters) may also be specified. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` and `POST` and defaults to `POST`. + :param status_callback_event: The conference state changes that should generate a call to `status_callback`. Can be: `initiated`, `ringing`, `answered`, and `completed`. Separate multiple values with a space. The default value is `completed`. + :param label: A label for this participant. If one is supplied, it may subsequently be used to fetch, update or delete the participant. + :param timeout: The number of seconds that we should allow the phone to ring before assuming there is no answer. Can be an integer between `5` and `600`, inclusive. The default value is `60`. We always add a 5-second timeout buffer to outgoing calls, so value of 10 would result in an actual timeout that was closer to 15 seconds. + :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. + :param muted: Whether the agent is muted in the conference. Can be `true` or `false` and the default is `false`. + :param beep: Whether to play a notification beep to the conference when the participant joins. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. Can be: `true` or `false` and defaults to `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_record: Whether to record the conference the participant is joining. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: Whether to trim leading and trailing silence from the conference recording. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference state changes that should generate a call to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `modify`, `speaker`, and `announcement`. Separate multiple values with a space. Defaults to `start end`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param recording_status_callback_event: The recording state changes that should generate a call to `recording_status_callback`. Can be: `started`, `in-progress`, `paused`, `resumed`, `stopped`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `'in-progress completed failed'`. + :param conference_recording_status_callback_event: The conference recording state changes that generate a call to `conference_recording_status_callback`. Can be: `in-progress`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `'in-progress completed failed'` + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + :param jitter_buffer_size: Jitter buffer size for the connecting participant. Twilio will use this setting to apply Jitter Buffer before participant's audio is mixed into the conference. Can be: `off`, `small`, `medium`, and `large`. Default to `large`. + :param byoc: The SID of a BYOC (Bring Your Own Carrier) trunk to route this call with. Note that `byoc` is only meaningful when `to` is a phone number; it will otherwise be ignored. (Beta) + :param caller_id: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `callerId` must also be a phone number. If `to` is sip address, this value of `callerId` should be a username portion to be used to populate the From header that is passed to the SIP endpoint. + :param call_reason: The Reason for the outgoing call. Use it to specify the purpose of the call that is presented on the called party's phone. (Branded Calls Beta) + :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is sent from Twilio. `both` records the audio that is received and sent by Twilio. + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + :param machine_detection: Whether to detect if a human, answering machine, or fax has picked up the call. Can be: `Enable` or `DetectMessageEnd`. Use `Enable` if you would like us to return `AnsweredBy` as soon as the called party is identified. Use `DetectMessageEnd`, if you would like to leave a message on an answering machine. For more information, see [Answering Machine Detection](https://www.twilio.com/docs/voice/answering-machine-detection). + :param machine_detection_timeout: The number of seconds that we should attempt to detect an answering machine before timing out and sending a voice request with `AnsweredBy` of `unknown`. The default timeout is 30 seconds. + :param machine_detection_speech_threshold: The number of milliseconds that is used as the measuring stick for the length of the speech activity, where durations lower than this value will be interpreted as a human and longer than this value as a machine. Possible Values: 1000-6000. Default: 2400. + :param machine_detection_speech_end_threshold: The number of milliseconds of silence after speech activity at which point the speech activity is considered complete. Possible Values: 500-5000. Default: 1200. + :param machine_detection_silence_timeout: The number of milliseconds of initial silence after which an `unknown` AnsweredBy result will be returned. Possible Values: 2000-10000. Default: 5000. + :param amd_status_callback: The URL that we should call using the `amd_status_callback_method` to notify customer application whether the call was answered by human, machine or fax. + :param amd_status_callback_method: The HTTP method we should use when calling the `amd_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param trim: Whether to trim any leading and trailing silence from the participant recording. Can be: `trim-silence` or `do-not-trim` and the default is `trim-silence`. + :param call_token: A token string needed to invoke a forwarded call. A call_token is generated when an incoming call is received on a Twilio number. Pass an incoming call's call_token value to a forwarded call via the call_token parameter when creating a new call. A forwarded call should bear the same CallerID of the original incoming call. + + :returns: The created ParticipantInstance + """ + + data = values.of( + { + "From": from_, + "To": to, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "Label": label, + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "Muted": serialize.boolean_to_string(muted), + "Beep": beep, + "StartConferenceOnEnter": serialize.boolean_to_string( + start_conference_on_enter + ), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "EarlyMedia": serialize.boolean_to_string(early_media), + "MaxParticipants": max_participants, + "ConferenceRecord": conference_record, + "ConferenceTrim": conference_trim, + "ConferenceStatusCallback": conference_status_callback, + "ConferenceStatusCallbackMethod": conference_status_callback_method, + "ConferenceStatusCallbackEvent": serialize.map( + conference_status_callback_event, lambda e: e + ), + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "Region": region, + "ConferenceRecordingStatusCallback": conference_recording_status_callback, + "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, + "RecordingStatusCallbackEvent": serialize.map( + recording_status_callback_event, lambda e: e + ), + "ConferenceRecordingStatusCallbackEvent": serialize.map( + conference_recording_status_callback_event, lambda e: e + ), + "Coaching": serialize.boolean_to_string(coaching), + "CallSidToCoach": call_sid_to_coach, + "JitterBufferSize": jitter_buffer_size, + "Byoc": byoc, + "CallerId": caller_id, + "CallReason": call_reason, + "RecordingTrack": recording_track, + "TimeLimit": time_limit, + "MachineDetection": machine_detection, + "MachineDetectionTimeout": machine_detection_timeout, + "MachineDetectionSpeechThreshold": machine_detection_speech_threshold, + "MachineDetectionSpeechEndThreshold": machine_detection_speech_end_threshold, + "MachineDetectionSilenceTimeout": machine_detection_silence_timeout, + "AmdStatusCallback": amd_status_callback, + "AmdStatusCallbackMethod": amd_status_callback_method, + "Trim": trim, + "CallToken": call_token, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + ) + + def stream( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ParticipantInstance]: + """ + Streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param bool hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param bool coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + muted=muted, hold=hold, coaching=coaching, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ParticipantInstance]: + """ + Asynchronously streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param bool hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param bool coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + muted=muted, hold=hold, coaching=coaching, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param bool hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param bool coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + muted=muted, + hold=hold, + coaching=coaching, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Asynchronously lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param bool hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param bool coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + muted=muted, + hold=hold, + coaching=coaching, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "Muted": serialize.boolean_to_string(muted), + "Hold": serialize.boolean_to_string(hold), + "Coaching": serialize.boolean_to_string(coaching), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) + + async def page_async( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Asynchronously retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "Muted": serialize.boolean_to_string(muted), + "Hold": serialize.boolean_to_string(hold), + "Coaching": serialize.boolean_to_string(coaching), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ParticipantPage: + """ + Retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ParticipantPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ParticipantPage: + """ + Asynchronously retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ParticipantPage(self._version, response, self._solution) + + def get(self, call_sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID or label of the participant to update. Non URL safe characters in a label must be percent encoded, for example, a space character is represented as %20. + """ + return ParticipantContext( + self._version, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=call_sid, + ) + + def __call__(self, call_sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID or label of the participant to update. Non URL safe characters in a label must be percent encoded, for example, a space character is represented as %20. + """ + return ParticipantContext( + self._version, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=call_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/conference/recording.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/conference/recording.py new file mode 100644 index 00000000..12008ed3 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/conference/recording.py @@ -0,0 +1,718 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RecordingInstance(InstanceResource): + + class Source(object): + DIALVERB = "DialVerb" + CONFERENCE = "Conference" + OUTBOUNDAPI = "OutboundAPI" + TRUNKING = "Trunking" + RECORDVERB = "RecordVerb" + STARTCALLRECORDINGAPI = "StartCallRecordingAPI" + STARTCONFERENCERECORDINGAPI = "StartConferenceRecordingAPI" + + class Status(object): + IN_PROGRESS = "in-progress" + PAUSED = "paused" + STOPPED = "stopped" + PROCESSING = "processing" + COMPLETED = "completed" + ABSENT = "absent" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Conference Recording resource. + :ivar api_version: The API version used to create the recording. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Conference Recording resource is associated with. + :ivar conference_sid: The Conference SID that identifies the conference associated with the recording. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar start_time: The start time of the recording in GMT and in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar duration: The length of the recording in seconds. + :ivar sid: The unique string that that we created to identify the Conference Recording resource. + :ivar price: The one-time cost of creating the recording in the `price_unit` currency. + :ivar price_unit: The currency used in the `price` property. Example: `USD`. + :ivar status: + :ivar channels: The number of channels in the final recording file. Can be: `1`, or `2`. Separating a two leg call into two separate channels of the recording file is supported in [Dial](https://www.twilio.com/docs/voice/twiml/dial#attributes-record) and [Outbound Rest API](https://www.twilio.com/docs/voice/make-calls) record options. + :ivar source: + :ivar error_code: The error code that describes why the recording is `absent`. The error code is described in our [Error Dictionary](https://www.twilio.com/docs/api/errors). This value is null if the recording `status` is not `absent`. + :ivar encryption_details: How to decrypt the recording if it was encrypted using [Call Recording Encryption](https://www.twilio.com/docs/voice/tutorials/voice-recording-encryption) feature. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + conference_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.call_sid: Optional[str] = payload.get("call_sid") + self.conference_sid: Optional[str] = payload.get("conference_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.start_time: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("start_time") + ) + self.duration: Optional[str] = payload.get("duration") + self.sid: Optional[str] = payload.get("sid") + self.price: Optional[str] = payload.get("price") + self.price_unit: Optional[str] = payload.get("price_unit") + self.status: Optional["RecordingInstance.Status"] = payload.get("status") + self.channels: Optional[int] = deserialize.integer(payload.get("channels")) + self.source: Optional["RecordingInstance.Source"] = payload.get("source") + self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) + self.encryption_details: Optional[Dict[str, object]] = payload.get( + "encryption_details" + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "conference_sid": conference_sid, + "sid": sid or self.sid, + } + self._context: Optional[RecordingContext] = None + + @property + def _proxy(self) -> "RecordingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RecordingContext for this RecordingInstance + """ + if self._context is None: + self._context = RecordingContext( + self._version, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RecordingInstance": + """ + Fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RecordingInstance": + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> "RecordingInstance": + """ + Update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance + """ + return self._proxy.update( + status=status, + pause_behavior=pause_behavior, + ) + + async def update_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> "RecordingInstance": + """ + Asynchronous coroutine to update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance + """ + return await self._proxy.update_async( + status=status, + pause_behavior=pause_behavior, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RecordingContext(InstanceContext): + + def __init__( + self, version: Version, account_sid: str, conference_sid: str, sid: str + ): + """ + Initialize the RecordingContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Conference Recording resource to update. + :param conference_sid: The Conference SID that identifies the conference associated with the recording to update. + :param sid: The Twilio-provided string that uniquely identifies the Conference Recording resource to update. Use `Twilio.CURRENT` to reference the current active recording. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "conference_sid": conference_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Conferences/{conference_sid}/Recordings/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RecordingInstance: + """ + Fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RecordingInstance: + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> RecordingInstance: + """ + Update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance + """ + + data = values.of( + { + "Status": status, + "PauseBehavior": pause_behavior, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> RecordingInstance: + """ + Asynchronous coroutine to update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance + """ + + data = values.of( + { + "Status": status, + "PauseBehavior": pause_behavior, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RecordingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RecordingInstance: + """ + Build an instance of RecordingInstance + + :param payload: Payload response from the API + """ + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RecordingList(ListResource): + + def __init__(self, version: Version, account_sid: str, conference_sid: str): + """ + Initialize the RecordingList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Conference Recording resources to read. + :param conference_sid: The Conference SID that identifies the conference associated with the recording to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "conference_sid": conference_sid, + } + self._uri = "/Accounts/{account_sid}/Conferences/{conference_sid}/Recordings.json".format( + **self._solution + ) + + def stream( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RecordingInstance]: + """ + Streams RecordingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RecordingInstance]: + """ + Asynchronously streams RecordingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RecordingInstance]: + """ + Lists RecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RecordingInstance]: + """ + Asynchronously lists RecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RecordingPage: + """ + Retrieve a single page of RecordingInstance records from the API. + Request is executed immediately + + :param date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordingInstance + """ + data = values.of( + { + "DateCreated": serialize.iso8601_date(date_created), + "DateCreated<": serialize.iso8601_date(date_created_before), + "DateCreated>": serialize.iso8601_date(date_created_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordingPage(self._version, response, self._solution) + + async def page_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RecordingPage: + """ + Asynchronously retrieve a single page of RecordingInstance records from the API. + Request is executed immediately + + :param date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordingInstance + """ + data = values.of( + { + "DateCreated": serialize.iso8601_date(date_created), + "DateCreated<": serialize.iso8601_date(date_created_before), + "DateCreated>": serialize.iso8601_date(date_created_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RecordingPage: + """ + Retrieve a specific page of RecordingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RecordingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RecordingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RecordingPage: + """ + Asynchronously retrieve a specific page of RecordingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RecordingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RecordingPage(self._version, response, self._solution) + + def get(self, sid: str) -> RecordingContext: + """ + Constructs a RecordingContext + + :param sid: The Twilio-provided string that uniquely identifies the Conference Recording resource to update. Use `Twilio.CURRENT` to reference the current active recording. + """ + return RecordingContext( + self._version, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> RecordingContext: + """ + Constructs a RecordingContext + + :param sid: The Twilio-provided string that uniquely identifies the Conference Recording resource to update. Use `Twilio.CURRENT` to reference the current active recording. + """ + return RecordingContext( + self._version, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/connect_app.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/connect_app.py new file mode 100644 index 00000000..689a2b18 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/connect_app.py @@ -0,0 +1,690 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ConnectAppInstance(InstanceResource): + + class Permission(object): + GET_ALL = "get-all" + POST_ALL = "post-all" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ConnectApp resource. + :ivar authorize_redirect_url: The URL we redirect the user to after we authenticate the user and obtain authorization to access the Connect App. + :ivar company_name: The company name set for the Connect App. + :ivar deauthorize_callback_method: The HTTP method we use to call `deauthorize_callback_url`. + :ivar deauthorize_callback_url: The URL we call using the `deauthorize_callback_method` to de-authorize the Connect App. + :ivar description: The description of the Connect App. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar homepage_url: The public URL where users can obtain more information about this Connect App. + :ivar permissions: The set of permissions that your ConnectApp requests. + :ivar sid: The unique string that that we created to identify the ConnectApp resource. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.authorize_redirect_url: Optional[str] = payload.get( + "authorize_redirect_url" + ) + self.company_name: Optional[str] = payload.get("company_name") + self.deauthorize_callback_method: Optional[str] = payload.get( + "deauthorize_callback_method" + ) + self.deauthorize_callback_url: Optional[str] = payload.get( + "deauthorize_callback_url" + ) + self.description: Optional[str] = payload.get("description") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.homepage_url: Optional[str] = payload.get("homepage_url") + self.permissions: Optional[List["ConnectAppInstance.Permission"]] = payload.get( + "permissions" + ) + self.sid: Optional[str] = payload.get("sid") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[ConnectAppContext] = None + + @property + def _proxy(self) -> "ConnectAppContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConnectAppContext for this ConnectAppInstance + """ + if self._context is None: + self._context = ConnectAppContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ConnectAppInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConnectAppInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ConnectAppInstance": + """ + Fetch the ConnectAppInstance + + + :returns: The fetched ConnectAppInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConnectAppInstance": + """ + Asynchronous coroutine to fetch the ConnectAppInstance + + + :returns: The fetched ConnectAppInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + authorize_redirect_url: Union[str, object] = values.unset, + company_name: Union[str, object] = values.unset, + deauthorize_callback_method: Union[str, object] = values.unset, + deauthorize_callback_url: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + homepage_url: Union[str, object] = values.unset, + permissions: Union[ + List["ConnectAppInstance.Permission"], object + ] = values.unset, + ) -> "ConnectAppInstance": + """ + Update the ConnectAppInstance + + :param authorize_redirect_url: The URL to redirect the user to after we authenticate the user and obtain authorization to access the Connect App. + :param company_name: The company name to set for the Connect App. + :param deauthorize_callback_method: The HTTP method to use when calling `deauthorize_callback_url`. + :param deauthorize_callback_url: The URL to call using the `deauthorize_callback_method` to de-authorize the Connect App. + :param description: A description of the Connect App. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param homepage_url: A public URL where users can obtain more information about this Connect App. + :param permissions: A comma-separated list of the permissions you will request from the users of this ConnectApp. Can include: `get-all` and `post-all`. + + :returns: The updated ConnectAppInstance + """ + return self._proxy.update( + authorize_redirect_url=authorize_redirect_url, + company_name=company_name, + deauthorize_callback_method=deauthorize_callback_method, + deauthorize_callback_url=deauthorize_callback_url, + description=description, + friendly_name=friendly_name, + homepage_url=homepage_url, + permissions=permissions, + ) + + async def update_async( + self, + authorize_redirect_url: Union[str, object] = values.unset, + company_name: Union[str, object] = values.unset, + deauthorize_callback_method: Union[str, object] = values.unset, + deauthorize_callback_url: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + homepage_url: Union[str, object] = values.unset, + permissions: Union[ + List["ConnectAppInstance.Permission"], object + ] = values.unset, + ) -> "ConnectAppInstance": + """ + Asynchronous coroutine to update the ConnectAppInstance + + :param authorize_redirect_url: The URL to redirect the user to after we authenticate the user and obtain authorization to access the Connect App. + :param company_name: The company name to set for the Connect App. + :param deauthorize_callback_method: The HTTP method to use when calling `deauthorize_callback_url`. + :param deauthorize_callback_url: The URL to call using the `deauthorize_callback_method` to de-authorize the Connect App. + :param description: A description of the Connect App. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param homepage_url: A public URL where users can obtain more information about this Connect App. + :param permissions: A comma-separated list of the permissions you will request from the users of this ConnectApp. Can include: `get-all` and `post-all`. + + :returns: The updated ConnectAppInstance + """ + return await self._proxy.update_async( + authorize_redirect_url=authorize_redirect_url, + company_name=company_name, + deauthorize_callback_method=deauthorize_callback_method, + deauthorize_callback_url=deauthorize_callback_url, + description=description, + friendly_name=friendly_name, + homepage_url=homepage_url, + permissions=permissions, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConnectAppContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the ConnectAppContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ConnectApp resources to update. + :param sid: The Twilio-provided string that uniquely identifies the ConnectApp resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/ConnectApps/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the ConnectAppInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConnectAppInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConnectAppInstance: + """ + Fetch the ConnectAppInstance + + + :returns: The fetched ConnectAppInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ConnectAppInstance: + """ + Asynchronous coroutine to fetch the ConnectAppInstance + + + :returns: The fetched ConnectAppInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + authorize_redirect_url: Union[str, object] = values.unset, + company_name: Union[str, object] = values.unset, + deauthorize_callback_method: Union[str, object] = values.unset, + deauthorize_callback_url: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + homepage_url: Union[str, object] = values.unset, + permissions: Union[ + List["ConnectAppInstance.Permission"], object + ] = values.unset, + ) -> ConnectAppInstance: + """ + Update the ConnectAppInstance + + :param authorize_redirect_url: The URL to redirect the user to after we authenticate the user and obtain authorization to access the Connect App. + :param company_name: The company name to set for the Connect App. + :param deauthorize_callback_method: The HTTP method to use when calling `deauthorize_callback_url`. + :param deauthorize_callback_url: The URL to call using the `deauthorize_callback_method` to de-authorize the Connect App. + :param description: A description of the Connect App. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param homepage_url: A public URL where users can obtain more information about this Connect App. + :param permissions: A comma-separated list of the permissions you will request from the users of this ConnectApp. Can include: `get-all` and `post-all`. + + :returns: The updated ConnectAppInstance + """ + + data = values.of( + { + "AuthorizeRedirectUrl": authorize_redirect_url, + "CompanyName": company_name, + "DeauthorizeCallbackMethod": deauthorize_callback_method, + "DeauthorizeCallbackUrl": deauthorize_callback_url, + "Description": description, + "FriendlyName": friendly_name, + "HomepageUrl": homepage_url, + "Permissions": serialize.map(permissions, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + authorize_redirect_url: Union[str, object] = values.unset, + company_name: Union[str, object] = values.unset, + deauthorize_callback_method: Union[str, object] = values.unset, + deauthorize_callback_url: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + homepage_url: Union[str, object] = values.unset, + permissions: Union[ + List["ConnectAppInstance.Permission"], object + ] = values.unset, + ) -> ConnectAppInstance: + """ + Asynchronous coroutine to update the ConnectAppInstance + + :param authorize_redirect_url: The URL to redirect the user to after we authenticate the user and obtain authorization to access the Connect App. + :param company_name: The company name to set for the Connect App. + :param deauthorize_callback_method: The HTTP method to use when calling `deauthorize_callback_url`. + :param deauthorize_callback_url: The URL to call using the `deauthorize_callback_method` to de-authorize the Connect App. + :param description: A description of the Connect App. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param homepage_url: A public URL where users can obtain more information about this Connect App. + :param permissions: A comma-separated list of the permissions you will request from the users of this ConnectApp. Can include: `get-all` and `post-all`. + + :returns: The updated ConnectAppInstance + """ + + data = values.of( + { + "AuthorizeRedirectUrl": authorize_redirect_url, + "CompanyName": company_name, + "DeauthorizeCallbackMethod": deauthorize_callback_method, + "DeauthorizeCallbackUrl": deauthorize_callback_url, + "Description": description, + "FriendlyName": friendly_name, + "HomepageUrl": homepage_url, + "Permissions": serialize.map(permissions, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConnectAppPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ConnectAppInstance: + """ + Build an instance of ConnectAppInstance + + :param payload: Payload response from the API + """ + return ConnectAppInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ConnectAppList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the ConnectAppList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ConnectApp resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/ConnectApps.json".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConnectAppInstance]: + """ + Streams ConnectAppInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConnectAppInstance]: + """ + Asynchronously streams ConnectAppInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConnectAppInstance]: + """ + Lists ConnectAppInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConnectAppInstance]: + """ + Asynchronously lists ConnectAppInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConnectAppPage: + """ + Retrieve a single page of ConnectAppInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConnectAppInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConnectAppPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConnectAppPage: + """ + Asynchronously retrieve a single page of ConnectAppInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConnectAppInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConnectAppPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ConnectAppPage: + """ + Retrieve a specific page of ConnectAppInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConnectAppInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConnectAppPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ConnectAppPage: + """ + Asynchronously retrieve a specific page of ConnectAppInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConnectAppInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConnectAppPage(self._version, response, self._solution) + + def get(self, sid: str) -> ConnectAppContext: + """ + Constructs a ConnectAppContext + + :param sid: The Twilio-provided string that uniquely identifies the ConnectApp resource to update. + """ + return ConnectAppContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ConnectAppContext: + """ + Constructs a ConnectAppContext + + :param sid: The Twilio-provided string that uniquely identifies the ConnectApp resource to update. + """ + return ConnectAppContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py new file mode 100644 index 00000000..c7c1eebc --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py @@ -0,0 +1,1310 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on import ( + AssignedAddOnList, +) +from twilio.rest.api.v2010.account.incoming_phone_number.local import LocalList +from twilio.rest.api.v2010.account.incoming_phone_number.mobile import MobileList +from twilio.rest.api.v2010.account.incoming_phone_number.toll_free import TollFreeList + + +class IncomingPhoneNumberInstance(InstanceResource): + + class AddressRequirement(object): + NONE = "none" + ANY = "any" + LOCAL = "local" + FOREIGN = "foreign" + + class EmergencyAddressStatus(object): + REGISTERED = "registered" + UNREGISTERED = "unregistered" + PENDING_REGISTRATION = "pending-registration" + REGISTRATION_FAILURE = "registration-failure" + PENDING_UNREGISTRATION = "pending-unregistration" + UNREGISTRATION_FAILURE = "unregistration-failure" + + class EmergencyStatus(object): + ACTIVE = "Active" + INACTIVE = "Inactive" + + class VoiceReceiveMode(object): + VOICE = "voice" + FAX = "fax" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this IncomingPhoneNumber resource. + :ivar address_sid: The SID of the Address resource associated with the phone number. + :ivar address_requirements: + :ivar api_version: The API version used to start a new TwiML session. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar identity_sid: The SID of the Identity resource that we associate with the phone number. Some regions require an Identity to meet local regulations. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar origin: The phone number's origin. `twilio` identifies Twilio-owned phone numbers and `hosted` identifies hosted phone numbers. + :ivar sid: The unique string that that we created to identify this IncomingPhoneNumber resource. + :ivar sms_application_sid: The SID of the application that handles SMS messages sent to the phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :ivar sms_fallback_method: The HTTP method we use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :ivar sms_fallback_url: The URL that we call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :ivar sms_method: The HTTP method we use to call `sms_url`. Can be: `GET` or `POST`. + :ivar sms_url: The URL we call when the phone number receives an incoming SMS message. + :ivar status_callback: The URL we call using the `status_callback_method` to send status information to your application. + :ivar status_callback_method: The HTTP method we use to call `status_callback`. Can be: `GET` or `POST`. + :ivar trunk_sid: The SID of the Trunk that handles calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar voice_receive_mode: + :ivar voice_application_sid: The SID of the application that handles calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :ivar voice_caller_id_lookup: Whether we look up the caller's caller-ID name from the CNAM database ($0.01 per look up). Can be: `true` or `false`. + :ivar voice_fallback_method: The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_url: The URL that we call when an error occurs retrieving or executing the TwiML requested by `url`. + :ivar voice_method: The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + :ivar voice_url: The URL we call when the phone number receives a call. The `voice_url` will not be used if a `voice_application_sid` or a `trunk_sid` is set. + :ivar emergency_status: + :ivar emergency_address_sid: The SID of the emergency address configuration that we use for emergency calling from this phone number. + :ivar emergency_address_status: + :ivar bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + :ivar status: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.address_sid: Optional[str] = payload.get("address_sid") + self.address_requirements: Optional[ + "IncomingPhoneNumberInstance.AddressRequirement" + ] = payload.get("address_requirements") + self.api_version: Optional[str] = payload.get("api_version") + self.beta: Optional[bool] = payload.get("beta") + self.capabilities: Optional[str] = payload.get("capabilities") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.identity_sid: Optional[str] = payload.get("identity_sid") + self.phone_number: Optional[str] = payload.get("phone_number") + self.origin: Optional[str] = payload.get("origin") + self.sid: Optional[str] = payload.get("sid") + self.sms_application_sid: Optional[str] = payload.get("sms_application_sid") + self.sms_fallback_method: Optional[str] = payload.get("sms_fallback_method") + self.sms_fallback_url: Optional[str] = payload.get("sms_fallback_url") + self.sms_method: Optional[str] = payload.get("sms_method") + self.sms_url: Optional[str] = payload.get("sms_url") + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.trunk_sid: Optional[str] = payload.get("trunk_sid") + self.uri: Optional[str] = payload.get("uri") + self.voice_receive_mode: Optional[ + "IncomingPhoneNumberInstance.VoiceReceiveMode" + ] = payload.get("voice_receive_mode") + self.voice_application_sid: Optional[str] = payload.get("voice_application_sid") + self.voice_caller_id_lookup: Optional[bool] = payload.get( + "voice_caller_id_lookup" + ) + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_url: Optional[str] = payload.get("voice_url") + self.emergency_status: Optional[ + "IncomingPhoneNumberInstance.EmergencyStatus" + ] = payload.get("emergency_status") + self.emergency_address_sid: Optional[str] = payload.get("emergency_address_sid") + self.emergency_address_status: Optional[ + "IncomingPhoneNumberInstance.EmergencyAddressStatus" + ] = payload.get("emergency_address_status") + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.status: Optional[str] = payload.get("status") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[IncomingPhoneNumberContext] = None + + @property + def _proxy(self) -> "IncomingPhoneNumberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: IncomingPhoneNumberContext for this IncomingPhoneNumberInstance + """ + if self._context is None: + self._context = IncomingPhoneNumberContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the IncomingPhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IncomingPhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "IncomingPhoneNumberInstance": + """ + Fetch the IncomingPhoneNumberInstance + + + :returns: The fetched IncomingPhoneNumberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "IncomingPhoneNumberInstance": + """ + Asynchronous coroutine to fetch the IncomingPhoneNumberInstance + + + :returns: The fetched IncomingPhoneNumberInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + account_sid: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> "IncomingPhoneNumberInstance": + """ + Update the IncomingPhoneNumberInstance + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resource to update. For more information, see [Exchanging Numbers Between Subaccounts](https://www.twilio.com/docs/iam/api/subaccounts#exchanging-numbers). + :param api_version: The API version to use for incoming calls made to the phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe this phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle phone calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from this phone number. + :param trunk_sid: The SID of the Trunk we should use to handle phone calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param identity_sid: The SID of the Identity resource that we should associate with the phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the phone number. Some regions require addresses to meet local regulations. + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The updated IncomingPhoneNumberInstance + """ + return self._proxy.update( + account_sid=account_sid, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + identity_sid=identity_sid, + address_sid=address_sid, + bundle_sid=bundle_sid, + ) + + async def update_async( + self, + account_sid: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> "IncomingPhoneNumberInstance": + """ + Asynchronous coroutine to update the IncomingPhoneNumberInstance + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resource to update. For more information, see [Exchanging Numbers Between Subaccounts](https://www.twilio.com/docs/iam/api/subaccounts#exchanging-numbers). + :param api_version: The API version to use for incoming calls made to the phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe this phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle phone calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from this phone number. + :param trunk_sid: The SID of the Trunk we should use to handle phone calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param identity_sid: The SID of the Identity resource that we should associate with the phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the phone number. Some regions require addresses to meet local regulations. + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The updated IncomingPhoneNumberInstance + """ + return await self._proxy.update_async( + account_sid=account_sid, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + identity_sid=identity_sid, + address_sid=address_sid, + bundle_sid=bundle_sid, + ) + + @property + def assigned_add_ons(self) -> AssignedAddOnList: + """ + Access the assigned_add_ons + """ + return self._proxy.assigned_add_ons + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class IncomingPhoneNumberContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the IncomingPhoneNumberContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resource to update. For more information, see [Exchanging Numbers Between Subaccounts](https://www.twilio.com/docs/iam/api/subaccounts#exchanging-numbers). + :param sid: The Twilio-provided string that uniquely identifies the IncomingPhoneNumber resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/{sid}.json".format( + **self._solution + ) + + self._assigned_add_ons: Optional[AssignedAddOnList] = None + + def delete(self) -> bool: + """ + Deletes the IncomingPhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IncomingPhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> IncomingPhoneNumberInstance: + """ + Fetch the IncomingPhoneNumberInstance + + + :returns: The fetched IncomingPhoneNumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return IncomingPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> IncomingPhoneNumberInstance: + """ + Asynchronous coroutine to fetch the IncomingPhoneNumberInstance + + + :returns: The fetched IncomingPhoneNumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return IncomingPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + account_sid: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> IncomingPhoneNumberInstance: + """ + Update the IncomingPhoneNumberInstance + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resource to update. For more information, see [Exchanging Numbers Between Subaccounts](https://www.twilio.com/docs/iam/api/subaccounts#exchanging-numbers). + :param api_version: The API version to use for incoming calls made to the phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe this phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle phone calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from this phone number. + :param trunk_sid: The SID of the Trunk we should use to handle phone calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param identity_sid: The SID of the Identity resource that we should associate with the phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the phone number. Some regions require addresses to meet local regulations. + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The updated IncomingPhoneNumberInstance + """ + + data = values.of( + { + "AccountSid": account_sid, + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "BundleSid": bundle_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IncomingPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + account_sid: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> IncomingPhoneNumberInstance: + """ + Asynchronous coroutine to update the IncomingPhoneNumberInstance + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resource to update. For more information, see [Exchanging Numbers Between Subaccounts](https://www.twilio.com/docs/iam/api/subaccounts#exchanging-numbers). + :param api_version: The API version to use for incoming calls made to the phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe this phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle phone calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from this phone number. + :param trunk_sid: The SID of the Trunk we should use to handle phone calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param identity_sid: The SID of the Identity resource that we should associate with the phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the phone number. Some regions require addresses to meet local regulations. + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The updated IncomingPhoneNumberInstance + """ + + data = values.of( + { + "AccountSid": account_sid, + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "BundleSid": bundle_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IncomingPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + @property + def assigned_add_ons(self) -> AssignedAddOnList: + """ + Access the assigned_add_ons + """ + if self._assigned_add_ons is None: + self._assigned_add_ons = AssignedAddOnList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._assigned_add_ons + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class IncomingPhoneNumberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> IncomingPhoneNumberInstance: + """ + Build an instance of IncomingPhoneNumberInstance + + :param payload: Payload response from the API + """ + return IncomingPhoneNumberInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class IncomingPhoneNumberList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the IncomingPhoneNumberList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers.json".format( + **self._solution + ) + + self._local: Optional[LocalList] = None + self._mobile: Optional[MobileList] = None + self._toll_free: Optional[TollFreeList] = None + + def create( + self, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + area_code: Union[str, object] = values.unset, + ) -> IncomingPhoneNumberInstance: + """ + Create the IncomingPhoneNumberInstance + + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the new phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param area_code: The desired area code for your new incoming phone number. Can be any three-digit, US or Canada area code. We will provision an available phone number within this area code for you. **You must provide an `area_code` or a `phone_number`.** (US and Canada only). + + :returns: The created IncomingPhoneNumberInstance + """ + + data = values.of( + { + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_sid, + "PhoneNumber": phone_number, + "AreaCode": area_code, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IncomingPhoneNumberInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + area_code: Union[str, object] = values.unset, + ) -> IncomingPhoneNumberInstance: + """ + Asynchronously create the IncomingPhoneNumberInstance + + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the new phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param area_code: The desired area code for your new incoming phone number. Can be any three-digit, US or Canada area code. We will provision an available phone number within this area code for you. **You must provide an `area_code` or a `phone_number`.** (US and Canada only). + + :returns: The created IncomingPhoneNumberInstance + """ + + data = values.of( + { + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_sid, + "PhoneNumber": phone_number, + "AreaCode": area_code, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IncomingPhoneNumberInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[IncomingPhoneNumberInstance]: + """ + Streams IncomingPhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the IncomingPhoneNumber resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IncomingPhoneNumberInstance]: + """ + Asynchronously streams IncomingPhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the IncomingPhoneNumber resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IncomingPhoneNumberInstance]: + """ + Lists IncomingPhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the IncomingPhoneNumber resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IncomingPhoneNumberInstance]: + """ + Asynchronously lists IncomingPhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the IncomingPhoneNumber resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IncomingPhoneNumberPage: + """ + Retrieve a single page of IncomingPhoneNumberInstance records from the API. + Request is executed immediately + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the IncomingPhoneNumber resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IncomingPhoneNumberInstance + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IncomingPhoneNumberPage(self._version, response, self._solution) + + async def page_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IncomingPhoneNumberPage: + """ + Asynchronously retrieve a single page of IncomingPhoneNumberInstance records from the API. + Request is executed immediately + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the IncomingPhoneNumber resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IncomingPhoneNumberInstance + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IncomingPhoneNumberPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> IncomingPhoneNumberPage: + """ + Retrieve a specific page of IncomingPhoneNumberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IncomingPhoneNumberInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return IncomingPhoneNumberPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> IncomingPhoneNumberPage: + """ + Asynchronously retrieve a specific page of IncomingPhoneNumberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IncomingPhoneNumberInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return IncomingPhoneNumberPage(self._version, response, self._solution) + + @property + def local(self) -> LocalList: + """ + Access the local + """ + if self._local is None: + self._local = LocalList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._local + + @property + def mobile(self) -> MobileList: + """ + Access the mobile + """ + if self._mobile is None: + self._mobile = MobileList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._mobile + + @property + def toll_free(self) -> TollFreeList: + """ + Access the toll_free + """ + if self._toll_free is None: + self._toll_free = TollFreeList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._toll_free + + def get(self, sid: str) -> IncomingPhoneNumberContext: + """ + Constructs a IncomingPhoneNumberContext + + :param sid: The Twilio-provided string that uniquely identifies the IncomingPhoneNumber resource to update. + """ + return IncomingPhoneNumberContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> IncomingPhoneNumberContext: + """ + Constructs a IncomingPhoneNumberContext + + :param sid: The Twilio-provided string that uniquely identifies the IncomingPhoneNumber resource to update. + """ + return IncomingPhoneNumberContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..8045f73b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/__pycache__/local.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/__pycache__/local.cpython-312.pyc new file mode 100644 index 00000000..381f6d73 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/__pycache__/local.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/__pycache__/mobile.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/__pycache__/mobile.cpython-312.pyc new file mode 100644 index 00000000..bfdfec5c Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/__pycache__/mobile.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/__pycache__/toll_free.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/__pycache__/toll_free.cpython-312.pyc new file mode 100644 index 00000000..fee45443 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/__pycache__/toll_free.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/__init__.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/__init__.py new file mode 100644 index 00000000..52fe2a52 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/__init__.py @@ -0,0 +1,602 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension import ( + AssignedAddOnExtensionList, +) + + +class AssignedAddOnInstance(InstanceResource): + """ + :ivar sid: The unique string that that we created to identify the resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resource. + :ivar resource_sid: The SID of the Phone Number to which the Add-on is assigned. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar description: A short description of the functionality that the Add-on provides. + :ivar configuration: A JSON string that represents the current configuration of this Add-on installation. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar subresource_uris: A list of related resources identified by their relative URIs. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + resource_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.resource_sid: Optional[str] = payload.get("resource_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + self.unique_name: Optional[str] = payload.get("unique_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.uri: Optional[str] = payload.get("uri") + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + + self._solution = { + "account_sid": account_sid, + "resource_sid": resource_sid, + "sid": sid or self.sid, + } + self._context: Optional[AssignedAddOnContext] = None + + @property + def _proxy(self) -> "AssignedAddOnContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AssignedAddOnContext for this AssignedAddOnInstance + """ + if self._context is None: + self._context = AssignedAddOnContext( + self._version, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AssignedAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AssignedAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AssignedAddOnInstance": + """ + Fetch the AssignedAddOnInstance + + + :returns: The fetched AssignedAddOnInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AssignedAddOnInstance": + """ + Asynchronous coroutine to fetch the AssignedAddOnInstance + + + :returns: The fetched AssignedAddOnInstance + """ + return await self._proxy.fetch_async() + + @property + def extensions(self) -> AssignedAddOnExtensionList: + """ + Access the extensions + """ + return self._proxy.extensions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AssignedAddOnContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, resource_sid: str, sid: str): + """ + Initialize the AssignedAddOnContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resource to fetch. + :param resource_sid: The SID of the Phone Number to which the Add-on is assigned. + :param sid: The Twilio-provided string that uniquely identifies the resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "resource_sid": resource_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/{resource_sid}/AssignedAddOns/{sid}.json".format( + **self._solution + ) + + self._extensions: Optional[AssignedAddOnExtensionList] = None + + def delete(self) -> bool: + """ + Deletes the AssignedAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AssignedAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AssignedAddOnInstance: + """ + Fetch the AssignedAddOnInstance + + + :returns: The fetched AssignedAddOnInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AssignedAddOnInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AssignedAddOnInstance: + """ + Asynchronous coroutine to fetch the AssignedAddOnInstance + + + :returns: The fetched AssignedAddOnInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AssignedAddOnInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + sid=self._solution["sid"], + ) + + @property + def extensions(self) -> AssignedAddOnExtensionList: + """ + Access the extensions + """ + if self._extensions is None: + self._extensions = AssignedAddOnExtensionList( + self._version, + self._solution["account_sid"], + self._solution["resource_sid"], + self._solution["sid"], + ) + return self._extensions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AssignedAddOnPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AssignedAddOnInstance: + """ + Build an instance of AssignedAddOnInstance + + :param payload: Payload response from the API + """ + return AssignedAddOnInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AssignedAddOnList(ListResource): + + def __init__(self, version: Version, account_sid: str, resource_sid: str): + """ + Initialize the AssignedAddOnList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resources to read. + :param resource_sid: The SID of the Phone Number to which the Add-on is assigned. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "resource_sid": resource_sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/{resource_sid}/AssignedAddOns.json".format( + **self._solution + ) + + def create(self, installed_add_on_sid: str) -> AssignedAddOnInstance: + """ + Create the AssignedAddOnInstance + + :param installed_add_on_sid: The SID that identifies the Add-on installation. + + :returns: The created AssignedAddOnInstance + """ + + data = values.of( + { + "InstalledAddOnSid": installed_add_on_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AssignedAddOnInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + ) + + async def create_async(self, installed_add_on_sid: str) -> AssignedAddOnInstance: + """ + Asynchronously create the AssignedAddOnInstance + + :param installed_add_on_sid: The SID that identifies the Add-on installation. + + :returns: The created AssignedAddOnInstance + """ + + data = values.of( + { + "InstalledAddOnSid": installed_add_on_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AssignedAddOnInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AssignedAddOnInstance]: + """ + Streams AssignedAddOnInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AssignedAddOnInstance]: + """ + Asynchronously streams AssignedAddOnInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssignedAddOnInstance]: + """ + Lists AssignedAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssignedAddOnInstance]: + """ + Asynchronously lists AssignedAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssignedAddOnPage: + """ + Retrieve a single page of AssignedAddOnInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssignedAddOnInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssignedAddOnPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssignedAddOnPage: + """ + Asynchronously retrieve a single page of AssignedAddOnInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssignedAddOnInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssignedAddOnPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AssignedAddOnPage: + """ + Retrieve a specific page of AssignedAddOnInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssignedAddOnInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AssignedAddOnPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AssignedAddOnPage: + """ + Asynchronously retrieve a specific page of AssignedAddOnInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssignedAddOnInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AssignedAddOnPage(self._version, response, self._solution) + + def get(self, sid: str) -> AssignedAddOnContext: + """ + Constructs a AssignedAddOnContext + + :param sid: The Twilio-provided string that uniquely identifies the resource to fetch. + """ + return AssignedAddOnContext( + self._version, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> AssignedAddOnContext: + """ + Constructs a AssignedAddOnContext + + :param sid: The Twilio-provided string that uniquely identifies the resource to fetch. + """ + return AssignedAddOnContext( + self._version, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..1bb24310 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/__pycache__/assigned_add_on_extension.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/__pycache__/assigned_add_on_extension.cpython-312.pyc new file mode 100644 index 00000000..514e6d5f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/__pycache__/assigned_add_on_extension.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/assigned_add_on_extension.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/assigned_add_on_extension.py new file mode 100644 index 00000000..1a7d9cdc --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/assigned_add_on_extension.py @@ -0,0 +1,484 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AssignedAddOnExtensionInstance(InstanceResource): + """ + :ivar sid: The unique string that that we created to identify the resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resource. + :ivar resource_sid: The SID of the Phone Number to which the Add-on is assigned. + :ivar assigned_add_on_sid: The SID that uniquely identifies the assigned Add-on installation. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar product_name: A string that you assigned to describe the Product this Extension is used within. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar enabled: Whether the Extension will be invoked. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + resource_sid: str, + assigned_add_on_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.resource_sid: Optional[str] = payload.get("resource_sid") + self.assigned_add_on_sid: Optional[str] = payload.get("assigned_add_on_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.product_name: Optional[str] = payload.get("product_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.uri: Optional[str] = payload.get("uri") + self.enabled: Optional[bool] = payload.get("enabled") + + self._solution = { + "account_sid": account_sid, + "resource_sid": resource_sid, + "assigned_add_on_sid": assigned_add_on_sid, + "sid": sid or self.sid, + } + self._context: Optional[AssignedAddOnExtensionContext] = None + + @property + def _proxy(self) -> "AssignedAddOnExtensionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AssignedAddOnExtensionContext for this AssignedAddOnExtensionInstance + """ + if self._context is None: + self._context = AssignedAddOnExtensionContext( + self._version, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + assigned_add_on_sid=self._solution["assigned_add_on_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "AssignedAddOnExtensionInstance": + """ + Fetch the AssignedAddOnExtensionInstance + + + :returns: The fetched AssignedAddOnExtensionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AssignedAddOnExtensionInstance": + """ + Asynchronous coroutine to fetch the AssignedAddOnExtensionInstance + + + :returns: The fetched AssignedAddOnExtensionInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AssignedAddOnExtensionContext(InstanceContext): + + def __init__( + self, + version: Version, + account_sid: str, + resource_sid: str, + assigned_add_on_sid: str, + sid: str, + ): + """ + Initialize the AssignedAddOnExtensionContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resource to fetch. + :param resource_sid: The SID of the Phone Number to which the Add-on is assigned. + :param assigned_add_on_sid: The SID that uniquely identifies the assigned Add-on installation. + :param sid: The Twilio-provided string that uniquely identifies the resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "resource_sid": resource_sid, + "assigned_add_on_sid": assigned_add_on_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/{resource_sid}/AssignedAddOns/{assigned_add_on_sid}/Extensions/{sid}.json".format( + **self._solution + ) + + def fetch(self) -> AssignedAddOnExtensionInstance: + """ + Fetch the AssignedAddOnExtensionInstance + + + :returns: The fetched AssignedAddOnExtensionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AssignedAddOnExtensionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + assigned_add_on_sid=self._solution["assigned_add_on_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AssignedAddOnExtensionInstance: + """ + Asynchronous coroutine to fetch the AssignedAddOnExtensionInstance + + + :returns: The fetched AssignedAddOnExtensionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AssignedAddOnExtensionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + assigned_add_on_sid=self._solution["assigned_add_on_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AssignedAddOnExtensionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AssignedAddOnExtensionInstance: + """ + Build an instance of AssignedAddOnExtensionInstance + + :param payload: Payload response from the API + """ + return AssignedAddOnExtensionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + assigned_add_on_sid=self._solution["assigned_add_on_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AssignedAddOnExtensionList(ListResource): + + def __init__( + self, + version: Version, + account_sid: str, + resource_sid: str, + assigned_add_on_sid: str, + ): + """ + Initialize the AssignedAddOnExtensionList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resources to read. + :param resource_sid: The SID of the Phone Number to which the Add-on is assigned. + :param assigned_add_on_sid: The SID that uniquely identifies the assigned Add-on installation. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "resource_sid": resource_sid, + "assigned_add_on_sid": assigned_add_on_sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/{resource_sid}/AssignedAddOns/{assigned_add_on_sid}/Extensions.json".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AssignedAddOnExtensionInstance]: + """ + Streams AssignedAddOnExtensionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AssignedAddOnExtensionInstance]: + """ + Asynchronously streams AssignedAddOnExtensionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssignedAddOnExtensionInstance]: + """ + Lists AssignedAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssignedAddOnExtensionInstance]: + """ + Asynchronously lists AssignedAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssignedAddOnExtensionPage: + """ + Retrieve a single page of AssignedAddOnExtensionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssignedAddOnExtensionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssignedAddOnExtensionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssignedAddOnExtensionPage: + """ + Asynchronously retrieve a single page of AssignedAddOnExtensionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssignedAddOnExtensionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssignedAddOnExtensionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AssignedAddOnExtensionPage: + """ + Retrieve a specific page of AssignedAddOnExtensionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssignedAddOnExtensionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AssignedAddOnExtensionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AssignedAddOnExtensionPage: + """ + Asynchronously retrieve a specific page of AssignedAddOnExtensionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssignedAddOnExtensionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AssignedAddOnExtensionPage(self._version, response, self._solution) + + def get(self, sid: str) -> AssignedAddOnExtensionContext: + """ + Constructs a AssignedAddOnExtensionContext + + :param sid: The Twilio-provided string that uniquely identifies the resource to fetch. + """ + return AssignedAddOnExtensionContext( + self._version, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + assigned_add_on_sid=self._solution["assigned_add_on_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> AssignedAddOnExtensionContext: + """ + Constructs a AssignedAddOnExtensionContext + + :param sid: The Twilio-provided string that uniquely identifies the resource to fetch. + """ + return AssignedAddOnExtensionContext( + self._version, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + assigned_add_on_sid=self._solution["assigned_add_on_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/local.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/local.py new file mode 100644 index 00000000..af67fb0a --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/local.py @@ -0,0 +1,672 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class LocalInstance(InstanceResource): + + class AddressRequirement(object): + NONE = "none" + ANY = "any" + LOCAL = "local" + FOREIGN = "foreign" + + class EmergencyAddressStatus(object): + REGISTERED = "registered" + UNREGISTERED = "unregistered" + PENDING_REGISTRATION = "pending-registration" + REGISTRATION_FAILURE = "registration-failure" + PENDING_UNREGISTRATION = "pending-unregistration" + UNREGISTRATION_FAILURE = "unregistration-failure" + + class EmergencyStatus(object): + ACTIVE = "Active" + INACTIVE = "Inactive" + + class VoiceReceiveMode(object): + VOICE = "voice" + FAX = "fax" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resource. + :ivar address_sid: The SID of the Address resource associated with the phone number. + :ivar address_requirements: + :ivar api_version: The API version used to start a new TwiML session. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar identity_sid: The SID of the Identity resource that we associate with the phone number. Some regions require an Identity to meet local regulations. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar origin: The phone number's origin. `twilio` identifies Twilio-owned phone numbers and `hosted` identifies hosted phone numbers. + :ivar sid: The unique string that that we created to identify the resource. + :ivar sms_application_sid: The SID of the application that handles SMS messages sent to the phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :ivar sms_fallback_method: The HTTP method we use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :ivar sms_fallback_url: The URL that we call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :ivar sms_method: The HTTP method we use to call `sms_url`. Can be: `GET` or `POST`. + :ivar sms_url: The URL we call when the phone number receives an incoming SMS message. + :ivar status_callback: The URL we call using the `status_callback_method` to send status information to your application. + :ivar status_callback_method: The HTTP method we use to call `status_callback`. Can be: `GET` or `POST`. + :ivar trunk_sid: The SID of the Trunk that handles calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar voice_receive_mode: + :ivar voice_application_sid: The SID of the application that handles calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :ivar voice_caller_id_lookup: Whether we look up the caller's caller-ID name from the CNAM database ($0.01 per look up). Can be: `true` or `false`. + :ivar voice_fallback_method: The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_url: The URL that we call when an error occurs retrieving or executing the TwiML requested by `url`. + :ivar voice_method: The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + :ivar voice_url: The URL we call when this phone number receives a call. The `voice_url` will not be used if a `voice_application_sid` or a `trunk_sid` is set. + :ivar emergency_status: + :ivar emergency_address_sid: The SID of the emergency address configuration that we use for emergency calling from this phone number. + :ivar emergency_address_status: + :ivar bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + :ivar status: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.address_sid: Optional[str] = payload.get("address_sid") + self.address_requirements: Optional["LocalInstance.AddressRequirement"] = ( + payload.get("address_requirements") + ) + self.api_version: Optional[str] = payload.get("api_version") + self.beta: Optional[bool] = payload.get("beta") + self.capabilities: Optional[str] = payload.get("capabilities") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.identity_sid: Optional[str] = payload.get("identity_sid") + self.phone_number: Optional[str] = payload.get("phone_number") + self.origin: Optional[str] = payload.get("origin") + self.sid: Optional[str] = payload.get("sid") + self.sms_application_sid: Optional[str] = payload.get("sms_application_sid") + self.sms_fallback_method: Optional[str] = payload.get("sms_fallback_method") + self.sms_fallback_url: Optional[str] = payload.get("sms_fallback_url") + self.sms_method: Optional[str] = payload.get("sms_method") + self.sms_url: Optional[str] = payload.get("sms_url") + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.trunk_sid: Optional[str] = payload.get("trunk_sid") + self.uri: Optional[str] = payload.get("uri") + self.voice_receive_mode: Optional["LocalInstance.VoiceReceiveMode"] = ( + payload.get("voice_receive_mode") + ) + self.voice_application_sid: Optional[str] = payload.get("voice_application_sid") + self.voice_caller_id_lookup: Optional[bool] = payload.get( + "voice_caller_id_lookup" + ) + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_url: Optional[str] = payload.get("voice_url") + self.emergency_status: Optional["LocalInstance.EmergencyStatus"] = payload.get( + "emergency_status" + ) + self.emergency_address_sid: Optional[str] = payload.get("emergency_address_sid") + self.emergency_address_status: Optional[ + "LocalInstance.EmergencyAddressStatus" + ] = payload.get("emergency_address_status") + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.status: Optional[str] = payload.get("status") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class LocalPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> LocalInstance: + """ + Build an instance of LocalInstance + + :param payload: Payload response from the API + """ + return LocalInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class LocalList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the LocalList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/Local.json".format( + **self._solution + ) + + def create( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union["LocalInstance.EmergencyStatus", object] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "LocalInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> LocalInstance: + """ + Create the LocalInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The created LocalInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return LocalInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union["LocalInstance.EmergencyStatus", object] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "LocalInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> LocalInstance: + """ + Asynchronously create the LocalInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The created LocalInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return LocalInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[LocalInstance]: + """ + Streams LocalInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[LocalInstance]: + """ + Asynchronously streams LocalInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[LocalInstance]: + """ + Lists LocalInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[LocalInstance]: + """ + Asynchronously lists LocalInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> LocalPage: + """ + Retrieve a single page of LocalInstance records from the API. + Request is executed immediately + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of LocalInstance + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LocalPage(self._version, response, self._solution) + + async def page_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> LocalPage: + """ + Asynchronously retrieve a single page of LocalInstance records from the API. + Request is executed immediately + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of LocalInstance + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LocalPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> LocalPage: + """ + Retrieve a specific page of LocalInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of LocalInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return LocalPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> LocalPage: + """ + Asynchronously retrieve a specific page of LocalInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of LocalInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return LocalPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/mobile.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/mobile.py new file mode 100644 index 00000000..27fc8a0e --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/mobile.py @@ -0,0 +1,676 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MobileInstance(InstanceResource): + + class AddressRequirement(object): + NONE = "none" + ANY = "any" + LOCAL = "local" + FOREIGN = "foreign" + + class EmergencyAddressStatus(object): + REGISTERED = "registered" + UNREGISTERED = "unregistered" + PENDING_REGISTRATION = "pending-registration" + REGISTRATION_FAILURE = "registration-failure" + PENDING_UNREGISTRATION = "pending-unregistration" + UNREGISTRATION_FAILURE = "unregistration-failure" + + class EmergencyStatus(object): + ACTIVE = "Active" + INACTIVE = "Inactive" + + class VoiceReceiveMode(object): + VOICE = "voice" + FAX = "fax" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resource. + :ivar address_sid: The SID of the Address resource associated with the phone number. + :ivar address_requirements: + :ivar api_version: The API version used to start a new TwiML session. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar identity_sid: The SID of the Identity resource that we associate with the phone number. Some regions require an Identity to meet local regulations. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar origin: The phone number's origin. `twilio` identifies Twilio-owned phone numbers and `hosted` identifies hosted phone numbers. + :ivar sid: The unique string that that we created to identify the resource. + :ivar sms_application_sid: The SID of the application that handles SMS messages sent to the phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :ivar sms_fallback_method: The HTTP method we use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :ivar sms_fallback_url: The URL that we call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :ivar sms_method: The HTTP method we use to call `sms_url`. Can be: `GET` or `POST`. + :ivar sms_url: The URL we call when the phone number receives an incoming SMS message. + :ivar status_callback: The URL we call using the `status_callback_method` to send status information to your application. + :ivar status_callback_method: The HTTP method we use to call `status_callback`. Can be: `GET` or `POST`. + :ivar trunk_sid: The SID of the Trunk that handles calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar voice_receive_mode: + :ivar voice_application_sid: The SID of the application that handles calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :ivar voice_caller_id_lookup: Whether we look up the caller's caller-ID name from the CNAM database ($0.01 per look up). Can be: `true` or `false`. + :ivar voice_fallback_method: The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_url: The URL that we call when an error occurs retrieving or executing the TwiML requested by `url`. + :ivar voice_method: The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + :ivar voice_url: The URL we call when the phone number receives a call. The `voice_url` will not be used if a `voice_application_sid` or a `trunk_sid` is set. + :ivar emergency_status: + :ivar emergency_address_sid: The SID of the emergency address configuration that we use for emergency calling from this phone number. + :ivar emergency_address_status: + :ivar bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + :ivar status: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.address_sid: Optional[str] = payload.get("address_sid") + self.address_requirements: Optional["MobileInstance.AddressRequirement"] = ( + payload.get("address_requirements") + ) + self.api_version: Optional[str] = payload.get("api_version") + self.beta: Optional[bool] = payload.get("beta") + self.capabilities: Optional[str] = payload.get("capabilities") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.identity_sid: Optional[str] = payload.get("identity_sid") + self.phone_number: Optional[str] = payload.get("phone_number") + self.origin: Optional[str] = payload.get("origin") + self.sid: Optional[str] = payload.get("sid") + self.sms_application_sid: Optional[str] = payload.get("sms_application_sid") + self.sms_fallback_method: Optional[str] = payload.get("sms_fallback_method") + self.sms_fallback_url: Optional[str] = payload.get("sms_fallback_url") + self.sms_method: Optional[str] = payload.get("sms_method") + self.sms_url: Optional[str] = payload.get("sms_url") + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.trunk_sid: Optional[str] = payload.get("trunk_sid") + self.uri: Optional[str] = payload.get("uri") + self.voice_receive_mode: Optional["MobileInstance.VoiceReceiveMode"] = ( + payload.get("voice_receive_mode") + ) + self.voice_application_sid: Optional[str] = payload.get("voice_application_sid") + self.voice_caller_id_lookup: Optional[bool] = payload.get( + "voice_caller_id_lookup" + ) + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_url: Optional[str] = payload.get("voice_url") + self.emergency_status: Optional["MobileInstance.EmergencyStatus"] = payload.get( + "emergency_status" + ) + self.emergency_address_sid: Optional[str] = payload.get("emergency_address_sid") + self.emergency_address_status: Optional[ + "MobileInstance.EmergencyAddressStatus" + ] = payload.get("emergency_address_status") + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.status: Optional[str] = payload.get("status") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MobilePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MobileInstance: + """ + Build an instance of MobileInstance + + :param payload: Payload response from the API + """ + return MobileInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MobileList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the MobileList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/Mobile.json".format( + **self._solution + ) + + def create( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "MobileInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "MobileInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> MobileInstance: + """ + Create the MobileInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, the is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The created MobileInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MobileInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "MobileInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "MobileInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> MobileInstance: + """ + Asynchronously create the MobileInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, the is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The created MobileInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MobileInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MobileInstance]: + """ + Streams MobileInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MobileInstance]: + """ + Asynchronously streams MobileInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MobileInstance]: + """ + Lists MobileInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MobileInstance]: + """ + Asynchronously lists MobileInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MobilePage: + """ + Retrieve a single page of MobileInstance records from the API. + Request is executed immediately + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MobileInstance + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MobilePage(self._version, response, self._solution) + + async def page_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MobilePage: + """ + Asynchronously retrieve a single page of MobileInstance records from the API. + Request is executed immediately + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MobileInstance + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MobilePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MobilePage: + """ + Retrieve a specific page of MobileInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MobileInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MobilePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MobilePage: + """ + Asynchronously retrieve a specific page of MobileInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MobileInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MobilePage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/toll_free.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/toll_free.py new file mode 100644 index 00000000..86290ff9 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/toll_free.py @@ -0,0 +1,676 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TollFreeInstance(InstanceResource): + + class AddressRequirement(object): + NONE = "none" + ANY = "any" + LOCAL = "local" + FOREIGN = "foreign" + + class EmergencyAddressStatus(object): + REGISTERED = "registered" + UNREGISTERED = "unregistered" + PENDING_REGISTRATION = "pending-registration" + REGISTRATION_FAILURE = "registration-failure" + PENDING_UNREGISTRATION = "pending-unregistration" + UNREGISTRATION_FAILURE = "unregistration-failure" + + class EmergencyStatus(object): + ACTIVE = "Active" + INACTIVE = "Inactive" + + class VoiceReceiveMode(object): + VOICE = "voice" + FAX = "fax" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resource. + :ivar address_sid: The SID of the Address resource associated with the phone number. + :ivar address_requirements: + :ivar api_version: The API version used to start a new TwiML session. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar identity_sid: The SID of the Identity resource that we associate with the phone number. Some regions require an Identity to meet local regulations. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar origin: The phone number's origin. `twilio` identifies Twilio-owned phone numbers and `hosted` identifies hosted phone numbers. + :ivar sid: The unique string that that we created to identify the resource. + :ivar sms_application_sid: The SID of the application that handles SMS messages sent to the phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :ivar sms_fallback_method: The HTTP method we use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :ivar sms_fallback_url: The URL that we call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :ivar sms_method: The HTTP method we use to call `sms_url`. Can be: `GET` or `POST`. + :ivar sms_url: The URL we call when the phone number receives an incoming SMS message. + :ivar status_callback: The URL we call using the `status_callback_method` to send status information to your application. + :ivar status_callback_method: The HTTP method we use to call `status_callback`. Can be: `GET` or `POST`. + :ivar trunk_sid: The SID of the Trunk that handles calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar voice_receive_mode: + :ivar voice_application_sid: The SID of the application that handles calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :ivar voice_caller_id_lookup: Whether we look up the caller's caller-ID name from the CNAM database ($0.01 per look up). Can be: `true` or `false`. + :ivar voice_fallback_method: The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_url: The URL that we call when an error occurs retrieving or executing the TwiML requested by `url`. + :ivar voice_method: The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + :ivar voice_url: The URL we call when the phone number receives a call. The `voice_url` will not be used if a `voice_application_sid` or a `trunk_sid` is set. + :ivar emergency_status: + :ivar emergency_address_sid: The SID of the emergency address configuration that we use for emergency calling from this phone number. + :ivar emergency_address_status: + :ivar bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + :ivar status: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.address_sid: Optional[str] = payload.get("address_sid") + self.address_requirements: Optional["TollFreeInstance.AddressRequirement"] = ( + payload.get("address_requirements") + ) + self.api_version: Optional[str] = payload.get("api_version") + self.beta: Optional[bool] = payload.get("beta") + self.capabilities: Optional[str] = payload.get("capabilities") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.identity_sid: Optional[str] = payload.get("identity_sid") + self.phone_number: Optional[str] = payload.get("phone_number") + self.origin: Optional[str] = payload.get("origin") + self.sid: Optional[str] = payload.get("sid") + self.sms_application_sid: Optional[str] = payload.get("sms_application_sid") + self.sms_fallback_method: Optional[str] = payload.get("sms_fallback_method") + self.sms_fallback_url: Optional[str] = payload.get("sms_fallback_url") + self.sms_method: Optional[str] = payload.get("sms_method") + self.sms_url: Optional[str] = payload.get("sms_url") + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.trunk_sid: Optional[str] = payload.get("trunk_sid") + self.uri: Optional[str] = payload.get("uri") + self.voice_receive_mode: Optional["TollFreeInstance.VoiceReceiveMode"] = ( + payload.get("voice_receive_mode") + ) + self.voice_application_sid: Optional[str] = payload.get("voice_application_sid") + self.voice_caller_id_lookup: Optional[bool] = payload.get( + "voice_caller_id_lookup" + ) + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_url: Optional[str] = payload.get("voice_url") + self.emergency_status: Optional["TollFreeInstance.EmergencyStatus"] = ( + payload.get("emergency_status") + ) + self.emergency_address_sid: Optional[str] = payload.get("emergency_address_sid") + self.emergency_address_status: Optional[ + "TollFreeInstance.EmergencyAddressStatus" + ] = payload.get("emergency_address_status") + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.status: Optional[str] = payload.get("status") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TollFreePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TollFreeInstance: + """ + Build an instance of TollFreeInstance + + :param payload: Payload response from the API + """ + return TollFreeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TollFreeList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the TollFreeList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/TollFree.json".format( + **self._solution + ) + + def create( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "TollFreeInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "TollFreeInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> TollFreeInstance: + """ + Create the TollFreeInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an Identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The created TollFreeInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TollFreeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "TollFreeInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "TollFreeInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> TollFreeInstance: + """ + Asynchronously create the TollFreeInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an Identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The created TollFreeInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TollFreeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TollFreeInstance]: + """ + Streams TollFreeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TollFreeInstance]: + """ + Asynchronously streams TollFreeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TollFreeInstance]: + """ + Lists TollFreeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TollFreeInstance]: + """ + Asynchronously lists TollFreeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TollFreePage: + """ + Retrieve a single page of TollFreeInstance records from the API. + Request is executed immediately + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TollFreeInstance + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TollFreePage(self._version, response, self._solution) + + async def page_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TollFreePage: + """ + Asynchronously retrieve a single page of TollFreeInstance records from the API. + Request is executed immediately + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TollFreeInstance + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TollFreePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> TollFreePage: + """ + Retrieve a specific page of TollFreeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TollFreeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TollFreePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> TollFreePage: + """ + Asynchronously retrieve a specific page of TollFreeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TollFreeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TollFreePage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/key.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/key.py new file mode 100644 index 00000000..8b18dbd4 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/key.py @@ -0,0 +1,566 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class KeyInstance(InstanceResource): + """ + :ivar sid: The unique string that that we created to identify the Key resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[KeyContext] = None + + @property + def _proxy(self) -> "KeyContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: KeyContext for this KeyInstance + """ + if self._context is None: + self._context = KeyContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the KeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the KeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "KeyInstance": + """ + Fetch the KeyInstance + + + :returns: The fetched KeyInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "KeyInstance": + """ + Asynchronous coroutine to fetch the KeyInstance + + + :returns: The fetched KeyInstance + """ + return await self._proxy.fetch_async() + + def update(self, friendly_name: Union[str, object] = values.unset) -> "KeyInstance": + """ + Update the KeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated KeyInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "KeyInstance": + """ + Asynchronous coroutine to update the KeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated KeyInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class KeyContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the KeyContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Key resources to update. + :param sid: The Twilio-provided string that uniquely identifies the Key resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Keys/{sid}.json".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the KeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the KeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> KeyInstance: + """ + Fetch the KeyInstance + + + :returns: The fetched KeyInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return KeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> KeyInstance: + """ + Asynchronous coroutine to fetch the KeyInstance + + + :returns: The fetched KeyInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return KeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update(self, friendly_name: Union[str, object] = values.unset) -> KeyInstance: + """ + Update the KeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated KeyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return KeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> KeyInstance: + """ + Asynchronous coroutine to update the KeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated KeyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return KeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class KeyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> KeyInstance: + """ + Build an instance of KeyInstance + + :param payload: Payload response from the API + """ + return KeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class KeyList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the KeyList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Key resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Keys.json".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[KeyInstance]: + """ + Streams KeyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[KeyInstance]: + """ + Asynchronously streams KeyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[KeyInstance]: + """ + Lists KeyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[KeyInstance]: + """ + Asynchronously lists KeyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> KeyPage: + """ + Retrieve a single page of KeyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of KeyInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return KeyPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> KeyPage: + """ + Asynchronously retrieve a single page of KeyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of KeyInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return KeyPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> KeyPage: + """ + Retrieve a specific page of KeyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of KeyInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return KeyPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> KeyPage: + """ + Asynchronously retrieve a specific page of KeyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of KeyInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return KeyPage(self._version, response, self._solution) + + def get(self, sid: str) -> KeyContext: + """ + Constructs a KeyContext + + :param sid: The Twilio-provided string that uniquely identifies the Key resource to update. + """ + return KeyContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> KeyContext: + """ + Constructs a KeyContext + + :param sid: The Twilio-provided string that uniquely identifies the Key resource to update. + """ + return KeyContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/message/__init__.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/message/__init__.py new file mode 100644 index 00000000..d5369d11 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/message/__init__.py @@ -0,0 +1,1014 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.message.feedback import FeedbackList +from twilio.rest.api.v2010.account.message.media import MediaList + + +class MessageInstance(InstanceResource): + + class AddressRetention(object): + RETAIN = "retain" + OBFUSCATE = "obfuscate" + + class ContentRetention(object): + RETAIN = "retain" + DISCARD = "discard" + + class Direction(object): + INBOUND = "inbound" + OUTBOUND_API = "outbound-api" + OUTBOUND_CALL = "outbound-call" + OUTBOUND_REPLY = "outbound-reply" + + class RiskCheck(object): + ENABLE = "enable" + DISABLE = "disable" + + class ScheduleType(object): + FIXED = "fixed" + + class Status(object): + QUEUED = "queued" + SENDING = "sending" + SENT = "sent" + FAILED = "failed" + DELIVERED = "delivered" + UNDELIVERED = "undelivered" + RECEIVING = "receiving" + RECEIVED = "received" + ACCEPTED = "accepted" + SCHEDULED = "scheduled" + READ = "read" + PARTIALLY_DELIVERED = "partially_delivered" + CANCELED = "canceled" + + class TrafficType(object): + FREE = "free" + + class UpdateStatus(object): + CANCELED = "canceled" + + """ + :ivar body: The text content of the message + :ivar num_segments: The number of segments that make up the complete message. SMS message bodies that exceed the [character limit](https://www.twilio.com/docs/glossary/what-sms-character-limit) are segmented and charged as multiple messages. Note: For messages sent via a Messaging Service, `num_segments` is initially `0`, since a sender hasn't yet been assigned. + :ivar direction: + :ivar from_: The sender's phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), [Wireless SIM](https://www.twilio.com/docs/iot/wireless/programmable-wireless-send-machine-machine-sms-commands), [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g., `whatsapp:+15554449999`). For incoming messages, this is the number or channel address of the sender. For outgoing messages, this value is a Twilio phone number, alphanumeric sender ID, short code, or channel address from which the message is sent. + :ivar to: The recipient's phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format) or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g. `whatsapp:+15552229999`) + :ivar date_updated: The [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822#section-3.3) timestamp (in GMT) of when the Message resource was last updated + :ivar price: The amount billed for the message in the currency specified by `price_unit`. The `price` is populated after the message has been sent/received, and may not be immediately availalble. View the [Pricing page](https://www.twilio.com/en-us/pricing) for more details. + :ivar error_message: The description of the `error_code` if the Message `status` is `failed` or `undelivered`. If no error was encountered, the value is `null`. The value returned in this field for a specific error cause is subject to change as Twilio improves errors. Users should not use the `error_code` and `error_message` fields programmatically. + :ivar uri: The URI of the Message resource, relative to `https://api.twilio.com`. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with the Message resource + :ivar num_media: The number of media files associated with the Message resource. + :ivar status: + :ivar messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) associated with the Message resource. A unique default value is assigned if a Messaging Service is not used. + :ivar sid: The unique, Twilio-provided string that identifies the Message resource. + :ivar date_sent: The [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822#section-3.3) timestamp (in GMT) of when the Message was sent. For an outgoing message, this is when Twilio sent the message. For an incoming message, this is when Twilio sent the HTTP request to your incoming message webhook URL. + :ivar date_created: The [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822#section-3.3) timestamp (in GMT) of when the Message resource was created + :ivar error_code: The [error code](https://www.twilio.com/docs/api/errors) returned if the Message `status` is `failed` or `undelivered`. If no error was encountered, the value is `null`. The value returned in this field for a specific error cause is subject to change as Twilio improves errors. Users should not use the `error_code` and `error_message` fields programmatically. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar api_version: The API version used to process the Message + :ivar subresource_uris: A list of related resources identified by their URIs relative to `https://api.twilio.com` + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.body: Optional[str] = payload.get("body") + self.num_segments: Optional[str] = payload.get("num_segments") + self.direction: Optional["MessageInstance.Direction"] = payload.get("direction") + self.from_: Optional[str] = payload.get("from") + self.to: Optional[str] = payload.get("to") + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.price: Optional[str] = payload.get("price") + self.error_message: Optional[str] = payload.get("error_message") + self.uri: Optional[str] = payload.get("uri") + self.account_sid: Optional[str] = payload.get("account_sid") + self.num_media: Optional[str] = payload.get("num_media") + self.status: Optional["MessageInstance.Status"] = payload.get("status") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.sid: Optional[str] = payload.get("sid") + self.date_sent: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_sent") + ) + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.api_version: Optional[str] = payload.get("api_version") + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[MessageContext] = None + + @property + def _proxy(self) -> "MessageContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MessageContext for this MessageInstance + """ + if self._context is None: + self._context = MessageContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "MessageInstance": + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MessageInstance": + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> "MessageInstance": + """ + Update the MessageInstance + + :param body: The new `body` of the Message resource. To redact the text content of a Message, this parameter's value must be an empty string + :param status: + + :returns: The updated MessageInstance + """ + return self._proxy.update( + body=body, + status=status, + ) + + async def update_async( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> "MessageInstance": + """ + Asynchronous coroutine to update the MessageInstance + + :param body: The new `body` of the Message resource. To redact the text content of a Message, this parameter's value must be an empty string + :param status: + + :returns: The updated MessageInstance + """ + return await self._proxy.update_async( + body=body, + status=status, + ) + + @property + def feedback(self) -> FeedbackList: + """ + Access the feedback + """ + return self._proxy.feedback + + @property + def media(self) -> MediaList: + """ + Access the media + """ + return self._proxy.media + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MessageContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the MessageContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Message resources to update. + :param sid: The SID of the Message resource to be updated + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Messages/{sid}.json".format( + **self._solution + ) + + self._feedback: Optional[FeedbackList] = None + self._media: Optional[MediaList] = None + + def delete(self) -> bool: + """ + Deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> MessageInstance: + """ + Update the MessageInstance + + :param body: The new `body` of the Message resource. To redact the text content of a Message, this parameter's value must be an empty string + :param status: + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Body": body, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> MessageInstance: + """ + Asynchronous coroutine to update the MessageInstance + + :param body: The new `body` of the Message resource. To redact the text content of a Message, this parameter's value must be an empty string + :param status: + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Body": body, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + @property + def feedback(self) -> FeedbackList: + """ + Access the feedback + """ + if self._feedback is None: + self._feedback = FeedbackList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._feedback + + @property + def media(self) -> MediaList: + """ + Access the media + """ + if self._media is None: + self._media = MediaList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._media + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MessagePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: + """ + Build an instance of MessageInstance + + :param payload: Payload response from the API + """ + return MessageInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MessageList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the MessageList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with the Message resources. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Messages.json".format(**self._solution) + + def create( + self, + to: str, + status_callback: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + max_price: Union[float, object] = values.unset, + provide_feedback: Union[bool, object] = values.unset, + attempt: Union[int, object] = values.unset, + validity_period: Union[int, object] = values.unset, + force_delivery: Union[bool, object] = values.unset, + content_retention: Union[ + "MessageInstance.ContentRetention", object + ] = values.unset, + address_retention: Union[ + "MessageInstance.AddressRetention", object + ] = values.unset, + smart_encoded: Union[bool, object] = values.unset, + persistent_action: Union[List[str], object] = values.unset, + traffic_type: Union["MessageInstance.TrafficType", object] = values.unset, + shorten_urls: Union[bool, object] = values.unset, + schedule_type: Union["MessageInstance.ScheduleType", object] = values.unset, + send_at: Union[datetime, object] = values.unset, + send_as_mms: Union[bool, object] = values.unset, + content_variables: Union[str, object] = values.unset, + risk_check: Union["MessageInstance.RiskCheck", object] = values.unset, + from_: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + content_sid: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Create the MessageInstance + + :param to: The recipient's phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (for SMS/MMS) or [channel address](https://www.twilio.com/docs/messaging/channels), e.g. `whatsapp:+15552229999`. + :param status_callback: The URL of the endpoint to which Twilio sends [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url). URL must contain a valid hostname and underscores are not allowed. If you include this parameter with the `messaging_service_sid`, Twilio uses this URL instead of the Status Callback URL of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource). + :param application_sid: The SID of the associated [TwiML Application](https://www.twilio.com/docs/usage/api/applications). [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url) are sent to the TwiML App's `message_status_callback` URL. Note that the `status_callback` parameter of a request takes priority over the `application_sid` parameter; if both are included `application_sid` is ignored. + :param max_price: [OBSOLETE] This parameter will no longer have any effect as of 2024-06-03. + :param provide_feedback: Boolean indicating whether or not you intend to provide delivery confirmation feedback to Twilio (used in conjunction with the [Message Feedback subresource](https://www.twilio.com/docs/sms/api/message-feedback-resource)). Default value is `false`. + :param attempt: Total number of attempts made (including this request) to send the message regardless of the provider used + :param validity_period: The maximum length in seconds that the Message can remain in Twilio's outgoing message queue. If a queued Message exceeds the `validity_period`, the Message is not sent. Accepted values are integers from `1` to `36000`. Default value is `36000`. A `validity_period` greater than `5` is recommended. [Learn more about the validity period](https://www.twilio.com/blog/take-more-control-of-outbound-messages-using-validity-period-html) + :param force_delivery: Reserved + :param content_retention: + :param address_retention: + :param smart_encoded: Whether to detect Unicode characters that have a similar GSM-7 character and replace them. Can be: `true` or `false`. + :param persistent_action: Rich actions for non-SMS/MMS channels. Used for [sending location in WhatsApp messages](https://www.twilio.com/docs/whatsapp/message-features#location-messages-with-whatsapp). + :param traffic_type: + :param shorten_urls: For Messaging Services with [Link Shortening configured](https://www.twilio.com/docs/messaging/features/link-shortening) only: A Boolean indicating whether or not Twilio should shorten links in the `body` of the Message. Default value is `false`. If `true`, the `messaging_service_sid` parameter must also be provided. + :param schedule_type: + :param send_at: The time that Twilio will send the message. Must be in ISO 8601 format. + :param send_as_mms: If set to `true`, Twilio delivers the message as a single MMS message, regardless of the presence of media. + :param content_variables: For [Content Editor/API](https://www.twilio.com/docs/content) only: Key-value pairs of [Template variables](https://www.twilio.com/docs/content/using-variables-with-content-api) and their substitution values. `content_sid` parameter must also be provided. If values are not defined in the `content_variables` parameter, the [Template's default placeholder values](https://www.twilio.com/docs/content/content-api-resources#create-templates) are used. + :param risk_check: + :param from_: The sender's Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), [Wireless SIM](https://www.twilio.com/docs/iot/wireless/programmable-wireless-send-machine-machine-sms-commands), [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g., `whatsapp:+15554449999`). The value of the `from` parameter must be a sender that is hosted within Twilio and belongs to the Account creating the Message. If you are using `messaging_service_sid`, this parameter can be empty (Twilio assigns a `from` value from the Messaging Service's Sender Pool) or you can provide a specific sender from your Sender Pool. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) you want to associate with the Message. When this parameter is provided and the `from` parameter is omitted, Twilio selects the optimal sender from the Messaging Service's Sender Pool. You may also provide a `from` parameter if you want to use a specific Sender from the Sender Pool. + :param body: The text content of the outgoing message. Can be up to 1,600 characters in length. SMS only: If the `body` contains more than 160 [GSM-7](https://www.twilio.com/docs/glossary/what-is-gsm-7-character-encoding) characters (or 70 [UCS-2](https://www.twilio.com/docs/glossary/what-is-ucs-2-character-encoding) characters), the message is segmented and charged accordingly. For long `body` text, consider using the [send_as_mms parameter](https://www.twilio.com/blog/mms-for-long-text-messages). + :param media_url: The URL of media to include in the Message content. `jpeg`, `jpg`, `gif`, and `png` file types are fully supported by Twilio and content is formatted for delivery on destination devices. The media size limit is 5 MB for supported file types (`jpeg`, `jpg`, `png`, `gif`) and 500 KB for [other types](https://www.twilio.com/docs/messaging/guides/accepted-mime-types) of accepted media. To send more than one image in the message, provide multiple `media_url` parameters in the POST request. You can include up to ten `media_url` parameters per message. [International](https://support.twilio.com/hc/en-us/articles/223179808-Sending-and-receiving-MMS-messages) and [carrier](https://support.twilio.com/hc/en-us/articles/223133707-Is-MMS-supported-for-all-carriers-in-US-and-Canada-) limits apply. + :param content_sid: For [Content Editor/API](https://www.twilio.com/docs/content) only: The SID of the Content Template to be used with the Message, e.g., `HXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`. If this parameter is not provided, a Content Template is not used. Find the SID in the Console on the Content Editor page. For Content API users, the SID is found in Twilio's response when [creating the Template](https://www.twilio.com/docs/content/content-api-resources#create-templates) or by [fetching your Templates](https://www.twilio.com/docs/content/content-api-resources#fetch-all-content-resources). + + :returns: The created MessageInstance + """ + + data = values.of( + { + "To": to, + "StatusCallback": status_callback, + "ApplicationSid": application_sid, + "MaxPrice": max_price, + "ProvideFeedback": serialize.boolean_to_string(provide_feedback), + "Attempt": attempt, + "ValidityPeriod": validity_period, + "ForceDelivery": serialize.boolean_to_string(force_delivery), + "ContentRetention": content_retention, + "AddressRetention": address_retention, + "SmartEncoded": serialize.boolean_to_string(smart_encoded), + "PersistentAction": serialize.map(persistent_action, lambda e: e), + "TrafficType": traffic_type, + "ShortenUrls": serialize.boolean_to_string(shorten_urls), + "ScheduleType": schedule_type, + "SendAt": serialize.iso8601_datetime(send_at), + "SendAsMms": serialize.boolean_to_string(send_as_mms), + "ContentVariables": content_variables, + "RiskCheck": risk_check, + "From": from_, + "MessagingServiceSid": messaging_service_sid, + "Body": body, + "MediaUrl": serialize.map(media_url, lambda e: e), + "ContentSid": content_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, + to: str, + status_callback: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + max_price: Union[float, object] = values.unset, + provide_feedback: Union[bool, object] = values.unset, + attempt: Union[int, object] = values.unset, + validity_period: Union[int, object] = values.unset, + force_delivery: Union[bool, object] = values.unset, + content_retention: Union[ + "MessageInstance.ContentRetention", object + ] = values.unset, + address_retention: Union[ + "MessageInstance.AddressRetention", object + ] = values.unset, + smart_encoded: Union[bool, object] = values.unset, + persistent_action: Union[List[str], object] = values.unset, + traffic_type: Union["MessageInstance.TrafficType", object] = values.unset, + shorten_urls: Union[bool, object] = values.unset, + schedule_type: Union["MessageInstance.ScheduleType", object] = values.unset, + send_at: Union[datetime, object] = values.unset, + send_as_mms: Union[bool, object] = values.unset, + content_variables: Union[str, object] = values.unset, + risk_check: Union["MessageInstance.RiskCheck", object] = values.unset, + from_: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + content_sid: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param to: The recipient's phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (for SMS/MMS) or [channel address](https://www.twilio.com/docs/messaging/channels), e.g. `whatsapp:+15552229999`. + :param status_callback: The URL of the endpoint to which Twilio sends [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url). URL must contain a valid hostname and underscores are not allowed. If you include this parameter with the `messaging_service_sid`, Twilio uses this URL instead of the Status Callback URL of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource). + :param application_sid: The SID of the associated [TwiML Application](https://www.twilio.com/docs/usage/api/applications). [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url) are sent to the TwiML App's `message_status_callback` URL. Note that the `status_callback` parameter of a request takes priority over the `application_sid` parameter; if both are included `application_sid` is ignored. + :param max_price: [OBSOLETE] This parameter will no longer have any effect as of 2024-06-03. + :param provide_feedback: Boolean indicating whether or not you intend to provide delivery confirmation feedback to Twilio (used in conjunction with the [Message Feedback subresource](https://www.twilio.com/docs/sms/api/message-feedback-resource)). Default value is `false`. + :param attempt: Total number of attempts made (including this request) to send the message regardless of the provider used + :param validity_period: The maximum length in seconds that the Message can remain in Twilio's outgoing message queue. If a queued Message exceeds the `validity_period`, the Message is not sent. Accepted values are integers from `1` to `36000`. Default value is `36000`. A `validity_period` greater than `5` is recommended. [Learn more about the validity period](https://www.twilio.com/blog/take-more-control-of-outbound-messages-using-validity-period-html) + :param force_delivery: Reserved + :param content_retention: + :param address_retention: + :param smart_encoded: Whether to detect Unicode characters that have a similar GSM-7 character and replace them. Can be: `true` or `false`. + :param persistent_action: Rich actions for non-SMS/MMS channels. Used for [sending location in WhatsApp messages](https://www.twilio.com/docs/whatsapp/message-features#location-messages-with-whatsapp). + :param traffic_type: + :param shorten_urls: For Messaging Services with [Link Shortening configured](https://www.twilio.com/docs/messaging/features/link-shortening) only: A Boolean indicating whether or not Twilio should shorten links in the `body` of the Message. Default value is `false`. If `true`, the `messaging_service_sid` parameter must also be provided. + :param schedule_type: + :param send_at: The time that Twilio will send the message. Must be in ISO 8601 format. + :param send_as_mms: If set to `true`, Twilio delivers the message as a single MMS message, regardless of the presence of media. + :param content_variables: For [Content Editor/API](https://www.twilio.com/docs/content) only: Key-value pairs of [Template variables](https://www.twilio.com/docs/content/using-variables-with-content-api) and their substitution values. `content_sid` parameter must also be provided. If values are not defined in the `content_variables` parameter, the [Template's default placeholder values](https://www.twilio.com/docs/content/content-api-resources#create-templates) are used. + :param risk_check: + :param from_: The sender's Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), [Wireless SIM](https://www.twilio.com/docs/iot/wireless/programmable-wireless-send-machine-machine-sms-commands), [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g., `whatsapp:+15554449999`). The value of the `from` parameter must be a sender that is hosted within Twilio and belongs to the Account creating the Message. If you are using `messaging_service_sid`, this parameter can be empty (Twilio assigns a `from` value from the Messaging Service's Sender Pool) or you can provide a specific sender from your Sender Pool. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) you want to associate with the Message. When this parameter is provided and the `from` parameter is omitted, Twilio selects the optimal sender from the Messaging Service's Sender Pool. You may also provide a `from` parameter if you want to use a specific Sender from the Sender Pool. + :param body: The text content of the outgoing message. Can be up to 1,600 characters in length. SMS only: If the `body` contains more than 160 [GSM-7](https://www.twilio.com/docs/glossary/what-is-gsm-7-character-encoding) characters (or 70 [UCS-2](https://www.twilio.com/docs/glossary/what-is-ucs-2-character-encoding) characters), the message is segmented and charged accordingly. For long `body` text, consider using the [send_as_mms parameter](https://www.twilio.com/blog/mms-for-long-text-messages). + :param media_url: The URL of media to include in the Message content. `jpeg`, `jpg`, `gif`, and `png` file types are fully supported by Twilio and content is formatted for delivery on destination devices. The media size limit is 5 MB for supported file types (`jpeg`, `jpg`, `png`, `gif`) and 500 KB for [other types](https://www.twilio.com/docs/messaging/guides/accepted-mime-types) of accepted media. To send more than one image in the message, provide multiple `media_url` parameters in the POST request. You can include up to ten `media_url` parameters per message. [International](https://support.twilio.com/hc/en-us/articles/223179808-Sending-and-receiving-MMS-messages) and [carrier](https://support.twilio.com/hc/en-us/articles/223133707-Is-MMS-supported-for-all-carriers-in-US-and-Canada-) limits apply. + :param content_sid: For [Content Editor/API](https://www.twilio.com/docs/content) only: The SID of the Content Template to be used with the Message, e.g., `HXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`. If this parameter is not provided, a Content Template is not used. Find the SID in the Console on the Content Editor page. For Content API users, the SID is found in Twilio's response when [creating the Template](https://www.twilio.com/docs/content/content-api-resources#create-templates) or by [fetching your Templates](https://www.twilio.com/docs/content/content-api-resources#fetch-all-content-resources). + + :returns: The created MessageInstance + """ + + data = values.of( + { + "To": to, + "StatusCallback": status_callback, + "ApplicationSid": application_sid, + "MaxPrice": max_price, + "ProvideFeedback": serialize.boolean_to_string(provide_feedback), + "Attempt": attempt, + "ValidityPeriod": validity_period, + "ForceDelivery": serialize.boolean_to_string(force_delivery), + "ContentRetention": content_retention, + "AddressRetention": address_retention, + "SmartEncoded": serialize.boolean_to_string(smart_encoded), + "PersistentAction": serialize.map(persistent_action, lambda e: e), + "TrafficType": traffic_type, + "ShortenUrls": serialize.boolean_to_string(shorten_urls), + "ScheduleType": schedule_type, + "SendAt": serialize.iso8601_datetime(send_at), + "SendAsMms": serialize.boolean_to_string(send_as_mms), + "ContentVariables": content_variables, + "RiskCheck": risk_check, + "From": from_, + "MessagingServiceSid": messaging_service_sid, + "Body": body, + "MediaUrl": serialize.map(media_url, lambda e: e), + "ContentSid": content_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + date_sent: Union[datetime, object] = values.unset, + date_sent_before: Union[datetime, object] = values.unset, + date_sent_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: + """ + Streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` + :param str from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param datetime date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + to=to, + from_=from_, + date_sent=date_sent, + date_sent_before=date_sent_before, + date_sent_after=date_sent_after, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + date_sent: Union[datetime, object] = values.unset, + date_sent_before: Union[datetime, object] = values.unset, + date_sent_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessageInstance]: + """ + Asynchronously streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` + :param str from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param datetime date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + to=to, + from_=from_, + date_sent=date_sent, + date_sent_before=date_sent_before, + date_sent_after=date_sent_after, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + date_sent: Union[datetime, object] = values.unset, + date_sent_before: Union[datetime, object] = values.unset, + date_sent_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` + :param str from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param datetime date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + to=to, + from_=from_, + date_sent=date_sent, + date_sent_before=date_sent_before, + date_sent_after=date_sent_after, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + date_sent: Union[datetime, object] = values.unset, + date_sent_before: Union[datetime, object] = values.unset, + date_sent_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Asynchronously lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` + :param str from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param datetime date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + to=to, + from_=from_, + date_sent=date_sent, + date_sent_before=date_sent_before, + date_sent_after=date_sent_after, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + date_sent: Union[datetime, object] = values.unset, + date_sent_before: Union[datetime, object] = values.unset, + date_sent_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` + :param from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "To": to, + "From": from_, + "DateSent": serialize.iso8601_datetime(date_sent), + "DateSent<": serialize.iso8601_datetime(date_sent_before), + "DateSent>": serialize.iso8601_datetime(date_sent_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + async def page_async( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + date_sent: Union[datetime, object] = values.unset, + date_sent_before: Union[datetime, object] = values.unset, + date_sent_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` + :param from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "To": to, + "From": from_, + "DateSent": serialize.iso8601_datetime(date_sent), + "DateSent<": serialize.iso8601_datetime(date_sent_before), + "DateSent>": serialize.iso8601_datetime(date_sent_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MessagePage: + """ + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MessagePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MessagePage: + """ + Asynchronously retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagePage(self._version, response, self._solution) + + def get(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: The SID of the Message resource to be updated + """ + return MessageContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: The SID of the Message resource to be updated + """ + return MessageContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/message/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/message/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..09430ae6 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/message/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/message/__pycache__/feedback.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/message/__pycache__/feedback.cpython-312.pyc new file mode 100644 index 00000000..e415f8fe Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/message/__pycache__/feedback.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/message/__pycache__/media.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/message/__pycache__/media.cpython-312.pyc new file mode 100644 index 00000000..3e5739dc Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/message/__pycache__/media.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/message/feedback.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/message/feedback.py new file mode 100644 index 00000000..cda2de2f --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/message/feedback.py @@ -0,0 +1,170 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class FeedbackInstance(InstanceResource): + + class Outcome(object): + CONFIRMED = "confirmed" + UNCONFIRMED = "unconfirmed" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with this MessageFeedback resource. + :ivar message_sid: The SID of the Message resource associated with this MessageFeedback resource. + :ivar outcome: + :ivar date_created: The date and time in GMT when this MessageFeedback resource was created, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when this MessageFeedback resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + message_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.message_sid: Optional[str] = payload.get("message_sid") + self.outcome: Optional["FeedbackInstance.Outcome"] = payload.get("outcome") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "message_sid": message_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FeedbackList(ListResource): + + def __init__(self, version: Version, account_sid: str, message_sid: str): + """ + Initialize the FeedbackList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with the Message resource for which to create MessageFeedback. + :param message_sid: The SID of the Message resource for which to create MessageFeedback. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "message_sid": message_sid, + } + self._uri = ( + "/Accounts/{account_sid}/Messages/{message_sid}/Feedback.json".format( + **self._solution + ) + ) + + def create( + self, outcome: Union["FeedbackInstance.Outcome", object] = values.unset + ) -> FeedbackInstance: + """ + Create the FeedbackInstance + + :param outcome: + + :returns: The created FeedbackInstance + """ + + data = values.of( + { + "Outcome": outcome, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FeedbackInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + ) + + async def create_async( + self, outcome: Union["FeedbackInstance.Outcome", object] = values.unset + ) -> FeedbackInstance: + """ + Asynchronously create the FeedbackInstance + + :param outcome: + + :returns: The created FeedbackInstance + """ + + data = values.of( + { + "Outcome": outcome, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FeedbackInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/message/media.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/message/media.py new file mode 100644 index 00000000..b5d2926d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/message/media.py @@ -0,0 +1,564 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MediaInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with this Media resource. + :ivar content_type: The default [MIME type](https://en.wikipedia.org/wiki/Internet_media_type) of the media, for example `image/jpeg`, `image/png`, or `image/gif`. + :ivar date_created: The date and time in GMT when this Media resource was created, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when this Media resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar parent_sid: The SID of the Message resource that is associated with this Media resource. + :ivar sid: The unique string that identifies this Media resource. + :ivar uri: The URI of this Media resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + message_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.content_type: Optional[str] = payload.get("content_type") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.parent_sid: Optional[str] = payload.get("parent_sid") + self.sid: Optional[str] = payload.get("sid") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "message_sid": message_sid, + "sid": sid or self.sid, + } + self._context: Optional[MediaContext] = None + + @property + def _proxy(self) -> "MediaContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MediaContext for this MediaInstance + """ + if self._context is None: + self._context = MediaContext( + self._version, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the MediaInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MediaInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "MediaInstance": + """ + Fetch the MediaInstance + + + :returns: The fetched MediaInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MediaInstance": + """ + Asynchronous coroutine to fetch the MediaInstance + + + :returns: The fetched MediaInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MediaContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, message_sid: str, sid: str): + """ + Initialize the MediaContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with the Media resource. + :param message_sid: The SID of the Message resource that is associated with the Media resource. + :param sid: The Twilio-provided string that uniquely identifies the Media resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "message_sid": message_sid, + "sid": sid, + } + self._uri = ( + "/Accounts/{account_sid}/Messages/{message_sid}/Media/{sid}.json".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the MediaInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MediaInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MediaInstance: + """ + Fetch the MediaInstance + + + :returns: The fetched MediaInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MediaInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MediaInstance: + """ + Asynchronous coroutine to fetch the MediaInstance + + + :returns: The fetched MediaInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MediaInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MediaPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MediaInstance: + """ + Build an instance of MediaInstance + + :param payload: Payload response from the API + """ + return MediaInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MediaList(ListResource): + + def __init__(self, version: Version, account_sid: str, message_sid: str): + """ + Initialize the MediaList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that is associated with the Media resources. + :param message_sid: The SID of the Message resource that is associated with the Media resources. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "message_sid": message_sid, + } + self._uri = "/Accounts/{account_sid}/Messages/{message_sid}/Media.json".format( + **self._solution + ) + + def stream( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MediaInstance]: + """ + Streams MediaInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime date_created: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_before: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_after: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MediaInstance]: + """ + Asynchronously streams MediaInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime date_created: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_before: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_after: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MediaInstance]: + """ + Lists MediaInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime date_created: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_before: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_after: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MediaInstance]: + """ + Asynchronously lists MediaInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime date_created: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_before: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_after: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MediaPage: + """ + Retrieve a single page of MediaInstance records from the API. + Request is executed immediately + + :param date_created: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param date_created_before: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param date_created_after: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MediaInstance + """ + data = values.of( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "DateCreated<": serialize.iso8601_datetime(date_created_before), + "DateCreated>": serialize.iso8601_datetime(date_created_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MediaPage(self._version, response, self._solution) + + async def page_async( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MediaPage: + """ + Asynchronously retrieve a single page of MediaInstance records from the API. + Request is executed immediately + + :param date_created: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param date_created_before: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param date_created_after: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MediaInstance + """ + data = values.of( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "DateCreated<": serialize.iso8601_datetime(date_created_before), + "DateCreated>": serialize.iso8601_datetime(date_created_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MediaPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MediaPage: + """ + Retrieve a specific page of MediaInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MediaInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MediaPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MediaPage: + """ + Asynchronously retrieve a specific page of MediaInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MediaInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MediaPage(self._version, response, self._solution) + + def get(self, sid: str) -> MediaContext: + """ + Constructs a MediaContext + + :param sid: The Twilio-provided string that uniquely identifies the Media resource to fetch. + """ + return MediaContext( + self._version, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> MediaContext: + """ + Constructs a MediaContext + + :param sid: The Twilio-provided string that uniquely identifies the Media resource to fetch. + """ + return MediaContext( + self._version, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/new_key.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/new_key.py new file mode 100644 index 00000000..ba811ec1 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/new_key.py @@ -0,0 +1,144 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NewKeyInstance(InstanceResource): + """ + :ivar sid: The unique string that that we created to identify the NewKey resource. You will use this as the basic-auth `user` when authenticating to the API. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT that the API Key was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the new API Key was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar secret: The secret your application uses to sign Access Tokens and to authenticate to the REST API (you will use this as the basic-auth `password`). **Note that for security reasons, this field is ONLY returned when the API Key is first created.** + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.secret: Optional[str] = payload.get("secret") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NewKeyList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the NewKeyList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that will be responsible for the new Key resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Keys.json".format(**self._solution) + + def create( + self, friendly_name: Union[str, object] = values.unset + ) -> NewKeyInstance: + """ + Create the NewKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The created NewKeyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NewKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> NewKeyInstance: + """ + Asynchronously create the NewKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The created NewKeyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NewKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/new_signing_key.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/new_signing_key.py new file mode 100644 index 00000000..95341d31 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/new_signing_key.py @@ -0,0 +1,144 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NewSigningKeyInstance(InstanceResource): + """ + :ivar sid: The unique string that that we created to identify the NewSigningKey resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar secret: The secret your application uses to sign Access Tokens and to authenticate to the REST API (you will use this as the basic-auth `password`). **Note that for security reasons, this field is ONLY returned when the API Key is first created.** + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.secret: Optional[str] = payload.get("secret") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NewSigningKeyList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the NewSigningKeyList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that will be responsible for the new Key resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/SigningKeys.json".format(**self._solution) + + def create( + self, friendly_name: Union[str, object] = values.unset + ) -> NewSigningKeyInstance: + """ + Create the NewSigningKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The created NewSigningKeyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NewSigningKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> NewSigningKeyInstance: + """ + Asynchronously create the NewSigningKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The created NewSigningKeyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NewSigningKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/notification.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/notification.py new file mode 100644 index 00000000..cd35efea --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/notification.py @@ -0,0 +1,540 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class NotificationInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Notification resource. + :ivar api_version: The API version used to generate the notification. Can be empty for events that don't have a specific API version, such as incoming phone calls. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Notification resource is associated with. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar error_code: A unique error code for the error condition that is described in our [Error Dictionary](https://www.twilio.com/docs/api/errors). + :ivar log: An integer log level that corresponds to the type of notification: `0` is ERROR, `1` is WARNING. + :ivar message_date: The date the notification was actually generated in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. Message buffering can cause this value to differ from `date_created`. + :ivar message_text: The text of the notification. + :ivar more_info: The URL for more information about the error condition. This value is a page in our [Error Dictionary](https://www.twilio.com/docs/api/errors). + :ivar request_method: The HTTP method used to generate the notification. If the notification was generated during a phone call, this is the HTTP Method used to request the resource on your server. If the notification was generated by your use of our REST API, this is the HTTP method used to call the resource on our servers. + :ivar request_url: The URL of the resource that generated the notification. If the notification was generated during a phone call, this is the URL of the resource on your server that caused the notification. If the notification was generated by your use of our REST API, this is the URL of the resource you called. + :ivar request_variables: The HTTP GET or POST variables we sent to your server. However, if the notification was generated by our REST API, this contains the HTTP POST or PUT variables you sent to our API. + :ivar response_body: The HTTP body returned by your server. + :ivar response_headers: The HTTP headers returned by your server. + :ivar sid: The unique string that that we created to identify the Notification resource. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.call_sid: Optional[str] = payload.get("call_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.error_code: Optional[str] = payload.get("error_code") + self.log: Optional[str] = payload.get("log") + self.message_date: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("message_date") + ) + self.message_text: Optional[str] = payload.get("message_text") + self.more_info: Optional[str] = payload.get("more_info") + self.request_method: Optional[str] = payload.get("request_method") + self.request_url: Optional[str] = payload.get("request_url") + self.request_variables: Optional[str] = payload.get("request_variables") + self.response_body: Optional[str] = payload.get("response_body") + self.response_headers: Optional[str] = payload.get("response_headers") + self.sid: Optional[str] = payload.get("sid") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[NotificationContext] = None + + @property + def _proxy(self) -> "NotificationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: NotificationContext for this NotificationInstance + """ + if self._context is None: + self._context = NotificationContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "NotificationInstance": + """ + Fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "NotificationInstance": + """ + Asynchronous coroutine to fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NotificationContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the NotificationContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Notification resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Notification resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Notifications/{sid}.json".format( + **self._solution + ) + + def fetch(self) -> NotificationInstance: + """ + Fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> NotificationInstance: + """ + Asynchronous coroutine to fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NotificationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> NotificationInstance: + """ + Build an instance of NotificationInstance + + :param payload: Payload response from the API + """ + return NotificationInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class NotificationList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the NotificationList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Notification resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Notifications.json".format( + **self._solution + ) + + def stream( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[NotificationInstance]: + """ + Streams NotificationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[NotificationInstance]: + """ + Asynchronously streams NotificationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NotificationInstance]: + """ + Lists NotificationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NotificationInstance]: + """ + Asynchronously lists NotificationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NotificationPage: + """ + Retrieve a single page of NotificationInstance records from the API. + Request is executed immediately + + :param log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NotificationInstance + """ + data = values.of( + { + "Log": log, + "MessageDate": serialize.iso8601_date(message_date), + "MessageDate<": serialize.iso8601_date(message_date_before), + "MessageDate>": serialize.iso8601_date(message_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NotificationPage(self._version, response, self._solution) + + async def page_async( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NotificationPage: + """ + Asynchronously retrieve a single page of NotificationInstance records from the API. + Request is executed immediately + + :param log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NotificationInstance + """ + data = values.of( + { + "Log": log, + "MessageDate": serialize.iso8601_date(message_date), + "MessageDate<": serialize.iso8601_date(message_date_before), + "MessageDate>": serialize.iso8601_date(message_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NotificationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> NotificationPage: + """ + Retrieve a specific page of NotificationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NotificationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return NotificationPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> NotificationPage: + """ + Asynchronously retrieve a specific page of NotificationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NotificationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return NotificationPage(self._version, response, self._solution) + + def get(self, sid: str) -> NotificationContext: + """ + Constructs a NotificationContext + + :param sid: The Twilio-provided string that uniquely identifies the Notification resource to fetch. + """ + return NotificationContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> NotificationContext: + """ + Constructs a NotificationContext + + :param sid: The Twilio-provided string that uniquely identifies the Notification resource to fetch. + """ + return NotificationContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/outgoing_caller_id.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/outgoing_caller_id.py new file mode 100644 index 00000000..eeb9954c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/outgoing_caller_id.py @@ -0,0 +1,620 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class OutgoingCallerIdInstance(InstanceResource): + """ + :ivar sid: The unique string that that we created to identify the OutgoingCallerId resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the OutgoingCallerId resource. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.phone_number: Optional[str] = payload.get("phone_number") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[OutgoingCallerIdContext] = None + + @property + def _proxy(self) -> "OutgoingCallerIdContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OutgoingCallerIdContext for this OutgoingCallerIdInstance + """ + if self._context is None: + self._context = OutgoingCallerIdContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the OutgoingCallerIdInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OutgoingCallerIdInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "OutgoingCallerIdInstance": + """ + Fetch the OutgoingCallerIdInstance + + + :returns: The fetched OutgoingCallerIdInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "OutgoingCallerIdInstance": + """ + Asynchronous coroutine to fetch the OutgoingCallerIdInstance + + + :returns: The fetched OutgoingCallerIdInstance + """ + return await self._proxy.fetch_async() + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> "OutgoingCallerIdInstance": + """ + Update the OutgoingCallerIdInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated OutgoingCallerIdInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "OutgoingCallerIdInstance": + """ + Asynchronous coroutine to update the OutgoingCallerIdInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated OutgoingCallerIdInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OutgoingCallerIdContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the OutgoingCallerIdContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the OutgoingCallerId resources to update. + :param sid: The Twilio-provided string that uniquely identifies the OutgoingCallerId resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/OutgoingCallerIds/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the OutgoingCallerIdInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OutgoingCallerIdInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> OutgoingCallerIdInstance: + """ + Fetch the OutgoingCallerIdInstance + + + :returns: The fetched OutgoingCallerIdInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return OutgoingCallerIdInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> OutgoingCallerIdInstance: + """ + Asynchronous coroutine to fetch the OutgoingCallerIdInstance + + + :returns: The fetched OutgoingCallerIdInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return OutgoingCallerIdInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> OutgoingCallerIdInstance: + """ + Update the OutgoingCallerIdInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated OutgoingCallerIdInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return OutgoingCallerIdInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> OutgoingCallerIdInstance: + """ + Asynchronous coroutine to update the OutgoingCallerIdInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated OutgoingCallerIdInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return OutgoingCallerIdInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OutgoingCallerIdPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> OutgoingCallerIdInstance: + """ + Build an instance of OutgoingCallerIdInstance + + :param payload: Payload response from the API + """ + return OutgoingCallerIdInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class OutgoingCallerIdList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the OutgoingCallerIdList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the OutgoingCallerId resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/OutgoingCallerIds.json".format( + **self._solution + ) + + def stream( + self, + phone_number: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[OutgoingCallerIdInstance]: + """ + Streams OutgoingCallerIdInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str phone_number: The phone number of the OutgoingCallerId resources to read. + :param str friendly_name: The string that identifies the OutgoingCallerId resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + phone_number=phone_number, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + phone_number: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[OutgoingCallerIdInstance]: + """ + Asynchronously streams OutgoingCallerIdInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str phone_number: The phone number of the OutgoingCallerId resources to read. + :param str friendly_name: The string that identifies the OutgoingCallerId resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + phone_number=phone_number, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + phone_number: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OutgoingCallerIdInstance]: + """ + Lists OutgoingCallerIdInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str phone_number: The phone number of the OutgoingCallerId resources to read. + :param str friendly_name: The string that identifies the OutgoingCallerId resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + phone_number=phone_number, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + phone_number: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OutgoingCallerIdInstance]: + """ + Asynchronously lists OutgoingCallerIdInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str phone_number: The phone number of the OutgoingCallerId resources to read. + :param str friendly_name: The string that identifies the OutgoingCallerId resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + phone_number=phone_number, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + phone_number: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OutgoingCallerIdPage: + """ + Retrieve a single page of OutgoingCallerIdInstance records from the API. + Request is executed immediately + + :param phone_number: The phone number of the OutgoingCallerId resources to read. + :param friendly_name: The string that identifies the OutgoingCallerId resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of OutgoingCallerIdInstance + """ + data = values.of( + { + "PhoneNumber": phone_number, + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OutgoingCallerIdPage(self._version, response, self._solution) + + async def page_async( + self, + phone_number: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OutgoingCallerIdPage: + """ + Asynchronously retrieve a single page of OutgoingCallerIdInstance records from the API. + Request is executed immediately + + :param phone_number: The phone number of the OutgoingCallerId resources to read. + :param friendly_name: The string that identifies the OutgoingCallerId resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of OutgoingCallerIdInstance + """ + data = values.of( + { + "PhoneNumber": phone_number, + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OutgoingCallerIdPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> OutgoingCallerIdPage: + """ + Retrieve a specific page of OutgoingCallerIdInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OutgoingCallerIdInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return OutgoingCallerIdPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> OutgoingCallerIdPage: + """ + Asynchronously retrieve a specific page of OutgoingCallerIdInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OutgoingCallerIdInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return OutgoingCallerIdPage(self._version, response, self._solution) + + def get(self, sid: str) -> OutgoingCallerIdContext: + """ + Constructs a OutgoingCallerIdContext + + :param sid: The Twilio-provided string that uniquely identifies the OutgoingCallerId resource to update. + """ + return OutgoingCallerIdContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> OutgoingCallerIdContext: + """ + Constructs a OutgoingCallerIdContext + + :param sid: The Twilio-provided string that uniquely identifies the OutgoingCallerId resource to update. + """ + return OutgoingCallerIdContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/queue/__init__.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/queue/__init__.py new file mode 100644 index 00000000..e76fda12 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/queue/__init__.py @@ -0,0 +1,687 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.queue.member import MemberList + + +class QueueInstance(InstanceResource): + """ + :ivar date_updated: The date and time in GMT that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar current_size: The number of calls currently in the queue. + :ivar friendly_name: A string that you assigned to describe this resource. + :ivar uri: The URI of this resource, relative to `https://api.twilio.com`. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Queue resource. + :ivar average_wait_time: The average wait time in seconds of the members in this queue. This is calculated at the time of the request. + :ivar sid: The unique string that that we created to identify this Queue resource. + :ivar date_created: The date and time in GMT that this resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar max_size: The maximum number of calls that can be in the queue. The default is 1000 and the maximum is 5000. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.current_size: Optional[int] = deserialize.integer( + payload.get("current_size") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.uri: Optional[str] = payload.get("uri") + self.account_sid: Optional[str] = payload.get("account_sid") + self.average_wait_time: Optional[int] = deserialize.integer( + payload.get("average_wait_time") + ) + self.sid: Optional[str] = payload.get("sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.max_size: Optional[int] = deserialize.integer(payload.get("max_size")) + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[QueueContext] = None + + @property + def _proxy(self) -> "QueueContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: QueueContext for this QueueInstance + """ + if self._context is None: + self._context = QueueContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the QueueInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the QueueInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "QueueInstance": + """ + Fetch the QueueInstance + + + :returns: The fetched QueueInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "QueueInstance": + """ + Asynchronous coroutine to fetch the QueueInstance + + + :returns: The fetched QueueInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> "QueueInstance": + """ + Update the QueueInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: The updated QueueInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + max_size=max_size, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> "QueueInstance": + """ + Asynchronous coroutine to update the QueueInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: The updated QueueInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + max_size=max_size, + ) + + @property + def members(self) -> MemberList: + """ + Access the members + """ + return self._proxy.members + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class QueueContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the QueueContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Queue resource to update. + :param sid: The Twilio-provided string that uniquely identifies the Queue resource to update + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Queues/{sid}.json".format(**self._solution) + + self._members: Optional[MemberList] = None + + def delete(self) -> bool: + """ + Deletes the QueueInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the QueueInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> QueueInstance: + """ + Fetch the QueueInstance + + + :returns: The fetched QueueInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return QueueInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> QueueInstance: + """ + Asynchronous coroutine to fetch the QueueInstance + + + :returns: The fetched QueueInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return QueueInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> QueueInstance: + """ + Update the QueueInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: The updated QueueInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "MaxSize": max_size, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return QueueInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> QueueInstance: + """ + Asynchronous coroutine to update the QueueInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: The updated QueueInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "MaxSize": max_size, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return QueueInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + @property + def members(self) -> MemberList: + """ + Access the members + """ + if self._members is None: + self._members = MemberList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._members + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class QueuePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> QueueInstance: + """ + Build an instance of QueueInstance + + :param payload: Payload response from the API + """ + return QueueInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class QueueList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the QueueList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Queue resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Queues.json".format(**self._solution) + + def create( + self, friendly_name: str, max_size: Union[int, object] = values.unset + ) -> QueueInstance: + """ + Create the QueueInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: The created QueueInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "MaxSize": max_size, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return QueueInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, friendly_name: str, max_size: Union[int, object] = values.unset + ) -> QueueInstance: + """ + Asynchronously create the QueueInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: The created QueueInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "MaxSize": max_size, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return QueueInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[QueueInstance]: + """ + Streams QueueInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[QueueInstance]: + """ + Asynchronously streams QueueInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[QueueInstance]: + """ + Lists QueueInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[QueueInstance]: + """ + Asynchronously lists QueueInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> QueuePage: + """ + Retrieve a single page of QueueInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of QueueInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return QueuePage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> QueuePage: + """ + Asynchronously retrieve a single page of QueueInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of QueueInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return QueuePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> QueuePage: + """ + Retrieve a specific page of QueueInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of QueueInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return QueuePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> QueuePage: + """ + Asynchronously retrieve a specific page of QueueInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of QueueInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return QueuePage(self._version, response, self._solution) + + def get(self, sid: str) -> QueueContext: + """ + Constructs a QueueContext + + :param sid: The Twilio-provided string that uniquely identifies the Queue resource to update + """ + return QueueContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> QueueContext: + """ + Constructs a QueueContext + + :param sid: The Twilio-provided string that uniquely identifies the Queue resource to update + """ + return QueueContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/queue/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/queue/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..890cc0e4 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/queue/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/queue/__pycache__/member.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/queue/__pycache__/member.cpython-312.pyc new file mode 100644 index 00000000..711df37b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/queue/__pycache__/member.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/queue/member.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/queue/member.py new file mode 100644 index 00000000..30ff4abb --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/queue/member.py @@ -0,0 +1,564 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MemberInstance(InstanceResource): + """ + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Member resource is associated with. + :ivar date_enqueued: The date that the member was enqueued, given in RFC 2822 format. + :ivar position: This member's current position in the queue. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar wait_time: The number of seconds the member has been in the queue. + :ivar queue_sid: The SID of the Queue the member is in. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + queue_sid: str, + call_sid: Optional[str] = None, + ): + super().__init__(version) + + self.call_sid: Optional[str] = payload.get("call_sid") + self.date_enqueued: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_enqueued") + ) + self.position: Optional[int] = deserialize.integer(payload.get("position")) + self.uri: Optional[str] = payload.get("uri") + self.wait_time: Optional[int] = deserialize.integer(payload.get("wait_time")) + self.queue_sid: Optional[str] = payload.get("queue_sid") + + self._solution = { + "account_sid": account_sid, + "queue_sid": queue_sid, + "call_sid": call_sid or self.call_sid, + } + self._context: Optional[MemberContext] = None + + @property + def _proxy(self) -> "MemberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MemberContext for this MemberInstance + """ + if self._context is None: + self._context = MemberContext( + self._version, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], + ) + return self._context + + def fetch(self) -> "MemberInstance": + """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MemberInstance": + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + return await self._proxy.fetch_async() + + def update( + self, url: str, method: Union[str, object] = values.unset + ) -> "MemberInstance": + """ + Update the MemberInstance + + :param url: The absolute URL of the Queue resource. + :param method: How to pass the update request data. Can be `GET` or `POST` and the default is `POST`. `POST` sends the data as encoded form data and `GET` sends the data as query parameters. + + :returns: The updated MemberInstance + """ + return self._proxy.update( + url=url, + method=method, + ) + + async def update_async( + self, url: str, method: Union[str, object] = values.unset + ) -> "MemberInstance": + """ + Asynchronous coroutine to update the MemberInstance + + :param url: The absolute URL of the Queue resource. + :param method: How to pass the update request data. Can be `GET` or `POST` and the default is `POST`. `POST` sends the data as encoded form data and `GET` sends the data as query parameters. + + :returns: The updated MemberInstance + """ + return await self._proxy.update_async( + url=url, + method=method, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MemberContext(InstanceContext): + + def __init__( + self, version: Version, account_sid: str, queue_sid: str, call_sid: str + ): + """ + Initialize the MemberContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Member resource(s) to update. + :param queue_sid: The SID of the Queue in which to find the members to update. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resource(s) to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "queue_sid": queue_sid, + "call_sid": call_sid, + } + self._uri = ( + "/Accounts/{account_sid}/Queues/{queue_sid}/Members/{call_sid}.json".format( + **self._solution + ) + ) + + def fetch(self) -> MemberInstance: + """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MemberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], + ) + + async def fetch_async(self) -> MemberInstance: + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MemberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], + ) + + def update( + self, url: str, method: Union[str, object] = values.unset + ) -> MemberInstance: + """ + Update the MemberInstance + + :param url: The absolute URL of the Queue resource. + :param method: How to pass the update request data. Can be `GET` or `POST` and the default is `POST`. `POST` sends the data as encoded form data and `GET` sends the data as query parameters. + + :returns: The updated MemberInstance + """ + + data = values.of( + { + "Url": url, + "Method": method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], + ) + + async def update_async( + self, url: str, method: Union[str, object] = values.unset + ) -> MemberInstance: + """ + Asynchronous coroutine to update the MemberInstance + + :param url: The absolute URL of the Queue resource. + :param method: How to pass the update request data. Can be `GET` or `POST` and the default is `POST`. `POST` sends the data as encoded form data and `GET` sends the data as query parameters. + + :returns: The updated MemberInstance + """ + + data = values.of( + { + "Url": url, + "Method": method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MemberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: + """ + Build an instance of MemberInstance + + :param payload: Payload response from the API + """ + return MemberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MemberList(ListResource): + + def __init__(self, version: Version, account_sid: str, queue_sid: str): + """ + Initialize the MemberList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Member resource(s) to read. + :param queue_sid: The SID of the Queue in which to find the members + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "queue_sid": queue_sid, + } + self._uri = "/Accounts/{account_sid}/Queues/{queue_sid}/Members.json".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MemberInstance]: + """ + Streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MemberInstance]: + """ + Asynchronously streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: + """ + Lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: + """ + Asynchronously lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: + """ + Retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: + """ + Asynchronously retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MemberPage: + """ + Retrieve a specific page of MemberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MemberPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MemberPage: + """ + Asynchronously retrieve a specific page of MemberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MemberPage(self._version, response, self._solution) + + def get(self, call_sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resource(s) to update. + """ + return MemberContext( + self._version, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=call_sid, + ) + + def __call__(self, call_sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resource(s) to update. + """ + return MemberContext( + self._version, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=call_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/__init__.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/__init__.py new file mode 100644 index 00000000..807fb3ca --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/__init__.py @@ -0,0 +1,720 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.recording.add_on_result import AddOnResultList +from twilio.rest.api.v2010.account.recording.transcription import TranscriptionList + + +class RecordingInstance(InstanceResource): + + class Source(object): + DIALVERB = "DialVerb" + CONFERENCE = "Conference" + OUTBOUNDAPI = "OutboundAPI" + TRUNKING = "Trunking" + RECORDVERB = "RecordVerb" + STARTCALLRECORDINGAPI = "StartCallRecordingAPI" + STARTCONFERENCERECORDINGAPI = "StartConferenceRecordingAPI" + + class Status(object): + IN_PROGRESS = "in-progress" + PAUSED = "paused" + STOPPED = "stopped" + PROCESSING = "processing" + COMPLETED = "completed" + ABSENT = "absent" + DELETED = "deleted" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording resource. + :ivar api_version: The API version used during the recording. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Recording resource is associated with. This will always refer to the parent leg of a two-leg call. + :ivar conference_sid: The Conference SID that identifies the conference associated with the recording, if a conference recording. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar start_time: The start time of the recording in GMT and in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar duration: The length of the recording in seconds. + :ivar sid: The unique string that that we created to identify the Recording resource. + :ivar price: The one-time cost of creating the recording in the `price_unit` currency. + :ivar price_unit: The currency used in the `price` property. Example: `USD`. + :ivar status: + :ivar channels: The number of channels in the final recording file. Can be: `1` or `2`. Default: `1`. + :ivar source: + :ivar error_code: The error code that describes why the recording is `absent`. The error code is described in our [Error Dictionary](https://www.twilio.com/docs/api/errors). This value is null if the recording `status` is not `absent`. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar encryption_details: How to decrypt the recording if it was encrypted using [Call Recording Encryption](https://www.twilio.com/docs/voice/tutorials/voice-recording-encryption) feature. + :ivar subresource_uris: A list of related resources identified by their relative URIs. + :ivar media_url: The URL of the media file associated with this recording resource. When stored externally, this is the full URL location of the media file. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.call_sid: Optional[str] = payload.get("call_sid") + self.conference_sid: Optional[str] = payload.get("conference_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.start_time: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("start_time") + ) + self.duration: Optional[str] = payload.get("duration") + self.sid: Optional[str] = payload.get("sid") + self.price: Optional[str] = payload.get("price") + self.price_unit: Optional[str] = payload.get("price_unit") + self.status: Optional["RecordingInstance.Status"] = payload.get("status") + self.channels: Optional[int] = deserialize.integer(payload.get("channels")) + self.source: Optional["RecordingInstance.Source"] = payload.get("source") + self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) + self.uri: Optional[str] = payload.get("uri") + self.encryption_details: Optional[Dict[str, object]] = payload.get( + "encryption_details" + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.media_url: Optional[str] = payload.get("media_url") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[RecordingContext] = None + + @property + def _proxy(self) -> "RecordingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RecordingContext for this RecordingInstance + """ + if self._context is None: + self._context = RecordingContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> "RecordingInstance": + """ + Fetch the RecordingInstance + + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + + :returns: The fetched RecordingInstance + """ + return self._proxy.fetch( + include_soft_deleted=include_soft_deleted, + ) + + async def fetch_async( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> "RecordingInstance": + """ + Asynchronous coroutine to fetch the RecordingInstance + + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + + :returns: The fetched RecordingInstance + """ + return await self._proxy.fetch_async( + include_soft_deleted=include_soft_deleted, + ) + + @property + def add_on_results(self) -> AddOnResultList: + """ + Access the add_on_results + """ + return self._proxy.add_on_results + + @property + def transcriptions(self) -> TranscriptionList: + """ + Access the transcriptions + """ + return self._proxy.transcriptions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RecordingContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the RecordingContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Recording resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Recordings/{sid}.json".format( + **self._solution + ) + + self._add_on_results: Optional[AddOnResultList] = None + self._transcriptions: Optional[TranscriptionList] = None + + def delete(self) -> bool: + """ + Deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> RecordingInstance: + """ + Fetch the RecordingInstance + + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + + :returns: The fetched RecordingInstance + """ + + data = values.of( + { + "IncludeSoftDeleted": serialize.boolean_to_string(include_soft_deleted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> RecordingInstance: + """ + Asynchronous coroutine to fetch the RecordingInstance + + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + + :returns: The fetched RecordingInstance + """ + + data = values.of( + { + "IncludeSoftDeleted": serialize.boolean_to_string(include_soft_deleted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + @property + def add_on_results(self) -> AddOnResultList: + """ + Access the add_on_results + """ + if self._add_on_results is None: + self._add_on_results = AddOnResultList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._add_on_results + + @property + def transcriptions(self) -> TranscriptionList: + """ + Access the transcriptions + """ + if self._transcriptions is None: + self._transcriptions = TranscriptionList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._transcriptions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RecordingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RecordingInstance: + """ + Build an instance of RecordingInstance + + :param payload: Payload response from the API + """ + return RecordingInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RecordingList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the RecordingList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Recordings.json".format(**self._solution) + + def stream( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + call_sid: Union[str, object] = values.unset, + conference_sid: Union[str, object] = values.unset, + include_soft_deleted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RecordingInstance]: + """ + Streams RecordingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param str call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param str conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param bool include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + call_sid=call_sid, + conference_sid=conference_sid, + include_soft_deleted=include_soft_deleted, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + call_sid: Union[str, object] = values.unset, + conference_sid: Union[str, object] = values.unset, + include_soft_deleted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RecordingInstance]: + """ + Asynchronously streams RecordingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param str call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param str conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param bool include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + call_sid=call_sid, + conference_sid=conference_sid, + include_soft_deleted=include_soft_deleted, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + call_sid: Union[str, object] = values.unset, + conference_sid: Union[str, object] = values.unset, + include_soft_deleted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RecordingInstance]: + """ + Lists RecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param str call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param str conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param bool include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + call_sid=call_sid, + conference_sid=conference_sid, + include_soft_deleted=include_soft_deleted, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + call_sid: Union[str, object] = values.unset, + conference_sid: Union[str, object] = values.unset, + include_soft_deleted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RecordingInstance]: + """ + Asynchronously lists RecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param str call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param str conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param bool include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + call_sid=call_sid, + conference_sid=conference_sid, + include_soft_deleted=include_soft_deleted, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + call_sid: Union[str, object] = values.unset, + conference_sid: Union[str, object] = values.unset, + include_soft_deleted: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RecordingPage: + """ + Retrieve a single page of RecordingInstance records from the API. + Request is executed immediately + + :param date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordingInstance + """ + data = values.of( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "DateCreated<": serialize.iso8601_datetime(date_created_before), + "DateCreated>": serialize.iso8601_datetime(date_created_after), + "CallSid": call_sid, + "ConferenceSid": conference_sid, + "IncludeSoftDeleted": serialize.boolean_to_string(include_soft_deleted), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordingPage(self._version, response, self._solution) + + async def page_async( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + call_sid: Union[str, object] = values.unset, + conference_sid: Union[str, object] = values.unset, + include_soft_deleted: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RecordingPage: + """ + Asynchronously retrieve a single page of RecordingInstance records from the API. + Request is executed immediately + + :param date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordingInstance + """ + data = values.of( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "DateCreated<": serialize.iso8601_datetime(date_created_before), + "DateCreated>": serialize.iso8601_datetime(date_created_after), + "CallSid": call_sid, + "ConferenceSid": conference_sid, + "IncludeSoftDeleted": serialize.boolean_to_string(include_soft_deleted), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RecordingPage: + """ + Retrieve a specific page of RecordingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RecordingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RecordingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RecordingPage: + """ + Asynchronously retrieve a specific page of RecordingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RecordingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RecordingPage(self._version, response, self._solution) + + def get(self, sid: str) -> RecordingContext: + """ + Constructs a RecordingContext + + :param sid: The Twilio-provided string that uniquely identifies the Recording resource to fetch. + """ + return RecordingContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RecordingContext: + """ + Constructs a RecordingContext + + :param sid: The Twilio-provided string that uniquely identifies the Recording resource to fetch. + """ + return RecordingContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..42c75009 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/__pycache__/transcription.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/__pycache__/transcription.cpython-312.pyc new file mode 100644 index 00000000..01b512a1 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/__pycache__/transcription.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/add_on_result/__init__.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/add_on_result/__init__.py new file mode 100644 index 00000000..95296f3c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/add_on_result/__init__.py @@ -0,0 +1,553 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.recording.add_on_result.payload import PayloadList + + +class AddOnResultInstance(InstanceResource): + + class Status(object): + CANCELED = "canceled" + COMPLETED = "completed" + DELETED = "deleted" + FAILED = "failed" + IN_PROGRESS = "in-progress" + INIT = "init" + PROCESSING = "processing" + QUEUED = "queued" + + """ + :ivar sid: The unique string that that we created to identify the Recording AddOnResult resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording AddOnResult resource. + :ivar status: + :ivar add_on_sid: The SID of the Add-on to which the result belongs. + :ivar add_on_configuration_sid: The SID of the Add-on configuration. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_completed: The date and time in GMT that the result was completed specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar reference_sid: The SID of the recording to which the AddOnResult resource belongs. + :ivar subresource_uris: A list of related resources identified by their relative URIs. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + reference_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.status: Optional["AddOnResultInstance.Status"] = payload.get("status") + self.add_on_sid: Optional[str] = payload.get("add_on_sid") + self.add_on_configuration_sid: Optional[str] = payload.get( + "add_on_configuration_sid" + ) + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.date_completed: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_completed") + ) + self.reference_sid: Optional[str] = payload.get("reference_sid") + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + + self._solution = { + "account_sid": account_sid, + "reference_sid": reference_sid, + "sid": sid or self.sid, + } + self._context: Optional[AddOnResultContext] = None + + @property + def _proxy(self) -> "AddOnResultContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AddOnResultContext for this AddOnResultInstance + """ + if self._context is None: + self._context = AddOnResultContext( + self._version, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AddOnResultInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AddOnResultInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AddOnResultInstance": + """ + Fetch the AddOnResultInstance + + + :returns: The fetched AddOnResultInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AddOnResultInstance": + """ + Asynchronous coroutine to fetch the AddOnResultInstance + + + :returns: The fetched AddOnResultInstance + """ + return await self._proxy.fetch_async() + + @property + def payloads(self) -> PayloadList: + """ + Access the payloads + """ + return self._proxy.payloads + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AddOnResultContext(InstanceContext): + + def __init__( + self, version: Version, account_sid: str, reference_sid: str, sid: str + ): + """ + Initialize the AddOnResultContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording AddOnResult resource to fetch. + :param reference_sid: The SID of the recording to which the result to fetch belongs. + :param sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "reference_sid": reference_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Recordings/{reference_sid}/AddOnResults/{sid}.json".format( + **self._solution + ) + + self._payloads: Optional[PayloadList] = None + + def delete(self) -> bool: + """ + Deletes the AddOnResultInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AddOnResultInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AddOnResultInstance: + """ + Fetch the AddOnResultInstance + + + :returns: The fetched AddOnResultInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AddOnResultInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AddOnResultInstance: + """ + Asynchronous coroutine to fetch the AddOnResultInstance + + + :returns: The fetched AddOnResultInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AddOnResultInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + sid=self._solution["sid"], + ) + + @property + def payloads(self) -> PayloadList: + """ + Access the payloads + """ + if self._payloads is None: + self._payloads = PayloadList( + self._version, + self._solution["account_sid"], + self._solution["reference_sid"], + self._solution["sid"], + ) + return self._payloads + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AddOnResultPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AddOnResultInstance: + """ + Build an instance of AddOnResultInstance + + :param payload: Payload response from the API + """ + return AddOnResultInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AddOnResultList(ListResource): + + def __init__(self, version: Version, account_sid: str, reference_sid: str): + """ + Initialize the AddOnResultList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording AddOnResult resources to read. + :param reference_sid: The SID of the recording to which the result to read belongs. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "reference_sid": reference_sid, + } + self._uri = "/Accounts/{account_sid}/Recordings/{reference_sid}/AddOnResults.json".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AddOnResultInstance]: + """ + Streams AddOnResultInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AddOnResultInstance]: + """ + Asynchronously streams AddOnResultInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AddOnResultInstance]: + """ + Lists AddOnResultInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AddOnResultInstance]: + """ + Asynchronously lists AddOnResultInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AddOnResultPage: + """ + Retrieve a single page of AddOnResultInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AddOnResultInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AddOnResultPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AddOnResultPage: + """ + Asynchronously retrieve a single page of AddOnResultInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AddOnResultInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AddOnResultPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AddOnResultPage: + """ + Retrieve a specific page of AddOnResultInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AddOnResultInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AddOnResultPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AddOnResultPage: + """ + Asynchronously retrieve a specific page of AddOnResultInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AddOnResultInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AddOnResultPage(self._version, response, self._solution) + + def get(self, sid: str) -> AddOnResultContext: + """ + Constructs a AddOnResultContext + + :param sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult resource to fetch. + """ + return AddOnResultContext( + self._version, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> AddOnResultContext: + """ + Constructs a AddOnResultContext + + :param sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult resource to fetch. + """ + return AddOnResultContext( + self._version, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/add_on_result/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/add_on_result/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..623ba5fe Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/add_on_result/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/add_on_result/payload/__init__.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/add_on_result/payload/__init__.py new file mode 100644 index 00000000..08e6ea21 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/add_on_result/payload/__init__.py @@ -0,0 +1,566 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.recording.add_on_result.payload.data import DataList + + +class PayloadInstance(InstanceResource): + """ + :ivar sid: The unique string that that we created to identify the Recording AddOnResult Payload resource. + :ivar add_on_result_sid: The SID of the AddOnResult to which the payload belongs. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording AddOnResult Payload resource. + :ivar label: The string provided by the vendor that describes the payload. + :ivar add_on_sid: The SID of the Add-on to which the result belongs. + :ivar add_on_configuration_sid: The SID of the Add-on configuration. + :ivar content_type: The MIME type of the payload. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar reference_sid: The SID of the recording to which the AddOnResult resource that contains the payload belongs. + :ivar subresource_uris: A list of related resources identified by their relative URIs. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + reference_sid: str, + add_on_result_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.add_on_result_sid: Optional[str] = payload.get("add_on_result_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.label: Optional[str] = payload.get("label") + self.add_on_sid: Optional[str] = payload.get("add_on_sid") + self.add_on_configuration_sid: Optional[str] = payload.get( + "add_on_configuration_sid" + ) + self.content_type: Optional[str] = payload.get("content_type") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.reference_sid: Optional[str] = payload.get("reference_sid") + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + + self._solution = { + "account_sid": account_sid, + "reference_sid": reference_sid, + "add_on_result_sid": add_on_result_sid, + "sid": sid or self.sid, + } + self._context: Optional[PayloadContext] = None + + @property + def _proxy(self) -> "PayloadContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PayloadContext for this PayloadInstance + """ + if self._context is None: + self._context = PayloadContext( + self._version, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the PayloadInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PayloadInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "PayloadInstance": + """ + Fetch the PayloadInstance + + + :returns: The fetched PayloadInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PayloadInstance": + """ + Asynchronous coroutine to fetch the PayloadInstance + + + :returns: The fetched PayloadInstance + """ + return await self._proxy.fetch_async() + + @property + def data(self) -> DataList: + """ + Access the data + """ + return self._proxy.data + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PayloadContext(InstanceContext): + + def __init__( + self, + version: Version, + account_sid: str, + reference_sid: str, + add_on_result_sid: str, + sid: str, + ): + """ + Initialize the PayloadContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording AddOnResult Payload resource to fetch. + :param reference_sid: The SID of the recording to which the AddOnResult resource that contains the payload to fetch belongs. + :param add_on_result_sid: The SID of the AddOnResult to which the payload to fetch belongs. + :param sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult Payload resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "reference_sid": reference_sid, + "add_on_result_sid": add_on_result_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Recordings/{reference_sid}/AddOnResults/{add_on_result_sid}/Payloads/{sid}.json".format( + **self._solution + ) + + self._data: Optional[DataList] = None + + def delete(self) -> bool: + """ + Deletes the PayloadInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PayloadInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> PayloadInstance: + """ + Fetch the PayloadInstance + + + :returns: The fetched PayloadInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PayloadInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> PayloadInstance: + """ + Asynchronous coroutine to fetch the PayloadInstance + + + :returns: The fetched PayloadInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PayloadInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + sid=self._solution["sid"], + ) + + @property + def data(self) -> DataList: + """ + Access the data + """ + if self._data is None: + self._data = DataList( + self._version, + self._solution["account_sid"], + self._solution["reference_sid"], + self._solution["add_on_result_sid"], + self._solution["sid"], + ) + return self._data + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PayloadPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PayloadInstance: + """ + Build an instance of PayloadInstance + + :param payload: Payload response from the API + """ + return PayloadInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class PayloadList(ListResource): + + def __init__( + self, + version: Version, + account_sid: str, + reference_sid: str, + add_on_result_sid: str, + ): + """ + Initialize the PayloadList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording AddOnResult Payload resources to read. + :param reference_sid: The SID of the recording to which the AddOnResult resource that contains the payloads to read belongs. + :param add_on_result_sid: The SID of the AddOnResult to which the payloads to read belongs. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "reference_sid": reference_sid, + "add_on_result_sid": add_on_result_sid, + } + self._uri = "/Accounts/{account_sid}/Recordings/{reference_sid}/AddOnResults/{add_on_result_sid}/Payloads.json".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PayloadInstance]: + """ + Streams PayloadInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PayloadInstance]: + """ + Asynchronously streams PayloadInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PayloadInstance]: + """ + Lists PayloadInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PayloadInstance]: + """ + Asynchronously lists PayloadInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PayloadPage: + """ + Retrieve a single page of PayloadInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PayloadInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PayloadPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PayloadPage: + """ + Asynchronously retrieve a single page of PayloadInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PayloadInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PayloadPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> PayloadPage: + """ + Retrieve a specific page of PayloadInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PayloadInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PayloadPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> PayloadPage: + """ + Asynchronously retrieve a specific page of PayloadInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PayloadInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PayloadPage(self._version, response, self._solution) + + def get(self, sid: str) -> PayloadContext: + """ + Constructs a PayloadContext + + :param sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult Payload resource to fetch. + """ + return PayloadContext( + self._version, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> PayloadContext: + """ + Constructs a PayloadContext + + :param sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult Payload resource to fetch. + """ + return PayloadContext( + self._version, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/add_on_result/payload/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/add_on_result/payload/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..32f9bb73 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/add_on_result/payload/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/add_on_result/payload/__pycache__/data.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/add_on_result/payload/__pycache__/data.cpython-312.pyc new file mode 100644 index 00000000..f119675a Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/add_on_result/payload/__pycache__/data.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/add_on_result/payload/data.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/add_on_result/payload/data.py new file mode 100644 index 00000000..48567bad --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/add_on_result/payload/data.py @@ -0,0 +1,247 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class DataInstance(InstanceResource): + """ + :ivar redirect_to: The URL to redirect to to get the data returned by the AddOn that was previously stored. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + reference_sid: str, + add_on_result_sid: str, + payload_sid: str, + ): + super().__init__(version) + + self.redirect_to: Optional[str] = payload.get("redirect_to") + + self._solution = { + "account_sid": account_sid, + "reference_sid": reference_sid, + "add_on_result_sid": add_on_result_sid, + "payload_sid": payload_sid, + } + self._context: Optional[DataContext] = None + + @property + def _proxy(self) -> "DataContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DataContext for this DataInstance + """ + if self._context is None: + self._context = DataContext( + self._version, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + payload_sid=self._solution["payload_sid"], + ) + return self._context + + def fetch(self) -> "DataInstance": + """ + Fetch the DataInstance + + + :returns: The fetched DataInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DataInstance": + """ + Asynchronous coroutine to fetch the DataInstance + + + :returns: The fetched DataInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DataContext(InstanceContext): + + def __init__( + self, + version: Version, + account_sid: str, + reference_sid: str, + add_on_result_sid: str, + payload_sid: str, + ): + """ + Initialize the DataContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording AddOnResult Payload resource to fetch. + :param reference_sid: The SID of the recording to which the AddOnResult resource that contains the payload to fetch belongs. + :param add_on_result_sid: The SID of the AddOnResult to which the payload to fetch belongs. + :param payload_sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult Payload resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "reference_sid": reference_sid, + "add_on_result_sid": add_on_result_sid, + "payload_sid": payload_sid, + } + self._uri = "/Accounts/{account_sid}/Recordings/{reference_sid}/AddOnResults/{add_on_result_sid}/Payloads/{payload_sid}/Data.json".format( + **self._solution + ) + + def fetch(self) -> DataInstance: + """ + Fetch the DataInstance + + + :returns: The fetched DataInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DataInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + payload_sid=self._solution["payload_sid"], + ) + + async def fetch_async(self) -> DataInstance: + """ + Asynchronous coroutine to fetch the DataInstance + + + :returns: The fetched DataInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DataInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + payload_sid=self._solution["payload_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DataList(ListResource): + + def __init__( + self, + version: Version, + account_sid: str, + reference_sid: str, + add_on_result_sid: str, + payload_sid: str, + ): + """ + Initialize the DataList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording AddOnResult Payload resource to fetch. + :param reference_sid: The SID of the recording to which the AddOnResult resource that contains the payload to fetch belongs. + :param add_on_result_sid: The SID of the AddOnResult to which the payload to fetch belongs. + :param payload_sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult Payload resource to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "reference_sid": reference_sid, + "add_on_result_sid": add_on_result_sid, + "payload_sid": payload_sid, + } + + def get(self) -> DataContext: + """ + Constructs a DataContext + + """ + return DataContext( + self._version, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + payload_sid=self._solution["payload_sid"], + ) + + def __call__(self) -> DataContext: + """ + Constructs a DataContext + + """ + return DataContext( + self._version, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + payload_sid=self._solution["payload_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/transcription.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/transcription.py new file mode 100644 index 00000000..472f5b2b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/recording/transcription.py @@ -0,0 +1,524 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TranscriptionInstance(InstanceResource): + + class Status(object): + IN_PROGRESS = "in-progress" + COMPLETED = "completed" + FAILED = "failed" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Transcription resource. + :ivar api_version: The API version used to create the transcription. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar duration: The duration of the transcribed audio in seconds. + :ivar price: The charge for the transcript in the currency associated with the account. This value is populated after the transcript is complete so it may not be available immediately. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar recording_sid: The SID of the [Recording](https://www.twilio.com/docs/voice/api/recording) from which the transcription was created. + :ivar sid: The unique string that that we created to identify the Transcription resource. + :ivar status: + :ivar transcription_text: The text content of the transcription. + :ivar type: The transcription type. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + recording_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.duration: Optional[str] = payload.get("duration") + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.recording_sid: Optional[str] = payload.get("recording_sid") + self.sid: Optional[str] = payload.get("sid") + self.status: Optional["TranscriptionInstance.Status"] = payload.get("status") + self.transcription_text: Optional[str] = payload.get("transcription_text") + self.type: Optional[str] = payload.get("type") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "recording_sid": recording_sid, + "sid": sid or self.sid, + } + self._context: Optional[TranscriptionContext] = None + + @property + def _proxy(self) -> "TranscriptionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TranscriptionContext for this TranscriptionInstance + """ + if self._context is None: + self._context = TranscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + recording_sid=self._solution["recording_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TranscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TranscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "TranscriptionInstance": + """ + Fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TranscriptionInstance": + """ + Asynchronous coroutine to fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TranscriptionContext(InstanceContext): + + def __init__( + self, version: Version, account_sid: str, recording_sid: str, sid: str + ): + """ + Initialize the TranscriptionContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Transcription resource to fetch. + :param recording_sid: The SID of the [Recording](https://www.twilio.com/docs/voice/api/recording) that created the transcription to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Transcription resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "recording_sid": recording_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Recordings/{recording_sid}/Transcriptions/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the TranscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TranscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TranscriptionInstance: + """ + Fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + recording_sid=self._solution["recording_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TranscriptionInstance: + """ + Asynchronous coroutine to fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + recording_sid=self._solution["recording_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TranscriptionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TranscriptionInstance: + """ + Build an instance of TranscriptionInstance + + :param payload: Payload response from the API + """ + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + recording_sid=self._solution["recording_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TranscriptionList(ListResource): + + def __init__(self, version: Version, account_sid: str, recording_sid: str): + """ + Initialize the TranscriptionList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Transcription resources to read. + :param recording_sid: The SID of the [Recording](https://www.twilio.com/docs/voice/api/recording) that created the transcriptions to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "recording_sid": recording_sid, + } + self._uri = "/Accounts/{account_sid}/Recordings/{recording_sid}/Transcriptions.json".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TranscriptionInstance]: + """ + Streams TranscriptionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TranscriptionInstance]: + """ + Asynchronously streams TranscriptionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TranscriptionInstance]: + """ + Lists TranscriptionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TranscriptionInstance]: + """ + Asynchronously lists TranscriptionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TranscriptionPage: + """ + Retrieve a single page of TranscriptionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TranscriptionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TranscriptionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TranscriptionPage: + """ + Asynchronously retrieve a single page of TranscriptionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TranscriptionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TranscriptionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> TranscriptionPage: + """ + Retrieve a specific page of TranscriptionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TranscriptionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TranscriptionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> TranscriptionPage: + """ + Asynchronously retrieve a specific page of TranscriptionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TranscriptionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TranscriptionPage(self._version, response, self._solution) + + def get(self, sid: str) -> TranscriptionContext: + """ + Constructs a TranscriptionContext + + :param sid: The Twilio-provided string that uniquely identifies the Transcription resource to fetch. + """ + return TranscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + recording_sid=self._solution["recording_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> TranscriptionContext: + """ + Constructs a TranscriptionContext + + :param sid: The Twilio-provided string that uniquely identifies the Transcription resource to fetch. + """ + return TranscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + recording_sid=self._solution["recording_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/short_code.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/short_code.py new file mode 100644 index 00000000..eae35c4a --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/short_code.py @@ -0,0 +1,650 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ShortCodeInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this ShortCode resource. + :ivar api_version: The API version used to start a new TwiML session when an SMS message is sent to this short code. + :ivar date_created: The date and time in GMT that this resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: A string that you assigned to describe this resource. By default, the `FriendlyName` is the short code. + :ivar short_code: The short code. e.g., 894546. + :ivar sid: The unique string that that we created to identify this ShortCode resource. + :ivar sms_fallback_method: The HTTP method we use to call the `sms_fallback_url`. Can be: `GET` or `POST`. + :ivar sms_fallback_url: The URL that we call if an error occurs while retrieving or executing the TwiML from `sms_url`. + :ivar sms_method: The HTTP method we use to call the `sms_url`. Can be: `GET` or `POST`. + :ivar sms_url: The URL we call when receiving an incoming SMS message to this short code. + :ivar uri: The URI of this resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.short_code: Optional[str] = payload.get("short_code") + self.sid: Optional[str] = payload.get("sid") + self.sms_fallback_method: Optional[str] = payload.get("sms_fallback_method") + self.sms_fallback_url: Optional[str] = payload.get("sms_fallback_url") + self.sms_method: Optional[str] = payload.get("sms_method") + self.sms_url: Optional[str] = payload.get("sms_url") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[ShortCodeContext] = None + + @property + def _proxy(self) -> "ShortCodeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ShortCodeContext for this ShortCodeInstance + """ + if self._context is None: + self._context = ShortCodeContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "ShortCodeInstance": + """ + Fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ShortCodeInstance": + """ + Asynchronous coroutine to fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + ) -> "ShortCodeInstance": + """ + Update the ShortCodeInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. By default, the `FriendlyName` is the short code. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. + :param sms_url: The URL we should call when receiving an incoming SMS message to this short code. + :param sms_method: The HTTP method we should use when calling the `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call if an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method that we should use to call the `sms_fallback_url`. Can be: `GET` or `POST`. + + :returns: The updated ShortCodeInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + api_version=api_version, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + ) -> "ShortCodeInstance": + """ + Asynchronous coroutine to update the ShortCodeInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. By default, the `FriendlyName` is the short code. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. + :param sms_url: The URL we should call when receiving an incoming SMS message to this short code. + :param sms_method: The HTTP method we should use when calling the `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call if an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method that we should use to call the `sms_fallback_url`. Can be: `GET` or `POST`. + + :returns: The updated ShortCodeInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + api_version=api_version, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ShortCodeContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the ShortCodeContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ShortCode resource(s) to update. + :param sid: The Twilio-provided string that uniquely identifies the ShortCode resource to update + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SMS/ShortCodes/{sid}.json".format( + **self._solution + ) + + def fetch(self) -> ShortCodeInstance: + """ + Fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ShortCodeInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ShortCodeInstance: + """ + Asynchronous coroutine to fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ShortCodeInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + ) -> ShortCodeInstance: + """ + Update the ShortCodeInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. By default, the `FriendlyName` is the short code. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. + :param sms_url: The URL we should call when receiving an incoming SMS message to this short code. + :param sms_method: The HTTP method we should use when calling the `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call if an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method that we should use to call the `sms_fallback_url`. Can be: `GET` or `POST`. + + :returns: The updated ShortCodeInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ApiVersion": api_version, + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsFallbackMethod": sms_fallback_method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ShortCodeInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + ) -> ShortCodeInstance: + """ + Asynchronous coroutine to update the ShortCodeInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. By default, the `FriendlyName` is the short code. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. + :param sms_url: The URL we should call when receiving an incoming SMS message to this short code. + :param sms_method: The HTTP method we should use when calling the `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call if an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method that we should use to call the `sms_fallback_url`. Can be: `GET` or `POST`. + + :returns: The updated ShortCodeInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ApiVersion": api_version, + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsFallbackMethod": sms_fallback_method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ShortCodeInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ShortCodePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ShortCodeInstance: + """ + Build an instance of ShortCodeInstance + + :param payload: Payload response from the API + """ + return ShortCodeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ShortCodeList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the ShortCodeList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ShortCode resource(s) to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/SMS/ShortCodes.json".format( + **self._solution + ) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + short_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ShortCodeInstance]: + """ + Streams ShortCodeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The string that identifies the ShortCode resources to read. + :param str short_code: Only show the ShortCode resources that match this pattern. You can specify partial numbers and use '*' as a wildcard for any digit. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + friendly_name=friendly_name, + short_code=short_code, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + short_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ShortCodeInstance]: + """ + Asynchronously streams ShortCodeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The string that identifies the ShortCode resources to read. + :param str short_code: Only show the ShortCode resources that match this pattern. You can specify partial numbers and use '*' as a wildcard for any digit. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, + short_code=short_code, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + short_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ShortCodeInstance]: + """ + Lists ShortCodeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The string that identifies the ShortCode resources to read. + :param str short_code: Only show the ShortCode resources that match this pattern. You can specify partial numbers and use '*' as a wildcard for any digit. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + friendly_name=friendly_name, + short_code=short_code, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + short_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ShortCodeInstance]: + """ + Asynchronously lists ShortCodeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The string that identifies the ShortCode resources to read. + :param str short_code: Only show the ShortCode resources that match this pattern. You can specify partial numbers and use '*' as a wildcard for any digit. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + short_code=short_code, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + friendly_name: Union[str, object] = values.unset, + short_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ShortCodePage: + """ + Retrieve a single page of ShortCodeInstance records from the API. + Request is executed immediately + + :param friendly_name: The string that identifies the ShortCode resources to read. + :param short_code: Only show the ShortCode resources that match this pattern. You can specify partial numbers and use '*' as a wildcard for any digit. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ShortCodeInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "ShortCode": short_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ShortCodePage(self._version, response, self._solution) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + short_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ShortCodePage: + """ + Asynchronously retrieve a single page of ShortCodeInstance records from the API. + Request is executed immediately + + :param friendly_name: The string that identifies the ShortCode resources to read. + :param short_code: Only show the ShortCode resources that match this pattern. You can specify partial numbers and use '*' as a wildcard for any digit. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ShortCodeInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "ShortCode": short_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ShortCodePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ShortCodePage: + """ + Retrieve a specific page of ShortCodeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ShortCodeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ShortCodePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ShortCodePage: + """ + Asynchronously retrieve a specific page of ShortCodeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ShortCodeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ShortCodePage(self._version, response, self._solution) + + def get(self, sid: str) -> ShortCodeContext: + """ + Constructs a ShortCodeContext + + :param sid: The Twilio-provided string that uniquely identifies the ShortCode resource to update + """ + return ShortCodeContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ShortCodeContext: + """ + Constructs a ShortCodeContext + + :param sid: The Twilio-provided string that uniquely identifies the ShortCode resource to update + """ + return ShortCodeContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/signing_key.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/signing_key.py new file mode 100644 index 00000000..8e33f218 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/signing_key.py @@ -0,0 +1,572 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SigningKeyInstance(InstanceResource): + """ + :ivar sid: + :ivar friendly_name: + :ivar date_created: + :ivar date_updated: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[SigningKeyContext] = None + + @property + def _proxy(self) -> "SigningKeyContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SigningKeyContext for this SigningKeyInstance + """ + if self._context is None: + self._context = SigningKeyContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SigningKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SigningKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SigningKeyInstance": + """ + Fetch the SigningKeyInstance + + + :returns: The fetched SigningKeyInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SigningKeyInstance": + """ + Asynchronous coroutine to fetch the SigningKeyInstance + + + :returns: The fetched SigningKeyInstance + """ + return await self._proxy.fetch_async() + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> "SigningKeyInstance": + """ + Update the SigningKeyInstance + + :param friendly_name: + + :returns: The updated SigningKeyInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "SigningKeyInstance": + """ + Asynchronous coroutine to update the SigningKeyInstance + + :param friendly_name: + + :returns: The updated SigningKeyInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SigningKeyContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the SigningKeyContext + + :param version: Version that contains the resource + :param account_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SigningKeys/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the SigningKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SigningKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SigningKeyInstance: + """ + Fetch the SigningKeyInstance + + + :returns: The fetched SigningKeyInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SigningKeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SigningKeyInstance: + """ + Asynchronous coroutine to fetch the SigningKeyInstance + + + :returns: The fetched SigningKeyInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SigningKeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> SigningKeyInstance: + """ + Update the SigningKeyInstance + + :param friendly_name: + + :returns: The updated SigningKeyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SigningKeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> SigningKeyInstance: + """ + Asynchronous coroutine to update the SigningKeyInstance + + :param friendly_name: + + :returns: The updated SigningKeyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SigningKeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SigningKeyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SigningKeyInstance: + """ + Build an instance of SigningKeyInstance + + :param payload: Payload response from the API + """ + return SigningKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SigningKeyList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the SigningKeyList + + :param version: Version that contains the resource + :param account_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/SigningKeys.json".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SigningKeyInstance]: + """ + Streams SigningKeyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SigningKeyInstance]: + """ + Asynchronously streams SigningKeyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SigningKeyInstance]: + """ + Lists SigningKeyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SigningKeyInstance]: + """ + Asynchronously lists SigningKeyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SigningKeyPage: + """ + Retrieve a single page of SigningKeyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SigningKeyInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SigningKeyPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SigningKeyPage: + """ + Asynchronously retrieve a single page of SigningKeyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SigningKeyInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SigningKeyPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SigningKeyPage: + """ + Retrieve a specific page of SigningKeyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SigningKeyInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SigningKeyPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SigningKeyPage: + """ + Asynchronously retrieve a specific page of SigningKeyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SigningKeyInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SigningKeyPage(self._version, response, self._solution) + + def get(self, sid: str) -> SigningKeyContext: + """ + Constructs a SigningKeyContext + + :param sid: + """ + return SigningKeyContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> SigningKeyContext: + """ + Constructs a SigningKeyContext + + :param sid: + """ + return SigningKeyContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/__init__.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/__init__.py new file mode 100644 index 00000000..12c695ff --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/__init__.py @@ -0,0 +1,89 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.api.v2010.account.sip.credential_list import CredentialListList +from twilio.rest.api.v2010.account.sip.domain import DomainList +from twilio.rest.api.v2010.account.sip.ip_access_control_list import ( + IpAccessControlListList, +) + + +class SipList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the SipList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the SipDomain resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/SIP.json".format(**self._solution) + + self._credential_lists: Optional[CredentialListList] = None + self._domains: Optional[DomainList] = None + self._ip_access_control_lists: Optional[IpAccessControlListList] = None + + @property + def credential_lists(self) -> CredentialListList: + """ + Access the credential_lists + """ + if self._credential_lists is None: + self._credential_lists = CredentialListList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._credential_lists + + @property + def domains(self) -> DomainList: + """ + Access the domains + """ + if self._domains is None: + self._domains = DomainList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._domains + + @property + def ip_access_control_lists(self) -> IpAccessControlListList: + """ + Access the ip_access_control_lists + """ + if self._ip_access_control_lists is None: + self._ip_access_control_lists = IpAccessControlListList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._ip_access_control_lists + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..7d5d388b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/credential_list/__init__.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/credential_list/__init__.py new file mode 100644 index 00000000..d1be747b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/credential_list/__init__.py @@ -0,0 +1,653 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.sip.credential_list.credential import CredentialList + + +class CredentialListInstance(InstanceResource): + """ + :ivar account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) that owns this resource. + :ivar date_created: The date that this resource was created, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar date_updated: The date that this resource was last updated, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar friendly_name: A human readable descriptive text that describes the CredentialList, up to 64 characters long. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar subresource_uris: A list of credentials associated with this credential list. + :ivar uri: The URI for this resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.sid: Optional[str] = payload.get("sid") + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[CredentialListContext] = None + + @property + def _proxy(self) -> "CredentialListContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CredentialListContext for this CredentialListInstance + """ + if self._context is None: + self._context = CredentialListContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CredentialListInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialListInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CredentialListInstance": + """ + Fetch the CredentialListInstance + + + :returns: The fetched CredentialListInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CredentialListInstance": + """ + Asynchronous coroutine to fetch the CredentialListInstance + + + :returns: The fetched CredentialListInstance + """ + return await self._proxy.fetch_async() + + def update(self, friendly_name: str) -> "CredentialListInstance": + """ + Update the CredentialListInstance + + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. + + :returns: The updated CredentialListInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async(self, friendly_name: str) -> "CredentialListInstance": + """ + Asynchronous coroutine to update the CredentialListInstance + + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. + + :returns: The updated CredentialListInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + @property + def credentials(self) -> CredentialList: + """ + Access the credentials + """ + return self._proxy.credentials + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialListContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the CredentialListContext + + :param version: Version that contains the resource + :param account_sid: The unique id of the Account that is responsible for this resource. + :param sid: The credential list Sid that uniquely identifies this resource + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SIP/CredentialLists/{sid}.json".format( + **self._solution + ) + + self._credentials: Optional[CredentialList] = None + + def delete(self) -> bool: + """ + Deletes the CredentialListInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialListInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialListInstance: + """ + Fetch the CredentialListInstance + + + :returns: The fetched CredentialListInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CredentialListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialListInstance: + """ + Asynchronous coroutine to fetch the CredentialListInstance + + + :returns: The fetched CredentialListInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CredentialListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update(self, friendly_name: str) -> CredentialListInstance: + """ + Update the CredentialListInstance + + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. + + :returns: The updated CredentialListInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, friendly_name: str) -> CredentialListInstance: + """ + Asynchronous coroutine to update the CredentialListInstance + + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. + + :returns: The updated CredentialListInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + @property + def credentials(self) -> CredentialList: + """ + Access the credentials + """ + if self._credentials is None: + self._credentials = CredentialList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._credentials + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialListPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialListInstance: + """ + Build an instance of CredentialListInstance + + :param payload: Payload response from the API + """ + return CredentialListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CredentialListList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the CredentialListList + + :param version: Version that contains the resource + :param account_sid: The unique id of the Account that is responsible for this resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/CredentialLists.json".format( + **self._solution + ) + + def create(self, friendly_name: str) -> CredentialListInstance: + """ + Create the CredentialListInstance + + :param friendly_name: A human readable descriptive text that describes the CredentialList, up to 64 characters long. + + :returns: The created CredentialListInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async(self, friendly_name: str) -> CredentialListInstance: + """ + Asynchronously create the CredentialListInstance + + :param friendly_name: A human readable descriptive text that describes the CredentialList, up to 64 characters long. + + :returns: The created CredentialListInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialListInstance]: + """ + Streams CredentialListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialListInstance]: + """ + Asynchronously streams CredentialListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialListInstance]: + """ + Lists CredentialListInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialListInstance]: + """ + Asynchronously lists CredentialListInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialListPage: + """ + Retrieve a single page of CredentialListInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialListInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialListPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialListPage: + """ + Asynchronously retrieve a single page of CredentialListInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialListInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialListPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> CredentialListPage: + """ + Retrieve a specific page of CredentialListInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialListInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialListPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> CredentialListPage: + """ + Asynchronously retrieve a specific page of CredentialListInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialListInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialListPage(self._version, response, self._solution) + + def get(self, sid: str) -> CredentialListContext: + """ + Constructs a CredentialListContext + + :param sid: The credential list Sid that uniquely identifies this resource + """ + return CredentialListContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> CredentialListContext: + """ + Constructs a CredentialListContext + + :param sid: The credential list Sid that uniquely identifies this resource + """ + return CredentialListContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/credential_list/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/credential_list/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..d0cb4402 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/credential_list/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/credential_list/__pycache__/credential.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/credential_list/__pycache__/credential.cpython-312.pyc new file mode 100644 index 00000000..4c567212 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/credential_list/__pycache__/credential.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/credential_list/credential.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/credential_list/credential.py new file mode 100644 index 00000000..9c52a110 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/credential_list/credential.py @@ -0,0 +1,666 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CredentialInstance(InstanceResource): + """ + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar account_sid: The unique id of the Account that is responsible for this resource. + :ivar credential_list_sid: The unique id that identifies the credential list that includes this credential. + :ivar username: The username for this credential. + :ivar date_created: The date that this resource was created, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar date_updated: The date that this resource was last updated, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar uri: The URI for this resource, relative to `https://api.twilio.com` + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + credential_list_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.credential_list_sid: Optional[str] = payload.get("credential_list_sid") + self.username: Optional[str] = payload.get("username") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "credential_list_sid": credential_list_sid, + "sid": sid or self.sid, + } + self._context: Optional[CredentialContext] = None + + @property + def _proxy(self) -> "CredentialContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CredentialInstance": + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CredentialInstance": + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return await self._proxy.fetch_async() + + def update( + self, password: Union[str, object] = values.unset + ) -> "CredentialInstance": + """ + Update the CredentialInstance + + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: The updated CredentialInstance + """ + return self._proxy.update( + password=password, + ) + + async def update_async( + self, password: Union[str, object] = values.unset + ) -> "CredentialInstance": + """ + Asynchronous coroutine to update the CredentialInstance + + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: The updated CredentialInstance + """ + return await self._proxy.update_async( + password=password, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialContext(InstanceContext): + + def __init__( + self, version: Version, account_sid: str, credential_list_sid: str, sid: str + ): + """ + Initialize the CredentialContext + + :param version: Version that contains the resource + :param account_sid: The unique id of the Account that is responsible for this resource. + :param credential_list_sid: The unique id that identifies the credential list that includes this credential. + :param sid: The unique id that identifies the resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "credential_list_sid": credential_list_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SIP/CredentialLists/{credential_list_sid}/Credentials/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialInstance: + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=self._solution["sid"], + ) + + def update(self, password: Union[str, object] = values.unset) -> CredentialInstance: + """ + Update the CredentialInstance + + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "Password": password, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, password: Union[str, object] = values.unset + ) -> CredentialInstance: + """ + Asynchronous coroutine to update the CredentialInstance + + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "Password": password, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: + """ + Build an instance of CredentialInstance + + :param payload: Payload response from the API + """ + return CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CredentialList(ListResource): + + def __init__(self, version: Version, account_sid: str, credential_list_sid: str): + """ + Initialize the CredentialList + + :param version: Version that contains the resource + :param account_sid: The unique id of the Account that is responsible for this resource. + :param credential_list_sid: The unique id that identifies the credential list that contains the desired credentials. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "credential_list_sid": credential_list_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/CredentialLists/{credential_list_sid}/Credentials.json".format( + **self._solution + ) + + def create(self, username: str, password: str) -> CredentialInstance: + """ + Create the CredentialInstance + + :param username: The username that will be passed when authenticating SIP requests. The username should be sent in response to Twilio's challenge of the initial INVITE. It can be up to 32 characters long. + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Username": username, + "Password": password, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + ) + + async def create_async(self, username: str, password: str) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param username: The username that will be passed when authenticating SIP requests. The username should be sent in response to Twilio's challenge of the initial INVITE. It can be up to 32 characters long. + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Username": username, + "Password": password, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialInstance]: + """ + Streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialInstance]: + """ + Asynchronously streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Asynchronously lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Asynchronously retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> CredentialPage: + """ + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> CredentialPage: + """ + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response, self._solution) + + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: The unique id that identifies the resource to update. + """ + return CredentialContext( + self._version, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: The unique id that identifies the resource to update. + """ + return CredentialContext( + self._version, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/__init__.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/__init__.py new file mode 100644 index 00000000..0a45e682 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/__init__.py @@ -0,0 +1,977 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.sip.domain.auth_types import AuthTypesList +from twilio.rest.api.v2010.account.sip.domain.credential_list_mapping import ( + CredentialListMappingList, +) +from twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping import ( + IpAccessControlListMappingList, +) + + +class DomainInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the SipDomain resource. + :ivar api_version: The API version used to process the call. + :ivar auth_type: The types of authentication you have mapped to your domain. Can be: `IP_ACL` and `CREDENTIAL_LIST`. If you have both defined for your domain, both will be returned in a comma delimited string. If `auth_type` is not defined, the domain will not be able to receive any traffic. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \"-\" and must end with `sip.twilio.com`. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar sid: The unique string that that we created to identify the SipDomain resource. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar voice_fallback_method: The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_url: The URL that we call when an error occurs while retrieving or executing the TwiML requested from `voice_url`. + :ivar voice_method: The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + :ivar voice_status_callback_method: The HTTP method we use to call `voice_status_callback_url`. Either `GET` or `POST`. + :ivar voice_status_callback_url: The URL that we call to pass status parameters (such as call ended) to your application. + :ivar voice_url: The URL we call using the `voice_method` when the domain receives a call. + :ivar subresource_uris: A list of mapping resources associated with the SIP Domain resource identified by their relative URIs. + :ivar sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. + :ivar emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :ivar secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :ivar byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :ivar emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.auth_type: Optional[str] = payload.get("auth_type") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.domain_name: Optional[str] = payload.get("domain_name") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.sid: Optional[str] = payload.get("sid") + self.uri: Optional[str] = payload.get("uri") + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_status_callback_method: Optional[str] = payload.get( + "voice_status_callback_method" + ) + self.voice_status_callback_url: Optional[str] = payload.get( + "voice_status_callback_url" + ) + self.voice_url: Optional[str] = payload.get("voice_url") + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.sip_registration: Optional[bool] = payload.get("sip_registration") + self.emergency_calling_enabled: Optional[bool] = payload.get( + "emergency_calling_enabled" + ) + self.secure: Optional[bool] = payload.get("secure") + self.byoc_trunk_sid: Optional[str] = payload.get("byoc_trunk_sid") + self.emergency_caller_sid: Optional[str] = payload.get("emergency_caller_sid") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[DomainContext] = None + + @property + def _proxy(self) -> "DomainContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DomainContext for this DomainInstance + """ + if self._context is None: + self._context = DomainContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the DomainInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DomainInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "DomainInstance": + """ + Fetch the DomainInstance + + + :returns: The fetched DomainInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DomainInstance": + """ + Asynchronous coroutine to fetch the DomainInstance + + + :returns: The fetched DomainInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + domain_name: Union[str, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> "DomainInstance": + """ + Update the DomainInstance + + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_url: The URL we should call when the domain receives a call. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: The updated DomainInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_status_callback_method=voice_status_callback_method, + voice_status_callback_url=voice_status_callback_url, + voice_url=voice_url, + sip_registration=sip_registration, + domain_name=domain_name, + emergency_calling_enabled=emergency_calling_enabled, + secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + domain_name: Union[str, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> "DomainInstance": + """ + Asynchronous coroutine to update the DomainInstance + + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_url: The URL we should call when the domain receives a call. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: The updated DomainInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_status_callback_method=voice_status_callback_method, + voice_status_callback_url=voice_status_callback_url, + voice_url=voice_url, + sip_registration=sip_registration, + domain_name=domain_name, + emergency_calling_enabled=emergency_calling_enabled, + secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, + ) + + @property + def auth(self) -> AuthTypesList: + """ + Access the auth + """ + return self._proxy.auth + + @property + def credential_list_mappings(self) -> CredentialListMappingList: + """ + Access the credential_list_mappings + """ + return self._proxy.credential_list_mappings + + @property + def ip_access_control_list_mappings(self) -> IpAccessControlListMappingList: + """ + Access the ip_access_control_list_mappings + """ + return self._proxy.ip_access_control_list_mappings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DomainContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the DomainContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the SipDomain resource to update. + :param sid: The Twilio-provided string that uniquely identifies the SipDomain resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{sid}.json".format( + **self._solution + ) + + self._auth: Optional[AuthTypesList] = None + self._credential_list_mappings: Optional[CredentialListMappingList] = None + self._ip_access_control_list_mappings: Optional[ + IpAccessControlListMappingList + ] = None + + def delete(self) -> bool: + """ + Deletes the DomainInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DomainInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> DomainInstance: + """ + Fetch the DomainInstance + + + :returns: The fetched DomainInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> DomainInstance: + """ + Asynchronous coroutine to fetch the DomainInstance + + + :returns: The fetched DomainInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + domain_name: Union[str, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> DomainInstance: + """ + Update the DomainInstance + + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_url: The URL we should call when the domain receives a call. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: The updated DomainInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceStatusCallbackMethod": voice_status_callback_method, + "VoiceStatusCallbackUrl": voice_status_callback_url, + "VoiceUrl": voice_url, + "SipRegistration": serialize.boolean_to_string(sip_registration), + "DomainName": domain_name, + "EmergencyCallingEnabled": serialize.boolean_to_string( + emergency_calling_enabled + ), + "Secure": serialize.boolean_to_string(secure), + "ByocTrunkSid": byoc_trunk_sid, + "EmergencyCallerSid": emergency_caller_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + domain_name: Union[str, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> DomainInstance: + """ + Asynchronous coroutine to update the DomainInstance + + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_url: The URL we should call when the domain receives a call. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: The updated DomainInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceStatusCallbackMethod": voice_status_callback_method, + "VoiceStatusCallbackUrl": voice_status_callback_url, + "VoiceUrl": voice_url, + "SipRegistration": serialize.boolean_to_string(sip_registration), + "DomainName": domain_name, + "EmergencyCallingEnabled": serialize.boolean_to_string( + emergency_calling_enabled + ), + "Secure": serialize.boolean_to_string(secure), + "ByocTrunkSid": byoc_trunk_sid, + "EmergencyCallerSid": emergency_caller_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + @property + def auth(self) -> AuthTypesList: + """ + Access the auth + """ + if self._auth is None: + self._auth = AuthTypesList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._auth + + @property + def credential_list_mappings(self) -> CredentialListMappingList: + """ + Access the credential_list_mappings + """ + if self._credential_list_mappings is None: + self._credential_list_mappings = CredentialListMappingList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._credential_list_mappings + + @property + def ip_access_control_list_mappings(self) -> IpAccessControlListMappingList: + """ + Access the ip_access_control_list_mappings + """ + if self._ip_access_control_list_mappings is None: + self._ip_access_control_list_mappings = IpAccessControlListMappingList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._ip_access_control_list_mappings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DomainPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DomainInstance: + """ + Build an instance of DomainInstance + + :param payload: Payload response from the API + """ + return DomainInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class DomainList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the DomainList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the SipDomain resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains.json".format(**self._solution) + + def create( + self, + domain_name: str, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> DomainInstance: + """ + Create the DomainInstance + + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_url: The URL we should when the domain receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: The created DomainInstance + """ + + data = values.of( + { + "DomainName": domain_name, + "FriendlyName": friendly_name, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceStatusCallbackUrl": voice_status_callback_url, + "VoiceStatusCallbackMethod": voice_status_callback_method, + "SipRegistration": serialize.boolean_to_string(sip_registration), + "EmergencyCallingEnabled": serialize.boolean_to_string( + emergency_calling_enabled + ), + "Secure": serialize.boolean_to_string(secure), + "ByocTrunkSid": byoc_trunk_sid, + "EmergencyCallerSid": emergency_caller_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DomainInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, + domain_name: str, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> DomainInstance: + """ + Asynchronously create the DomainInstance + + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_url: The URL we should when the domain receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: The created DomainInstance + """ + + data = values.of( + { + "DomainName": domain_name, + "FriendlyName": friendly_name, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceStatusCallbackUrl": voice_status_callback_url, + "VoiceStatusCallbackMethod": voice_status_callback_method, + "SipRegistration": serialize.boolean_to_string(sip_registration), + "EmergencyCallingEnabled": serialize.boolean_to_string( + emergency_calling_enabled + ), + "Secure": serialize.boolean_to_string(secure), + "ByocTrunkSid": byoc_trunk_sid, + "EmergencyCallerSid": emergency_caller_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DomainInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DomainInstance]: + """ + Streams DomainInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DomainInstance]: + """ + Asynchronously streams DomainInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DomainInstance]: + """ + Lists DomainInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DomainInstance]: + """ + Asynchronously lists DomainInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DomainPage: + """ + Retrieve a single page of DomainInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DomainInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DomainPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DomainPage: + """ + Asynchronously retrieve a single page of DomainInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DomainInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DomainPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DomainPage: + """ + Retrieve a specific page of DomainInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DomainInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DomainPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DomainPage: + """ + Asynchronously retrieve a specific page of DomainInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DomainInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DomainPage(self._version, response, self._solution) + + def get(self, sid: str) -> DomainContext: + """ + Constructs a DomainContext + + :param sid: The Twilio-provided string that uniquely identifies the SipDomain resource to update. + """ + return DomainContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> DomainContext: + """ + Constructs a DomainContext + + :param sid: The Twilio-provided string that uniquely identifies the SipDomain resource to update. + """ + return DomainContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..8ce19a67 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/__pycache__/credential_list_mapping.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/__pycache__/credential_list_mapping.cpython-312.pyc new file mode 100644 index 00000000..1e44a14b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/__pycache__/credential_list_mapping.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/__pycache__/ip_access_control_list_mapping.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/__pycache__/ip_access_control_list_mapping.cpython-312.pyc new file mode 100644 index 00000000..9482a6c8 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/__pycache__/ip_access_control_list_mapping.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/__init__.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/__init__.py new file mode 100644 index 00000000..73a81ac9 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/__init__.py @@ -0,0 +1,86 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.api.v2010.account.sip.domain.auth_types.auth_type_calls import ( + AuthTypeCallsList, +) +from twilio.rest.api.v2010.account.sip.domain.auth_types.auth_type_registrations import ( + AuthTypeRegistrationsList, +) + + +class AuthTypesList(ListResource): + + def __init__(self, version: Version, account_sid: str, domain_sid: str): + """ + Initialize the AuthTypesList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping resource to fetch. + :param domain_sid: The SID of the SIP domain that contains the resource to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/Auth.json".format( + **self._solution + ) + + self._calls: Optional[AuthTypeCallsList] = None + self._registrations: Optional[AuthTypeRegistrationsList] = None + + @property + def calls(self) -> AuthTypeCallsList: + """ + Access the calls + """ + if self._calls is None: + self._calls = AuthTypeCallsList( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return self._calls + + @property + def registrations(self) -> AuthTypeRegistrationsList: + """ + Access the registrations + """ + if self._registrations is None: + self._registrations = AuthTypeRegistrationsList( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return self._registrations + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..791839b4 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/__init__.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/__init__.py new file mode 100644 index 00000000..79a42fa0 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/__init__.py @@ -0,0 +1,96 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.api.v2010.account.sip.domain.auth_types.auth_type_calls.auth_calls_credential_list_mapping import ( + AuthCallsCredentialListMappingList, +) +from twilio.rest.api.v2010.account.sip.domain.auth_types.auth_type_calls.auth_calls_ip_access_control_list_mapping import ( + AuthCallsIpAccessControlListMappingList, +) + + +class AuthTypeCallsList(ListResource): + + def __init__(self, version: Version, account_sid: str, domain_sid: str): + """ + Initialize the AuthTypeCallsList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping resource to fetch. + :param domain_sid: The SID of the SIP domain that contains the resource to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + } + self._uri = ( + "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/Auth/Calls.json".format( + **self._solution + ) + ) + + self._credential_list_mappings: Optional[AuthCallsCredentialListMappingList] = ( + None + ) + self._ip_access_control_list_mappings: Optional[ + AuthCallsIpAccessControlListMappingList + ] = None + + @property + def credential_list_mappings(self) -> AuthCallsCredentialListMappingList: + """ + Access the credential_list_mappings + """ + if self._credential_list_mappings is None: + self._credential_list_mappings = AuthCallsCredentialListMappingList( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return self._credential_list_mappings + + @property + def ip_access_control_list_mappings( + self, + ) -> AuthCallsIpAccessControlListMappingList: + """ + Access the ip_access_control_list_mappings + """ + if self._ip_access_control_list_mappings is None: + self._ip_access_control_list_mappings = ( + AuthCallsIpAccessControlListMappingList( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + ) + return self._ip_access_control_list_mappings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..e74c7abe Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/__pycache__/auth_calls_credential_list_mapping.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/__pycache__/auth_calls_credential_list_mapping.cpython-312.pyc new file mode 100644 index 00000000..9fa6b760 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/__pycache__/auth_calls_credential_list_mapping.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/__pycache__/auth_calls_ip_access_control_list_mapping.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/__pycache__/auth_calls_ip_access_control_list_mapping.cpython-312.pyc new file mode 100644 index 00000000..7512c346 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/__pycache__/auth_calls_ip_access_control_list_mapping.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_credential_list_mapping.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_credential_list_mapping.py new file mode 100644 index 00000000..4839f17d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_credential_list_mapping.py @@ -0,0 +1,582 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AuthCallsCredentialListMappingInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar sid: The unique string that that we created to identify the CredentialListMapping resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + domain_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.sid: Optional[str] = payload.get("sid") + + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + "sid": sid or self.sid, + } + self._context: Optional[AuthCallsCredentialListMappingContext] = None + + @property + def _proxy(self) -> "AuthCallsCredentialListMappingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AuthCallsCredentialListMappingContext for this AuthCallsCredentialListMappingInstance + """ + if self._context is None: + self._context = AuthCallsCredentialListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AuthCallsCredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AuthCallsCredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AuthCallsCredentialListMappingInstance": + """ + Fetch the AuthCallsCredentialListMappingInstance + + + :returns: The fetched AuthCallsCredentialListMappingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AuthCallsCredentialListMappingInstance": + """ + Asynchronous coroutine to fetch the AuthCallsCredentialListMappingInstance + + + :returns: The fetched AuthCallsCredentialListMappingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class AuthCallsCredentialListMappingContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str): + """ + Initialize the AuthCallsCredentialListMappingContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping resource to fetch. + :param domain_sid: The SID of the SIP domain that contains the resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the CredentialListMapping resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/Auth/Calls/CredentialListMappings/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the AuthCallsCredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AuthCallsCredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AuthCallsCredentialListMappingInstance: + """ + Fetch the AuthCallsCredentialListMappingInstance + + + :returns: The fetched AuthCallsCredentialListMappingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AuthCallsCredentialListMappingInstance: + """ + Asynchronous coroutine to fetch the AuthCallsCredentialListMappingInstance + + + :returns: The fetched AuthCallsCredentialListMappingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class AuthCallsCredentialListMappingPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> AuthCallsCredentialListMappingInstance: + """ + Build an instance of AuthCallsCredentialListMappingInstance + + :param payload: Payload response from the API + """ + return AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AuthCallsCredentialListMappingList(ListResource): + + def __init__(self, version: Version, account_sid: str, domain_sid: str): + """ + Initialize the AuthCallsCredentialListMappingList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping resources to read. + :param domain_sid: The SID of the SIP domain that contains the resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/Auth/Calls/CredentialListMappings.json".format( + **self._solution + ) + + def create( + self, credential_list_sid: str + ) -> AuthCallsCredentialListMappingInstance: + """ + Create the AuthCallsCredentialListMappingInstance + + :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. + + :returns: The created AuthCallsCredentialListMappingInstance + """ + + data = values.of( + { + "CredentialListSid": credential_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + async def create_async( + self, credential_list_sid: str + ) -> AuthCallsCredentialListMappingInstance: + """ + Asynchronously create the AuthCallsCredentialListMappingInstance + + :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. + + :returns: The created AuthCallsCredentialListMappingInstance + """ + + data = values.of( + { + "CredentialListSid": credential_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AuthCallsCredentialListMappingInstance]: + """ + Streams AuthCallsCredentialListMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AuthCallsCredentialListMappingInstance]: + """ + Asynchronously streams AuthCallsCredentialListMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthCallsCredentialListMappingInstance]: + """ + Lists AuthCallsCredentialListMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthCallsCredentialListMappingInstance]: + """ + Asynchronously lists AuthCallsCredentialListMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AuthCallsCredentialListMappingPage: + """ + Retrieve a single page of AuthCallsCredentialListMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AuthCallsCredentialListMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthCallsCredentialListMappingPage( + self._version, response, self._solution + ) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AuthCallsCredentialListMappingPage: + """ + Asynchronously retrieve a single page of AuthCallsCredentialListMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AuthCallsCredentialListMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthCallsCredentialListMappingPage( + self._version, response, self._solution + ) + + def get_page(self, target_url: str) -> AuthCallsCredentialListMappingPage: + """ + Retrieve a specific page of AuthCallsCredentialListMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthCallsCredentialListMappingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AuthCallsCredentialListMappingPage( + self._version, response, self._solution + ) + + async def get_page_async( + self, target_url: str + ) -> AuthCallsCredentialListMappingPage: + """ + Asynchronously retrieve a specific page of AuthCallsCredentialListMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthCallsCredentialListMappingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AuthCallsCredentialListMappingPage( + self._version, response, self._solution + ) + + def get(self, sid: str) -> AuthCallsCredentialListMappingContext: + """ + Constructs a AuthCallsCredentialListMappingContext + + :param sid: The Twilio-provided string that uniquely identifies the CredentialListMapping resource to fetch. + """ + return AuthCallsCredentialListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> AuthCallsCredentialListMappingContext: + """ + Constructs a AuthCallsCredentialListMappingContext + + :param sid: The Twilio-provided string that uniquely identifies the CredentialListMapping resource to fetch. + """ + return AuthCallsCredentialListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_ip_access_control_list_mapping.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_ip_access_control_list_mapping.py new file mode 100644 index 00000000..198f4fc4 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_ip_access_control_list_mapping.py @@ -0,0 +1,586 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AuthCallsIpAccessControlListMappingInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IpAccessControlListMapping resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar sid: The unique string that that we created to identify the IpAccessControlListMapping resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + domain_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.sid: Optional[str] = payload.get("sid") + + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + "sid": sid or self.sid, + } + self._context: Optional[AuthCallsIpAccessControlListMappingContext] = None + + @property + def _proxy(self) -> "AuthCallsIpAccessControlListMappingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AuthCallsIpAccessControlListMappingContext for this AuthCallsIpAccessControlListMappingInstance + """ + if self._context is None: + self._context = AuthCallsIpAccessControlListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AuthCallsIpAccessControlListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AuthCallsIpAccessControlListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AuthCallsIpAccessControlListMappingInstance": + """ + Fetch the AuthCallsIpAccessControlListMappingInstance + + + :returns: The fetched AuthCallsIpAccessControlListMappingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AuthCallsIpAccessControlListMappingInstance": + """ + Asynchronous coroutine to fetch the AuthCallsIpAccessControlListMappingInstance + + + :returns: The fetched AuthCallsIpAccessControlListMappingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return ( + "".format( + context + ) + ) + + +class AuthCallsIpAccessControlListMappingContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str): + """ + Initialize the AuthCallsIpAccessControlListMappingContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IpAccessControlListMapping resource to fetch. + :param domain_sid: The SID of the SIP domain that contains the resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the IpAccessControlListMapping resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/Auth/Calls/IpAccessControlListMappings/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the AuthCallsIpAccessControlListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AuthCallsIpAccessControlListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AuthCallsIpAccessControlListMappingInstance: + """ + Fetch the AuthCallsIpAccessControlListMappingInstance + + + :returns: The fetched AuthCallsIpAccessControlListMappingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AuthCallsIpAccessControlListMappingInstance: + """ + Asynchronous coroutine to fetch the AuthCallsIpAccessControlListMappingInstance + + + :returns: The fetched AuthCallsIpAccessControlListMappingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return ( + "".format( + context + ) + ) + + +class AuthCallsIpAccessControlListMappingPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> AuthCallsIpAccessControlListMappingInstance: + """ + Build an instance of AuthCallsIpAccessControlListMappingInstance + + :param payload: Payload response from the API + """ + return AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AuthCallsIpAccessControlListMappingList(ListResource): + + def __init__(self, version: Version, account_sid: str, domain_sid: str): + """ + Initialize the AuthCallsIpAccessControlListMappingList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IpAccessControlListMapping resources to read. + :param domain_sid: The SID of the SIP domain that contains the resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/Auth/Calls/IpAccessControlListMappings.json".format( + **self._solution + ) + + def create( + self, ip_access_control_list_sid: str + ) -> AuthCallsIpAccessControlListMappingInstance: + """ + Create the AuthCallsIpAccessControlListMappingInstance + + :param ip_access_control_list_sid: The SID of the IpAccessControlList resource to map to the SIP domain. + + :returns: The created AuthCallsIpAccessControlListMappingInstance + """ + + data = values.of( + { + "IpAccessControlListSid": ip_access_control_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + async def create_async( + self, ip_access_control_list_sid: str + ) -> AuthCallsIpAccessControlListMappingInstance: + """ + Asynchronously create the AuthCallsIpAccessControlListMappingInstance + + :param ip_access_control_list_sid: The SID of the IpAccessControlList resource to map to the SIP domain. + + :returns: The created AuthCallsIpAccessControlListMappingInstance + """ + + data = values.of( + { + "IpAccessControlListSid": ip_access_control_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AuthCallsIpAccessControlListMappingInstance]: + """ + Streams AuthCallsIpAccessControlListMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AuthCallsIpAccessControlListMappingInstance]: + """ + Asynchronously streams AuthCallsIpAccessControlListMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthCallsIpAccessControlListMappingInstance]: + """ + Lists AuthCallsIpAccessControlListMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthCallsIpAccessControlListMappingInstance]: + """ + Asynchronously lists AuthCallsIpAccessControlListMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AuthCallsIpAccessControlListMappingPage: + """ + Retrieve a single page of AuthCallsIpAccessControlListMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AuthCallsIpAccessControlListMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthCallsIpAccessControlListMappingPage( + self._version, response, self._solution + ) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AuthCallsIpAccessControlListMappingPage: + """ + Asynchronously retrieve a single page of AuthCallsIpAccessControlListMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AuthCallsIpAccessControlListMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthCallsIpAccessControlListMappingPage( + self._version, response, self._solution + ) + + def get_page(self, target_url: str) -> AuthCallsIpAccessControlListMappingPage: + """ + Retrieve a specific page of AuthCallsIpAccessControlListMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthCallsIpAccessControlListMappingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AuthCallsIpAccessControlListMappingPage( + self._version, response, self._solution + ) + + async def get_page_async( + self, target_url: str + ) -> AuthCallsIpAccessControlListMappingPage: + """ + Asynchronously retrieve a specific page of AuthCallsIpAccessControlListMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthCallsIpAccessControlListMappingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AuthCallsIpAccessControlListMappingPage( + self._version, response, self._solution + ) + + def get(self, sid: str) -> AuthCallsIpAccessControlListMappingContext: + """ + Constructs a AuthCallsIpAccessControlListMappingContext + + :param sid: The Twilio-provided string that uniquely identifies the IpAccessControlListMapping resource to fetch. + """ + return AuthCallsIpAccessControlListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> AuthCallsIpAccessControlListMappingContext: + """ + Constructs a AuthCallsIpAccessControlListMappingContext + + :param sid: The Twilio-provided string that uniquely identifies the IpAccessControlListMapping resource to fetch. + """ + return AuthCallsIpAccessControlListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/__init__.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/__init__.py new file mode 100644 index 00000000..c10c7473 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/__init__.py @@ -0,0 +1,71 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.api.v2010.account.sip.domain.auth_types.auth_type_registrations.auth_registrations_credential_list_mapping import ( + AuthRegistrationsCredentialListMappingList, +) + + +class AuthTypeRegistrationsList(ListResource): + + def __init__(self, version: Version, account_sid: str, domain_sid: str): + """ + Initialize the AuthTypeRegistrationsList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping resource to fetch. + :param domain_sid: The SID of the SIP domain that contains the resource to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/Auth/Registrations.json".format( + **self._solution + ) + + self._credential_list_mappings: Optional[ + AuthRegistrationsCredentialListMappingList + ] = None + + @property + def credential_list_mappings(self) -> AuthRegistrationsCredentialListMappingList: + """ + Access the credential_list_mappings + """ + if self._credential_list_mappings is None: + self._credential_list_mappings = AuthRegistrationsCredentialListMappingList( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return self._credential_list_mappings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..550775ce Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/__pycache__/auth_registrations_credential_list_mapping.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/__pycache__/auth_registrations_credential_list_mapping.cpython-312.pyc new file mode 100644 index 00000000..1272dc69 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/__pycache__/auth_registrations_credential_list_mapping.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/auth_registrations_credential_list_mapping.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/auth_registrations_credential_list_mapping.py new file mode 100644 index 00000000..e4b1bf0d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/auth_registrations_credential_list_mapping.py @@ -0,0 +1,582 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AuthRegistrationsCredentialListMappingInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar sid: The unique string that that we created to identify the CredentialListMapping resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + domain_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.sid: Optional[str] = payload.get("sid") + + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + "sid": sid or self.sid, + } + self._context: Optional[AuthRegistrationsCredentialListMappingContext] = None + + @property + def _proxy(self) -> "AuthRegistrationsCredentialListMappingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AuthRegistrationsCredentialListMappingContext for this AuthRegistrationsCredentialListMappingInstance + """ + if self._context is None: + self._context = AuthRegistrationsCredentialListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AuthRegistrationsCredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AuthRegistrationsCredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AuthRegistrationsCredentialListMappingInstance": + """ + Fetch the AuthRegistrationsCredentialListMappingInstance + + + :returns: The fetched AuthRegistrationsCredentialListMappingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AuthRegistrationsCredentialListMappingInstance": + """ + Asynchronous coroutine to fetch the AuthRegistrationsCredentialListMappingInstance + + + :returns: The fetched AuthRegistrationsCredentialListMappingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class AuthRegistrationsCredentialListMappingContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str): + """ + Initialize the AuthRegistrationsCredentialListMappingContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping resource to fetch. + :param domain_sid: The SID of the SIP domain that contains the resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the CredentialListMapping resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/Auth/Registrations/CredentialListMappings/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the AuthRegistrationsCredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AuthRegistrationsCredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AuthRegistrationsCredentialListMappingInstance: + """ + Fetch the AuthRegistrationsCredentialListMappingInstance + + + :returns: The fetched AuthRegistrationsCredentialListMappingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AuthRegistrationsCredentialListMappingInstance: + """ + Asynchronous coroutine to fetch the AuthRegistrationsCredentialListMappingInstance + + + :returns: The fetched AuthRegistrationsCredentialListMappingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class AuthRegistrationsCredentialListMappingPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> AuthRegistrationsCredentialListMappingInstance: + """ + Build an instance of AuthRegistrationsCredentialListMappingInstance + + :param payload: Payload response from the API + """ + return AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AuthRegistrationsCredentialListMappingList(ListResource): + + def __init__(self, version: Version, account_sid: str, domain_sid: str): + """ + Initialize the AuthRegistrationsCredentialListMappingList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping resources to read. + :param domain_sid: The SID of the SIP domain that contains the resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/Auth/Registrations/CredentialListMappings.json".format( + **self._solution + ) + + def create( + self, credential_list_sid: str + ) -> AuthRegistrationsCredentialListMappingInstance: + """ + Create the AuthRegistrationsCredentialListMappingInstance + + :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. + + :returns: The created AuthRegistrationsCredentialListMappingInstance + """ + + data = values.of( + { + "CredentialListSid": credential_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + async def create_async( + self, credential_list_sid: str + ) -> AuthRegistrationsCredentialListMappingInstance: + """ + Asynchronously create the AuthRegistrationsCredentialListMappingInstance + + :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. + + :returns: The created AuthRegistrationsCredentialListMappingInstance + """ + + data = values.of( + { + "CredentialListSid": credential_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AuthRegistrationsCredentialListMappingInstance]: + """ + Streams AuthRegistrationsCredentialListMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AuthRegistrationsCredentialListMappingInstance]: + """ + Asynchronously streams AuthRegistrationsCredentialListMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthRegistrationsCredentialListMappingInstance]: + """ + Lists AuthRegistrationsCredentialListMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthRegistrationsCredentialListMappingInstance]: + """ + Asynchronously lists AuthRegistrationsCredentialListMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AuthRegistrationsCredentialListMappingPage: + """ + Retrieve a single page of AuthRegistrationsCredentialListMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AuthRegistrationsCredentialListMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthRegistrationsCredentialListMappingPage( + self._version, response, self._solution + ) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AuthRegistrationsCredentialListMappingPage: + """ + Asynchronously retrieve a single page of AuthRegistrationsCredentialListMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AuthRegistrationsCredentialListMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthRegistrationsCredentialListMappingPage( + self._version, response, self._solution + ) + + def get_page(self, target_url: str) -> AuthRegistrationsCredentialListMappingPage: + """ + Retrieve a specific page of AuthRegistrationsCredentialListMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthRegistrationsCredentialListMappingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AuthRegistrationsCredentialListMappingPage( + self._version, response, self._solution + ) + + async def get_page_async( + self, target_url: str + ) -> AuthRegistrationsCredentialListMappingPage: + """ + Asynchronously retrieve a specific page of AuthRegistrationsCredentialListMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthRegistrationsCredentialListMappingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AuthRegistrationsCredentialListMappingPage( + self._version, response, self._solution + ) + + def get(self, sid: str) -> AuthRegistrationsCredentialListMappingContext: + """ + Constructs a AuthRegistrationsCredentialListMappingContext + + :param sid: The Twilio-provided string that uniquely identifies the CredentialListMapping resource to fetch. + """ + return AuthRegistrationsCredentialListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> AuthRegistrationsCredentialListMappingContext: + """ + Constructs a AuthRegistrationsCredentialListMappingContext + + :param sid: The Twilio-provided string that uniquely identifies the CredentialListMapping resource to fetch. + """ + return AuthRegistrationsCredentialListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/credential_list_mapping.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/credential_list_mapping.py new file mode 100644 index 00000000..b520f481 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/credential_list_mapping.py @@ -0,0 +1,568 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CredentialListMappingInstance(InstanceResource): + """ + :ivar account_sid: The unique id of the Account that is responsible for this resource. + :ivar date_created: The date that this resource was created, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar date_updated: The date that this resource was last updated, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar domain_sid: The unique string that is created to identify the SipDomain resource. + :ivar friendly_name: A human readable descriptive text for this resource, up to 64 characters long. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar uri: The URI for this resource, relative to `https://api.twilio.com` + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + domain_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.domain_sid: Optional[str] = payload.get("domain_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.sid: Optional[str] = payload.get("sid") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + "sid": sid or self.sid, + } + self._context: Optional[CredentialListMappingContext] = None + + @property + def _proxy(self) -> "CredentialListMappingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CredentialListMappingContext for this CredentialListMappingInstance + """ + if self._context is None: + self._context = CredentialListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CredentialListMappingInstance": + """ + Fetch the CredentialListMappingInstance + + + :returns: The fetched CredentialListMappingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CredentialListMappingInstance": + """ + Asynchronous coroutine to fetch the CredentialListMappingInstance + + + :returns: The fetched CredentialListMappingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialListMappingContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str): + """ + Initialize the CredentialListMappingContext + + :param version: Version that contains the resource + :param account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this resource. + :param domain_sid: A 34 character string that uniquely identifies the SIP Domain that includes the resource to fetch. + :param sid: A 34 character string that uniquely identifies the resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/CredentialListMappings/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the CredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialListMappingInstance: + """ + Fetch the CredentialListMappingInstance + + + :returns: The fetched CredentialListMappingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialListMappingInstance: + """ + Asynchronous coroutine to fetch the CredentialListMappingInstance + + + :returns: The fetched CredentialListMappingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialListMappingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialListMappingInstance: + """ + Build an instance of CredentialListMappingInstance + + :param payload: Payload response from the API + """ + return CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CredentialListMappingList(ListResource): + + def __init__(self, version: Version, account_sid: str, domain_sid: str): + """ + Initialize the CredentialListMappingList + + :param version: Version that contains the resource + :param account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this resource. + :param domain_sid: A 34 character string that uniquely identifies the SIP Domain that includes the resource to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/CredentialListMappings.json".format( + **self._solution + ) + + def create(self, credential_list_sid: str) -> CredentialListMappingInstance: + """ + Create the CredentialListMappingInstance + + :param credential_list_sid: A 34 character string that uniquely identifies the CredentialList resource to map to the SIP domain. + + :returns: The created CredentialListMappingInstance + """ + + data = values.of( + { + "CredentialListSid": credential_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + async def create_async( + self, credential_list_sid: str + ) -> CredentialListMappingInstance: + """ + Asynchronously create the CredentialListMappingInstance + + :param credential_list_sid: A 34 character string that uniquely identifies the CredentialList resource to map to the SIP domain. + + :returns: The created CredentialListMappingInstance + """ + + data = values.of( + { + "CredentialListSid": credential_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialListMappingInstance]: + """ + Streams CredentialListMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialListMappingInstance]: + """ + Asynchronously streams CredentialListMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialListMappingInstance]: + """ + Lists CredentialListMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialListMappingInstance]: + """ + Asynchronously lists CredentialListMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialListMappingPage: + """ + Retrieve a single page of CredentialListMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialListMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialListMappingPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialListMappingPage: + """ + Asynchronously retrieve a single page of CredentialListMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialListMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialListMappingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> CredentialListMappingPage: + """ + Retrieve a specific page of CredentialListMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialListMappingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialListMappingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> CredentialListMappingPage: + """ + Asynchronously retrieve a specific page of CredentialListMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialListMappingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialListMappingPage(self._version, response, self._solution) + + def get(self, sid: str) -> CredentialListMappingContext: + """ + Constructs a CredentialListMappingContext + + :param sid: A 34 character string that uniquely identifies the resource to fetch. + """ + return CredentialListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> CredentialListMappingContext: + """ + Constructs a CredentialListMappingContext + + :param sid: A 34 character string that uniquely identifies the resource to fetch. + """ + return CredentialListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/ip_access_control_list_mapping.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/ip_access_control_list_mapping.py new file mode 100644 index 00000000..4dfecfe8 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/domain/ip_access_control_list_mapping.py @@ -0,0 +1,574 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class IpAccessControlListMappingInstance(InstanceResource): + """ + :ivar account_sid: The unique id of the Account that is responsible for this resource. + :ivar date_created: The date that this resource was created, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar date_updated: The date that this resource was last updated, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar domain_sid: The unique string that is created to identify the SipDomain resource. + :ivar friendly_name: A human readable descriptive text for this resource, up to 64 characters long. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar uri: The URI for this resource, relative to `https://api.twilio.com` + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + domain_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.domain_sid: Optional[str] = payload.get("domain_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.sid: Optional[str] = payload.get("sid") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + "sid": sid or self.sid, + } + self._context: Optional[IpAccessControlListMappingContext] = None + + @property + def _proxy(self) -> "IpAccessControlListMappingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: IpAccessControlListMappingContext for this IpAccessControlListMappingInstance + """ + if self._context is None: + self._context = IpAccessControlListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the IpAccessControlListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpAccessControlListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "IpAccessControlListMappingInstance": + """ + Fetch the IpAccessControlListMappingInstance + + + :returns: The fetched IpAccessControlListMappingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "IpAccessControlListMappingInstance": + """ + Asynchronous coroutine to fetch the IpAccessControlListMappingInstance + + + :returns: The fetched IpAccessControlListMappingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class IpAccessControlListMappingContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str): + """ + Initialize the IpAccessControlListMappingContext + + :param version: Version that contains the resource + :param account_sid: The unique id of the Account that is responsible for this resource. + :param domain_sid: A 34 character string that uniquely identifies the SIP domain. + :param sid: A 34 character string that uniquely identifies the resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/IpAccessControlListMappings/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the IpAccessControlListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpAccessControlListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> IpAccessControlListMappingInstance: + """ + Fetch the IpAccessControlListMappingInstance + + + :returns: The fetched IpAccessControlListMappingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return IpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> IpAccessControlListMappingInstance: + """ + Asynchronous coroutine to fetch the IpAccessControlListMappingInstance + + + :returns: The fetched IpAccessControlListMappingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return IpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class IpAccessControlListMappingPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> IpAccessControlListMappingInstance: + """ + Build an instance of IpAccessControlListMappingInstance + + :param payload: Payload response from the API + """ + return IpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class IpAccessControlListMappingList(ListResource): + + def __init__(self, version: Version, account_sid: str, domain_sid: str): + """ + Initialize the IpAccessControlListMappingList + + :param version: Version that contains the resource + :param account_sid: The unique id of the Account that is responsible for this resource. + :param domain_sid: A 34 character string that uniquely identifies the SIP domain. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/IpAccessControlListMappings.json".format( + **self._solution + ) + + def create( + self, ip_access_control_list_sid: str + ) -> IpAccessControlListMappingInstance: + """ + Create the IpAccessControlListMappingInstance + + :param ip_access_control_list_sid: The unique id of the IP access control list to map to the SIP domain. + + :returns: The created IpAccessControlListMappingInstance + """ + + data = values.of( + { + "IpAccessControlListSid": ip_access_control_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + async def create_async( + self, ip_access_control_list_sid: str + ) -> IpAccessControlListMappingInstance: + """ + Asynchronously create the IpAccessControlListMappingInstance + + :param ip_access_control_list_sid: The unique id of the IP access control list to map to the SIP domain. + + :returns: The created IpAccessControlListMappingInstance + """ + + data = values.of( + { + "IpAccessControlListSid": ip_access_control_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[IpAccessControlListMappingInstance]: + """ + Streams IpAccessControlListMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IpAccessControlListMappingInstance]: + """ + Asynchronously streams IpAccessControlListMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAccessControlListMappingInstance]: + """ + Lists IpAccessControlListMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAccessControlListMappingInstance]: + """ + Asynchronously lists IpAccessControlListMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpAccessControlListMappingPage: + """ + Retrieve a single page of IpAccessControlListMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpAccessControlListMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpAccessControlListMappingPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpAccessControlListMappingPage: + """ + Asynchronously retrieve a single page of IpAccessControlListMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpAccessControlListMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpAccessControlListMappingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> IpAccessControlListMappingPage: + """ + Retrieve a specific page of IpAccessControlListMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpAccessControlListMappingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return IpAccessControlListMappingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> IpAccessControlListMappingPage: + """ + Asynchronously retrieve a specific page of IpAccessControlListMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpAccessControlListMappingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return IpAccessControlListMappingPage(self._version, response, self._solution) + + def get(self, sid: str) -> IpAccessControlListMappingContext: + """ + Constructs a IpAccessControlListMappingContext + + :param sid: A 34 character string that uniquely identifies the resource to fetch. + """ + return IpAccessControlListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> IpAccessControlListMappingContext: + """ + Constructs a IpAccessControlListMappingContext + + :param sid: A 34 character string that uniquely identifies the resource to fetch. + """ + return IpAccessControlListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/ip_access_control_list/__init__.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/ip_access_control_list/__init__.py new file mode 100644 index 00000000..afa504c2 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/ip_access_control_list/__init__.py @@ -0,0 +1,657 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address import ( + IpAddressList, +) + + +class IpAccessControlListInstance(InstanceResource): + """ + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) that owns this resource. + :ivar friendly_name: A human readable descriptive text, up to 255 characters long. + :ivar date_created: The date that this resource was created, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar date_updated: The date that this resource was last updated, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar subresource_uris: A list of the IpAddress resources associated with this IP access control list resource. + :ivar uri: The URI for this resource, relative to `https://api.twilio.com` + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[IpAccessControlListContext] = None + + @property + def _proxy(self) -> "IpAccessControlListContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: IpAccessControlListContext for this IpAccessControlListInstance + """ + if self._context is None: + self._context = IpAccessControlListContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the IpAccessControlListInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpAccessControlListInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "IpAccessControlListInstance": + """ + Fetch the IpAccessControlListInstance + + + :returns: The fetched IpAccessControlListInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "IpAccessControlListInstance": + """ + Asynchronous coroutine to fetch the IpAccessControlListInstance + + + :returns: The fetched IpAccessControlListInstance + """ + return await self._proxy.fetch_async() + + def update(self, friendly_name: str) -> "IpAccessControlListInstance": + """ + Update the IpAccessControlListInstance + + :param friendly_name: A human readable descriptive text, up to 255 characters long. + + :returns: The updated IpAccessControlListInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async(self, friendly_name: str) -> "IpAccessControlListInstance": + """ + Asynchronous coroutine to update the IpAccessControlListInstance + + :param friendly_name: A human readable descriptive text, up to 255 characters long. + + :returns: The updated IpAccessControlListInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + @property + def ip_addresses(self) -> IpAddressList: + """ + Access the ip_addresses + """ + return self._proxy.ip_addresses + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class IpAccessControlListContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the IpAccessControlListContext + + :param version: Version that contains the resource + :param account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this resource. + :param sid: A 34 character string that uniquely identifies the resource to udpate. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = ( + "/Accounts/{account_sid}/SIP/IpAccessControlLists/{sid}.json".format( + **self._solution + ) + ) + + self._ip_addresses: Optional[IpAddressList] = None + + def delete(self) -> bool: + """ + Deletes the IpAccessControlListInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpAccessControlListInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> IpAccessControlListInstance: + """ + Fetch the IpAccessControlListInstance + + + :returns: The fetched IpAccessControlListInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return IpAccessControlListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> IpAccessControlListInstance: + """ + Asynchronous coroutine to fetch the IpAccessControlListInstance + + + :returns: The fetched IpAccessControlListInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return IpAccessControlListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update(self, friendly_name: str) -> IpAccessControlListInstance: + """ + Update the IpAccessControlListInstance + + :param friendly_name: A human readable descriptive text, up to 255 characters long. + + :returns: The updated IpAccessControlListInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpAccessControlListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, friendly_name: str) -> IpAccessControlListInstance: + """ + Asynchronous coroutine to update the IpAccessControlListInstance + + :param friendly_name: A human readable descriptive text, up to 255 characters long. + + :returns: The updated IpAccessControlListInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpAccessControlListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + @property + def ip_addresses(self) -> IpAddressList: + """ + Access the ip_addresses + """ + if self._ip_addresses is None: + self._ip_addresses = IpAddressList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._ip_addresses + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class IpAccessControlListPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> IpAccessControlListInstance: + """ + Build an instance of IpAccessControlListInstance + + :param payload: Payload response from the API + """ + return IpAccessControlListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class IpAccessControlListList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the IpAccessControlListList + + :param version: Version that contains the resource + :param account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/IpAccessControlLists.json".format( + **self._solution + ) + + def create(self, friendly_name: str) -> IpAccessControlListInstance: + """ + Create the IpAccessControlListInstance + + :param friendly_name: A human readable descriptive text that describes the IpAccessControlList, up to 255 characters long. + + :returns: The created IpAccessControlListInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpAccessControlListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async(self, friendly_name: str) -> IpAccessControlListInstance: + """ + Asynchronously create the IpAccessControlListInstance + + :param friendly_name: A human readable descriptive text that describes the IpAccessControlList, up to 255 characters long. + + :returns: The created IpAccessControlListInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpAccessControlListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[IpAccessControlListInstance]: + """ + Streams IpAccessControlListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IpAccessControlListInstance]: + """ + Asynchronously streams IpAccessControlListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAccessControlListInstance]: + """ + Lists IpAccessControlListInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAccessControlListInstance]: + """ + Asynchronously lists IpAccessControlListInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpAccessControlListPage: + """ + Retrieve a single page of IpAccessControlListInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpAccessControlListInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpAccessControlListPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpAccessControlListPage: + """ + Asynchronously retrieve a single page of IpAccessControlListInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpAccessControlListInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpAccessControlListPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> IpAccessControlListPage: + """ + Retrieve a specific page of IpAccessControlListInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpAccessControlListInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return IpAccessControlListPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> IpAccessControlListPage: + """ + Asynchronously retrieve a specific page of IpAccessControlListInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpAccessControlListInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return IpAccessControlListPage(self._version, response, self._solution) + + def get(self, sid: str) -> IpAccessControlListContext: + """ + Constructs a IpAccessControlListContext + + :param sid: A 34 character string that uniquely identifies the resource to udpate. + """ + return IpAccessControlListContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> IpAccessControlListContext: + """ + Constructs a IpAccessControlListContext + + :param sid: A 34 character string that uniquely identifies the resource to udpate. + """ + return IpAccessControlListContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/ip_access_control_list/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/ip_access_control_list/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..f9772945 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/ip_access_control_list/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/ip_access_control_list/__pycache__/ip_address.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/ip_access_control_list/__pycache__/ip_address.cpython-312.pyc new file mode 100644 index 00000000..b29ebcec Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/ip_access_control_list/__pycache__/ip_address.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/ip_access_control_list/ip_address.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/ip_access_control_list/ip_address.py new file mode 100644 index 00000000..ca2f82ea --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/sip/ip_access_control_list/ip_address.py @@ -0,0 +1,724 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class IpAddressInstance(InstanceResource): + """ + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar account_sid: The unique id of the Account that is responsible for this resource. + :ivar friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :ivar ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :ivar cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + :ivar ip_access_control_list_sid: The unique id of the IpAccessControlList resource that includes this resource. + :ivar date_created: The date that this resource was created, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar date_updated: The date that this resource was last updated, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar uri: The URI for this resource, relative to `https://api.twilio.com` + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + ip_access_control_list_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.ip_address: Optional[str] = payload.get("ip_address") + self.cidr_prefix_length: Optional[int] = deserialize.integer( + payload.get("cidr_prefix_length") + ) + self.ip_access_control_list_sid: Optional[str] = payload.get( + "ip_access_control_list_sid" + ) + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "ip_access_control_list_sid": ip_access_control_list_sid, + "sid": sid or self.sid, + } + self._context: Optional[IpAddressContext] = None + + @property + def _proxy(self) -> "IpAddressContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: IpAddressContext for this IpAddressInstance + """ + if self._context is None: + self._context = IpAddressContext( + self._version, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the IpAddressInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpAddressInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "IpAddressInstance": + """ + Fetch the IpAddressInstance + + + :returns: The fetched IpAddressInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "IpAddressInstance": + """ + Asynchronous coroutine to fetch the IpAddressInstance + + + :returns: The fetched IpAddressInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + ip_address: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> "IpAddressInstance": + """ + Update the IpAddressInstance + + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: The updated IpAddressInstance + """ + return self._proxy.update( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + + async def update_async( + self, + ip_address: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> "IpAddressInstance": + """ + Asynchronous coroutine to update the IpAddressInstance + + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: The updated IpAddressInstance + """ + return await self._proxy.update_async( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class IpAddressContext(InstanceContext): + + def __init__( + self, + version: Version, + account_sid: str, + ip_access_control_list_sid: str, + sid: str, + ): + """ + Initialize the IpAddressContext + + :param version: Version that contains the resource + :param account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this resource. + :param ip_access_control_list_sid: The IpAccessControlList Sid that identifies the IpAddress resources to update. + :param sid: A 34 character string that identifies the IpAddress resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "ip_access_control_list_sid": ip_access_control_list_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SIP/IpAccessControlLists/{ip_access_control_list_sid}/IpAddresses/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the IpAddressInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpAddressInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> IpAddressInstance: + """ + Fetch the IpAddressInstance + + + :returns: The fetched IpAddressInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> IpAddressInstance: + """ + Asynchronous coroutine to fetch the IpAddressInstance + + + :returns: The fetched IpAddressInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + ip_address: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> IpAddressInstance: + """ + Update the IpAddressInstance + + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: The updated IpAddressInstance + """ + + data = values.of( + { + "IpAddress": ip_address, + "FriendlyName": friendly_name, + "CidrPrefixLength": cidr_prefix_length, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + ip_address: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> IpAddressInstance: + """ + Asynchronous coroutine to update the IpAddressInstance + + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: The updated IpAddressInstance + """ + + data = values.of( + { + "IpAddress": ip_address, + "FriendlyName": friendly_name, + "CidrPrefixLength": cidr_prefix_length, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class IpAddressPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> IpAddressInstance: + """ + Build an instance of IpAddressInstance + + :param payload: Payload response from the API + """ + return IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class IpAddressList(ListResource): + + def __init__( + self, version: Version, account_sid: str, ip_access_control_list_sid: str + ): + """ + Initialize the IpAddressList + + :param version: Version that contains the resource + :param account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this resource. + :param ip_access_control_list_sid: The IpAccessControlList Sid that identifies the IpAddress resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "ip_access_control_list_sid": ip_access_control_list_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/IpAccessControlLists/{ip_access_control_list_sid}/IpAddresses.json".format( + **self._solution + ) + + def create( + self, + friendly_name: str, + ip_address: str, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> IpAddressInstance: + """ + Create the IpAddressInstance + + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: The created IpAddressInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "IpAddress": ip_address, + "CidrPrefixLength": cidr_prefix_length, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + ) + + async def create_async( + self, + friendly_name: str, + ip_address: str, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> IpAddressInstance: + """ + Asynchronously create the IpAddressInstance + + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: The created IpAddressInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "IpAddress": ip_address, + "CidrPrefixLength": cidr_prefix_length, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[IpAddressInstance]: + """ + Streams IpAddressInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IpAddressInstance]: + """ + Asynchronously streams IpAddressInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAddressInstance]: + """ + Lists IpAddressInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAddressInstance]: + """ + Asynchronously lists IpAddressInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpAddressPage: + """ + Retrieve a single page of IpAddressInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpAddressInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpAddressPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpAddressPage: + """ + Asynchronously retrieve a single page of IpAddressInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpAddressInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpAddressPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> IpAddressPage: + """ + Retrieve a specific page of IpAddressInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpAddressInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return IpAddressPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> IpAddressPage: + """ + Asynchronously retrieve a specific page of IpAddressInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpAddressInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return IpAddressPage(self._version, response, self._solution) + + def get(self, sid: str) -> IpAddressContext: + """ + Constructs a IpAddressContext + + :param sid: A 34 character string that identifies the IpAddress resource to update. + """ + return IpAddressContext( + self._version, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> IpAddressContext: + """ + Constructs a IpAddressContext + + :param sid: A 34 character string that identifies the IpAddress resource to update. + """ + return IpAddressContext( + self._version, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/token.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/token.py new file mode 100644 index 00000000..fa43360f --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/token.py @@ -0,0 +1,146 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TokenInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Token resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar ice_servers: An array representing the ephemeral credentials and the STUN and TURN server URIs. + :ivar password: The temporary password that the username will use when authenticating with Twilio. + :ivar ttl: The duration in seconds for which the username and password are valid. + :ivar username: The temporary username that uniquely identifies a Token. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.ice_servers: Optional[List[str]] = payload.get("ice_servers") + self.password: Optional[str] = payload.get("password") + self.ttl: Optional[str] = payload.get("ttl") + self.username: Optional[str] = payload.get("username") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TokenList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the TokenList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that will create the resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Tokens.json".format(**self._solution) + + def create(self, ttl: Union[int, object] = values.unset) -> TokenInstance: + """ + Create the TokenInstance + + :param ttl: The duration in seconds for which the generated credentials are valid. The default value is 86400 (24 hours). + + :returns: The created TokenInstance + """ + + data = values.of( + { + "Ttl": ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TokenInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, ttl: Union[int, object] = values.unset + ) -> TokenInstance: + """ + Asynchronously create the TokenInstance + + :param ttl: The duration in seconds for which the generated credentials are valid. The default value is 86400 (24 hours). + + :returns: The created TokenInstance + """ + + data = values.of( + { + "Ttl": ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TokenInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/transcription.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/transcription.py new file mode 100644 index 00000000..386ff9ee --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/transcription.py @@ -0,0 +1,504 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TranscriptionInstance(InstanceResource): + + class Status(object): + IN_PROGRESS = "in-progress" + COMPLETED = "completed" + FAILED = "failed" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Transcription resource. + :ivar api_version: The API version used to create the transcription. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar duration: The duration of the transcribed audio in seconds. + :ivar price: The charge for the transcript in the currency associated with the account. This value is populated after the transcript is complete so it may not be available immediately. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar recording_sid: The SID of the [Recording](https://www.twilio.com/docs/voice/api/recording) from which the transcription was created. + :ivar sid: The unique string that that we created to identify the Transcription resource. + :ivar status: + :ivar transcription_text: The text content of the transcription. + :ivar type: The transcription type. Can only be: `fast`. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.duration: Optional[str] = payload.get("duration") + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.recording_sid: Optional[str] = payload.get("recording_sid") + self.sid: Optional[str] = payload.get("sid") + self.status: Optional["TranscriptionInstance.Status"] = payload.get("status") + self.transcription_text: Optional[str] = payload.get("transcription_text") + self.type: Optional[str] = payload.get("type") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[TranscriptionContext] = None + + @property + def _proxy(self) -> "TranscriptionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TranscriptionContext for this TranscriptionInstance + """ + if self._context is None: + self._context = TranscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TranscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TranscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "TranscriptionInstance": + """ + Fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TranscriptionInstance": + """ + Asynchronous coroutine to fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TranscriptionContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the TranscriptionContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Transcription resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Transcription resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Transcriptions/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the TranscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TranscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TranscriptionInstance: + """ + Fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TranscriptionInstance: + """ + Asynchronous coroutine to fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TranscriptionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TranscriptionInstance: + """ + Build an instance of TranscriptionInstance + + :param payload: Payload response from the API + """ + return TranscriptionInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TranscriptionList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the TranscriptionList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Transcription resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Transcriptions.json".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TranscriptionInstance]: + """ + Streams TranscriptionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TranscriptionInstance]: + """ + Asynchronously streams TranscriptionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TranscriptionInstance]: + """ + Lists TranscriptionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TranscriptionInstance]: + """ + Asynchronously lists TranscriptionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TranscriptionPage: + """ + Retrieve a single page of TranscriptionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TranscriptionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TranscriptionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TranscriptionPage: + """ + Asynchronously retrieve a single page of TranscriptionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TranscriptionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TranscriptionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> TranscriptionPage: + """ + Retrieve a specific page of TranscriptionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TranscriptionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TranscriptionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> TranscriptionPage: + """ + Asynchronously retrieve a specific page of TranscriptionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TranscriptionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TranscriptionPage(self._version, response, self._solution) + + def get(self, sid: str) -> TranscriptionContext: + """ + Constructs a TranscriptionContext + + :param sid: The Twilio-provided string that uniquely identifies the Transcription resource to fetch. + """ + return TranscriptionContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> TranscriptionContext: + """ + Constructs a TranscriptionContext + + :param sid: The Twilio-provided string that uniquely identifies the Transcription resource to fetch. + """ + return TranscriptionContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/__init__.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/__init__.py new file mode 100644 index 00000000..8fe80f64 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/__init__.py @@ -0,0 +1,74 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.api.v2010.account.usage.record import RecordList +from twilio.rest.api.v2010.account.usage.trigger import TriggerList + + +class UsageList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the UsageList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage.json".format(**self._solution) + + self._records: Optional[RecordList] = None + self._triggers: Optional[TriggerList] = None + + @property + def records(self) -> RecordList: + """ + Access the records + """ + if self._records is None: + self._records = RecordList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._records + + @property + def triggers(self) -> TriggerList: + """ + Access the triggers + """ + if self._triggers is None: + self._triggers = TriggerList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._triggers + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..1e0912f3 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/__pycache__/trigger.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/__pycache__/trigger.cpython-312.pyc new file mode 100644 index 00000000..c343aa82 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/__pycache__/trigger.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__init__.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__init__.py new file mode 100644 index 00000000..d60bde9b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__init__.py @@ -0,0 +1,1316 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.usage.record.all_time import AllTimeList +from twilio.rest.api.v2010.account.usage.record.daily import DailyList +from twilio.rest.api.v2010.account.usage.record.last_month import LastMonthList +from twilio.rest.api.v2010.account.usage.record.monthly import MonthlyList +from twilio.rest.api.v2010.account.usage.record.this_month import ThisMonthList +from twilio.rest.api.v2010.account.usage.record.today import TodayList +from twilio.rest.api.v2010.account.usage.record.yearly import YearlyList +from twilio.rest.api.v2010.account.usage.record.yesterday import YesterdayList + + +class RecordInstance(InstanceResource): + + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" + AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" + ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" + AUTHY_AUTHENTICATIONS = "authy-authentications" + AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" + AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" + AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" + AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" + AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" + CALL_PROGESS_EVENTS = "call-progess-events" + CALLERIDLOOKUPS = "calleridlookups" + CALLS = "calls" + CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" + CALLS_GLOBALCONFERENCE = "calls-globalconference" + CALLS_INBOUND = "calls-inbound" + CALLS_INBOUND_LOCAL = "calls-inbound-local" + CALLS_INBOUND_MOBILE = "calls-inbound-mobile" + CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" + CALLS_OUTBOUND = "calls-outbound" + CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" + CALLS_RECORDINGS = "calls-recordings" + CALLS_SIP = "calls-sip" + CALLS_SIP_INBOUND = "calls-sip-inbound" + CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" + CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" + CONVERSATIONS = "conversations" + CONVERSATIONS_API_REQUESTS = "conversations-api-requests" + CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" + CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" + CONVERSATIONS_EVENTS = "conversations-events" + CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" + CONVERSATIONS_PARTICIPANTS = "conversations-participants" + CPS = "cps" + CREDIT_TRANSFER = "credit-transfer" + EMAIL = "email" + EMERGING_TECH = "emerging-tech" + ENGAGEMENT_SUITE_PACKAGED_PLANS = "engagement-suite-packaged-plans" + ENHANCED_LINE_TYPE_LOOKUPS = "enhanced-line-type-lookups" + ENTERPRISE = "enterprise" + EVENTS = "events" + EXPERIMENT_FRANCE_SMS = "experiment-france-sms" + EXPERIMENT_INDIA_SMS = "experiment-india-sms" + EXPERIMENT_UK_SMS = "experiment-uk-sms" + FAILED_MESSAGE_PROCESSING_FEE = "failed-message-processing-fee" + FLEX = "flex" + FLEX_ACTIVE_USER_HOURS = "flex-active-user-hours" + FLEX_CONCURRENT_USERS = "flex-concurrent-users" + FLEX_CONVERSATIONAL_INSIGHTS = "flex-conversational-insights" + FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES = "flex-conversational-insights-messages" + FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = ( + "flex-conversational-insights-voice-minutes" + ) + FLEX_EMAIL_USAGE = "flex-email-usage" + FLEX_MESSAGING_USAGE = "flex-messaging-usage" + FLEX_PARTNER_SPINSCI = "flex-partner-spinsci" + FLEX_PARTNER_XCELERATE = "flex-partner-xcelerate" + FLEX_RESELLER_ECOSYSTEM = "flex-reseller-ecosystem" + FLEX_UNIQUE_USER = "flex-unique-user" + FLEX_USAGE = "flex-usage" + FLEX_USERS = "flex-users" + FLEX_VOICE_MINUTE = "flex-voice-minute" + FLEX_YTICA = "flex-ytica" + FRAUD_LOOKUPS = "fraud-lookups" + FRONTLINE = "frontline" + FRONTLINE_USERS = "frontline-users" + FUNCTIONS = "functions" + GENERIC_PAY_TRANSACTIONS = "generic-pay-transactions" + GROUP_ROOMS = "group-rooms" + GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" + GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" + GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" + GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" + GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" + GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" + GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" + GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" + IP_MESSAGING = "ip-messaging" + IP_MESSAGING_COMMANDS = "ip-messaging-commands" + IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" + IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" + IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" + IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" + IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" + LINE_STATUS_LOOKUPS = "line-status-lookups" + LIVE_ACTIVITY_LOOKUPS = "live-activity-lookups" + LOOKUP_BUCKET_ADJUSTMENT = "lookup-bucket-adjustment" + LOOKUP_IDENTITY_MATCH = "lookup-identity-match" + LOOKUPS = "lookups" + MARKETPLACE = "marketplace" + MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) + MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" + MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" + MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" + MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" + MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION = "marketplace-deepgram-transcription" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE = ( + "marketplace-deepgram-transcription-base" + ) + MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED = ( + "marketplace-deepgram-transscription-enhanced" + ) + MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( + "marketplace-digital-segment-business-info" + ) + MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( + "marketplace-facebook-offline-conversions" + ) + MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" + MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( + "marketplace-ibm-watson-message-insights" + ) + MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( + "marketplace-ibm-watson-message-sentiment" + ) + MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( + "marketplace-ibm-watson-recording-analysis" + ) + MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" + MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" + MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( + "marketplace-infogroup-dataaxle-bizinfo" + ) + MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( + "marketplace-keen-io-contact-center-analytics" + ) + MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" + MARKETPLACE_MARCHEX_RECORDING_ANALYSIS = ( + "marketplace-marchex-recording-analysis" + ) + MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( + "marketplace-marchex-sentiment-analysis-for-sms" + ) + MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( + "marketplace-marketplace-nextcaller-social-id" + ) + MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( + "marketplace-mobile-commons-opt-out-classifier" + ) + MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( + "marketplace-nexiwave-voicemail-to-text" + ) + MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( + "marketplace-nextcaller-advanced-caller-identification" + ) + MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" + MARKETPLACE_PAY_ADDONS = "marketplace-pay-addons" + MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR = ( + "marketplace-pay-addons-basecommerce-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR = ( + "marketplace-pay-addons-braintree-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR = ( + "marketplace-pay-addons-cardconnect-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR = ( + "marketplace-pay-addons-chase-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplace-pay-addons-shuttle-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplace-pay-addons-stripe-pay-connector" + ) + MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" + MARKETPLACE_POLY_AI_CONNECTOR = "marketplace-poly-ai-connector" + MARKETPLACE_REALPHONEVALIDATION = "marketplace-realphonevalidation" + MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( + "marketplace-remeeting-automatic-speech-recognition" + ) + MARKETPLACE_SPOKE_PHONE_LICENSE_PRO = "marketplace-spoke-phone-license-pro" + MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD = ( + "marketplace-spoke-phone-license-standard" + ) + MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( + "marketplace-tcpa-defense-solutions-blacklist-feed" + ) + MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" + MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION = ( + "marketplace-trestle-solutions-caller-identification" + ) + MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" + MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( + "marketplace-twilio-caller-name-lookup-us" + ) + MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( + "marketplace-twilio-carrier-information-lookup" + ) + MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" + MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" + MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) + MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" + MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( + "marketplace-ytica-contact-center-reporting-analytics" + ) + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplay-pay-addons-shuttle-pay-connector" + ) + MEDIA_COMPOSER_MINUTES = "media-composer-minutes" + MEDIASTORAGE = "mediastorage" + MIN_SPEND_ADJUSTMENTS = "min-spend-adjustments" + MMS = "mms" + MMS_INBOUND = "mms-inbound" + MMS_INBOUND_LONGCODE = "mms-inbound-longcode" + MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" + MMS_INBOUND_TOLL_FREE = "mms-inbound-toll-free" + MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" + MMS_OUTBOUND = "mms-outbound" + MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" + MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" + MMS_OUTBOUND_TOLLFREE = "mms-outbound-tollfree" + MONITOR = "monitor" + MONITOR_READS = "monitor-reads" + MONITOR_STORAGE = "monitor-storage" + MONITOR_WRITES = "monitor-writes" + NOTIFY = "notify" + NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" + NOTIFY_CHANNELS = "notify-channels" + NUMBER_FORMAT_LOOKUPS = "number-format-lookups" + PCHAT = "pchat" + PCHAT_ACTIONS = "pchat-actions" + PCHAT_APS = "pchat-aps" + PCHAT_CONV_MED_STORAGE = "pchat-conv-med-storage" + PCHAT_MESSAGES = "pchat-messages" + PCHAT_NOTIFICATIONS = "pchat-notifications" + PCHAT_READS = "pchat-reads" + PCHAT_USERS = "pchat-users" + PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "peer-to-peer-rooms-participant-minutes" + ) + PFAX = "pfax" + PFAX_MINUTES = "pfax-minutes" + PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" + PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" + PFAX_PAGES = "pfax-pages" + PHONE_QUALITY_SCORE_LOOKUPS = "phone-quality-score-lookups" + PHONENUMBERS = "phonenumbers" + PHONENUMBERS_CPS = "phonenumbers-cps" + PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" + PHONENUMBERS_LOCAL = "phonenumbers-local" + PHONENUMBERS_MOBILE = "phonenumbers-mobile" + PHONENUMBERS_PORTING = "phonenumbers-porting" + PHONENUMBERS_SETUPS = "phonenumbers-setups" + PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" + PREMIUMSUPPORT = "premiumsupport" + PREMIUMSUPPORT_PERCENTAGE_SPEND = "premiumsupport-percentage-spend" + PROGRAMMABLEVOICE_PLATFORM = "programmablevoice-platform" + PROGRAMMABLEVOICECONN_CLIENTSDK = "programmablevoiceconn-clientsdk" + PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND = ( + "programmablevoiceconn-clientsdk-inbound" + ) + PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND = ( + "programmablevoiceconn-clientsdk-outbound" + ) + PROGRAMMABLEVOICECONN_ONNET = "programmablevoiceconn-onnet" + PROGRAMMABLEVOICECONN_ONNET_INBOUND = "programmablevoiceconn-onnet-inbound" + PROGRAMMABLEVOICECONN_ONNET_OUTBOUND = "programmablevoiceconn-onnet-outbound" + PROGRAMMABLEVOICECONN_SIP = "programmablevoiceconn-sip" + PROGRAMMABLEVOICECONN_SIP_INBOUND = "programmablevoiceconn-sip-inbound" + PROGRAMMABLEVOICECONN_SIP_OUTBOUND = "programmablevoiceconn-sip-outbound" + PROGRAMMABLEVOICECONNECTIVITY = "programmablevoiceconnectivity" + PROXY = "proxy" + PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" + PROXY_BUCKET_ADJUSTMENT = "proxy-bucket-adjustment" + PROXY_LICENSES = "proxy-licenses" + PSTNCONNECTIVITY = "pstnconnectivity" + PSTNCONNECTIVITY_INBOUND = "pstnconnectivity-inbound" + PSTNCONNECTIVITY_OUTBOUND = "pstnconnectivity-outbound" + PV = "pv" + PV_BASIC_ROOMS = "pv-basic-rooms" + PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" + PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" + PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" + PV_COMPOSITION_MINUTES = "pv-composition-minutes" + PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" + PV_ROOM_PARTICIPANTS = "pv-room-participants" + PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" + PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" + PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" + PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" + PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" + PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" + PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" + PV_ROOMS = "pv-rooms" + PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" + RCS_MESSAGES = "rcs-messages" + REASSIGNED_NUMBER = "reassigned-number" + RECORDINGS = "recordings" + RECORDINGSTORAGE = "recordingstorage" + SHORTCODES = "shortcodes" + SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" + SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" + SHORTCODES_MPS = "shortcodes-mps" + SHORTCODES_RANDOM = "shortcodes-random" + SHORTCODES_SETUP_FEES = "shortcodes-setup-fees" + SHORTCODES_UK = "shortcodes-uk" + SHORTCODES_VANITY = "shortcodes-vanity" + SIM_SWAP_LOOKUPS = "sim-swap-lookups" + SIP_SECURE_MEDIA = "sip-secure-media" + SMALL_GROUP_ROOMS = "small-group-rooms" + SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" + SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" + SMS = "sms" + SMS_INBOUND = "sms-inbound" + SMS_INBOUND_LONGCODE = "sms-inbound-longcode" + SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" + SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" + SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) + SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" + SMS_OUTBOUND = "sms-outbound" + SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" + SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" + SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" + SPEECH_RECOGNITION = "speech-recognition" + STUDIO_ENGAGEMENTS = "studio-engagements" + SYNC = "sync" + SYNC_ACTIONS = "sync-actions" + SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" + SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" + TASKROUTER_TASKS = "taskrouter-tasks" + TOTALPRICE = "totalprice" + TRANSCRIPTIONS = "transcriptions" + TRUNKING_CPS = "trunking-cps" + TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" + TRUNKING_ORIGINATION = "trunking-origination" + TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" + TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" + TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" + TRUNKING_RECORDINGS = "trunking-recordings" + TRUNKING_SECURE = "trunking-secure" + TRUNKING_TERMINATION = "trunking-termination" + TTS_GOOGLE = "tts-google" + TURNMEGABYTES = "turnmegabytes" + TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" + TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" + TURNMEGABYTES_GERMANY = "turnmegabytes-germany" + TURNMEGABYTES_INDIA = "turnmegabytes-india" + TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" + TURNMEGABYTES_JAPAN = "turnmegabytes-japan" + TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" + TURNMEGABYTES_USEAST = "turnmegabytes-useast" + TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" + TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) + VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" + VOICE_INSIGHTS = "voice-insights" + VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-client-insights-on-demand-minute" + ) + VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-ptsn-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-interface-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-trunking-insights-on-demand-minute" + ) + VOICE_INTELLIGENCE = "voice-intelligence" + VOICE_INTELLIGENCE_EIP_OPERATORS = "voice-intelligence-eip-operators" + VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" + VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" + WDS = "wds" + WIRELESS = "wireless" + WIRELESS_DATA = "wireless-data" + WIRELESS_DATA_PAYG = "wireless-data-payg" + WIRELESS_DATA_PAYG_AFRICA = "wireless-data-payg-africa" + WIRELESS_DATA_PAYG_ASIA = "wireless-data-payg-asia" + WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA = ( + "wireless-data-payg-centralandsouthamerica" + ) + WIRELESS_DATA_PAYG_EUROPE = "wireless-data-payg-europe" + WIRELESS_DATA_PAYG_NORTHAMERICA = "wireless-data-payg-northamerica" + WIRELESS_DATA_PAYG_OCEANIA = "wireless-data-payg-oceania" + WIRELESS_DATA_QUOTA1 = "wireless-data-quota1" + WIRELESS_DATA_QUOTA1_AFRICA = "wireless-data-quota1-africa" + WIRELESS_DATA_QUOTA1_ASIA = "wireless-data-quota1-asia" + WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota1-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA1_EUROPE = "wireless-data-quota1-europe" + WIRELESS_DATA_QUOTA1_NORTHAMERICA = "wireless-data-quota1-northamerica" + WIRELESS_DATA_QUOTA1_OCEANIA = "wireless-data-quota1-oceania" + WIRELESS_DATA_QUOTA10 = "wireless-data-quota10" + WIRELESS_DATA_QUOTA10_AFRICA = "wireless-data-quota10-africa" + WIRELESS_DATA_QUOTA10_ASIA = "wireless-data-quota10-asia" + WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota10-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA10_EUROPE = "wireless-data-quota10-europe" + WIRELESS_DATA_QUOTA10_NORTHAMERICA = "wireless-data-quota10-northamerica" + WIRELESS_DATA_QUOTA10_OCEANIA = "wireless-data-quota10-oceania" + WIRELESS_DATA_QUOTA50 = "wireless-data-quota50" + WIRELESS_DATA_QUOTA50_AFRICA = "wireless-data-quota50-africa" + WIRELESS_DATA_QUOTA50_ASIA = "wireless-data-quota50-asia" + WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota50-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA50_EUROPE = "wireless-data-quota50-europe" + WIRELESS_DATA_QUOTA50_NORTHAMERICA = "wireless-data-quota50-northamerica" + WIRELESS_DATA_QUOTA50_OCEANIA = "wireless-data-quota50-oceania" + WIRELESS_DATA_QUOTACUSTOM = "wireless-data-quotacustom" + WIRELESS_DATA_QUOTACUSTOM_AFRICA = "wireless-data-quotacustom-africa" + WIRELESS_DATA_QUOTACUSTOM_ASIA = "wireless-data-quotacustom-asia" + WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quotacustom-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_EUROPE = "wireless-data-quotacustom-europe" + WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA = ( + "wireless-data-quotacustom-northamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_OCEANIA = "wireless-data-quotacustom-oceania" + WIRELESS_MRC_PAYG = "wireless-mrc-payg" + WIRELESS_MRC_QUOTA1 = "wireless-mrc-quota1" + WIRELESS_MRC_QUOTA10 = "wireless-mrc-quota10" + WIRELESS_MRC_QUOTA50 = "wireless-mrc-quota50" + WIRELESS_MRC_QUOTACUSTOM = "wireless-mrc-quotacustom" + WIRELESS_ORDERS = "wireless-orders" + WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" + WIRELESS_ORDERS_BULK = "wireless-orders-bulk" + WIRELESS_ORDERS_ESIM = "wireless-orders-esim" + WIRELESS_ORDERS_STARTER = "wireless-orders-starter" + WIRELESS_QUOTAS = "wireless-quotas" + WIRELESS_SMS_AFRICA = "wireless-sms-africa" + WIRELESS_SMS_ASIA = "wireless-sms-asia" + WIRELESS_SMS_CENTRALANDSOUTHAMERICA = "wireless-sms-centralandsouthamerica" + WIRELESS_SMS_EUROPE = "wireless-sms-europe" + WIRELESS_SMS_NORTHAMERICA = "wireless-sms-northamerica" + WIRELESS_SMS_OCEANIA = "wireless-sms-oceania" + WIRELESS_SUPER_SIM = "wireless-super-sim" + WIRELESS_SUPER_SIM_DATA = "wireless-super-sim-data" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA = ( + "wireless-super-sim-data-north-america-usa" + ) + WIRELESS_SUPER_SIM_DATA_PAYG = "wireless-super-sim-data-payg" + WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE = "wireless-super-sim-data-payg-europe" + WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA = ( + "wireless-super-sim-data-payg-north-america" + ) + WIRELESS_SUPER_SIM_HARDWARE = "wireless-super-sim-hardware" + WIRELESS_SUPER_SIM_HARDWARE_BULK = "wireless-super-sim-hardware-bulk" + WIRELESS_SUPER_SIM_SMSCOMMANDS = "wireless-super-sim-smscommands" + WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA = "wireless-super-sim-smscommands-africa" + WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA = "wireless-super-sim-smscommands-asia" + WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA = ( + "wireless-super-sim-smscommands-cent-and-south-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE = "wireless-super-sim-smscommands-europe" + WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA = ( + "wireless-super-sim-smscommands-north-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA = ( + "wireless-super-sim-smscommands-oceania" + ) + WIRELESS_SUPER_SIM_SUBSCRIPTION = "wireless-super-sim-subscription" + WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG = "wireless-super-sim-subscription-payg" + WIRELESS_USAGE = "wireless-usage" + WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" + WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" + WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" + WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-commands-centralandsouthamerica" + ) + WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" + WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" + WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" + WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" + WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" + WIRELESS_USAGE_DATA = "wireless-usage-data" + WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" + WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" + WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-data-centralandsouthamerica" + ) + WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( + "wireless-usage-data-custom-additionalmb" + ) + WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" + WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" + WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" + WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( + "wireless-usage-data-individual-additionalgb" + ) + WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( + "wireless-usage-data-individual-firstgb" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( + "wireless-usage-data-international-roaming-canada" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( + "wireless-usage-data-international-roaming-india" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( + "wireless-usage-data-international-roaming-mexico" + ) + WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" + WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" + WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" + WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" + WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" + WIRELESS_USAGE_MRC = "wireless-usage-mrc" + WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" + WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" + WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" + WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" + WIRELESS_USAGE_SMS = "wireless-usage-sms" + WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + :ivar api_version: The API version used to create the resource. + :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + :ivar category: + :ivar count: The number of usage events, such as the number of calls. + :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + :ivar description: A plain-language description of the usage category. + :ivar end_date: The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar price: The total price of the usage in the currency specified in `price_unit` and associated with the account. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + :ivar start_date: The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar subresource_uris: A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar usage: The amount used to bill usage and measured in units described in `usage_unit`. + :ivar usage_unit: The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.as_of: Optional[str] = payload.get("as_of") + self.category: Optional["RecordInstance.Category"] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RecordPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RecordInstance: + """ + Build an instance of RecordInstance + + :param payload: Payload response from the API + """ + return RecordInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RecordList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the RecordList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records.json".format( + **self._solution + ) + + self._all_time: Optional[AllTimeList] = None + self._daily: Optional[DailyList] = None + self._last_month: Optional[LastMonthList] = None + self._monthly: Optional[MonthlyList] = None + self._this_month: Optional[ThisMonthList] = None + self._today: Optional[TodayList] = None + self._yearly: Optional[YearlyList] = None + self._yesterday: Optional[YesterdayList] = None + + def stream( + self, + category: Union["RecordInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RecordInstance]: + """ + Streams RecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "RecordInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + category: Union["RecordInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RecordInstance]: + """ + Asynchronously streams RecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "RecordInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["RecordInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RecordInstance]: + """ + Lists RecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "RecordInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + category: Union["RecordInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RecordInstance]: + """ + Asynchronously lists RecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "RecordInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + category: Union["RecordInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RecordPage: + """ + Retrieve a single page of RecordInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordPage(self._version, response, self._solution) + + async def page_async( + self, + category: Union["RecordInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RecordPage: + """ + Asynchronously retrieve a single page of RecordInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RecordPage: + """ + Retrieve a specific page of RecordInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RecordInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RecordPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RecordPage: + """ + Asynchronously retrieve a specific page of RecordInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RecordInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RecordPage(self._version, response, self._solution) + + @property + def all_time(self) -> AllTimeList: + """ + Access the all_time + """ + if self._all_time is None: + self._all_time = AllTimeList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._all_time + + @property + def daily(self) -> DailyList: + """ + Access the daily + """ + if self._daily is None: + self._daily = DailyList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._daily + + @property + def last_month(self) -> LastMonthList: + """ + Access the last_month + """ + if self._last_month is None: + self._last_month = LastMonthList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._last_month + + @property + def monthly(self) -> MonthlyList: + """ + Access the monthly + """ + if self._monthly is None: + self._monthly = MonthlyList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._monthly + + @property + def this_month(self) -> ThisMonthList: + """ + Access the this_month + """ + if self._this_month is None: + self._this_month = ThisMonthList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._this_month + + @property + def today(self) -> TodayList: + """ + Access the today + """ + if self._today is None: + self._today = TodayList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._today + + @property + def yearly(self) -> YearlyList: + """ + Access the yearly + """ + if self._yearly is None: + self._yearly = YearlyList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._yearly + + @property + def yesterday(self) -> YesterdayList: + """ + Access the yesterday + """ + if self._yesterday is None: + self._yesterday = YesterdayList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._yesterday + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..36a023be Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/all_time.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/all_time.cpython-312.pyc new file mode 100644 index 00000000..75630e79 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/all_time.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/daily.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/daily.cpython-312.pyc new file mode 100644 index 00000000..181ab2c5 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/daily.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/last_month.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/last_month.cpython-312.pyc new file mode 100644 index 00000000..c3f9dcfd Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/last_month.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/monthly.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/monthly.cpython-312.pyc new file mode 100644 index 00000000..bfd496c9 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/monthly.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/this_month.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/this_month.cpython-312.pyc new file mode 100644 index 00000000..86df194d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/this_month.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/today.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/today.cpython-312.pyc new file mode 100644 index 00000000..40a57138 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/today.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/yearly.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/yearly.cpython-312.pyc new file mode 100644 index 00000000..03c46117 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/yearly.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/yesterday.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/yesterday.cpython-312.pyc new file mode 100644 index 00000000..8d8c9567 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/__pycache__/yesterday.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/all_time.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/all_time.py new file mode 100644 index 00000000..991f4a0b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/all_time.py @@ -0,0 +1,1211 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AllTimeInstance(InstanceResource): + + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" + AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" + ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" + AUTHY_AUTHENTICATIONS = "authy-authentications" + AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" + AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" + AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" + AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" + AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" + CALL_PROGESS_EVENTS = "call-progess-events" + CALLERIDLOOKUPS = "calleridlookups" + CALLS = "calls" + CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" + CALLS_GLOBALCONFERENCE = "calls-globalconference" + CALLS_INBOUND = "calls-inbound" + CALLS_INBOUND_LOCAL = "calls-inbound-local" + CALLS_INBOUND_MOBILE = "calls-inbound-mobile" + CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" + CALLS_OUTBOUND = "calls-outbound" + CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" + CALLS_RECORDINGS = "calls-recordings" + CALLS_SIP = "calls-sip" + CALLS_SIP_INBOUND = "calls-sip-inbound" + CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" + CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" + CONVERSATIONS = "conversations" + CONVERSATIONS_API_REQUESTS = "conversations-api-requests" + CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" + CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" + CONVERSATIONS_EVENTS = "conversations-events" + CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" + CONVERSATIONS_PARTICIPANTS = "conversations-participants" + CPS = "cps" + CREDIT_TRANSFER = "credit-transfer" + EMAIL = "email" + EMERGING_TECH = "emerging-tech" + ENGAGEMENT_SUITE_PACKAGED_PLANS = "engagement-suite-packaged-plans" + ENHANCED_LINE_TYPE_LOOKUPS = "enhanced-line-type-lookups" + ENTERPRISE = "enterprise" + EVENTS = "events" + EXPERIMENT_FRANCE_SMS = "experiment-france-sms" + EXPERIMENT_INDIA_SMS = "experiment-india-sms" + EXPERIMENT_UK_SMS = "experiment-uk-sms" + FAILED_MESSAGE_PROCESSING_FEE = "failed-message-processing-fee" + FLEX = "flex" + FLEX_ACTIVE_USER_HOURS = "flex-active-user-hours" + FLEX_CONCURRENT_USERS = "flex-concurrent-users" + FLEX_CONVERSATIONAL_INSIGHTS = "flex-conversational-insights" + FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES = "flex-conversational-insights-messages" + FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = ( + "flex-conversational-insights-voice-minutes" + ) + FLEX_EMAIL_USAGE = "flex-email-usage" + FLEX_MESSAGING_USAGE = "flex-messaging-usage" + FLEX_PARTNER_SPINSCI = "flex-partner-spinsci" + FLEX_PARTNER_XCELERATE = "flex-partner-xcelerate" + FLEX_RESELLER_ECOSYSTEM = "flex-reseller-ecosystem" + FLEX_UNIQUE_USER = "flex-unique-user" + FLEX_USAGE = "flex-usage" + FLEX_USERS = "flex-users" + FLEX_VOICE_MINUTE = "flex-voice-minute" + FLEX_YTICA = "flex-ytica" + FRAUD_LOOKUPS = "fraud-lookups" + FRONTLINE = "frontline" + FRONTLINE_USERS = "frontline-users" + FUNCTIONS = "functions" + GENERIC_PAY_TRANSACTIONS = "generic-pay-transactions" + GROUP_ROOMS = "group-rooms" + GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" + GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" + GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" + GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" + GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" + GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" + GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" + GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" + IP_MESSAGING = "ip-messaging" + IP_MESSAGING_COMMANDS = "ip-messaging-commands" + IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" + IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" + IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" + IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" + IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" + LINE_STATUS_LOOKUPS = "line-status-lookups" + LIVE_ACTIVITY_LOOKUPS = "live-activity-lookups" + LOOKUP_BUCKET_ADJUSTMENT = "lookup-bucket-adjustment" + LOOKUP_IDENTITY_MATCH = "lookup-identity-match" + LOOKUPS = "lookups" + MARKETPLACE = "marketplace" + MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) + MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" + MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" + MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" + MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" + MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION = "marketplace-deepgram-transcription" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE = ( + "marketplace-deepgram-transcription-base" + ) + MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED = ( + "marketplace-deepgram-transscription-enhanced" + ) + MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( + "marketplace-digital-segment-business-info" + ) + MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( + "marketplace-facebook-offline-conversions" + ) + MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" + MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( + "marketplace-ibm-watson-message-insights" + ) + MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( + "marketplace-ibm-watson-message-sentiment" + ) + MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( + "marketplace-ibm-watson-recording-analysis" + ) + MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" + MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" + MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( + "marketplace-infogroup-dataaxle-bizinfo" + ) + MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( + "marketplace-keen-io-contact-center-analytics" + ) + MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" + MARKETPLACE_MARCHEX_RECORDING_ANALYSIS = ( + "marketplace-marchex-recording-analysis" + ) + MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( + "marketplace-marchex-sentiment-analysis-for-sms" + ) + MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( + "marketplace-marketplace-nextcaller-social-id" + ) + MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( + "marketplace-mobile-commons-opt-out-classifier" + ) + MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( + "marketplace-nexiwave-voicemail-to-text" + ) + MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( + "marketplace-nextcaller-advanced-caller-identification" + ) + MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" + MARKETPLACE_PAY_ADDONS = "marketplace-pay-addons" + MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR = ( + "marketplace-pay-addons-basecommerce-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR = ( + "marketplace-pay-addons-braintree-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR = ( + "marketplace-pay-addons-cardconnect-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR = ( + "marketplace-pay-addons-chase-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplace-pay-addons-shuttle-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplace-pay-addons-stripe-pay-connector" + ) + MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" + MARKETPLACE_POLY_AI_CONNECTOR = "marketplace-poly-ai-connector" + MARKETPLACE_REALPHONEVALIDATION = "marketplace-realphonevalidation" + MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( + "marketplace-remeeting-automatic-speech-recognition" + ) + MARKETPLACE_SPOKE_PHONE_LICENSE_PRO = "marketplace-spoke-phone-license-pro" + MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD = ( + "marketplace-spoke-phone-license-standard" + ) + MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( + "marketplace-tcpa-defense-solutions-blacklist-feed" + ) + MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" + MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION = ( + "marketplace-trestle-solutions-caller-identification" + ) + MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" + MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( + "marketplace-twilio-caller-name-lookup-us" + ) + MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( + "marketplace-twilio-carrier-information-lookup" + ) + MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" + MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" + MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) + MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" + MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( + "marketplace-ytica-contact-center-reporting-analytics" + ) + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplay-pay-addons-shuttle-pay-connector" + ) + MEDIA_COMPOSER_MINUTES = "media-composer-minutes" + MEDIASTORAGE = "mediastorage" + MIN_SPEND_ADJUSTMENTS = "min-spend-adjustments" + MMS = "mms" + MMS_INBOUND = "mms-inbound" + MMS_INBOUND_LONGCODE = "mms-inbound-longcode" + MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" + MMS_INBOUND_TOLL_FREE = "mms-inbound-toll-free" + MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" + MMS_OUTBOUND = "mms-outbound" + MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" + MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" + MMS_OUTBOUND_TOLLFREE = "mms-outbound-tollfree" + MONITOR = "monitor" + MONITOR_READS = "monitor-reads" + MONITOR_STORAGE = "monitor-storage" + MONITOR_WRITES = "monitor-writes" + NOTIFY = "notify" + NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" + NOTIFY_CHANNELS = "notify-channels" + NUMBER_FORMAT_LOOKUPS = "number-format-lookups" + PCHAT = "pchat" + PCHAT_ACTIONS = "pchat-actions" + PCHAT_APS = "pchat-aps" + PCHAT_CONV_MED_STORAGE = "pchat-conv-med-storage" + PCHAT_MESSAGES = "pchat-messages" + PCHAT_NOTIFICATIONS = "pchat-notifications" + PCHAT_READS = "pchat-reads" + PCHAT_USERS = "pchat-users" + PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "peer-to-peer-rooms-participant-minutes" + ) + PFAX = "pfax" + PFAX_MINUTES = "pfax-minutes" + PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" + PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" + PFAX_PAGES = "pfax-pages" + PHONE_QUALITY_SCORE_LOOKUPS = "phone-quality-score-lookups" + PHONENUMBERS = "phonenumbers" + PHONENUMBERS_CPS = "phonenumbers-cps" + PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" + PHONENUMBERS_LOCAL = "phonenumbers-local" + PHONENUMBERS_MOBILE = "phonenumbers-mobile" + PHONENUMBERS_PORTING = "phonenumbers-porting" + PHONENUMBERS_SETUPS = "phonenumbers-setups" + PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" + PREMIUMSUPPORT = "premiumsupport" + PREMIUMSUPPORT_PERCENTAGE_SPEND = "premiumsupport-percentage-spend" + PROGRAMMABLEVOICE_PLATFORM = "programmablevoice-platform" + PROGRAMMABLEVOICECONN_CLIENTSDK = "programmablevoiceconn-clientsdk" + PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND = ( + "programmablevoiceconn-clientsdk-inbound" + ) + PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND = ( + "programmablevoiceconn-clientsdk-outbound" + ) + PROGRAMMABLEVOICECONN_ONNET = "programmablevoiceconn-onnet" + PROGRAMMABLEVOICECONN_ONNET_INBOUND = "programmablevoiceconn-onnet-inbound" + PROGRAMMABLEVOICECONN_ONNET_OUTBOUND = "programmablevoiceconn-onnet-outbound" + PROGRAMMABLEVOICECONN_SIP = "programmablevoiceconn-sip" + PROGRAMMABLEVOICECONN_SIP_INBOUND = "programmablevoiceconn-sip-inbound" + PROGRAMMABLEVOICECONN_SIP_OUTBOUND = "programmablevoiceconn-sip-outbound" + PROGRAMMABLEVOICECONNECTIVITY = "programmablevoiceconnectivity" + PROXY = "proxy" + PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" + PROXY_BUCKET_ADJUSTMENT = "proxy-bucket-adjustment" + PROXY_LICENSES = "proxy-licenses" + PSTNCONNECTIVITY = "pstnconnectivity" + PSTNCONNECTIVITY_INBOUND = "pstnconnectivity-inbound" + PSTNCONNECTIVITY_OUTBOUND = "pstnconnectivity-outbound" + PV = "pv" + PV_BASIC_ROOMS = "pv-basic-rooms" + PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" + PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" + PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" + PV_COMPOSITION_MINUTES = "pv-composition-minutes" + PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" + PV_ROOM_PARTICIPANTS = "pv-room-participants" + PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" + PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" + PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" + PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" + PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" + PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" + PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" + PV_ROOMS = "pv-rooms" + PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" + RCS_MESSAGES = "rcs-messages" + REASSIGNED_NUMBER = "reassigned-number" + RECORDINGS = "recordings" + RECORDINGSTORAGE = "recordingstorage" + SHORTCODES = "shortcodes" + SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" + SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" + SHORTCODES_MPS = "shortcodes-mps" + SHORTCODES_RANDOM = "shortcodes-random" + SHORTCODES_SETUP_FEES = "shortcodes-setup-fees" + SHORTCODES_UK = "shortcodes-uk" + SHORTCODES_VANITY = "shortcodes-vanity" + SIM_SWAP_LOOKUPS = "sim-swap-lookups" + SIP_SECURE_MEDIA = "sip-secure-media" + SMALL_GROUP_ROOMS = "small-group-rooms" + SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" + SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" + SMS = "sms" + SMS_INBOUND = "sms-inbound" + SMS_INBOUND_LONGCODE = "sms-inbound-longcode" + SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" + SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" + SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) + SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" + SMS_OUTBOUND = "sms-outbound" + SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" + SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" + SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" + SPEECH_RECOGNITION = "speech-recognition" + STUDIO_ENGAGEMENTS = "studio-engagements" + SYNC = "sync" + SYNC_ACTIONS = "sync-actions" + SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" + SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" + TASKROUTER_TASKS = "taskrouter-tasks" + TOTALPRICE = "totalprice" + TRANSCRIPTIONS = "transcriptions" + TRUNKING_CPS = "trunking-cps" + TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" + TRUNKING_ORIGINATION = "trunking-origination" + TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" + TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" + TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" + TRUNKING_RECORDINGS = "trunking-recordings" + TRUNKING_SECURE = "trunking-secure" + TRUNKING_TERMINATION = "trunking-termination" + TTS_GOOGLE = "tts-google" + TURNMEGABYTES = "turnmegabytes" + TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" + TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" + TURNMEGABYTES_GERMANY = "turnmegabytes-germany" + TURNMEGABYTES_INDIA = "turnmegabytes-india" + TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" + TURNMEGABYTES_JAPAN = "turnmegabytes-japan" + TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" + TURNMEGABYTES_USEAST = "turnmegabytes-useast" + TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" + TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) + VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" + VOICE_INSIGHTS = "voice-insights" + VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-client-insights-on-demand-minute" + ) + VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-ptsn-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-interface-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-trunking-insights-on-demand-minute" + ) + VOICE_INTELLIGENCE = "voice-intelligence" + VOICE_INTELLIGENCE_EIP_OPERATORS = "voice-intelligence-eip-operators" + VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" + VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" + WDS = "wds" + WIRELESS = "wireless" + WIRELESS_DATA = "wireless-data" + WIRELESS_DATA_PAYG = "wireless-data-payg" + WIRELESS_DATA_PAYG_AFRICA = "wireless-data-payg-africa" + WIRELESS_DATA_PAYG_ASIA = "wireless-data-payg-asia" + WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA = ( + "wireless-data-payg-centralandsouthamerica" + ) + WIRELESS_DATA_PAYG_EUROPE = "wireless-data-payg-europe" + WIRELESS_DATA_PAYG_NORTHAMERICA = "wireless-data-payg-northamerica" + WIRELESS_DATA_PAYG_OCEANIA = "wireless-data-payg-oceania" + WIRELESS_DATA_QUOTA1 = "wireless-data-quota1" + WIRELESS_DATA_QUOTA1_AFRICA = "wireless-data-quota1-africa" + WIRELESS_DATA_QUOTA1_ASIA = "wireless-data-quota1-asia" + WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota1-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA1_EUROPE = "wireless-data-quota1-europe" + WIRELESS_DATA_QUOTA1_NORTHAMERICA = "wireless-data-quota1-northamerica" + WIRELESS_DATA_QUOTA1_OCEANIA = "wireless-data-quota1-oceania" + WIRELESS_DATA_QUOTA10 = "wireless-data-quota10" + WIRELESS_DATA_QUOTA10_AFRICA = "wireless-data-quota10-africa" + WIRELESS_DATA_QUOTA10_ASIA = "wireless-data-quota10-asia" + WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota10-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA10_EUROPE = "wireless-data-quota10-europe" + WIRELESS_DATA_QUOTA10_NORTHAMERICA = "wireless-data-quota10-northamerica" + WIRELESS_DATA_QUOTA10_OCEANIA = "wireless-data-quota10-oceania" + WIRELESS_DATA_QUOTA50 = "wireless-data-quota50" + WIRELESS_DATA_QUOTA50_AFRICA = "wireless-data-quota50-africa" + WIRELESS_DATA_QUOTA50_ASIA = "wireless-data-quota50-asia" + WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota50-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA50_EUROPE = "wireless-data-quota50-europe" + WIRELESS_DATA_QUOTA50_NORTHAMERICA = "wireless-data-quota50-northamerica" + WIRELESS_DATA_QUOTA50_OCEANIA = "wireless-data-quota50-oceania" + WIRELESS_DATA_QUOTACUSTOM = "wireless-data-quotacustom" + WIRELESS_DATA_QUOTACUSTOM_AFRICA = "wireless-data-quotacustom-africa" + WIRELESS_DATA_QUOTACUSTOM_ASIA = "wireless-data-quotacustom-asia" + WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quotacustom-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_EUROPE = "wireless-data-quotacustom-europe" + WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA = ( + "wireless-data-quotacustom-northamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_OCEANIA = "wireless-data-quotacustom-oceania" + WIRELESS_MRC_PAYG = "wireless-mrc-payg" + WIRELESS_MRC_QUOTA1 = "wireless-mrc-quota1" + WIRELESS_MRC_QUOTA10 = "wireless-mrc-quota10" + WIRELESS_MRC_QUOTA50 = "wireless-mrc-quota50" + WIRELESS_MRC_QUOTACUSTOM = "wireless-mrc-quotacustom" + WIRELESS_ORDERS = "wireless-orders" + WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" + WIRELESS_ORDERS_BULK = "wireless-orders-bulk" + WIRELESS_ORDERS_ESIM = "wireless-orders-esim" + WIRELESS_ORDERS_STARTER = "wireless-orders-starter" + WIRELESS_QUOTAS = "wireless-quotas" + WIRELESS_SMS_AFRICA = "wireless-sms-africa" + WIRELESS_SMS_ASIA = "wireless-sms-asia" + WIRELESS_SMS_CENTRALANDSOUTHAMERICA = "wireless-sms-centralandsouthamerica" + WIRELESS_SMS_EUROPE = "wireless-sms-europe" + WIRELESS_SMS_NORTHAMERICA = "wireless-sms-northamerica" + WIRELESS_SMS_OCEANIA = "wireless-sms-oceania" + WIRELESS_SUPER_SIM = "wireless-super-sim" + WIRELESS_SUPER_SIM_DATA = "wireless-super-sim-data" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA = ( + "wireless-super-sim-data-north-america-usa" + ) + WIRELESS_SUPER_SIM_DATA_PAYG = "wireless-super-sim-data-payg" + WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE = "wireless-super-sim-data-payg-europe" + WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA = ( + "wireless-super-sim-data-payg-north-america" + ) + WIRELESS_SUPER_SIM_HARDWARE = "wireless-super-sim-hardware" + WIRELESS_SUPER_SIM_HARDWARE_BULK = "wireless-super-sim-hardware-bulk" + WIRELESS_SUPER_SIM_SMSCOMMANDS = "wireless-super-sim-smscommands" + WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA = "wireless-super-sim-smscommands-africa" + WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA = "wireless-super-sim-smscommands-asia" + WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA = ( + "wireless-super-sim-smscommands-cent-and-south-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE = "wireless-super-sim-smscommands-europe" + WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA = ( + "wireless-super-sim-smscommands-north-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA = ( + "wireless-super-sim-smscommands-oceania" + ) + WIRELESS_SUPER_SIM_SUBSCRIPTION = "wireless-super-sim-subscription" + WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG = "wireless-super-sim-subscription-payg" + WIRELESS_USAGE = "wireless-usage" + WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" + WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" + WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" + WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-commands-centralandsouthamerica" + ) + WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" + WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" + WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" + WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" + WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" + WIRELESS_USAGE_DATA = "wireless-usage-data" + WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" + WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" + WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-data-centralandsouthamerica" + ) + WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( + "wireless-usage-data-custom-additionalmb" + ) + WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" + WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" + WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" + WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( + "wireless-usage-data-individual-additionalgb" + ) + WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( + "wireless-usage-data-individual-firstgb" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( + "wireless-usage-data-international-roaming-canada" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( + "wireless-usage-data-international-roaming-india" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( + "wireless-usage-data-international-roaming-mexico" + ) + WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" + WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" + WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" + WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" + WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" + WIRELESS_USAGE_MRC = "wireless-usage-mrc" + WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" + WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" + WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" + WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" + WIRELESS_USAGE_SMS = "wireless-usage-sms" + WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + :ivar api_version: The API version used to create the resource. + :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + :ivar category: + :ivar count: The number of usage events, such as the number of calls. + :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + :ivar description: A plain-language description of the usage category. + :ivar end_date: The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar price: The total price of the usage in the currency specified in `price_unit` and associated with the account. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + :ivar start_date: The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar subresource_uris: A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar usage: The amount used to bill usage and measured in units described in `usage_unit`. + :ivar usage_unit: The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.as_of: Optional[str] = payload.get("as_of") + self.category: Optional["AllTimeInstance.Category"] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AllTimePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AllTimeInstance: + """ + Build an instance of AllTimeInstance + + :param payload: Payload response from the API + """ + return AllTimeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AllTimeList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the AllTimeList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records/AllTime.json".format( + **self._solution + ) + + def stream( + self, + category: Union["AllTimeInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AllTimeInstance]: + """ + Streams AllTimeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "AllTimeInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + category: Union["AllTimeInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AllTimeInstance]: + """ + Asynchronously streams AllTimeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "AllTimeInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["AllTimeInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AllTimeInstance]: + """ + Lists AllTimeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "AllTimeInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + category: Union["AllTimeInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AllTimeInstance]: + """ + Asynchronously lists AllTimeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "AllTimeInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + category: Union["AllTimeInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AllTimePage: + """ + Retrieve a single page of AllTimeInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AllTimeInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AllTimePage(self._version, response, self._solution) + + async def page_async( + self, + category: Union["AllTimeInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AllTimePage: + """ + Asynchronously retrieve a single page of AllTimeInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AllTimeInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AllTimePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AllTimePage: + """ + Retrieve a specific page of AllTimeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AllTimeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AllTimePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AllTimePage: + """ + Asynchronously retrieve a specific page of AllTimeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AllTimeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AllTimePage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/daily.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/daily.py new file mode 100644 index 00000000..e89c75cb --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/daily.py @@ -0,0 +1,1211 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DailyInstance(InstanceResource): + + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" + AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" + ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" + AUTHY_AUTHENTICATIONS = "authy-authentications" + AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" + AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" + AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" + AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" + AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" + CALL_PROGESS_EVENTS = "call-progess-events" + CALLERIDLOOKUPS = "calleridlookups" + CALLS = "calls" + CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" + CALLS_GLOBALCONFERENCE = "calls-globalconference" + CALLS_INBOUND = "calls-inbound" + CALLS_INBOUND_LOCAL = "calls-inbound-local" + CALLS_INBOUND_MOBILE = "calls-inbound-mobile" + CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" + CALLS_OUTBOUND = "calls-outbound" + CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" + CALLS_RECORDINGS = "calls-recordings" + CALLS_SIP = "calls-sip" + CALLS_SIP_INBOUND = "calls-sip-inbound" + CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" + CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" + CONVERSATIONS = "conversations" + CONVERSATIONS_API_REQUESTS = "conversations-api-requests" + CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" + CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" + CONVERSATIONS_EVENTS = "conversations-events" + CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" + CONVERSATIONS_PARTICIPANTS = "conversations-participants" + CPS = "cps" + CREDIT_TRANSFER = "credit-transfer" + EMAIL = "email" + EMERGING_TECH = "emerging-tech" + ENGAGEMENT_SUITE_PACKAGED_PLANS = "engagement-suite-packaged-plans" + ENHANCED_LINE_TYPE_LOOKUPS = "enhanced-line-type-lookups" + ENTERPRISE = "enterprise" + EVENTS = "events" + EXPERIMENT_FRANCE_SMS = "experiment-france-sms" + EXPERIMENT_INDIA_SMS = "experiment-india-sms" + EXPERIMENT_UK_SMS = "experiment-uk-sms" + FAILED_MESSAGE_PROCESSING_FEE = "failed-message-processing-fee" + FLEX = "flex" + FLEX_ACTIVE_USER_HOURS = "flex-active-user-hours" + FLEX_CONCURRENT_USERS = "flex-concurrent-users" + FLEX_CONVERSATIONAL_INSIGHTS = "flex-conversational-insights" + FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES = "flex-conversational-insights-messages" + FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = ( + "flex-conversational-insights-voice-minutes" + ) + FLEX_EMAIL_USAGE = "flex-email-usage" + FLEX_MESSAGING_USAGE = "flex-messaging-usage" + FLEX_PARTNER_SPINSCI = "flex-partner-spinsci" + FLEX_PARTNER_XCELERATE = "flex-partner-xcelerate" + FLEX_RESELLER_ECOSYSTEM = "flex-reseller-ecosystem" + FLEX_UNIQUE_USER = "flex-unique-user" + FLEX_USAGE = "flex-usage" + FLEX_USERS = "flex-users" + FLEX_VOICE_MINUTE = "flex-voice-minute" + FLEX_YTICA = "flex-ytica" + FRAUD_LOOKUPS = "fraud-lookups" + FRONTLINE = "frontline" + FRONTLINE_USERS = "frontline-users" + FUNCTIONS = "functions" + GENERIC_PAY_TRANSACTIONS = "generic-pay-transactions" + GROUP_ROOMS = "group-rooms" + GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" + GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" + GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" + GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" + GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" + GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" + GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" + GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" + IP_MESSAGING = "ip-messaging" + IP_MESSAGING_COMMANDS = "ip-messaging-commands" + IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" + IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" + IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" + IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" + IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" + LINE_STATUS_LOOKUPS = "line-status-lookups" + LIVE_ACTIVITY_LOOKUPS = "live-activity-lookups" + LOOKUP_BUCKET_ADJUSTMENT = "lookup-bucket-adjustment" + LOOKUP_IDENTITY_MATCH = "lookup-identity-match" + LOOKUPS = "lookups" + MARKETPLACE = "marketplace" + MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) + MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" + MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" + MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" + MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" + MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION = "marketplace-deepgram-transcription" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE = ( + "marketplace-deepgram-transcription-base" + ) + MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED = ( + "marketplace-deepgram-transscription-enhanced" + ) + MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( + "marketplace-digital-segment-business-info" + ) + MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( + "marketplace-facebook-offline-conversions" + ) + MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" + MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( + "marketplace-ibm-watson-message-insights" + ) + MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( + "marketplace-ibm-watson-message-sentiment" + ) + MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( + "marketplace-ibm-watson-recording-analysis" + ) + MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" + MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" + MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( + "marketplace-infogroup-dataaxle-bizinfo" + ) + MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( + "marketplace-keen-io-contact-center-analytics" + ) + MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" + MARKETPLACE_MARCHEX_RECORDING_ANALYSIS = ( + "marketplace-marchex-recording-analysis" + ) + MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( + "marketplace-marchex-sentiment-analysis-for-sms" + ) + MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( + "marketplace-marketplace-nextcaller-social-id" + ) + MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( + "marketplace-mobile-commons-opt-out-classifier" + ) + MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( + "marketplace-nexiwave-voicemail-to-text" + ) + MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( + "marketplace-nextcaller-advanced-caller-identification" + ) + MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" + MARKETPLACE_PAY_ADDONS = "marketplace-pay-addons" + MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR = ( + "marketplace-pay-addons-basecommerce-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR = ( + "marketplace-pay-addons-braintree-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR = ( + "marketplace-pay-addons-cardconnect-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR = ( + "marketplace-pay-addons-chase-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplace-pay-addons-shuttle-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplace-pay-addons-stripe-pay-connector" + ) + MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" + MARKETPLACE_POLY_AI_CONNECTOR = "marketplace-poly-ai-connector" + MARKETPLACE_REALPHONEVALIDATION = "marketplace-realphonevalidation" + MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( + "marketplace-remeeting-automatic-speech-recognition" + ) + MARKETPLACE_SPOKE_PHONE_LICENSE_PRO = "marketplace-spoke-phone-license-pro" + MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD = ( + "marketplace-spoke-phone-license-standard" + ) + MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( + "marketplace-tcpa-defense-solutions-blacklist-feed" + ) + MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" + MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION = ( + "marketplace-trestle-solutions-caller-identification" + ) + MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" + MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( + "marketplace-twilio-caller-name-lookup-us" + ) + MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( + "marketplace-twilio-carrier-information-lookup" + ) + MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" + MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" + MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) + MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" + MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( + "marketplace-ytica-contact-center-reporting-analytics" + ) + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplay-pay-addons-shuttle-pay-connector" + ) + MEDIA_COMPOSER_MINUTES = "media-composer-minutes" + MEDIASTORAGE = "mediastorage" + MIN_SPEND_ADJUSTMENTS = "min-spend-adjustments" + MMS = "mms" + MMS_INBOUND = "mms-inbound" + MMS_INBOUND_LONGCODE = "mms-inbound-longcode" + MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" + MMS_INBOUND_TOLL_FREE = "mms-inbound-toll-free" + MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" + MMS_OUTBOUND = "mms-outbound" + MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" + MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" + MMS_OUTBOUND_TOLLFREE = "mms-outbound-tollfree" + MONITOR = "monitor" + MONITOR_READS = "monitor-reads" + MONITOR_STORAGE = "monitor-storage" + MONITOR_WRITES = "monitor-writes" + NOTIFY = "notify" + NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" + NOTIFY_CHANNELS = "notify-channels" + NUMBER_FORMAT_LOOKUPS = "number-format-lookups" + PCHAT = "pchat" + PCHAT_ACTIONS = "pchat-actions" + PCHAT_APS = "pchat-aps" + PCHAT_CONV_MED_STORAGE = "pchat-conv-med-storage" + PCHAT_MESSAGES = "pchat-messages" + PCHAT_NOTIFICATIONS = "pchat-notifications" + PCHAT_READS = "pchat-reads" + PCHAT_USERS = "pchat-users" + PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "peer-to-peer-rooms-participant-minutes" + ) + PFAX = "pfax" + PFAX_MINUTES = "pfax-minutes" + PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" + PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" + PFAX_PAGES = "pfax-pages" + PHONE_QUALITY_SCORE_LOOKUPS = "phone-quality-score-lookups" + PHONENUMBERS = "phonenumbers" + PHONENUMBERS_CPS = "phonenumbers-cps" + PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" + PHONENUMBERS_LOCAL = "phonenumbers-local" + PHONENUMBERS_MOBILE = "phonenumbers-mobile" + PHONENUMBERS_PORTING = "phonenumbers-porting" + PHONENUMBERS_SETUPS = "phonenumbers-setups" + PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" + PREMIUMSUPPORT = "premiumsupport" + PREMIUMSUPPORT_PERCENTAGE_SPEND = "premiumsupport-percentage-spend" + PROGRAMMABLEVOICE_PLATFORM = "programmablevoice-platform" + PROGRAMMABLEVOICECONN_CLIENTSDK = "programmablevoiceconn-clientsdk" + PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND = ( + "programmablevoiceconn-clientsdk-inbound" + ) + PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND = ( + "programmablevoiceconn-clientsdk-outbound" + ) + PROGRAMMABLEVOICECONN_ONNET = "programmablevoiceconn-onnet" + PROGRAMMABLEVOICECONN_ONNET_INBOUND = "programmablevoiceconn-onnet-inbound" + PROGRAMMABLEVOICECONN_ONNET_OUTBOUND = "programmablevoiceconn-onnet-outbound" + PROGRAMMABLEVOICECONN_SIP = "programmablevoiceconn-sip" + PROGRAMMABLEVOICECONN_SIP_INBOUND = "programmablevoiceconn-sip-inbound" + PROGRAMMABLEVOICECONN_SIP_OUTBOUND = "programmablevoiceconn-sip-outbound" + PROGRAMMABLEVOICECONNECTIVITY = "programmablevoiceconnectivity" + PROXY = "proxy" + PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" + PROXY_BUCKET_ADJUSTMENT = "proxy-bucket-adjustment" + PROXY_LICENSES = "proxy-licenses" + PSTNCONNECTIVITY = "pstnconnectivity" + PSTNCONNECTIVITY_INBOUND = "pstnconnectivity-inbound" + PSTNCONNECTIVITY_OUTBOUND = "pstnconnectivity-outbound" + PV = "pv" + PV_BASIC_ROOMS = "pv-basic-rooms" + PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" + PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" + PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" + PV_COMPOSITION_MINUTES = "pv-composition-minutes" + PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" + PV_ROOM_PARTICIPANTS = "pv-room-participants" + PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" + PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" + PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" + PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" + PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" + PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" + PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" + PV_ROOMS = "pv-rooms" + PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" + RCS_MESSAGES = "rcs-messages" + REASSIGNED_NUMBER = "reassigned-number" + RECORDINGS = "recordings" + RECORDINGSTORAGE = "recordingstorage" + SHORTCODES = "shortcodes" + SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" + SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" + SHORTCODES_MPS = "shortcodes-mps" + SHORTCODES_RANDOM = "shortcodes-random" + SHORTCODES_SETUP_FEES = "shortcodes-setup-fees" + SHORTCODES_UK = "shortcodes-uk" + SHORTCODES_VANITY = "shortcodes-vanity" + SIM_SWAP_LOOKUPS = "sim-swap-lookups" + SIP_SECURE_MEDIA = "sip-secure-media" + SMALL_GROUP_ROOMS = "small-group-rooms" + SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" + SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" + SMS = "sms" + SMS_INBOUND = "sms-inbound" + SMS_INBOUND_LONGCODE = "sms-inbound-longcode" + SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" + SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" + SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) + SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" + SMS_OUTBOUND = "sms-outbound" + SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" + SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" + SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" + SPEECH_RECOGNITION = "speech-recognition" + STUDIO_ENGAGEMENTS = "studio-engagements" + SYNC = "sync" + SYNC_ACTIONS = "sync-actions" + SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" + SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" + TASKROUTER_TASKS = "taskrouter-tasks" + TOTALPRICE = "totalprice" + TRANSCRIPTIONS = "transcriptions" + TRUNKING_CPS = "trunking-cps" + TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" + TRUNKING_ORIGINATION = "trunking-origination" + TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" + TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" + TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" + TRUNKING_RECORDINGS = "trunking-recordings" + TRUNKING_SECURE = "trunking-secure" + TRUNKING_TERMINATION = "trunking-termination" + TTS_GOOGLE = "tts-google" + TURNMEGABYTES = "turnmegabytes" + TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" + TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" + TURNMEGABYTES_GERMANY = "turnmegabytes-germany" + TURNMEGABYTES_INDIA = "turnmegabytes-india" + TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" + TURNMEGABYTES_JAPAN = "turnmegabytes-japan" + TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" + TURNMEGABYTES_USEAST = "turnmegabytes-useast" + TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" + TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) + VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" + VOICE_INSIGHTS = "voice-insights" + VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-client-insights-on-demand-minute" + ) + VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-ptsn-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-interface-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-trunking-insights-on-demand-minute" + ) + VOICE_INTELLIGENCE = "voice-intelligence" + VOICE_INTELLIGENCE_EIP_OPERATORS = "voice-intelligence-eip-operators" + VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" + VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" + WDS = "wds" + WIRELESS = "wireless" + WIRELESS_DATA = "wireless-data" + WIRELESS_DATA_PAYG = "wireless-data-payg" + WIRELESS_DATA_PAYG_AFRICA = "wireless-data-payg-africa" + WIRELESS_DATA_PAYG_ASIA = "wireless-data-payg-asia" + WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA = ( + "wireless-data-payg-centralandsouthamerica" + ) + WIRELESS_DATA_PAYG_EUROPE = "wireless-data-payg-europe" + WIRELESS_DATA_PAYG_NORTHAMERICA = "wireless-data-payg-northamerica" + WIRELESS_DATA_PAYG_OCEANIA = "wireless-data-payg-oceania" + WIRELESS_DATA_QUOTA1 = "wireless-data-quota1" + WIRELESS_DATA_QUOTA1_AFRICA = "wireless-data-quota1-africa" + WIRELESS_DATA_QUOTA1_ASIA = "wireless-data-quota1-asia" + WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota1-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA1_EUROPE = "wireless-data-quota1-europe" + WIRELESS_DATA_QUOTA1_NORTHAMERICA = "wireless-data-quota1-northamerica" + WIRELESS_DATA_QUOTA1_OCEANIA = "wireless-data-quota1-oceania" + WIRELESS_DATA_QUOTA10 = "wireless-data-quota10" + WIRELESS_DATA_QUOTA10_AFRICA = "wireless-data-quota10-africa" + WIRELESS_DATA_QUOTA10_ASIA = "wireless-data-quota10-asia" + WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota10-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA10_EUROPE = "wireless-data-quota10-europe" + WIRELESS_DATA_QUOTA10_NORTHAMERICA = "wireless-data-quota10-northamerica" + WIRELESS_DATA_QUOTA10_OCEANIA = "wireless-data-quota10-oceania" + WIRELESS_DATA_QUOTA50 = "wireless-data-quota50" + WIRELESS_DATA_QUOTA50_AFRICA = "wireless-data-quota50-africa" + WIRELESS_DATA_QUOTA50_ASIA = "wireless-data-quota50-asia" + WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota50-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA50_EUROPE = "wireless-data-quota50-europe" + WIRELESS_DATA_QUOTA50_NORTHAMERICA = "wireless-data-quota50-northamerica" + WIRELESS_DATA_QUOTA50_OCEANIA = "wireless-data-quota50-oceania" + WIRELESS_DATA_QUOTACUSTOM = "wireless-data-quotacustom" + WIRELESS_DATA_QUOTACUSTOM_AFRICA = "wireless-data-quotacustom-africa" + WIRELESS_DATA_QUOTACUSTOM_ASIA = "wireless-data-quotacustom-asia" + WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quotacustom-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_EUROPE = "wireless-data-quotacustom-europe" + WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA = ( + "wireless-data-quotacustom-northamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_OCEANIA = "wireless-data-quotacustom-oceania" + WIRELESS_MRC_PAYG = "wireless-mrc-payg" + WIRELESS_MRC_QUOTA1 = "wireless-mrc-quota1" + WIRELESS_MRC_QUOTA10 = "wireless-mrc-quota10" + WIRELESS_MRC_QUOTA50 = "wireless-mrc-quota50" + WIRELESS_MRC_QUOTACUSTOM = "wireless-mrc-quotacustom" + WIRELESS_ORDERS = "wireless-orders" + WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" + WIRELESS_ORDERS_BULK = "wireless-orders-bulk" + WIRELESS_ORDERS_ESIM = "wireless-orders-esim" + WIRELESS_ORDERS_STARTER = "wireless-orders-starter" + WIRELESS_QUOTAS = "wireless-quotas" + WIRELESS_SMS_AFRICA = "wireless-sms-africa" + WIRELESS_SMS_ASIA = "wireless-sms-asia" + WIRELESS_SMS_CENTRALANDSOUTHAMERICA = "wireless-sms-centralandsouthamerica" + WIRELESS_SMS_EUROPE = "wireless-sms-europe" + WIRELESS_SMS_NORTHAMERICA = "wireless-sms-northamerica" + WIRELESS_SMS_OCEANIA = "wireless-sms-oceania" + WIRELESS_SUPER_SIM = "wireless-super-sim" + WIRELESS_SUPER_SIM_DATA = "wireless-super-sim-data" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA = ( + "wireless-super-sim-data-north-america-usa" + ) + WIRELESS_SUPER_SIM_DATA_PAYG = "wireless-super-sim-data-payg" + WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE = "wireless-super-sim-data-payg-europe" + WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA = ( + "wireless-super-sim-data-payg-north-america" + ) + WIRELESS_SUPER_SIM_HARDWARE = "wireless-super-sim-hardware" + WIRELESS_SUPER_SIM_HARDWARE_BULK = "wireless-super-sim-hardware-bulk" + WIRELESS_SUPER_SIM_SMSCOMMANDS = "wireless-super-sim-smscommands" + WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA = "wireless-super-sim-smscommands-africa" + WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA = "wireless-super-sim-smscommands-asia" + WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA = ( + "wireless-super-sim-smscommands-cent-and-south-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE = "wireless-super-sim-smscommands-europe" + WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA = ( + "wireless-super-sim-smscommands-north-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA = ( + "wireless-super-sim-smscommands-oceania" + ) + WIRELESS_SUPER_SIM_SUBSCRIPTION = "wireless-super-sim-subscription" + WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG = "wireless-super-sim-subscription-payg" + WIRELESS_USAGE = "wireless-usage" + WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" + WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" + WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" + WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-commands-centralandsouthamerica" + ) + WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" + WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" + WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" + WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" + WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" + WIRELESS_USAGE_DATA = "wireless-usage-data" + WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" + WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" + WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-data-centralandsouthamerica" + ) + WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( + "wireless-usage-data-custom-additionalmb" + ) + WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" + WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" + WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" + WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( + "wireless-usage-data-individual-additionalgb" + ) + WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( + "wireless-usage-data-individual-firstgb" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( + "wireless-usage-data-international-roaming-canada" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( + "wireless-usage-data-international-roaming-india" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( + "wireless-usage-data-international-roaming-mexico" + ) + WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" + WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" + WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" + WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" + WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" + WIRELESS_USAGE_MRC = "wireless-usage-mrc" + WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" + WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" + WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" + WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" + WIRELESS_USAGE_SMS = "wireless-usage-sms" + WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + :ivar api_version: The API version used to create the resource. + :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + :ivar category: + :ivar count: The number of usage events, such as the number of calls. + :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + :ivar description: A plain-language description of the usage category. + :ivar end_date: The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar price: The total price of the usage in the currency specified in `price_unit` and associated with the account. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + :ivar start_date: The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar subresource_uris: A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar usage: The amount used to bill usage and measured in units described in `usage_unit`. + :ivar usage_unit: The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.as_of: Optional[str] = payload.get("as_of") + self.category: Optional["DailyInstance.Category"] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DailyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DailyInstance: + """ + Build an instance of DailyInstance + + :param payload: Payload response from the API + """ + return DailyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class DailyList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the DailyList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records/Daily.json".format( + **self._solution + ) + + def stream( + self, + category: Union["DailyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DailyInstance]: + """ + Streams DailyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "DailyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + category: Union["DailyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DailyInstance]: + """ + Asynchronously streams DailyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "DailyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["DailyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DailyInstance]: + """ + Lists DailyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "DailyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + category: Union["DailyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DailyInstance]: + """ + Asynchronously lists DailyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "DailyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + category: Union["DailyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DailyPage: + """ + Retrieve a single page of DailyInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DailyInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DailyPage(self._version, response, self._solution) + + async def page_async( + self, + category: Union["DailyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DailyPage: + """ + Asynchronously retrieve a single page of DailyInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DailyInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DailyPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DailyPage: + """ + Retrieve a specific page of DailyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DailyInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DailyPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DailyPage: + """ + Asynchronously retrieve a specific page of DailyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DailyInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DailyPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/last_month.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/last_month.py new file mode 100644 index 00000000..4057283e --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/last_month.py @@ -0,0 +1,1211 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class LastMonthInstance(InstanceResource): + + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" + AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" + ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" + AUTHY_AUTHENTICATIONS = "authy-authentications" + AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" + AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" + AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" + AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" + AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" + CALL_PROGESS_EVENTS = "call-progess-events" + CALLERIDLOOKUPS = "calleridlookups" + CALLS = "calls" + CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" + CALLS_GLOBALCONFERENCE = "calls-globalconference" + CALLS_INBOUND = "calls-inbound" + CALLS_INBOUND_LOCAL = "calls-inbound-local" + CALLS_INBOUND_MOBILE = "calls-inbound-mobile" + CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" + CALLS_OUTBOUND = "calls-outbound" + CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" + CALLS_RECORDINGS = "calls-recordings" + CALLS_SIP = "calls-sip" + CALLS_SIP_INBOUND = "calls-sip-inbound" + CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" + CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" + CONVERSATIONS = "conversations" + CONVERSATIONS_API_REQUESTS = "conversations-api-requests" + CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" + CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" + CONVERSATIONS_EVENTS = "conversations-events" + CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" + CONVERSATIONS_PARTICIPANTS = "conversations-participants" + CPS = "cps" + CREDIT_TRANSFER = "credit-transfer" + EMAIL = "email" + EMERGING_TECH = "emerging-tech" + ENGAGEMENT_SUITE_PACKAGED_PLANS = "engagement-suite-packaged-plans" + ENHANCED_LINE_TYPE_LOOKUPS = "enhanced-line-type-lookups" + ENTERPRISE = "enterprise" + EVENTS = "events" + EXPERIMENT_FRANCE_SMS = "experiment-france-sms" + EXPERIMENT_INDIA_SMS = "experiment-india-sms" + EXPERIMENT_UK_SMS = "experiment-uk-sms" + FAILED_MESSAGE_PROCESSING_FEE = "failed-message-processing-fee" + FLEX = "flex" + FLEX_ACTIVE_USER_HOURS = "flex-active-user-hours" + FLEX_CONCURRENT_USERS = "flex-concurrent-users" + FLEX_CONVERSATIONAL_INSIGHTS = "flex-conversational-insights" + FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES = "flex-conversational-insights-messages" + FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = ( + "flex-conversational-insights-voice-minutes" + ) + FLEX_EMAIL_USAGE = "flex-email-usage" + FLEX_MESSAGING_USAGE = "flex-messaging-usage" + FLEX_PARTNER_SPINSCI = "flex-partner-spinsci" + FLEX_PARTNER_XCELERATE = "flex-partner-xcelerate" + FLEX_RESELLER_ECOSYSTEM = "flex-reseller-ecosystem" + FLEX_UNIQUE_USER = "flex-unique-user" + FLEX_USAGE = "flex-usage" + FLEX_USERS = "flex-users" + FLEX_VOICE_MINUTE = "flex-voice-minute" + FLEX_YTICA = "flex-ytica" + FRAUD_LOOKUPS = "fraud-lookups" + FRONTLINE = "frontline" + FRONTLINE_USERS = "frontline-users" + FUNCTIONS = "functions" + GENERIC_PAY_TRANSACTIONS = "generic-pay-transactions" + GROUP_ROOMS = "group-rooms" + GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" + GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" + GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" + GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" + GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" + GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" + GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" + GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" + IP_MESSAGING = "ip-messaging" + IP_MESSAGING_COMMANDS = "ip-messaging-commands" + IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" + IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" + IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" + IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" + IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" + LINE_STATUS_LOOKUPS = "line-status-lookups" + LIVE_ACTIVITY_LOOKUPS = "live-activity-lookups" + LOOKUP_BUCKET_ADJUSTMENT = "lookup-bucket-adjustment" + LOOKUP_IDENTITY_MATCH = "lookup-identity-match" + LOOKUPS = "lookups" + MARKETPLACE = "marketplace" + MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) + MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" + MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" + MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" + MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" + MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION = "marketplace-deepgram-transcription" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE = ( + "marketplace-deepgram-transcription-base" + ) + MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED = ( + "marketplace-deepgram-transscription-enhanced" + ) + MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( + "marketplace-digital-segment-business-info" + ) + MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( + "marketplace-facebook-offline-conversions" + ) + MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" + MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( + "marketplace-ibm-watson-message-insights" + ) + MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( + "marketplace-ibm-watson-message-sentiment" + ) + MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( + "marketplace-ibm-watson-recording-analysis" + ) + MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" + MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" + MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( + "marketplace-infogroup-dataaxle-bizinfo" + ) + MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( + "marketplace-keen-io-contact-center-analytics" + ) + MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" + MARKETPLACE_MARCHEX_RECORDING_ANALYSIS = ( + "marketplace-marchex-recording-analysis" + ) + MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( + "marketplace-marchex-sentiment-analysis-for-sms" + ) + MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( + "marketplace-marketplace-nextcaller-social-id" + ) + MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( + "marketplace-mobile-commons-opt-out-classifier" + ) + MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( + "marketplace-nexiwave-voicemail-to-text" + ) + MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( + "marketplace-nextcaller-advanced-caller-identification" + ) + MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" + MARKETPLACE_PAY_ADDONS = "marketplace-pay-addons" + MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR = ( + "marketplace-pay-addons-basecommerce-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR = ( + "marketplace-pay-addons-braintree-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR = ( + "marketplace-pay-addons-cardconnect-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR = ( + "marketplace-pay-addons-chase-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplace-pay-addons-shuttle-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplace-pay-addons-stripe-pay-connector" + ) + MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" + MARKETPLACE_POLY_AI_CONNECTOR = "marketplace-poly-ai-connector" + MARKETPLACE_REALPHONEVALIDATION = "marketplace-realphonevalidation" + MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( + "marketplace-remeeting-automatic-speech-recognition" + ) + MARKETPLACE_SPOKE_PHONE_LICENSE_PRO = "marketplace-spoke-phone-license-pro" + MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD = ( + "marketplace-spoke-phone-license-standard" + ) + MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( + "marketplace-tcpa-defense-solutions-blacklist-feed" + ) + MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" + MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION = ( + "marketplace-trestle-solutions-caller-identification" + ) + MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" + MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( + "marketplace-twilio-caller-name-lookup-us" + ) + MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( + "marketplace-twilio-carrier-information-lookup" + ) + MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" + MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" + MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) + MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" + MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( + "marketplace-ytica-contact-center-reporting-analytics" + ) + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplay-pay-addons-shuttle-pay-connector" + ) + MEDIA_COMPOSER_MINUTES = "media-composer-minutes" + MEDIASTORAGE = "mediastorage" + MIN_SPEND_ADJUSTMENTS = "min-spend-adjustments" + MMS = "mms" + MMS_INBOUND = "mms-inbound" + MMS_INBOUND_LONGCODE = "mms-inbound-longcode" + MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" + MMS_INBOUND_TOLL_FREE = "mms-inbound-toll-free" + MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" + MMS_OUTBOUND = "mms-outbound" + MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" + MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" + MMS_OUTBOUND_TOLLFREE = "mms-outbound-tollfree" + MONITOR = "monitor" + MONITOR_READS = "monitor-reads" + MONITOR_STORAGE = "monitor-storage" + MONITOR_WRITES = "monitor-writes" + NOTIFY = "notify" + NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" + NOTIFY_CHANNELS = "notify-channels" + NUMBER_FORMAT_LOOKUPS = "number-format-lookups" + PCHAT = "pchat" + PCHAT_ACTIONS = "pchat-actions" + PCHAT_APS = "pchat-aps" + PCHAT_CONV_MED_STORAGE = "pchat-conv-med-storage" + PCHAT_MESSAGES = "pchat-messages" + PCHAT_NOTIFICATIONS = "pchat-notifications" + PCHAT_READS = "pchat-reads" + PCHAT_USERS = "pchat-users" + PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "peer-to-peer-rooms-participant-minutes" + ) + PFAX = "pfax" + PFAX_MINUTES = "pfax-minutes" + PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" + PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" + PFAX_PAGES = "pfax-pages" + PHONE_QUALITY_SCORE_LOOKUPS = "phone-quality-score-lookups" + PHONENUMBERS = "phonenumbers" + PHONENUMBERS_CPS = "phonenumbers-cps" + PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" + PHONENUMBERS_LOCAL = "phonenumbers-local" + PHONENUMBERS_MOBILE = "phonenumbers-mobile" + PHONENUMBERS_PORTING = "phonenumbers-porting" + PHONENUMBERS_SETUPS = "phonenumbers-setups" + PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" + PREMIUMSUPPORT = "premiumsupport" + PREMIUMSUPPORT_PERCENTAGE_SPEND = "premiumsupport-percentage-spend" + PROGRAMMABLEVOICE_PLATFORM = "programmablevoice-platform" + PROGRAMMABLEVOICECONN_CLIENTSDK = "programmablevoiceconn-clientsdk" + PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND = ( + "programmablevoiceconn-clientsdk-inbound" + ) + PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND = ( + "programmablevoiceconn-clientsdk-outbound" + ) + PROGRAMMABLEVOICECONN_ONNET = "programmablevoiceconn-onnet" + PROGRAMMABLEVOICECONN_ONNET_INBOUND = "programmablevoiceconn-onnet-inbound" + PROGRAMMABLEVOICECONN_ONNET_OUTBOUND = "programmablevoiceconn-onnet-outbound" + PROGRAMMABLEVOICECONN_SIP = "programmablevoiceconn-sip" + PROGRAMMABLEVOICECONN_SIP_INBOUND = "programmablevoiceconn-sip-inbound" + PROGRAMMABLEVOICECONN_SIP_OUTBOUND = "programmablevoiceconn-sip-outbound" + PROGRAMMABLEVOICECONNECTIVITY = "programmablevoiceconnectivity" + PROXY = "proxy" + PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" + PROXY_BUCKET_ADJUSTMENT = "proxy-bucket-adjustment" + PROXY_LICENSES = "proxy-licenses" + PSTNCONNECTIVITY = "pstnconnectivity" + PSTNCONNECTIVITY_INBOUND = "pstnconnectivity-inbound" + PSTNCONNECTIVITY_OUTBOUND = "pstnconnectivity-outbound" + PV = "pv" + PV_BASIC_ROOMS = "pv-basic-rooms" + PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" + PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" + PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" + PV_COMPOSITION_MINUTES = "pv-composition-minutes" + PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" + PV_ROOM_PARTICIPANTS = "pv-room-participants" + PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" + PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" + PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" + PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" + PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" + PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" + PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" + PV_ROOMS = "pv-rooms" + PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" + RCS_MESSAGES = "rcs-messages" + REASSIGNED_NUMBER = "reassigned-number" + RECORDINGS = "recordings" + RECORDINGSTORAGE = "recordingstorage" + SHORTCODES = "shortcodes" + SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" + SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" + SHORTCODES_MPS = "shortcodes-mps" + SHORTCODES_RANDOM = "shortcodes-random" + SHORTCODES_SETUP_FEES = "shortcodes-setup-fees" + SHORTCODES_UK = "shortcodes-uk" + SHORTCODES_VANITY = "shortcodes-vanity" + SIM_SWAP_LOOKUPS = "sim-swap-lookups" + SIP_SECURE_MEDIA = "sip-secure-media" + SMALL_GROUP_ROOMS = "small-group-rooms" + SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" + SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" + SMS = "sms" + SMS_INBOUND = "sms-inbound" + SMS_INBOUND_LONGCODE = "sms-inbound-longcode" + SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" + SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" + SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) + SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" + SMS_OUTBOUND = "sms-outbound" + SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" + SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" + SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" + SPEECH_RECOGNITION = "speech-recognition" + STUDIO_ENGAGEMENTS = "studio-engagements" + SYNC = "sync" + SYNC_ACTIONS = "sync-actions" + SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" + SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" + TASKROUTER_TASKS = "taskrouter-tasks" + TOTALPRICE = "totalprice" + TRANSCRIPTIONS = "transcriptions" + TRUNKING_CPS = "trunking-cps" + TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" + TRUNKING_ORIGINATION = "trunking-origination" + TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" + TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" + TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" + TRUNKING_RECORDINGS = "trunking-recordings" + TRUNKING_SECURE = "trunking-secure" + TRUNKING_TERMINATION = "trunking-termination" + TTS_GOOGLE = "tts-google" + TURNMEGABYTES = "turnmegabytes" + TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" + TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" + TURNMEGABYTES_GERMANY = "turnmegabytes-germany" + TURNMEGABYTES_INDIA = "turnmegabytes-india" + TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" + TURNMEGABYTES_JAPAN = "turnmegabytes-japan" + TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" + TURNMEGABYTES_USEAST = "turnmegabytes-useast" + TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" + TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) + VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" + VOICE_INSIGHTS = "voice-insights" + VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-client-insights-on-demand-minute" + ) + VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-ptsn-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-interface-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-trunking-insights-on-demand-minute" + ) + VOICE_INTELLIGENCE = "voice-intelligence" + VOICE_INTELLIGENCE_EIP_OPERATORS = "voice-intelligence-eip-operators" + VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" + VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" + WDS = "wds" + WIRELESS = "wireless" + WIRELESS_DATA = "wireless-data" + WIRELESS_DATA_PAYG = "wireless-data-payg" + WIRELESS_DATA_PAYG_AFRICA = "wireless-data-payg-africa" + WIRELESS_DATA_PAYG_ASIA = "wireless-data-payg-asia" + WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA = ( + "wireless-data-payg-centralandsouthamerica" + ) + WIRELESS_DATA_PAYG_EUROPE = "wireless-data-payg-europe" + WIRELESS_DATA_PAYG_NORTHAMERICA = "wireless-data-payg-northamerica" + WIRELESS_DATA_PAYG_OCEANIA = "wireless-data-payg-oceania" + WIRELESS_DATA_QUOTA1 = "wireless-data-quota1" + WIRELESS_DATA_QUOTA1_AFRICA = "wireless-data-quota1-africa" + WIRELESS_DATA_QUOTA1_ASIA = "wireless-data-quota1-asia" + WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota1-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA1_EUROPE = "wireless-data-quota1-europe" + WIRELESS_DATA_QUOTA1_NORTHAMERICA = "wireless-data-quota1-northamerica" + WIRELESS_DATA_QUOTA1_OCEANIA = "wireless-data-quota1-oceania" + WIRELESS_DATA_QUOTA10 = "wireless-data-quota10" + WIRELESS_DATA_QUOTA10_AFRICA = "wireless-data-quota10-africa" + WIRELESS_DATA_QUOTA10_ASIA = "wireless-data-quota10-asia" + WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota10-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA10_EUROPE = "wireless-data-quota10-europe" + WIRELESS_DATA_QUOTA10_NORTHAMERICA = "wireless-data-quota10-northamerica" + WIRELESS_DATA_QUOTA10_OCEANIA = "wireless-data-quota10-oceania" + WIRELESS_DATA_QUOTA50 = "wireless-data-quota50" + WIRELESS_DATA_QUOTA50_AFRICA = "wireless-data-quota50-africa" + WIRELESS_DATA_QUOTA50_ASIA = "wireless-data-quota50-asia" + WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota50-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA50_EUROPE = "wireless-data-quota50-europe" + WIRELESS_DATA_QUOTA50_NORTHAMERICA = "wireless-data-quota50-northamerica" + WIRELESS_DATA_QUOTA50_OCEANIA = "wireless-data-quota50-oceania" + WIRELESS_DATA_QUOTACUSTOM = "wireless-data-quotacustom" + WIRELESS_DATA_QUOTACUSTOM_AFRICA = "wireless-data-quotacustom-africa" + WIRELESS_DATA_QUOTACUSTOM_ASIA = "wireless-data-quotacustom-asia" + WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quotacustom-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_EUROPE = "wireless-data-quotacustom-europe" + WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA = ( + "wireless-data-quotacustom-northamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_OCEANIA = "wireless-data-quotacustom-oceania" + WIRELESS_MRC_PAYG = "wireless-mrc-payg" + WIRELESS_MRC_QUOTA1 = "wireless-mrc-quota1" + WIRELESS_MRC_QUOTA10 = "wireless-mrc-quota10" + WIRELESS_MRC_QUOTA50 = "wireless-mrc-quota50" + WIRELESS_MRC_QUOTACUSTOM = "wireless-mrc-quotacustom" + WIRELESS_ORDERS = "wireless-orders" + WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" + WIRELESS_ORDERS_BULK = "wireless-orders-bulk" + WIRELESS_ORDERS_ESIM = "wireless-orders-esim" + WIRELESS_ORDERS_STARTER = "wireless-orders-starter" + WIRELESS_QUOTAS = "wireless-quotas" + WIRELESS_SMS_AFRICA = "wireless-sms-africa" + WIRELESS_SMS_ASIA = "wireless-sms-asia" + WIRELESS_SMS_CENTRALANDSOUTHAMERICA = "wireless-sms-centralandsouthamerica" + WIRELESS_SMS_EUROPE = "wireless-sms-europe" + WIRELESS_SMS_NORTHAMERICA = "wireless-sms-northamerica" + WIRELESS_SMS_OCEANIA = "wireless-sms-oceania" + WIRELESS_SUPER_SIM = "wireless-super-sim" + WIRELESS_SUPER_SIM_DATA = "wireless-super-sim-data" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA = ( + "wireless-super-sim-data-north-america-usa" + ) + WIRELESS_SUPER_SIM_DATA_PAYG = "wireless-super-sim-data-payg" + WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE = "wireless-super-sim-data-payg-europe" + WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA = ( + "wireless-super-sim-data-payg-north-america" + ) + WIRELESS_SUPER_SIM_HARDWARE = "wireless-super-sim-hardware" + WIRELESS_SUPER_SIM_HARDWARE_BULK = "wireless-super-sim-hardware-bulk" + WIRELESS_SUPER_SIM_SMSCOMMANDS = "wireless-super-sim-smscommands" + WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA = "wireless-super-sim-smscommands-africa" + WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA = "wireless-super-sim-smscommands-asia" + WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA = ( + "wireless-super-sim-smscommands-cent-and-south-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE = "wireless-super-sim-smscommands-europe" + WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA = ( + "wireless-super-sim-smscommands-north-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA = ( + "wireless-super-sim-smscommands-oceania" + ) + WIRELESS_SUPER_SIM_SUBSCRIPTION = "wireless-super-sim-subscription" + WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG = "wireless-super-sim-subscription-payg" + WIRELESS_USAGE = "wireless-usage" + WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" + WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" + WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" + WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-commands-centralandsouthamerica" + ) + WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" + WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" + WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" + WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" + WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" + WIRELESS_USAGE_DATA = "wireless-usage-data" + WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" + WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" + WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-data-centralandsouthamerica" + ) + WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( + "wireless-usage-data-custom-additionalmb" + ) + WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" + WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" + WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" + WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( + "wireless-usage-data-individual-additionalgb" + ) + WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( + "wireless-usage-data-individual-firstgb" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( + "wireless-usage-data-international-roaming-canada" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( + "wireless-usage-data-international-roaming-india" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( + "wireless-usage-data-international-roaming-mexico" + ) + WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" + WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" + WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" + WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" + WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" + WIRELESS_USAGE_MRC = "wireless-usage-mrc" + WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" + WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" + WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" + WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" + WIRELESS_USAGE_SMS = "wireless-usage-sms" + WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + :ivar api_version: The API version used to create the resource. + :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + :ivar category: + :ivar count: The number of usage events, such as the number of calls. + :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + :ivar description: A plain-language description of the usage category. + :ivar end_date: The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar price: The total price of the usage in the currency specified in `price_unit` and associated with the account. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + :ivar start_date: The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar subresource_uris: A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar usage: The amount used to bill usage and measured in units described in `usage_unit`. + :ivar usage_unit: The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.as_of: Optional[str] = payload.get("as_of") + self.category: Optional["LastMonthInstance.Category"] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class LastMonthPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> LastMonthInstance: + """ + Build an instance of LastMonthInstance + + :param payload: Payload response from the API + """ + return LastMonthInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class LastMonthList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the LastMonthList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records/LastMonth.json".format( + **self._solution + ) + + def stream( + self, + category: Union["LastMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[LastMonthInstance]: + """ + Streams LastMonthInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "LastMonthInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + category: Union["LastMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[LastMonthInstance]: + """ + Asynchronously streams LastMonthInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "LastMonthInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["LastMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[LastMonthInstance]: + """ + Lists LastMonthInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "LastMonthInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + category: Union["LastMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[LastMonthInstance]: + """ + Asynchronously lists LastMonthInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "LastMonthInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + category: Union["LastMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> LastMonthPage: + """ + Retrieve a single page of LastMonthInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of LastMonthInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LastMonthPage(self._version, response, self._solution) + + async def page_async( + self, + category: Union["LastMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> LastMonthPage: + """ + Asynchronously retrieve a single page of LastMonthInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of LastMonthInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LastMonthPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> LastMonthPage: + """ + Retrieve a specific page of LastMonthInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of LastMonthInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return LastMonthPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> LastMonthPage: + """ + Asynchronously retrieve a specific page of LastMonthInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of LastMonthInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return LastMonthPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/monthly.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/monthly.py new file mode 100644 index 00000000..117db692 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/monthly.py @@ -0,0 +1,1211 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MonthlyInstance(InstanceResource): + + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" + AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" + ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" + AUTHY_AUTHENTICATIONS = "authy-authentications" + AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" + AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" + AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" + AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" + AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" + CALL_PROGESS_EVENTS = "call-progess-events" + CALLERIDLOOKUPS = "calleridlookups" + CALLS = "calls" + CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" + CALLS_GLOBALCONFERENCE = "calls-globalconference" + CALLS_INBOUND = "calls-inbound" + CALLS_INBOUND_LOCAL = "calls-inbound-local" + CALLS_INBOUND_MOBILE = "calls-inbound-mobile" + CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" + CALLS_OUTBOUND = "calls-outbound" + CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" + CALLS_RECORDINGS = "calls-recordings" + CALLS_SIP = "calls-sip" + CALLS_SIP_INBOUND = "calls-sip-inbound" + CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" + CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" + CONVERSATIONS = "conversations" + CONVERSATIONS_API_REQUESTS = "conversations-api-requests" + CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" + CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" + CONVERSATIONS_EVENTS = "conversations-events" + CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" + CONVERSATIONS_PARTICIPANTS = "conversations-participants" + CPS = "cps" + CREDIT_TRANSFER = "credit-transfer" + EMAIL = "email" + EMERGING_TECH = "emerging-tech" + ENGAGEMENT_SUITE_PACKAGED_PLANS = "engagement-suite-packaged-plans" + ENHANCED_LINE_TYPE_LOOKUPS = "enhanced-line-type-lookups" + ENTERPRISE = "enterprise" + EVENTS = "events" + EXPERIMENT_FRANCE_SMS = "experiment-france-sms" + EXPERIMENT_INDIA_SMS = "experiment-india-sms" + EXPERIMENT_UK_SMS = "experiment-uk-sms" + FAILED_MESSAGE_PROCESSING_FEE = "failed-message-processing-fee" + FLEX = "flex" + FLEX_ACTIVE_USER_HOURS = "flex-active-user-hours" + FLEX_CONCURRENT_USERS = "flex-concurrent-users" + FLEX_CONVERSATIONAL_INSIGHTS = "flex-conversational-insights" + FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES = "flex-conversational-insights-messages" + FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = ( + "flex-conversational-insights-voice-minutes" + ) + FLEX_EMAIL_USAGE = "flex-email-usage" + FLEX_MESSAGING_USAGE = "flex-messaging-usage" + FLEX_PARTNER_SPINSCI = "flex-partner-spinsci" + FLEX_PARTNER_XCELERATE = "flex-partner-xcelerate" + FLEX_RESELLER_ECOSYSTEM = "flex-reseller-ecosystem" + FLEX_UNIQUE_USER = "flex-unique-user" + FLEX_USAGE = "flex-usage" + FLEX_USERS = "flex-users" + FLEX_VOICE_MINUTE = "flex-voice-minute" + FLEX_YTICA = "flex-ytica" + FRAUD_LOOKUPS = "fraud-lookups" + FRONTLINE = "frontline" + FRONTLINE_USERS = "frontline-users" + FUNCTIONS = "functions" + GENERIC_PAY_TRANSACTIONS = "generic-pay-transactions" + GROUP_ROOMS = "group-rooms" + GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" + GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" + GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" + GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" + GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" + GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" + GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" + GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" + IP_MESSAGING = "ip-messaging" + IP_MESSAGING_COMMANDS = "ip-messaging-commands" + IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" + IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" + IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" + IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" + IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" + LINE_STATUS_LOOKUPS = "line-status-lookups" + LIVE_ACTIVITY_LOOKUPS = "live-activity-lookups" + LOOKUP_BUCKET_ADJUSTMENT = "lookup-bucket-adjustment" + LOOKUP_IDENTITY_MATCH = "lookup-identity-match" + LOOKUPS = "lookups" + MARKETPLACE = "marketplace" + MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) + MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" + MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" + MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" + MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" + MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION = "marketplace-deepgram-transcription" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE = ( + "marketplace-deepgram-transcription-base" + ) + MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED = ( + "marketplace-deepgram-transscription-enhanced" + ) + MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( + "marketplace-digital-segment-business-info" + ) + MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( + "marketplace-facebook-offline-conversions" + ) + MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" + MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( + "marketplace-ibm-watson-message-insights" + ) + MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( + "marketplace-ibm-watson-message-sentiment" + ) + MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( + "marketplace-ibm-watson-recording-analysis" + ) + MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" + MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" + MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( + "marketplace-infogroup-dataaxle-bizinfo" + ) + MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( + "marketplace-keen-io-contact-center-analytics" + ) + MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" + MARKETPLACE_MARCHEX_RECORDING_ANALYSIS = ( + "marketplace-marchex-recording-analysis" + ) + MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( + "marketplace-marchex-sentiment-analysis-for-sms" + ) + MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( + "marketplace-marketplace-nextcaller-social-id" + ) + MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( + "marketplace-mobile-commons-opt-out-classifier" + ) + MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( + "marketplace-nexiwave-voicemail-to-text" + ) + MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( + "marketplace-nextcaller-advanced-caller-identification" + ) + MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" + MARKETPLACE_PAY_ADDONS = "marketplace-pay-addons" + MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR = ( + "marketplace-pay-addons-basecommerce-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR = ( + "marketplace-pay-addons-braintree-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR = ( + "marketplace-pay-addons-cardconnect-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR = ( + "marketplace-pay-addons-chase-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplace-pay-addons-shuttle-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplace-pay-addons-stripe-pay-connector" + ) + MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" + MARKETPLACE_POLY_AI_CONNECTOR = "marketplace-poly-ai-connector" + MARKETPLACE_REALPHONEVALIDATION = "marketplace-realphonevalidation" + MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( + "marketplace-remeeting-automatic-speech-recognition" + ) + MARKETPLACE_SPOKE_PHONE_LICENSE_PRO = "marketplace-spoke-phone-license-pro" + MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD = ( + "marketplace-spoke-phone-license-standard" + ) + MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( + "marketplace-tcpa-defense-solutions-blacklist-feed" + ) + MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" + MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION = ( + "marketplace-trestle-solutions-caller-identification" + ) + MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" + MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( + "marketplace-twilio-caller-name-lookup-us" + ) + MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( + "marketplace-twilio-carrier-information-lookup" + ) + MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" + MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" + MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) + MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" + MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( + "marketplace-ytica-contact-center-reporting-analytics" + ) + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplay-pay-addons-shuttle-pay-connector" + ) + MEDIA_COMPOSER_MINUTES = "media-composer-minutes" + MEDIASTORAGE = "mediastorage" + MIN_SPEND_ADJUSTMENTS = "min-spend-adjustments" + MMS = "mms" + MMS_INBOUND = "mms-inbound" + MMS_INBOUND_LONGCODE = "mms-inbound-longcode" + MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" + MMS_INBOUND_TOLL_FREE = "mms-inbound-toll-free" + MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" + MMS_OUTBOUND = "mms-outbound" + MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" + MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" + MMS_OUTBOUND_TOLLFREE = "mms-outbound-tollfree" + MONITOR = "monitor" + MONITOR_READS = "monitor-reads" + MONITOR_STORAGE = "monitor-storage" + MONITOR_WRITES = "monitor-writes" + NOTIFY = "notify" + NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" + NOTIFY_CHANNELS = "notify-channels" + NUMBER_FORMAT_LOOKUPS = "number-format-lookups" + PCHAT = "pchat" + PCHAT_ACTIONS = "pchat-actions" + PCHAT_APS = "pchat-aps" + PCHAT_CONV_MED_STORAGE = "pchat-conv-med-storage" + PCHAT_MESSAGES = "pchat-messages" + PCHAT_NOTIFICATIONS = "pchat-notifications" + PCHAT_READS = "pchat-reads" + PCHAT_USERS = "pchat-users" + PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "peer-to-peer-rooms-participant-minutes" + ) + PFAX = "pfax" + PFAX_MINUTES = "pfax-minutes" + PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" + PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" + PFAX_PAGES = "pfax-pages" + PHONE_QUALITY_SCORE_LOOKUPS = "phone-quality-score-lookups" + PHONENUMBERS = "phonenumbers" + PHONENUMBERS_CPS = "phonenumbers-cps" + PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" + PHONENUMBERS_LOCAL = "phonenumbers-local" + PHONENUMBERS_MOBILE = "phonenumbers-mobile" + PHONENUMBERS_PORTING = "phonenumbers-porting" + PHONENUMBERS_SETUPS = "phonenumbers-setups" + PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" + PREMIUMSUPPORT = "premiumsupport" + PREMIUMSUPPORT_PERCENTAGE_SPEND = "premiumsupport-percentage-spend" + PROGRAMMABLEVOICE_PLATFORM = "programmablevoice-platform" + PROGRAMMABLEVOICECONN_CLIENTSDK = "programmablevoiceconn-clientsdk" + PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND = ( + "programmablevoiceconn-clientsdk-inbound" + ) + PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND = ( + "programmablevoiceconn-clientsdk-outbound" + ) + PROGRAMMABLEVOICECONN_ONNET = "programmablevoiceconn-onnet" + PROGRAMMABLEVOICECONN_ONNET_INBOUND = "programmablevoiceconn-onnet-inbound" + PROGRAMMABLEVOICECONN_ONNET_OUTBOUND = "programmablevoiceconn-onnet-outbound" + PROGRAMMABLEVOICECONN_SIP = "programmablevoiceconn-sip" + PROGRAMMABLEVOICECONN_SIP_INBOUND = "programmablevoiceconn-sip-inbound" + PROGRAMMABLEVOICECONN_SIP_OUTBOUND = "programmablevoiceconn-sip-outbound" + PROGRAMMABLEVOICECONNECTIVITY = "programmablevoiceconnectivity" + PROXY = "proxy" + PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" + PROXY_BUCKET_ADJUSTMENT = "proxy-bucket-adjustment" + PROXY_LICENSES = "proxy-licenses" + PSTNCONNECTIVITY = "pstnconnectivity" + PSTNCONNECTIVITY_INBOUND = "pstnconnectivity-inbound" + PSTNCONNECTIVITY_OUTBOUND = "pstnconnectivity-outbound" + PV = "pv" + PV_BASIC_ROOMS = "pv-basic-rooms" + PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" + PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" + PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" + PV_COMPOSITION_MINUTES = "pv-composition-minutes" + PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" + PV_ROOM_PARTICIPANTS = "pv-room-participants" + PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" + PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" + PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" + PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" + PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" + PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" + PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" + PV_ROOMS = "pv-rooms" + PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" + RCS_MESSAGES = "rcs-messages" + REASSIGNED_NUMBER = "reassigned-number" + RECORDINGS = "recordings" + RECORDINGSTORAGE = "recordingstorage" + SHORTCODES = "shortcodes" + SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" + SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" + SHORTCODES_MPS = "shortcodes-mps" + SHORTCODES_RANDOM = "shortcodes-random" + SHORTCODES_SETUP_FEES = "shortcodes-setup-fees" + SHORTCODES_UK = "shortcodes-uk" + SHORTCODES_VANITY = "shortcodes-vanity" + SIM_SWAP_LOOKUPS = "sim-swap-lookups" + SIP_SECURE_MEDIA = "sip-secure-media" + SMALL_GROUP_ROOMS = "small-group-rooms" + SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" + SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" + SMS = "sms" + SMS_INBOUND = "sms-inbound" + SMS_INBOUND_LONGCODE = "sms-inbound-longcode" + SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" + SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" + SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) + SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" + SMS_OUTBOUND = "sms-outbound" + SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" + SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" + SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" + SPEECH_RECOGNITION = "speech-recognition" + STUDIO_ENGAGEMENTS = "studio-engagements" + SYNC = "sync" + SYNC_ACTIONS = "sync-actions" + SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" + SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" + TASKROUTER_TASKS = "taskrouter-tasks" + TOTALPRICE = "totalprice" + TRANSCRIPTIONS = "transcriptions" + TRUNKING_CPS = "trunking-cps" + TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" + TRUNKING_ORIGINATION = "trunking-origination" + TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" + TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" + TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" + TRUNKING_RECORDINGS = "trunking-recordings" + TRUNKING_SECURE = "trunking-secure" + TRUNKING_TERMINATION = "trunking-termination" + TTS_GOOGLE = "tts-google" + TURNMEGABYTES = "turnmegabytes" + TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" + TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" + TURNMEGABYTES_GERMANY = "turnmegabytes-germany" + TURNMEGABYTES_INDIA = "turnmegabytes-india" + TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" + TURNMEGABYTES_JAPAN = "turnmegabytes-japan" + TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" + TURNMEGABYTES_USEAST = "turnmegabytes-useast" + TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" + TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) + VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" + VOICE_INSIGHTS = "voice-insights" + VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-client-insights-on-demand-minute" + ) + VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-ptsn-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-interface-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-trunking-insights-on-demand-minute" + ) + VOICE_INTELLIGENCE = "voice-intelligence" + VOICE_INTELLIGENCE_EIP_OPERATORS = "voice-intelligence-eip-operators" + VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" + VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" + WDS = "wds" + WIRELESS = "wireless" + WIRELESS_DATA = "wireless-data" + WIRELESS_DATA_PAYG = "wireless-data-payg" + WIRELESS_DATA_PAYG_AFRICA = "wireless-data-payg-africa" + WIRELESS_DATA_PAYG_ASIA = "wireless-data-payg-asia" + WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA = ( + "wireless-data-payg-centralandsouthamerica" + ) + WIRELESS_DATA_PAYG_EUROPE = "wireless-data-payg-europe" + WIRELESS_DATA_PAYG_NORTHAMERICA = "wireless-data-payg-northamerica" + WIRELESS_DATA_PAYG_OCEANIA = "wireless-data-payg-oceania" + WIRELESS_DATA_QUOTA1 = "wireless-data-quota1" + WIRELESS_DATA_QUOTA1_AFRICA = "wireless-data-quota1-africa" + WIRELESS_DATA_QUOTA1_ASIA = "wireless-data-quota1-asia" + WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota1-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA1_EUROPE = "wireless-data-quota1-europe" + WIRELESS_DATA_QUOTA1_NORTHAMERICA = "wireless-data-quota1-northamerica" + WIRELESS_DATA_QUOTA1_OCEANIA = "wireless-data-quota1-oceania" + WIRELESS_DATA_QUOTA10 = "wireless-data-quota10" + WIRELESS_DATA_QUOTA10_AFRICA = "wireless-data-quota10-africa" + WIRELESS_DATA_QUOTA10_ASIA = "wireless-data-quota10-asia" + WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota10-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA10_EUROPE = "wireless-data-quota10-europe" + WIRELESS_DATA_QUOTA10_NORTHAMERICA = "wireless-data-quota10-northamerica" + WIRELESS_DATA_QUOTA10_OCEANIA = "wireless-data-quota10-oceania" + WIRELESS_DATA_QUOTA50 = "wireless-data-quota50" + WIRELESS_DATA_QUOTA50_AFRICA = "wireless-data-quota50-africa" + WIRELESS_DATA_QUOTA50_ASIA = "wireless-data-quota50-asia" + WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota50-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA50_EUROPE = "wireless-data-quota50-europe" + WIRELESS_DATA_QUOTA50_NORTHAMERICA = "wireless-data-quota50-northamerica" + WIRELESS_DATA_QUOTA50_OCEANIA = "wireless-data-quota50-oceania" + WIRELESS_DATA_QUOTACUSTOM = "wireless-data-quotacustom" + WIRELESS_DATA_QUOTACUSTOM_AFRICA = "wireless-data-quotacustom-africa" + WIRELESS_DATA_QUOTACUSTOM_ASIA = "wireless-data-quotacustom-asia" + WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quotacustom-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_EUROPE = "wireless-data-quotacustom-europe" + WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA = ( + "wireless-data-quotacustom-northamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_OCEANIA = "wireless-data-quotacustom-oceania" + WIRELESS_MRC_PAYG = "wireless-mrc-payg" + WIRELESS_MRC_QUOTA1 = "wireless-mrc-quota1" + WIRELESS_MRC_QUOTA10 = "wireless-mrc-quota10" + WIRELESS_MRC_QUOTA50 = "wireless-mrc-quota50" + WIRELESS_MRC_QUOTACUSTOM = "wireless-mrc-quotacustom" + WIRELESS_ORDERS = "wireless-orders" + WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" + WIRELESS_ORDERS_BULK = "wireless-orders-bulk" + WIRELESS_ORDERS_ESIM = "wireless-orders-esim" + WIRELESS_ORDERS_STARTER = "wireless-orders-starter" + WIRELESS_QUOTAS = "wireless-quotas" + WIRELESS_SMS_AFRICA = "wireless-sms-africa" + WIRELESS_SMS_ASIA = "wireless-sms-asia" + WIRELESS_SMS_CENTRALANDSOUTHAMERICA = "wireless-sms-centralandsouthamerica" + WIRELESS_SMS_EUROPE = "wireless-sms-europe" + WIRELESS_SMS_NORTHAMERICA = "wireless-sms-northamerica" + WIRELESS_SMS_OCEANIA = "wireless-sms-oceania" + WIRELESS_SUPER_SIM = "wireless-super-sim" + WIRELESS_SUPER_SIM_DATA = "wireless-super-sim-data" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA = ( + "wireless-super-sim-data-north-america-usa" + ) + WIRELESS_SUPER_SIM_DATA_PAYG = "wireless-super-sim-data-payg" + WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE = "wireless-super-sim-data-payg-europe" + WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA = ( + "wireless-super-sim-data-payg-north-america" + ) + WIRELESS_SUPER_SIM_HARDWARE = "wireless-super-sim-hardware" + WIRELESS_SUPER_SIM_HARDWARE_BULK = "wireless-super-sim-hardware-bulk" + WIRELESS_SUPER_SIM_SMSCOMMANDS = "wireless-super-sim-smscommands" + WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA = "wireless-super-sim-smscommands-africa" + WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA = "wireless-super-sim-smscommands-asia" + WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA = ( + "wireless-super-sim-smscommands-cent-and-south-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE = "wireless-super-sim-smscommands-europe" + WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA = ( + "wireless-super-sim-smscommands-north-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA = ( + "wireless-super-sim-smscommands-oceania" + ) + WIRELESS_SUPER_SIM_SUBSCRIPTION = "wireless-super-sim-subscription" + WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG = "wireless-super-sim-subscription-payg" + WIRELESS_USAGE = "wireless-usage" + WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" + WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" + WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" + WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-commands-centralandsouthamerica" + ) + WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" + WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" + WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" + WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" + WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" + WIRELESS_USAGE_DATA = "wireless-usage-data" + WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" + WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" + WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-data-centralandsouthamerica" + ) + WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( + "wireless-usage-data-custom-additionalmb" + ) + WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" + WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" + WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" + WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( + "wireless-usage-data-individual-additionalgb" + ) + WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( + "wireless-usage-data-individual-firstgb" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( + "wireless-usage-data-international-roaming-canada" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( + "wireless-usage-data-international-roaming-india" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( + "wireless-usage-data-international-roaming-mexico" + ) + WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" + WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" + WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" + WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" + WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" + WIRELESS_USAGE_MRC = "wireless-usage-mrc" + WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" + WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" + WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" + WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" + WIRELESS_USAGE_SMS = "wireless-usage-sms" + WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + :ivar api_version: The API version used to create the resource. + :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + :ivar category: + :ivar count: The number of usage events, such as the number of calls. + :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + :ivar description: A plain-language description of the usage category. + :ivar end_date: The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar price: The total price of the usage in the currency specified in `price_unit` and associated with the account. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + :ivar start_date: The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar subresource_uris: A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar usage: The amount used to bill usage and measured in units described in `usage_unit`. + :ivar usage_unit: The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.as_of: Optional[str] = payload.get("as_of") + self.category: Optional["MonthlyInstance.Category"] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MonthlyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MonthlyInstance: + """ + Build an instance of MonthlyInstance + + :param payload: Payload response from the API + """ + return MonthlyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MonthlyList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the MonthlyList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records/Monthly.json".format( + **self._solution + ) + + def stream( + self, + category: Union["MonthlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MonthlyInstance]: + """ + Streams MonthlyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MonthlyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + category: Union["MonthlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MonthlyInstance]: + """ + Asynchronously streams MonthlyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MonthlyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["MonthlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MonthlyInstance]: + """ + Lists MonthlyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MonthlyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + category: Union["MonthlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MonthlyInstance]: + """ + Asynchronously lists MonthlyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MonthlyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + category: Union["MonthlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MonthlyPage: + """ + Retrieve a single page of MonthlyInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MonthlyInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MonthlyPage(self._version, response, self._solution) + + async def page_async( + self, + category: Union["MonthlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MonthlyPage: + """ + Asynchronously retrieve a single page of MonthlyInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MonthlyInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MonthlyPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MonthlyPage: + """ + Retrieve a specific page of MonthlyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MonthlyInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MonthlyPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MonthlyPage: + """ + Asynchronously retrieve a specific page of MonthlyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MonthlyInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MonthlyPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/this_month.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/this_month.py new file mode 100644 index 00000000..ab65a177 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/this_month.py @@ -0,0 +1,1211 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ThisMonthInstance(InstanceResource): + + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" + AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" + ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" + AUTHY_AUTHENTICATIONS = "authy-authentications" + AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" + AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" + AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" + AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" + AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" + CALL_PROGESS_EVENTS = "call-progess-events" + CALLERIDLOOKUPS = "calleridlookups" + CALLS = "calls" + CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" + CALLS_GLOBALCONFERENCE = "calls-globalconference" + CALLS_INBOUND = "calls-inbound" + CALLS_INBOUND_LOCAL = "calls-inbound-local" + CALLS_INBOUND_MOBILE = "calls-inbound-mobile" + CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" + CALLS_OUTBOUND = "calls-outbound" + CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" + CALLS_RECORDINGS = "calls-recordings" + CALLS_SIP = "calls-sip" + CALLS_SIP_INBOUND = "calls-sip-inbound" + CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" + CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" + CONVERSATIONS = "conversations" + CONVERSATIONS_API_REQUESTS = "conversations-api-requests" + CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" + CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" + CONVERSATIONS_EVENTS = "conversations-events" + CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" + CONVERSATIONS_PARTICIPANTS = "conversations-participants" + CPS = "cps" + CREDIT_TRANSFER = "credit-transfer" + EMAIL = "email" + EMERGING_TECH = "emerging-tech" + ENGAGEMENT_SUITE_PACKAGED_PLANS = "engagement-suite-packaged-plans" + ENHANCED_LINE_TYPE_LOOKUPS = "enhanced-line-type-lookups" + ENTERPRISE = "enterprise" + EVENTS = "events" + EXPERIMENT_FRANCE_SMS = "experiment-france-sms" + EXPERIMENT_INDIA_SMS = "experiment-india-sms" + EXPERIMENT_UK_SMS = "experiment-uk-sms" + FAILED_MESSAGE_PROCESSING_FEE = "failed-message-processing-fee" + FLEX = "flex" + FLEX_ACTIVE_USER_HOURS = "flex-active-user-hours" + FLEX_CONCURRENT_USERS = "flex-concurrent-users" + FLEX_CONVERSATIONAL_INSIGHTS = "flex-conversational-insights" + FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES = "flex-conversational-insights-messages" + FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = ( + "flex-conversational-insights-voice-minutes" + ) + FLEX_EMAIL_USAGE = "flex-email-usage" + FLEX_MESSAGING_USAGE = "flex-messaging-usage" + FLEX_PARTNER_SPINSCI = "flex-partner-spinsci" + FLEX_PARTNER_XCELERATE = "flex-partner-xcelerate" + FLEX_RESELLER_ECOSYSTEM = "flex-reseller-ecosystem" + FLEX_UNIQUE_USER = "flex-unique-user" + FLEX_USAGE = "flex-usage" + FLEX_USERS = "flex-users" + FLEX_VOICE_MINUTE = "flex-voice-minute" + FLEX_YTICA = "flex-ytica" + FRAUD_LOOKUPS = "fraud-lookups" + FRONTLINE = "frontline" + FRONTLINE_USERS = "frontline-users" + FUNCTIONS = "functions" + GENERIC_PAY_TRANSACTIONS = "generic-pay-transactions" + GROUP_ROOMS = "group-rooms" + GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" + GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" + GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" + GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" + GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" + GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" + GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" + GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" + IP_MESSAGING = "ip-messaging" + IP_MESSAGING_COMMANDS = "ip-messaging-commands" + IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" + IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" + IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" + IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" + IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" + LINE_STATUS_LOOKUPS = "line-status-lookups" + LIVE_ACTIVITY_LOOKUPS = "live-activity-lookups" + LOOKUP_BUCKET_ADJUSTMENT = "lookup-bucket-adjustment" + LOOKUP_IDENTITY_MATCH = "lookup-identity-match" + LOOKUPS = "lookups" + MARKETPLACE = "marketplace" + MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) + MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" + MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" + MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" + MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" + MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION = "marketplace-deepgram-transcription" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE = ( + "marketplace-deepgram-transcription-base" + ) + MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED = ( + "marketplace-deepgram-transscription-enhanced" + ) + MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( + "marketplace-digital-segment-business-info" + ) + MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( + "marketplace-facebook-offline-conversions" + ) + MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" + MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( + "marketplace-ibm-watson-message-insights" + ) + MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( + "marketplace-ibm-watson-message-sentiment" + ) + MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( + "marketplace-ibm-watson-recording-analysis" + ) + MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" + MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" + MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( + "marketplace-infogroup-dataaxle-bizinfo" + ) + MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( + "marketplace-keen-io-contact-center-analytics" + ) + MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" + MARKETPLACE_MARCHEX_RECORDING_ANALYSIS = ( + "marketplace-marchex-recording-analysis" + ) + MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( + "marketplace-marchex-sentiment-analysis-for-sms" + ) + MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( + "marketplace-marketplace-nextcaller-social-id" + ) + MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( + "marketplace-mobile-commons-opt-out-classifier" + ) + MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( + "marketplace-nexiwave-voicemail-to-text" + ) + MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( + "marketplace-nextcaller-advanced-caller-identification" + ) + MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" + MARKETPLACE_PAY_ADDONS = "marketplace-pay-addons" + MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR = ( + "marketplace-pay-addons-basecommerce-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR = ( + "marketplace-pay-addons-braintree-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR = ( + "marketplace-pay-addons-cardconnect-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR = ( + "marketplace-pay-addons-chase-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplace-pay-addons-shuttle-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplace-pay-addons-stripe-pay-connector" + ) + MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" + MARKETPLACE_POLY_AI_CONNECTOR = "marketplace-poly-ai-connector" + MARKETPLACE_REALPHONEVALIDATION = "marketplace-realphonevalidation" + MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( + "marketplace-remeeting-automatic-speech-recognition" + ) + MARKETPLACE_SPOKE_PHONE_LICENSE_PRO = "marketplace-spoke-phone-license-pro" + MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD = ( + "marketplace-spoke-phone-license-standard" + ) + MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( + "marketplace-tcpa-defense-solutions-blacklist-feed" + ) + MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" + MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION = ( + "marketplace-trestle-solutions-caller-identification" + ) + MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" + MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( + "marketplace-twilio-caller-name-lookup-us" + ) + MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( + "marketplace-twilio-carrier-information-lookup" + ) + MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" + MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" + MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) + MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" + MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( + "marketplace-ytica-contact-center-reporting-analytics" + ) + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplay-pay-addons-shuttle-pay-connector" + ) + MEDIA_COMPOSER_MINUTES = "media-composer-minutes" + MEDIASTORAGE = "mediastorage" + MIN_SPEND_ADJUSTMENTS = "min-spend-adjustments" + MMS = "mms" + MMS_INBOUND = "mms-inbound" + MMS_INBOUND_LONGCODE = "mms-inbound-longcode" + MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" + MMS_INBOUND_TOLL_FREE = "mms-inbound-toll-free" + MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" + MMS_OUTBOUND = "mms-outbound" + MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" + MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" + MMS_OUTBOUND_TOLLFREE = "mms-outbound-tollfree" + MONITOR = "monitor" + MONITOR_READS = "monitor-reads" + MONITOR_STORAGE = "monitor-storage" + MONITOR_WRITES = "monitor-writes" + NOTIFY = "notify" + NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" + NOTIFY_CHANNELS = "notify-channels" + NUMBER_FORMAT_LOOKUPS = "number-format-lookups" + PCHAT = "pchat" + PCHAT_ACTIONS = "pchat-actions" + PCHAT_APS = "pchat-aps" + PCHAT_CONV_MED_STORAGE = "pchat-conv-med-storage" + PCHAT_MESSAGES = "pchat-messages" + PCHAT_NOTIFICATIONS = "pchat-notifications" + PCHAT_READS = "pchat-reads" + PCHAT_USERS = "pchat-users" + PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "peer-to-peer-rooms-participant-minutes" + ) + PFAX = "pfax" + PFAX_MINUTES = "pfax-minutes" + PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" + PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" + PFAX_PAGES = "pfax-pages" + PHONE_QUALITY_SCORE_LOOKUPS = "phone-quality-score-lookups" + PHONENUMBERS = "phonenumbers" + PHONENUMBERS_CPS = "phonenumbers-cps" + PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" + PHONENUMBERS_LOCAL = "phonenumbers-local" + PHONENUMBERS_MOBILE = "phonenumbers-mobile" + PHONENUMBERS_PORTING = "phonenumbers-porting" + PHONENUMBERS_SETUPS = "phonenumbers-setups" + PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" + PREMIUMSUPPORT = "premiumsupport" + PREMIUMSUPPORT_PERCENTAGE_SPEND = "premiumsupport-percentage-spend" + PROGRAMMABLEVOICE_PLATFORM = "programmablevoice-platform" + PROGRAMMABLEVOICECONN_CLIENTSDK = "programmablevoiceconn-clientsdk" + PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND = ( + "programmablevoiceconn-clientsdk-inbound" + ) + PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND = ( + "programmablevoiceconn-clientsdk-outbound" + ) + PROGRAMMABLEVOICECONN_ONNET = "programmablevoiceconn-onnet" + PROGRAMMABLEVOICECONN_ONNET_INBOUND = "programmablevoiceconn-onnet-inbound" + PROGRAMMABLEVOICECONN_ONNET_OUTBOUND = "programmablevoiceconn-onnet-outbound" + PROGRAMMABLEVOICECONN_SIP = "programmablevoiceconn-sip" + PROGRAMMABLEVOICECONN_SIP_INBOUND = "programmablevoiceconn-sip-inbound" + PROGRAMMABLEVOICECONN_SIP_OUTBOUND = "programmablevoiceconn-sip-outbound" + PROGRAMMABLEVOICECONNECTIVITY = "programmablevoiceconnectivity" + PROXY = "proxy" + PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" + PROXY_BUCKET_ADJUSTMENT = "proxy-bucket-adjustment" + PROXY_LICENSES = "proxy-licenses" + PSTNCONNECTIVITY = "pstnconnectivity" + PSTNCONNECTIVITY_INBOUND = "pstnconnectivity-inbound" + PSTNCONNECTIVITY_OUTBOUND = "pstnconnectivity-outbound" + PV = "pv" + PV_BASIC_ROOMS = "pv-basic-rooms" + PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" + PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" + PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" + PV_COMPOSITION_MINUTES = "pv-composition-minutes" + PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" + PV_ROOM_PARTICIPANTS = "pv-room-participants" + PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" + PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" + PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" + PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" + PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" + PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" + PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" + PV_ROOMS = "pv-rooms" + PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" + RCS_MESSAGES = "rcs-messages" + REASSIGNED_NUMBER = "reassigned-number" + RECORDINGS = "recordings" + RECORDINGSTORAGE = "recordingstorage" + SHORTCODES = "shortcodes" + SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" + SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" + SHORTCODES_MPS = "shortcodes-mps" + SHORTCODES_RANDOM = "shortcodes-random" + SHORTCODES_SETUP_FEES = "shortcodes-setup-fees" + SHORTCODES_UK = "shortcodes-uk" + SHORTCODES_VANITY = "shortcodes-vanity" + SIM_SWAP_LOOKUPS = "sim-swap-lookups" + SIP_SECURE_MEDIA = "sip-secure-media" + SMALL_GROUP_ROOMS = "small-group-rooms" + SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" + SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" + SMS = "sms" + SMS_INBOUND = "sms-inbound" + SMS_INBOUND_LONGCODE = "sms-inbound-longcode" + SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" + SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" + SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) + SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" + SMS_OUTBOUND = "sms-outbound" + SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" + SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" + SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" + SPEECH_RECOGNITION = "speech-recognition" + STUDIO_ENGAGEMENTS = "studio-engagements" + SYNC = "sync" + SYNC_ACTIONS = "sync-actions" + SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" + SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" + TASKROUTER_TASKS = "taskrouter-tasks" + TOTALPRICE = "totalprice" + TRANSCRIPTIONS = "transcriptions" + TRUNKING_CPS = "trunking-cps" + TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" + TRUNKING_ORIGINATION = "trunking-origination" + TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" + TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" + TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" + TRUNKING_RECORDINGS = "trunking-recordings" + TRUNKING_SECURE = "trunking-secure" + TRUNKING_TERMINATION = "trunking-termination" + TTS_GOOGLE = "tts-google" + TURNMEGABYTES = "turnmegabytes" + TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" + TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" + TURNMEGABYTES_GERMANY = "turnmegabytes-germany" + TURNMEGABYTES_INDIA = "turnmegabytes-india" + TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" + TURNMEGABYTES_JAPAN = "turnmegabytes-japan" + TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" + TURNMEGABYTES_USEAST = "turnmegabytes-useast" + TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" + TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) + VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" + VOICE_INSIGHTS = "voice-insights" + VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-client-insights-on-demand-minute" + ) + VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-ptsn-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-interface-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-trunking-insights-on-demand-minute" + ) + VOICE_INTELLIGENCE = "voice-intelligence" + VOICE_INTELLIGENCE_EIP_OPERATORS = "voice-intelligence-eip-operators" + VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" + VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" + WDS = "wds" + WIRELESS = "wireless" + WIRELESS_DATA = "wireless-data" + WIRELESS_DATA_PAYG = "wireless-data-payg" + WIRELESS_DATA_PAYG_AFRICA = "wireless-data-payg-africa" + WIRELESS_DATA_PAYG_ASIA = "wireless-data-payg-asia" + WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA = ( + "wireless-data-payg-centralandsouthamerica" + ) + WIRELESS_DATA_PAYG_EUROPE = "wireless-data-payg-europe" + WIRELESS_DATA_PAYG_NORTHAMERICA = "wireless-data-payg-northamerica" + WIRELESS_DATA_PAYG_OCEANIA = "wireless-data-payg-oceania" + WIRELESS_DATA_QUOTA1 = "wireless-data-quota1" + WIRELESS_DATA_QUOTA1_AFRICA = "wireless-data-quota1-africa" + WIRELESS_DATA_QUOTA1_ASIA = "wireless-data-quota1-asia" + WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota1-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA1_EUROPE = "wireless-data-quota1-europe" + WIRELESS_DATA_QUOTA1_NORTHAMERICA = "wireless-data-quota1-northamerica" + WIRELESS_DATA_QUOTA1_OCEANIA = "wireless-data-quota1-oceania" + WIRELESS_DATA_QUOTA10 = "wireless-data-quota10" + WIRELESS_DATA_QUOTA10_AFRICA = "wireless-data-quota10-africa" + WIRELESS_DATA_QUOTA10_ASIA = "wireless-data-quota10-asia" + WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota10-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA10_EUROPE = "wireless-data-quota10-europe" + WIRELESS_DATA_QUOTA10_NORTHAMERICA = "wireless-data-quota10-northamerica" + WIRELESS_DATA_QUOTA10_OCEANIA = "wireless-data-quota10-oceania" + WIRELESS_DATA_QUOTA50 = "wireless-data-quota50" + WIRELESS_DATA_QUOTA50_AFRICA = "wireless-data-quota50-africa" + WIRELESS_DATA_QUOTA50_ASIA = "wireless-data-quota50-asia" + WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota50-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA50_EUROPE = "wireless-data-quota50-europe" + WIRELESS_DATA_QUOTA50_NORTHAMERICA = "wireless-data-quota50-northamerica" + WIRELESS_DATA_QUOTA50_OCEANIA = "wireless-data-quota50-oceania" + WIRELESS_DATA_QUOTACUSTOM = "wireless-data-quotacustom" + WIRELESS_DATA_QUOTACUSTOM_AFRICA = "wireless-data-quotacustom-africa" + WIRELESS_DATA_QUOTACUSTOM_ASIA = "wireless-data-quotacustom-asia" + WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quotacustom-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_EUROPE = "wireless-data-quotacustom-europe" + WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA = ( + "wireless-data-quotacustom-northamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_OCEANIA = "wireless-data-quotacustom-oceania" + WIRELESS_MRC_PAYG = "wireless-mrc-payg" + WIRELESS_MRC_QUOTA1 = "wireless-mrc-quota1" + WIRELESS_MRC_QUOTA10 = "wireless-mrc-quota10" + WIRELESS_MRC_QUOTA50 = "wireless-mrc-quota50" + WIRELESS_MRC_QUOTACUSTOM = "wireless-mrc-quotacustom" + WIRELESS_ORDERS = "wireless-orders" + WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" + WIRELESS_ORDERS_BULK = "wireless-orders-bulk" + WIRELESS_ORDERS_ESIM = "wireless-orders-esim" + WIRELESS_ORDERS_STARTER = "wireless-orders-starter" + WIRELESS_QUOTAS = "wireless-quotas" + WIRELESS_SMS_AFRICA = "wireless-sms-africa" + WIRELESS_SMS_ASIA = "wireless-sms-asia" + WIRELESS_SMS_CENTRALANDSOUTHAMERICA = "wireless-sms-centralandsouthamerica" + WIRELESS_SMS_EUROPE = "wireless-sms-europe" + WIRELESS_SMS_NORTHAMERICA = "wireless-sms-northamerica" + WIRELESS_SMS_OCEANIA = "wireless-sms-oceania" + WIRELESS_SUPER_SIM = "wireless-super-sim" + WIRELESS_SUPER_SIM_DATA = "wireless-super-sim-data" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA = ( + "wireless-super-sim-data-north-america-usa" + ) + WIRELESS_SUPER_SIM_DATA_PAYG = "wireless-super-sim-data-payg" + WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE = "wireless-super-sim-data-payg-europe" + WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA = ( + "wireless-super-sim-data-payg-north-america" + ) + WIRELESS_SUPER_SIM_HARDWARE = "wireless-super-sim-hardware" + WIRELESS_SUPER_SIM_HARDWARE_BULK = "wireless-super-sim-hardware-bulk" + WIRELESS_SUPER_SIM_SMSCOMMANDS = "wireless-super-sim-smscommands" + WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA = "wireless-super-sim-smscommands-africa" + WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA = "wireless-super-sim-smscommands-asia" + WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA = ( + "wireless-super-sim-smscommands-cent-and-south-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE = "wireless-super-sim-smscommands-europe" + WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA = ( + "wireless-super-sim-smscommands-north-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA = ( + "wireless-super-sim-smscommands-oceania" + ) + WIRELESS_SUPER_SIM_SUBSCRIPTION = "wireless-super-sim-subscription" + WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG = "wireless-super-sim-subscription-payg" + WIRELESS_USAGE = "wireless-usage" + WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" + WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" + WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" + WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-commands-centralandsouthamerica" + ) + WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" + WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" + WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" + WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" + WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" + WIRELESS_USAGE_DATA = "wireless-usage-data" + WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" + WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" + WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-data-centralandsouthamerica" + ) + WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( + "wireless-usage-data-custom-additionalmb" + ) + WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" + WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" + WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" + WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( + "wireless-usage-data-individual-additionalgb" + ) + WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( + "wireless-usage-data-individual-firstgb" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( + "wireless-usage-data-international-roaming-canada" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( + "wireless-usage-data-international-roaming-india" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( + "wireless-usage-data-international-roaming-mexico" + ) + WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" + WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" + WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" + WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" + WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" + WIRELESS_USAGE_MRC = "wireless-usage-mrc" + WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" + WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" + WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" + WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" + WIRELESS_USAGE_SMS = "wireless-usage-sms" + WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + :ivar api_version: The API version used to create the resource. + :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + :ivar category: + :ivar count: The number of usage events, such as the number of calls. + :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + :ivar description: A plain-language description of the usage category. + :ivar end_date: The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar price: The total price of the usage in the currency specified in `price_unit` and associated with the account. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + :ivar start_date: The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar subresource_uris: A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar usage: The amount used to bill usage and measured in units described in `usage_unit`. + :ivar usage_unit: The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.as_of: Optional[str] = payload.get("as_of") + self.category: Optional["ThisMonthInstance.Category"] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ThisMonthPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ThisMonthInstance: + """ + Build an instance of ThisMonthInstance + + :param payload: Payload response from the API + """ + return ThisMonthInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ThisMonthList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the ThisMonthList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records/ThisMonth.json".format( + **self._solution + ) + + def stream( + self, + category: Union["ThisMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ThisMonthInstance]: + """ + Streams ThisMonthInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "ThisMonthInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + category: Union["ThisMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ThisMonthInstance]: + """ + Asynchronously streams ThisMonthInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "ThisMonthInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["ThisMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ThisMonthInstance]: + """ + Lists ThisMonthInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "ThisMonthInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + category: Union["ThisMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ThisMonthInstance]: + """ + Asynchronously lists ThisMonthInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "ThisMonthInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + category: Union["ThisMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ThisMonthPage: + """ + Retrieve a single page of ThisMonthInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ThisMonthInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ThisMonthPage(self._version, response, self._solution) + + async def page_async( + self, + category: Union["ThisMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ThisMonthPage: + """ + Asynchronously retrieve a single page of ThisMonthInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ThisMonthInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ThisMonthPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ThisMonthPage: + """ + Retrieve a specific page of ThisMonthInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ThisMonthInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ThisMonthPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ThisMonthPage: + """ + Asynchronously retrieve a specific page of ThisMonthInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ThisMonthInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ThisMonthPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/today.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/today.py new file mode 100644 index 00000000..393238e7 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/today.py @@ -0,0 +1,1211 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TodayInstance(InstanceResource): + + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" + AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" + ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" + AUTHY_AUTHENTICATIONS = "authy-authentications" + AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" + AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" + AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" + AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" + AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" + CALL_PROGESS_EVENTS = "call-progess-events" + CALLERIDLOOKUPS = "calleridlookups" + CALLS = "calls" + CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" + CALLS_GLOBALCONFERENCE = "calls-globalconference" + CALLS_INBOUND = "calls-inbound" + CALLS_INBOUND_LOCAL = "calls-inbound-local" + CALLS_INBOUND_MOBILE = "calls-inbound-mobile" + CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" + CALLS_OUTBOUND = "calls-outbound" + CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" + CALLS_RECORDINGS = "calls-recordings" + CALLS_SIP = "calls-sip" + CALLS_SIP_INBOUND = "calls-sip-inbound" + CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" + CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" + CONVERSATIONS = "conversations" + CONVERSATIONS_API_REQUESTS = "conversations-api-requests" + CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" + CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" + CONVERSATIONS_EVENTS = "conversations-events" + CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" + CONVERSATIONS_PARTICIPANTS = "conversations-participants" + CPS = "cps" + CREDIT_TRANSFER = "credit-transfer" + EMAIL = "email" + EMERGING_TECH = "emerging-tech" + ENGAGEMENT_SUITE_PACKAGED_PLANS = "engagement-suite-packaged-plans" + ENHANCED_LINE_TYPE_LOOKUPS = "enhanced-line-type-lookups" + ENTERPRISE = "enterprise" + EVENTS = "events" + EXPERIMENT_FRANCE_SMS = "experiment-france-sms" + EXPERIMENT_INDIA_SMS = "experiment-india-sms" + EXPERIMENT_UK_SMS = "experiment-uk-sms" + FAILED_MESSAGE_PROCESSING_FEE = "failed-message-processing-fee" + FLEX = "flex" + FLEX_ACTIVE_USER_HOURS = "flex-active-user-hours" + FLEX_CONCURRENT_USERS = "flex-concurrent-users" + FLEX_CONVERSATIONAL_INSIGHTS = "flex-conversational-insights" + FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES = "flex-conversational-insights-messages" + FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = ( + "flex-conversational-insights-voice-minutes" + ) + FLEX_EMAIL_USAGE = "flex-email-usage" + FLEX_MESSAGING_USAGE = "flex-messaging-usage" + FLEX_PARTNER_SPINSCI = "flex-partner-spinsci" + FLEX_PARTNER_XCELERATE = "flex-partner-xcelerate" + FLEX_RESELLER_ECOSYSTEM = "flex-reseller-ecosystem" + FLEX_UNIQUE_USER = "flex-unique-user" + FLEX_USAGE = "flex-usage" + FLEX_USERS = "flex-users" + FLEX_VOICE_MINUTE = "flex-voice-minute" + FLEX_YTICA = "flex-ytica" + FRAUD_LOOKUPS = "fraud-lookups" + FRONTLINE = "frontline" + FRONTLINE_USERS = "frontline-users" + FUNCTIONS = "functions" + GENERIC_PAY_TRANSACTIONS = "generic-pay-transactions" + GROUP_ROOMS = "group-rooms" + GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" + GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" + GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" + GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" + GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" + GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" + GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" + GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" + IP_MESSAGING = "ip-messaging" + IP_MESSAGING_COMMANDS = "ip-messaging-commands" + IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" + IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" + IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" + IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" + IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" + LINE_STATUS_LOOKUPS = "line-status-lookups" + LIVE_ACTIVITY_LOOKUPS = "live-activity-lookups" + LOOKUP_BUCKET_ADJUSTMENT = "lookup-bucket-adjustment" + LOOKUP_IDENTITY_MATCH = "lookup-identity-match" + LOOKUPS = "lookups" + MARKETPLACE = "marketplace" + MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) + MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" + MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" + MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" + MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" + MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION = "marketplace-deepgram-transcription" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE = ( + "marketplace-deepgram-transcription-base" + ) + MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED = ( + "marketplace-deepgram-transscription-enhanced" + ) + MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( + "marketplace-digital-segment-business-info" + ) + MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( + "marketplace-facebook-offline-conversions" + ) + MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" + MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( + "marketplace-ibm-watson-message-insights" + ) + MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( + "marketplace-ibm-watson-message-sentiment" + ) + MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( + "marketplace-ibm-watson-recording-analysis" + ) + MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" + MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" + MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( + "marketplace-infogroup-dataaxle-bizinfo" + ) + MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( + "marketplace-keen-io-contact-center-analytics" + ) + MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" + MARKETPLACE_MARCHEX_RECORDING_ANALYSIS = ( + "marketplace-marchex-recording-analysis" + ) + MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( + "marketplace-marchex-sentiment-analysis-for-sms" + ) + MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( + "marketplace-marketplace-nextcaller-social-id" + ) + MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( + "marketplace-mobile-commons-opt-out-classifier" + ) + MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( + "marketplace-nexiwave-voicemail-to-text" + ) + MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( + "marketplace-nextcaller-advanced-caller-identification" + ) + MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" + MARKETPLACE_PAY_ADDONS = "marketplace-pay-addons" + MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR = ( + "marketplace-pay-addons-basecommerce-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR = ( + "marketplace-pay-addons-braintree-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR = ( + "marketplace-pay-addons-cardconnect-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR = ( + "marketplace-pay-addons-chase-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplace-pay-addons-shuttle-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplace-pay-addons-stripe-pay-connector" + ) + MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" + MARKETPLACE_POLY_AI_CONNECTOR = "marketplace-poly-ai-connector" + MARKETPLACE_REALPHONEVALIDATION = "marketplace-realphonevalidation" + MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( + "marketplace-remeeting-automatic-speech-recognition" + ) + MARKETPLACE_SPOKE_PHONE_LICENSE_PRO = "marketplace-spoke-phone-license-pro" + MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD = ( + "marketplace-spoke-phone-license-standard" + ) + MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( + "marketplace-tcpa-defense-solutions-blacklist-feed" + ) + MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" + MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION = ( + "marketplace-trestle-solutions-caller-identification" + ) + MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" + MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( + "marketplace-twilio-caller-name-lookup-us" + ) + MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( + "marketplace-twilio-carrier-information-lookup" + ) + MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" + MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" + MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) + MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" + MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( + "marketplace-ytica-contact-center-reporting-analytics" + ) + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplay-pay-addons-shuttle-pay-connector" + ) + MEDIA_COMPOSER_MINUTES = "media-composer-minutes" + MEDIASTORAGE = "mediastorage" + MIN_SPEND_ADJUSTMENTS = "min-spend-adjustments" + MMS = "mms" + MMS_INBOUND = "mms-inbound" + MMS_INBOUND_LONGCODE = "mms-inbound-longcode" + MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" + MMS_INBOUND_TOLL_FREE = "mms-inbound-toll-free" + MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" + MMS_OUTBOUND = "mms-outbound" + MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" + MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" + MMS_OUTBOUND_TOLLFREE = "mms-outbound-tollfree" + MONITOR = "monitor" + MONITOR_READS = "monitor-reads" + MONITOR_STORAGE = "monitor-storage" + MONITOR_WRITES = "monitor-writes" + NOTIFY = "notify" + NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" + NOTIFY_CHANNELS = "notify-channels" + NUMBER_FORMAT_LOOKUPS = "number-format-lookups" + PCHAT = "pchat" + PCHAT_ACTIONS = "pchat-actions" + PCHAT_APS = "pchat-aps" + PCHAT_CONV_MED_STORAGE = "pchat-conv-med-storage" + PCHAT_MESSAGES = "pchat-messages" + PCHAT_NOTIFICATIONS = "pchat-notifications" + PCHAT_READS = "pchat-reads" + PCHAT_USERS = "pchat-users" + PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "peer-to-peer-rooms-participant-minutes" + ) + PFAX = "pfax" + PFAX_MINUTES = "pfax-minutes" + PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" + PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" + PFAX_PAGES = "pfax-pages" + PHONE_QUALITY_SCORE_LOOKUPS = "phone-quality-score-lookups" + PHONENUMBERS = "phonenumbers" + PHONENUMBERS_CPS = "phonenumbers-cps" + PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" + PHONENUMBERS_LOCAL = "phonenumbers-local" + PHONENUMBERS_MOBILE = "phonenumbers-mobile" + PHONENUMBERS_PORTING = "phonenumbers-porting" + PHONENUMBERS_SETUPS = "phonenumbers-setups" + PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" + PREMIUMSUPPORT = "premiumsupport" + PREMIUMSUPPORT_PERCENTAGE_SPEND = "premiumsupport-percentage-spend" + PROGRAMMABLEVOICE_PLATFORM = "programmablevoice-platform" + PROGRAMMABLEVOICECONN_CLIENTSDK = "programmablevoiceconn-clientsdk" + PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND = ( + "programmablevoiceconn-clientsdk-inbound" + ) + PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND = ( + "programmablevoiceconn-clientsdk-outbound" + ) + PROGRAMMABLEVOICECONN_ONNET = "programmablevoiceconn-onnet" + PROGRAMMABLEVOICECONN_ONNET_INBOUND = "programmablevoiceconn-onnet-inbound" + PROGRAMMABLEVOICECONN_ONNET_OUTBOUND = "programmablevoiceconn-onnet-outbound" + PROGRAMMABLEVOICECONN_SIP = "programmablevoiceconn-sip" + PROGRAMMABLEVOICECONN_SIP_INBOUND = "programmablevoiceconn-sip-inbound" + PROGRAMMABLEVOICECONN_SIP_OUTBOUND = "programmablevoiceconn-sip-outbound" + PROGRAMMABLEVOICECONNECTIVITY = "programmablevoiceconnectivity" + PROXY = "proxy" + PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" + PROXY_BUCKET_ADJUSTMENT = "proxy-bucket-adjustment" + PROXY_LICENSES = "proxy-licenses" + PSTNCONNECTIVITY = "pstnconnectivity" + PSTNCONNECTIVITY_INBOUND = "pstnconnectivity-inbound" + PSTNCONNECTIVITY_OUTBOUND = "pstnconnectivity-outbound" + PV = "pv" + PV_BASIC_ROOMS = "pv-basic-rooms" + PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" + PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" + PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" + PV_COMPOSITION_MINUTES = "pv-composition-minutes" + PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" + PV_ROOM_PARTICIPANTS = "pv-room-participants" + PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" + PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" + PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" + PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" + PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" + PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" + PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" + PV_ROOMS = "pv-rooms" + PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" + RCS_MESSAGES = "rcs-messages" + REASSIGNED_NUMBER = "reassigned-number" + RECORDINGS = "recordings" + RECORDINGSTORAGE = "recordingstorage" + SHORTCODES = "shortcodes" + SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" + SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" + SHORTCODES_MPS = "shortcodes-mps" + SHORTCODES_RANDOM = "shortcodes-random" + SHORTCODES_SETUP_FEES = "shortcodes-setup-fees" + SHORTCODES_UK = "shortcodes-uk" + SHORTCODES_VANITY = "shortcodes-vanity" + SIM_SWAP_LOOKUPS = "sim-swap-lookups" + SIP_SECURE_MEDIA = "sip-secure-media" + SMALL_GROUP_ROOMS = "small-group-rooms" + SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" + SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" + SMS = "sms" + SMS_INBOUND = "sms-inbound" + SMS_INBOUND_LONGCODE = "sms-inbound-longcode" + SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" + SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" + SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) + SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" + SMS_OUTBOUND = "sms-outbound" + SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" + SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" + SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" + SPEECH_RECOGNITION = "speech-recognition" + STUDIO_ENGAGEMENTS = "studio-engagements" + SYNC = "sync" + SYNC_ACTIONS = "sync-actions" + SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" + SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" + TASKROUTER_TASKS = "taskrouter-tasks" + TOTALPRICE = "totalprice" + TRANSCRIPTIONS = "transcriptions" + TRUNKING_CPS = "trunking-cps" + TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" + TRUNKING_ORIGINATION = "trunking-origination" + TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" + TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" + TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" + TRUNKING_RECORDINGS = "trunking-recordings" + TRUNKING_SECURE = "trunking-secure" + TRUNKING_TERMINATION = "trunking-termination" + TTS_GOOGLE = "tts-google" + TURNMEGABYTES = "turnmegabytes" + TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" + TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" + TURNMEGABYTES_GERMANY = "turnmegabytes-germany" + TURNMEGABYTES_INDIA = "turnmegabytes-india" + TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" + TURNMEGABYTES_JAPAN = "turnmegabytes-japan" + TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" + TURNMEGABYTES_USEAST = "turnmegabytes-useast" + TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" + TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) + VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" + VOICE_INSIGHTS = "voice-insights" + VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-client-insights-on-demand-minute" + ) + VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-ptsn-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-interface-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-trunking-insights-on-demand-minute" + ) + VOICE_INTELLIGENCE = "voice-intelligence" + VOICE_INTELLIGENCE_EIP_OPERATORS = "voice-intelligence-eip-operators" + VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" + VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" + WDS = "wds" + WIRELESS = "wireless" + WIRELESS_DATA = "wireless-data" + WIRELESS_DATA_PAYG = "wireless-data-payg" + WIRELESS_DATA_PAYG_AFRICA = "wireless-data-payg-africa" + WIRELESS_DATA_PAYG_ASIA = "wireless-data-payg-asia" + WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA = ( + "wireless-data-payg-centralandsouthamerica" + ) + WIRELESS_DATA_PAYG_EUROPE = "wireless-data-payg-europe" + WIRELESS_DATA_PAYG_NORTHAMERICA = "wireless-data-payg-northamerica" + WIRELESS_DATA_PAYG_OCEANIA = "wireless-data-payg-oceania" + WIRELESS_DATA_QUOTA1 = "wireless-data-quota1" + WIRELESS_DATA_QUOTA1_AFRICA = "wireless-data-quota1-africa" + WIRELESS_DATA_QUOTA1_ASIA = "wireless-data-quota1-asia" + WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota1-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA1_EUROPE = "wireless-data-quota1-europe" + WIRELESS_DATA_QUOTA1_NORTHAMERICA = "wireless-data-quota1-northamerica" + WIRELESS_DATA_QUOTA1_OCEANIA = "wireless-data-quota1-oceania" + WIRELESS_DATA_QUOTA10 = "wireless-data-quota10" + WIRELESS_DATA_QUOTA10_AFRICA = "wireless-data-quota10-africa" + WIRELESS_DATA_QUOTA10_ASIA = "wireless-data-quota10-asia" + WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota10-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA10_EUROPE = "wireless-data-quota10-europe" + WIRELESS_DATA_QUOTA10_NORTHAMERICA = "wireless-data-quota10-northamerica" + WIRELESS_DATA_QUOTA10_OCEANIA = "wireless-data-quota10-oceania" + WIRELESS_DATA_QUOTA50 = "wireless-data-quota50" + WIRELESS_DATA_QUOTA50_AFRICA = "wireless-data-quota50-africa" + WIRELESS_DATA_QUOTA50_ASIA = "wireless-data-quota50-asia" + WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota50-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA50_EUROPE = "wireless-data-quota50-europe" + WIRELESS_DATA_QUOTA50_NORTHAMERICA = "wireless-data-quota50-northamerica" + WIRELESS_DATA_QUOTA50_OCEANIA = "wireless-data-quota50-oceania" + WIRELESS_DATA_QUOTACUSTOM = "wireless-data-quotacustom" + WIRELESS_DATA_QUOTACUSTOM_AFRICA = "wireless-data-quotacustom-africa" + WIRELESS_DATA_QUOTACUSTOM_ASIA = "wireless-data-quotacustom-asia" + WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quotacustom-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_EUROPE = "wireless-data-quotacustom-europe" + WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA = ( + "wireless-data-quotacustom-northamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_OCEANIA = "wireless-data-quotacustom-oceania" + WIRELESS_MRC_PAYG = "wireless-mrc-payg" + WIRELESS_MRC_QUOTA1 = "wireless-mrc-quota1" + WIRELESS_MRC_QUOTA10 = "wireless-mrc-quota10" + WIRELESS_MRC_QUOTA50 = "wireless-mrc-quota50" + WIRELESS_MRC_QUOTACUSTOM = "wireless-mrc-quotacustom" + WIRELESS_ORDERS = "wireless-orders" + WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" + WIRELESS_ORDERS_BULK = "wireless-orders-bulk" + WIRELESS_ORDERS_ESIM = "wireless-orders-esim" + WIRELESS_ORDERS_STARTER = "wireless-orders-starter" + WIRELESS_QUOTAS = "wireless-quotas" + WIRELESS_SMS_AFRICA = "wireless-sms-africa" + WIRELESS_SMS_ASIA = "wireless-sms-asia" + WIRELESS_SMS_CENTRALANDSOUTHAMERICA = "wireless-sms-centralandsouthamerica" + WIRELESS_SMS_EUROPE = "wireless-sms-europe" + WIRELESS_SMS_NORTHAMERICA = "wireless-sms-northamerica" + WIRELESS_SMS_OCEANIA = "wireless-sms-oceania" + WIRELESS_SUPER_SIM = "wireless-super-sim" + WIRELESS_SUPER_SIM_DATA = "wireless-super-sim-data" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA = ( + "wireless-super-sim-data-north-america-usa" + ) + WIRELESS_SUPER_SIM_DATA_PAYG = "wireless-super-sim-data-payg" + WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE = "wireless-super-sim-data-payg-europe" + WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA = ( + "wireless-super-sim-data-payg-north-america" + ) + WIRELESS_SUPER_SIM_HARDWARE = "wireless-super-sim-hardware" + WIRELESS_SUPER_SIM_HARDWARE_BULK = "wireless-super-sim-hardware-bulk" + WIRELESS_SUPER_SIM_SMSCOMMANDS = "wireless-super-sim-smscommands" + WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA = "wireless-super-sim-smscommands-africa" + WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA = "wireless-super-sim-smscommands-asia" + WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA = ( + "wireless-super-sim-smscommands-cent-and-south-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE = "wireless-super-sim-smscommands-europe" + WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA = ( + "wireless-super-sim-smscommands-north-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA = ( + "wireless-super-sim-smscommands-oceania" + ) + WIRELESS_SUPER_SIM_SUBSCRIPTION = "wireless-super-sim-subscription" + WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG = "wireless-super-sim-subscription-payg" + WIRELESS_USAGE = "wireless-usage" + WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" + WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" + WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" + WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-commands-centralandsouthamerica" + ) + WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" + WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" + WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" + WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" + WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" + WIRELESS_USAGE_DATA = "wireless-usage-data" + WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" + WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" + WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-data-centralandsouthamerica" + ) + WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( + "wireless-usage-data-custom-additionalmb" + ) + WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" + WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" + WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" + WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( + "wireless-usage-data-individual-additionalgb" + ) + WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( + "wireless-usage-data-individual-firstgb" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( + "wireless-usage-data-international-roaming-canada" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( + "wireless-usage-data-international-roaming-india" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( + "wireless-usage-data-international-roaming-mexico" + ) + WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" + WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" + WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" + WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" + WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" + WIRELESS_USAGE_MRC = "wireless-usage-mrc" + WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" + WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" + WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" + WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" + WIRELESS_USAGE_SMS = "wireless-usage-sms" + WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + :ivar api_version: The API version used to create the resource. + :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + :ivar category: + :ivar count: The number of usage events, such as the number of calls. + :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + :ivar description: A plain-language description of the usage category. + :ivar end_date: The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar price: The total price of the usage in the currency specified in `price_unit` and associated with the account. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + :ivar start_date: The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar subresource_uris: A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar usage: The amount used to bill usage and measured in units described in `usage_unit`. + :ivar usage_unit: The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.as_of: Optional[str] = payload.get("as_of") + self.category: Optional["TodayInstance.Category"] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TodayPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TodayInstance: + """ + Build an instance of TodayInstance + + :param payload: Payload response from the API + """ + return TodayInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TodayList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the TodayList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records/Today.json".format( + **self._solution + ) + + def stream( + self, + category: Union["TodayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TodayInstance]: + """ + Streams TodayInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "TodayInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + category: Union["TodayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TodayInstance]: + """ + Asynchronously streams TodayInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "TodayInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["TodayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TodayInstance]: + """ + Lists TodayInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "TodayInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + category: Union["TodayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TodayInstance]: + """ + Asynchronously lists TodayInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "TodayInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + category: Union["TodayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TodayPage: + """ + Retrieve a single page of TodayInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TodayInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TodayPage(self._version, response, self._solution) + + async def page_async( + self, + category: Union["TodayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TodayPage: + """ + Asynchronously retrieve a single page of TodayInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TodayInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TodayPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> TodayPage: + """ + Retrieve a specific page of TodayInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TodayInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TodayPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> TodayPage: + """ + Asynchronously retrieve a specific page of TodayInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TodayInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TodayPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/yearly.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/yearly.py new file mode 100644 index 00000000..ad9e5a36 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/yearly.py @@ -0,0 +1,1211 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class YearlyInstance(InstanceResource): + + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" + AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" + ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" + AUTHY_AUTHENTICATIONS = "authy-authentications" + AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" + AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" + AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" + AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" + AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" + CALL_PROGESS_EVENTS = "call-progess-events" + CALLERIDLOOKUPS = "calleridlookups" + CALLS = "calls" + CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" + CALLS_GLOBALCONFERENCE = "calls-globalconference" + CALLS_INBOUND = "calls-inbound" + CALLS_INBOUND_LOCAL = "calls-inbound-local" + CALLS_INBOUND_MOBILE = "calls-inbound-mobile" + CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" + CALLS_OUTBOUND = "calls-outbound" + CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" + CALLS_RECORDINGS = "calls-recordings" + CALLS_SIP = "calls-sip" + CALLS_SIP_INBOUND = "calls-sip-inbound" + CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" + CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" + CONVERSATIONS = "conversations" + CONVERSATIONS_API_REQUESTS = "conversations-api-requests" + CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" + CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" + CONVERSATIONS_EVENTS = "conversations-events" + CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" + CONVERSATIONS_PARTICIPANTS = "conversations-participants" + CPS = "cps" + CREDIT_TRANSFER = "credit-transfer" + EMAIL = "email" + EMERGING_TECH = "emerging-tech" + ENGAGEMENT_SUITE_PACKAGED_PLANS = "engagement-suite-packaged-plans" + ENHANCED_LINE_TYPE_LOOKUPS = "enhanced-line-type-lookups" + ENTERPRISE = "enterprise" + EVENTS = "events" + EXPERIMENT_FRANCE_SMS = "experiment-france-sms" + EXPERIMENT_INDIA_SMS = "experiment-india-sms" + EXPERIMENT_UK_SMS = "experiment-uk-sms" + FAILED_MESSAGE_PROCESSING_FEE = "failed-message-processing-fee" + FLEX = "flex" + FLEX_ACTIVE_USER_HOURS = "flex-active-user-hours" + FLEX_CONCURRENT_USERS = "flex-concurrent-users" + FLEX_CONVERSATIONAL_INSIGHTS = "flex-conversational-insights" + FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES = "flex-conversational-insights-messages" + FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = ( + "flex-conversational-insights-voice-minutes" + ) + FLEX_EMAIL_USAGE = "flex-email-usage" + FLEX_MESSAGING_USAGE = "flex-messaging-usage" + FLEX_PARTNER_SPINSCI = "flex-partner-spinsci" + FLEX_PARTNER_XCELERATE = "flex-partner-xcelerate" + FLEX_RESELLER_ECOSYSTEM = "flex-reseller-ecosystem" + FLEX_UNIQUE_USER = "flex-unique-user" + FLEX_USAGE = "flex-usage" + FLEX_USERS = "flex-users" + FLEX_VOICE_MINUTE = "flex-voice-minute" + FLEX_YTICA = "flex-ytica" + FRAUD_LOOKUPS = "fraud-lookups" + FRONTLINE = "frontline" + FRONTLINE_USERS = "frontline-users" + FUNCTIONS = "functions" + GENERIC_PAY_TRANSACTIONS = "generic-pay-transactions" + GROUP_ROOMS = "group-rooms" + GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" + GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" + GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" + GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" + GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" + GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" + GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" + GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" + IP_MESSAGING = "ip-messaging" + IP_MESSAGING_COMMANDS = "ip-messaging-commands" + IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" + IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" + IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" + IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" + IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" + LINE_STATUS_LOOKUPS = "line-status-lookups" + LIVE_ACTIVITY_LOOKUPS = "live-activity-lookups" + LOOKUP_BUCKET_ADJUSTMENT = "lookup-bucket-adjustment" + LOOKUP_IDENTITY_MATCH = "lookup-identity-match" + LOOKUPS = "lookups" + MARKETPLACE = "marketplace" + MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) + MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" + MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" + MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" + MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" + MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION = "marketplace-deepgram-transcription" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE = ( + "marketplace-deepgram-transcription-base" + ) + MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED = ( + "marketplace-deepgram-transscription-enhanced" + ) + MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( + "marketplace-digital-segment-business-info" + ) + MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( + "marketplace-facebook-offline-conversions" + ) + MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" + MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( + "marketplace-ibm-watson-message-insights" + ) + MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( + "marketplace-ibm-watson-message-sentiment" + ) + MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( + "marketplace-ibm-watson-recording-analysis" + ) + MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" + MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" + MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( + "marketplace-infogroup-dataaxle-bizinfo" + ) + MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( + "marketplace-keen-io-contact-center-analytics" + ) + MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" + MARKETPLACE_MARCHEX_RECORDING_ANALYSIS = ( + "marketplace-marchex-recording-analysis" + ) + MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( + "marketplace-marchex-sentiment-analysis-for-sms" + ) + MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( + "marketplace-marketplace-nextcaller-social-id" + ) + MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( + "marketplace-mobile-commons-opt-out-classifier" + ) + MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( + "marketplace-nexiwave-voicemail-to-text" + ) + MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( + "marketplace-nextcaller-advanced-caller-identification" + ) + MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" + MARKETPLACE_PAY_ADDONS = "marketplace-pay-addons" + MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR = ( + "marketplace-pay-addons-basecommerce-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR = ( + "marketplace-pay-addons-braintree-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR = ( + "marketplace-pay-addons-cardconnect-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR = ( + "marketplace-pay-addons-chase-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplace-pay-addons-shuttle-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplace-pay-addons-stripe-pay-connector" + ) + MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" + MARKETPLACE_POLY_AI_CONNECTOR = "marketplace-poly-ai-connector" + MARKETPLACE_REALPHONEVALIDATION = "marketplace-realphonevalidation" + MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( + "marketplace-remeeting-automatic-speech-recognition" + ) + MARKETPLACE_SPOKE_PHONE_LICENSE_PRO = "marketplace-spoke-phone-license-pro" + MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD = ( + "marketplace-spoke-phone-license-standard" + ) + MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( + "marketplace-tcpa-defense-solutions-blacklist-feed" + ) + MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" + MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION = ( + "marketplace-trestle-solutions-caller-identification" + ) + MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" + MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( + "marketplace-twilio-caller-name-lookup-us" + ) + MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( + "marketplace-twilio-carrier-information-lookup" + ) + MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" + MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" + MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) + MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" + MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( + "marketplace-ytica-contact-center-reporting-analytics" + ) + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplay-pay-addons-shuttle-pay-connector" + ) + MEDIA_COMPOSER_MINUTES = "media-composer-minutes" + MEDIASTORAGE = "mediastorage" + MIN_SPEND_ADJUSTMENTS = "min-spend-adjustments" + MMS = "mms" + MMS_INBOUND = "mms-inbound" + MMS_INBOUND_LONGCODE = "mms-inbound-longcode" + MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" + MMS_INBOUND_TOLL_FREE = "mms-inbound-toll-free" + MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" + MMS_OUTBOUND = "mms-outbound" + MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" + MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" + MMS_OUTBOUND_TOLLFREE = "mms-outbound-tollfree" + MONITOR = "monitor" + MONITOR_READS = "monitor-reads" + MONITOR_STORAGE = "monitor-storage" + MONITOR_WRITES = "monitor-writes" + NOTIFY = "notify" + NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" + NOTIFY_CHANNELS = "notify-channels" + NUMBER_FORMAT_LOOKUPS = "number-format-lookups" + PCHAT = "pchat" + PCHAT_ACTIONS = "pchat-actions" + PCHAT_APS = "pchat-aps" + PCHAT_CONV_MED_STORAGE = "pchat-conv-med-storage" + PCHAT_MESSAGES = "pchat-messages" + PCHAT_NOTIFICATIONS = "pchat-notifications" + PCHAT_READS = "pchat-reads" + PCHAT_USERS = "pchat-users" + PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "peer-to-peer-rooms-participant-minutes" + ) + PFAX = "pfax" + PFAX_MINUTES = "pfax-minutes" + PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" + PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" + PFAX_PAGES = "pfax-pages" + PHONE_QUALITY_SCORE_LOOKUPS = "phone-quality-score-lookups" + PHONENUMBERS = "phonenumbers" + PHONENUMBERS_CPS = "phonenumbers-cps" + PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" + PHONENUMBERS_LOCAL = "phonenumbers-local" + PHONENUMBERS_MOBILE = "phonenumbers-mobile" + PHONENUMBERS_PORTING = "phonenumbers-porting" + PHONENUMBERS_SETUPS = "phonenumbers-setups" + PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" + PREMIUMSUPPORT = "premiumsupport" + PREMIUMSUPPORT_PERCENTAGE_SPEND = "premiumsupport-percentage-spend" + PROGRAMMABLEVOICE_PLATFORM = "programmablevoice-platform" + PROGRAMMABLEVOICECONN_CLIENTSDK = "programmablevoiceconn-clientsdk" + PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND = ( + "programmablevoiceconn-clientsdk-inbound" + ) + PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND = ( + "programmablevoiceconn-clientsdk-outbound" + ) + PROGRAMMABLEVOICECONN_ONNET = "programmablevoiceconn-onnet" + PROGRAMMABLEVOICECONN_ONNET_INBOUND = "programmablevoiceconn-onnet-inbound" + PROGRAMMABLEVOICECONN_ONNET_OUTBOUND = "programmablevoiceconn-onnet-outbound" + PROGRAMMABLEVOICECONN_SIP = "programmablevoiceconn-sip" + PROGRAMMABLEVOICECONN_SIP_INBOUND = "programmablevoiceconn-sip-inbound" + PROGRAMMABLEVOICECONN_SIP_OUTBOUND = "programmablevoiceconn-sip-outbound" + PROGRAMMABLEVOICECONNECTIVITY = "programmablevoiceconnectivity" + PROXY = "proxy" + PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" + PROXY_BUCKET_ADJUSTMENT = "proxy-bucket-adjustment" + PROXY_LICENSES = "proxy-licenses" + PSTNCONNECTIVITY = "pstnconnectivity" + PSTNCONNECTIVITY_INBOUND = "pstnconnectivity-inbound" + PSTNCONNECTIVITY_OUTBOUND = "pstnconnectivity-outbound" + PV = "pv" + PV_BASIC_ROOMS = "pv-basic-rooms" + PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" + PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" + PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" + PV_COMPOSITION_MINUTES = "pv-composition-minutes" + PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" + PV_ROOM_PARTICIPANTS = "pv-room-participants" + PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" + PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" + PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" + PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" + PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" + PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" + PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" + PV_ROOMS = "pv-rooms" + PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" + RCS_MESSAGES = "rcs-messages" + REASSIGNED_NUMBER = "reassigned-number" + RECORDINGS = "recordings" + RECORDINGSTORAGE = "recordingstorage" + SHORTCODES = "shortcodes" + SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" + SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" + SHORTCODES_MPS = "shortcodes-mps" + SHORTCODES_RANDOM = "shortcodes-random" + SHORTCODES_SETUP_FEES = "shortcodes-setup-fees" + SHORTCODES_UK = "shortcodes-uk" + SHORTCODES_VANITY = "shortcodes-vanity" + SIM_SWAP_LOOKUPS = "sim-swap-lookups" + SIP_SECURE_MEDIA = "sip-secure-media" + SMALL_GROUP_ROOMS = "small-group-rooms" + SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" + SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" + SMS = "sms" + SMS_INBOUND = "sms-inbound" + SMS_INBOUND_LONGCODE = "sms-inbound-longcode" + SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" + SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" + SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) + SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" + SMS_OUTBOUND = "sms-outbound" + SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" + SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" + SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" + SPEECH_RECOGNITION = "speech-recognition" + STUDIO_ENGAGEMENTS = "studio-engagements" + SYNC = "sync" + SYNC_ACTIONS = "sync-actions" + SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" + SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" + TASKROUTER_TASKS = "taskrouter-tasks" + TOTALPRICE = "totalprice" + TRANSCRIPTIONS = "transcriptions" + TRUNKING_CPS = "trunking-cps" + TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" + TRUNKING_ORIGINATION = "trunking-origination" + TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" + TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" + TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" + TRUNKING_RECORDINGS = "trunking-recordings" + TRUNKING_SECURE = "trunking-secure" + TRUNKING_TERMINATION = "trunking-termination" + TTS_GOOGLE = "tts-google" + TURNMEGABYTES = "turnmegabytes" + TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" + TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" + TURNMEGABYTES_GERMANY = "turnmegabytes-germany" + TURNMEGABYTES_INDIA = "turnmegabytes-india" + TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" + TURNMEGABYTES_JAPAN = "turnmegabytes-japan" + TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" + TURNMEGABYTES_USEAST = "turnmegabytes-useast" + TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" + TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) + VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" + VOICE_INSIGHTS = "voice-insights" + VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-client-insights-on-demand-minute" + ) + VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-ptsn-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-interface-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-trunking-insights-on-demand-minute" + ) + VOICE_INTELLIGENCE = "voice-intelligence" + VOICE_INTELLIGENCE_EIP_OPERATORS = "voice-intelligence-eip-operators" + VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" + VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" + WDS = "wds" + WIRELESS = "wireless" + WIRELESS_DATA = "wireless-data" + WIRELESS_DATA_PAYG = "wireless-data-payg" + WIRELESS_DATA_PAYG_AFRICA = "wireless-data-payg-africa" + WIRELESS_DATA_PAYG_ASIA = "wireless-data-payg-asia" + WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA = ( + "wireless-data-payg-centralandsouthamerica" + ) + WIRELESS_DATA_PAYG_EUROPE = "wireless-data-payg-europe" + WIRELESS_DATA_PAYG_NORTHAMERICA = "wireless-data-payg-northamerica" + WIRELESS_DATA_PAYG_OCEANIA = "wireless-data-payg-oceania" + WIRELESS_DATA_QUOTA1 = "wireless-data-quota1" + WIRELESS_DATA_QUOTA1_AFRICA = "wireless-data-quota1-africa" + WIRELESS_DATA_QUOTA1_ASIA = "wireless-data-quota1-asia" + WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota1-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA1_EUROPE = "wireless-data-quota1-europe" + WIRELESS_DATA_QUOTA1_NORTHAMERICA = "wireless-data-quota1-northamerica" + WIRELESS_DATA_QUOTA1_OCEANIA = "wireless-data-quota1-oceania" + WIRELESS_DATA_QUOTA10 = "wireless-data-quota10" + WIRELESS_DATA_QUOTA10_AFRICA = "wireless-data-quota10-africa" + WIRELESS_DATA_QUOTA10_ASIA = "wireless-data-quota10-asia" + WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota10-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA10_EUROPE = "wireless-data-quota10-europe" + WIRELESS_DATA_QUOTA10_NORTHAMERICA = "wireless-data-quota10-northamerica" + WIRELESS_DATA_QUOTA10_OCEANIA = "wireless-data-quota10-oceania" + WIRELESS_DATA_QUOTA50 = "wireless-data-quota50" + WIRELESS_DATA_QUOTA50_AFRICA = "wireless-data-quota50-africa" + WIRELESS_DATA_QUOTA50_ASIA = "wireless-data-quota50-asia" + WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota50-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA50_EUROPE = "wireless-data-quota50-europe" + WIRELESS_DATA_QUOTA50_NORTHAMERICA = "wireless-data-quota50-northamerica" + WIRELESS_DATA_QUOTA50_OCEANIA = "wireless-data-quota50-oceania" + WIRELESS_DATA_QUOTACUSTOM = "wireless-data-quotacustom" + WIRELESS_DATA_QUOTACUSTOM_AFRICA = "wireless-data-quotacustom-africa" + WIRELESS_DATA_QUOTACUSTOM_ASIA = "wireless-data-quotacustom-asia" + WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quotacustom-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_EUROPE = "wireless-data-quotacustom-europe" + WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA = ( + "wireless-data-quotacustom-northamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_OCEANIA = "wireless-data-quotacustom-oceania" + WIRELESS_MRC_PAYG = "wireless-mrc-payg" + WIRELESS_MRC_QUOTA1 = "wireless-mrc-quota1" + WIRELESS_MRC_QUOTA10 = "wireless-mrc-quota10" + WIRELESS_MRC_QUOTA50 = "wireless-mrc-quota50" + WIRELESS_MRC_QUOTACUSTOM = "wireless-mrc-quotacustom" + WIRELESS_ORDERS = "wireless-orders" + WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" + WIRELESS_ORDERS_BULK = "wireless-orders-bulk" + WIRELESS_ORDERS_ESIM = "wireless-orders-esim" + WIRELESS_ORDERS_STARTER = "wireless-orders-starter" + WIRELESS_QUOTAS = "wireless-quotas" + WIRELESS_SMS_AFRICA = "wireless-sms-africa" + WIRELESS_SMS_ASIA = "wireless-sms-asia" + WIRELESS_SMS_CENTRALANDSOUTHAMERICA = "wireless-sms-centralandsouthamerica" + WIRELESS_SMS_EUROPE = "wireless-sms-europe" + WIRELESS_SMS_NORTHAMERICA = "wireless-sms-northamerica" + WIRELESS_SMS_OCEANIA = "wireless-sms-oceania" + WIRELESS_SUPER_SIM = "wireless-super-sim" + WIRELESS_SUPER_SIM_DATA = "wireless-super-sim-data" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA = ( + "wireless-super-sim-data-north-america-usa" + ) + WIRELESS_SUPER_SIM_DATA_PAYG = "wireless-super-sim-data-payg" + WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE = "wireless-super-sim-data-payg-europe" + WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA = ( + "wireless-super-sim-data-payg-north-america" + ) + WIRELESS_SUPER_SIM_HARDWARE = "wireless-super-sim-hardware" + WIRELESS_SUPER_SIM_HARDWARE_BULK = "wireless-super-sim-hardware-bulk" + WIRELESS_SUPER_SIM_SMSCOMMANDS = "wireless-super-sim-smscommands" + WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA = "wireless-super-sim-smscommands-africa" + WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA = "wireless-super-sim-smscommands-asia" + WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA = ( + "wireless-super-sim-smscommands-cent-and-south-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE = "wireless-super-sim-smscommands-europe" + WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA = ( + "wireless-super-sim-smscommands-north-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA = ( + "wireless-super-sim-smscommands-oceania" + ) + WIRELESS_SUPER_SIM_SUBSCRIPTION = "wireless-super-sim-subscription" + WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG = "wireless-super-sim-subscription-payg" + WIRELESS_USAGE = "wireless-usage" + WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" + WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" + WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" + WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-commands-centralandsouthamerica" + ) + WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" + WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" + WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" + WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" + WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" + WIRELESS_USAGE_DATA = "wireless-usage-data" + WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" + WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" + WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-data-centralandsouthamerica" + ) + WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( + "wireless-usage-data-custom-additionalmb" + ) + WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" + WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" + WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" + WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( + "wireless-usage-data-individual-additionalgb" + ) + WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( + "wireless-usage-data-individual-firstgb" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( + "wireless-usage-data-international-roaming-canada" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( + "wireless-usage-data-international-roaming-india" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( + "wireless-usage-data-international-roaming-mexico" + ) + WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" + WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" + WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" + WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" + WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" + WIRELESS_USAGE_MRC = "wireless-usage-mrc" + WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" + WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" + WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" + WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" + WIRELESS_USAGE_SMS = "wireless-usage-sms" + WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + :ivar api_version: The API version used to create the resource. + :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + :ivar category: + :ivar count: The number of usage events, such as the number of calls. + :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + :ivar description: A plain-language description of the usage category. + :ivar end_date: The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar price: The total price of the usage in the currency specified in `price_unit` and associated with the account. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + :ivar start_date: The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar subresource_uris: A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar usage: The amount used to bill usage and measured in units described in `usage_unit`. + :ivar usage_unit: The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.as_of: Optional[str] = payload.get("as_of") + self.category: Optional["YearlyInstance.Category"] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class YearlyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> YearlyInstance: + """ + Build an instance of YearlyInstance + + :param payload: Payload response from the API + """ + return YearlyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class YearlyList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the YearlyList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records/Yearly.json".format( + **self._solution + ) + + def stream( + self, + category: Union["YearlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[YearlyInstance]: + """ + Streams YearlyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "YearlyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + category: Union["YearlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[YearlyInstance]: + """ + Asynchronously streams YearlyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "YearlyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["YearlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[YearlyInstance]: + """ + Lists YearlyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "YearlyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + category: Union["YearlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[YearlyInstance]: + """ + Asynchronously lists YearlyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "YearlyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + category: Union["YearlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> YearlyPage: + """ + Retrieve a single page of YearlyInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of YearlyInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return YearlyPage(self._version, response, self._solution) + + async def page_async( + self, + category: Union["YearlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> YearlyPage: + """ + Asynchronously retrieve a single page of YearlyInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of YearlyInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return YearlyPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> YearlyPage: + """ + Retrieve a specific page of YearlyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of YearlyInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return YearlyPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> YearlyPage: + """ + Asynchronously retrieve a specific page of YearlyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of YearlyInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return YearlyPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/yesterday.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/yesterday.py new file mode 100644 index 00000000..f3aacda8 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/record/yesterday.py @@ -0,0 +1,1211 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class YesterdayInstance(InstanceResource): + + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" + AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" + ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" + AUTHY_AUTHENTICATIONS = "authy-authentications" + AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" + AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" + AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" + AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" + AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" + CALL_PROGESS_EVENTS = "call-progess-events" + CALLERIDLOOKUPS = "calleridlookups" + CALLS = "calls" + CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" + CALLS_GLOBALCONFERENCE = "calls-globalconference" + CALLS_INBOUND = "calls-inbound" + CALLS_INBOUND_LOCAL = "calls-inbound-local" + CALLS_INBOUND_MOBILE = "calls-inbound-mobile" + CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" + CALLS_OUTBOUND = "calls-outbound" + CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" + CALLS_RECORDINGS = "calls-recordings" + CALLS_SIP = "calls-sip" + CALLS_SIP_INBOUND = "calls-sip-inbound" + CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" + CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" + CONVERSATIONS = "conversations" + CONVERSATIONS_API_REQUESTS = "conversations-api-requests" + CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" + CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" + CONVERSATIONS_EVENTS = "conversations-events" + CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" + CONVERSATIONS_PARTICIPANTS = "conversations-participants" + CPS = "cps" + CREDIT_TRANSFER = "credit-transfer" + EMAIL = "email" + EMERGING_TECH = "emerging-tech" + ENGAGEMENT_SUITE_PACKAGED_PLANS = "engagement-suite-packaged-plans" + ENHANCED_LINE_TYPE_LOOKUPS = "enhanced-line-type-lookups" + ENTERPRISE = "enterprise" + EVENTS = "events" + EXPERIMENT_FRANCE_SMS = "experiment-france-sms" + EXPERIMENT_INDIA_SMS = "experiment-india-sms" + EXPERIMENT_UK_SMS = "experiment-uk-sms" + FAILED_MESSAGE_PROCESSING_FEE = "failed-message-processing-fee" + FLEX = "flex" + FLEX_ACTIVE_USER_HOURS = "flex-active-user-hours" + FLEX_CONCURRENT_USERS = "flex-concurrent-users" + FLEX_CONVERSATIONAL_INSIGHTS = "flex-conversational-insights" + FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES = "flex-conversational-insights-messages" + FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = ( + "flex-conversational-insights-voice-minutes" + ) + FLEX_EMAIL_USAGE = "flex-email-usage" + FLEX_MESSAGING_USAGE = "flex-messaging-usage" + FLEX_PARTNER_SPINSCI = "flex-partner-spinsci" + FLEX_PARTNER_XCELERATE = "flex-partner-xcelerate" + FLEX_RESELLER_ECOSYSTEM = "flex-reseller-ecosystem" + FLEX_UNIQUE_USER = "flex-unique-user" + FLEX_USAGE = "flex-usage" + FLEX_USERS = "flex-users" + FLEX_VOICE_MINUTE = "flex-voice-minute" + FLEX_YTICA = "flex-ytica" + FRAUD_LOOKUPS = "fraud-lookups" + FRONTLINE = "frontline" + FRONTLINE_USERS = "frontline-users" + FUNCTIONS = "functions" + GENERIC_PAY_TRANSACTIONS = "generic-pay-transactions" + GROUP_ROOMS = "group-rooms" + GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" + GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" + GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" + GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" + GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" + GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" + GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" + GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" + IP_MESSAGING = "ip-messaging" + IP_MESSAGING_COMMANDS = "ip-messaging-commands" + IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" + IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" + IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" + IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" + IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" + LINE_STATUS_LOOKUPS = "line-status-lookups" + LIVE_ACTIVITY_LOOKUPS = "live-activity-lookups" + LOOKUP_BUCKET_ADJUSTMENT = "lookup-bucket-adjustment" + LOOKUP_IDENTITY_MATCH = "lookup-identity-match" + LOOKUPS = "lookups" + MARKETPLACE = "marketplace" + MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) + MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" + MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" + MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" + MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" + MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION = "marketplace-deepgram-transcription" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE = ( + "marketplace-deepgram-transcription-base" + ) + MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED = ( + "marketplace-deepgram-transscription-enhanced" + ) + MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( + "marketplace-digital-segment-business-info" + ) + MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( + "marketplace-facebook-offline-conversions" + ) + MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" + MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( + "marketplace-ibm-watson-message-insights" + ) + MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( + "marketplace-ibm-watson-message-sentiment" + ) + MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( + "marketplace-ibm-watson-recording-analysis" + ) + MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" + MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" + MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( + "marketplace-infogroup-dataaxle-bizinfo" + ) + MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( + "marketplace-keen-io-contact-center-analytics" + ) + MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" + MARKETPLACE_MARCHEX_RECORDING_ANALYSIS = ( + "marketplace-marchex-recording-analysis" + ) + MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( + "marketplace-marchex-sentiment-analysis-for-sms" + ) + MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( + "marketplace-marketplace-nextcaller-social-id" + ) + MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( + "marketplace-mobile-commons-opt-out-classifier" + ) + MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( + "marketplace-nexiwave-voicemail-to-text" + ) + MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( + "marketplace-nextcaller-advanced-caller-identification" + ) + MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" + MARKETPLACE_PAY_ADDONS = "marketplace-pay-addons" + MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR = ( + "marketplace-pay-addons-basecommerce-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR = ( + "marketplace-pay-addons-braintree-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR = ( + "marketplace-pay-addons-cardconnect-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR = ( + "marketplace-pay-addons-chase-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplace-pay-addons-shuttle-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplace-pay-addons-stripe-pay-connector" + ) + MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" + MARKETPLACE_POLY_AI_CONNECTOR = "marketplace-poly-ai-connector" + MARKETPLACE_REALPHONEVALIDATION = "marketplace-realphonevalidation" + MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( + "marketplace-remeeting-automatic-speech-recognition" + ) + MARKETPLACE_SPOKE_PHONE_LICENSE_PRO = "marketplace-spoke-phone-license-pro" + MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD = ( + "marketplace-spoke-phone-license-standard" + ) + MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( + "marketplace-tcpa-defense-solutions-blacklist-feed" + ) + MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" + MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION = ( + "marketplace-trestle-solutions-caller-identification" + ) + MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" + MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( + "marketplace-twilio-caller-name-lookup-us" + ) + MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( + "marketplace-twilio-carrier-information-lookup" + ) + MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" + MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" + MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) + MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" + MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( + "marketplace-ytica-contact-center-reporting-analytics" + ) + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplay-pay-addons-shuttle-pay-connector" + ) + MEDIA_COMPOSER_MINUTES = "media-composer-minutes" + MEDIASTORAGE = "mediastorage" + MIN_SPEND_ADJUSTMENTS = "min-spend-adjustments" + MMS = "mms" + MMS_INBOUND = "mms-inbound" + MMS_INBOUND_LONGCODE = "mms-inbound-longcode" + MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" + MMS_INBOUND_TOLL_FREE = "mms-inbound-toll-free" + MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" + MMS_OUTBOUND = "mms-outbound" + MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" + MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" + MMS_OUTBOUND_TOLLFREE = "mms-outbound-tollfree" + MONITOR = "monitor" + MONITOR_READS = "monitor-reads" + MONITOR_STORAGE = "monitor-storage" + MONITOR_WRITES = "monitor-writes" + NOTIFY = "notify" + NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" + NOTIFY_CHANNELS = "notify-channels" + NUMBER_FORMAT_LOOKUPS = "number-format-lookups" + PCHAT = "pchat" + PCHAT_ACTIONS = "pchat-actions" + PCHAT_APS = "pchat-aps" + PCHAT_CONV_MED_STORAGE = "pchat-conv-med-storage" + PCHAT_MESSAGES = "pchat-messages" + PCHAT_NOTIFICATIONS = "pchat-notifications" + PCHAT_READS = "pchat-reads" + PCHAT_USERS = "pchat-users" + PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "peer-to-peer-rooms-participant-minutes" + ) + PFAX = "pfax" + PFAX_MINUTES = "pfax-minutes" + PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" + PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" + PFAX_PAGES = "pfax-pages" + PHONE_QUALITY_SCORE_LOOKUPS = "phone-quality-score-lookups" + PHONENUMBERS = "phonenumbers" + PHONENUMBERS_CPS = "phonenumbers-cps" + PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" + PHONENUMBERS_LOCAL = "phonenumbers-local" + PHONENUMBERS_MOBILE = "phonenumbers-mobile" + PHONENUMBERS_PORTING = "phonenumbers-porting" + PHONENUMBERS_SETUPS = "phonenumbers-setups" + PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" + PREMIUMSUPPORT = "premiumsupport" + PREMIUMSUPPORT_PERCENTAGE_SPEND = "premiumsupport-percentage-spend" + PROGRAMMABLEVOICE_PLATFORM = "programmablevoice-platform" + PROGRAMMABLEVOICECONN_CLIENTSDK = "programmablevoiceconn-clientsdk" + PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND = ( + "programmablevoiceconn-clientsdk-inbound" + ) + PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND = ( + "programmablevoiceconn-clientsdk-outbound" + ) + PROGRAMMABLEVOICECONN_ONNET = "programmablevoiceconn-onnet" + PROGRAMMABLEVOICECONN_ONNET_INBOUND = "programmablevoiceconn-onnet-inbound" + PROGRAMMABLEVOICECONN_ONNET_OUTBOUND = "programmablevoiceconn-onnet-outbound" + PROGRAMMABLEVOICECONN_SIP = "programmablevoiceconn-sip" + PROGRAMMABLEVOICECONN_SIP_INBOUND = "programmablevoiceconn-sip-inbound" + PROGRAMMABLEVOICECONN_SIP_OUTBOUND = "programmablevoiceconn-sip-outbound" + PROGRAMMABLEVOICECONNECTIVITY = "programmablevoiceconnectivity" + PROXY = "proxy" + PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" + PROXY_BUCKET_ADJUSTMENT = "proxy-bucket-adjustment" + PROXY_LICENSES = "proxy-licenses" + PSTNCONNECTIVITY = "pstnconnectivity" + PSTNCONNECTIVITY_INBOUND = "pstnconnectivity-inbound" + PSTNCONNECTIVITY_OUTBOUND = "pstnconnectivity-outbound" + PV = "pv" + PV_BASIC_ROOMS = "pv-basic-rooms" + PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" + PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" + PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" + PV_COMPOSITION_MINUTES = "pv-composition-minutes" + PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" + PV_ROOM_PARTICIPANTS = "pv-room-participants" + PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" + PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" + PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" + PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" + PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" + PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" + PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" + PV_ROOMS = "pv-rooms" + PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" + RCS_MESSAGES = "rcs-messages" + REASSIGNED_NUMBER = "reassigned-number" + RECORDINGS = "recordings" + RECORDINGSTORAGE = "recordingstorage" + SHORTCODES = "shortcodes" + SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" + SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" + SHORTCODES_MPS = "shortcodes-mps" + SHORTCODES_RANDOM = "shortcodes-random" + SHORTCODES_SETUP_FEES = "shortcodes-setup-fees" + SHORTCODES_UK = "shortcodes-uk" + SHORTCODES_VANITY = "shortcodes-vanity" + SIM_SWAP_LOOKUPS = "sim-swap-lookups" + SIP_SECURE_MEDIA = "sip-secure-media" + SMALL_GROUP_ROOMS = "small-group-rooms" + SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" + SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" + SMS = "sms" + SMS_INBOUND = "sms-inbound" + SMS_INBOUND_LONGCODE = "sms-inbound-longcode" + SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" + SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" + SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) + SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" + SMS_OUTBOUND = "sms-outbound" + SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" + SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" + SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" + SPEECH_RECOGNITION = "speech-recognition" + STUDIO_ENGAGEMENTS = "studio-engagements" + SYNC = "sync" + SYNC_ACTIONS = "sync-actions" + SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" + SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" + TASKROUTER_TASKS = "taskrouter-tasks" + TOTALPRICE = "totalprice" + TRANSCRIPTIONS = "transcriptions" + TRUNKING_CPS = "trunking-cps" + TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" + TRUNKING_ORIGINATION = "trunking-origination" + TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" + TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" + TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" + TRUNKING_RECORDINGS = "trunking-recordings" + TRUNKING_SECURE = "trunking-secure" + TRUNKING_TERMINATION = "trunking-termination" + TTS_GOOGLE = "tts-google" + TURNMEGABYTES = "turnmegabytes" + TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" + TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" + TURNMEGABYTES_GERMANY = "turnmegabytes-germany" + TURNMEGABYTES_INDIA = "turnmegabytes-india" + TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" + TURNMEGABYTES_JAPAN = "turnmegabytes-japan" + TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" + TURNMEGABYTES_USEAST = "turnmegabytes-useast" + TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" + TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) + VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" + VOICE_INSIGHTS = "voice-insights" + VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-client-insights-on-demand-minute" + ) + VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-ptsn-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-interface-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-trunking-insights-on-demand-minute" + ) + VOICE_INTELLIGENCE = "voice-intelligence" + VOICE_INTELLIGENCE_EIP_OPERATORS = "voice-intelligence-eip-operators" + VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" + VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" + WDS = "wds" + WIRELESS = "wireless" + WIRELESS_DATA = "wireless-data" + WIRELESS_DATA_PAYG = "wireless-data-payg" + WIRELESS_DATA_PAYG_AFRICA = "wireless-data-payg-africa" + WIRELESS_DATA_PAYG_ASIA = "wireless-data-payg-asia" + WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA = ( + "wireless-data-payg-centralandsouthamerica" + ) + WIRELESS_DATA_PAYG_EUROPE = "wireless-data-payg-europe" + WIRELESS_DATA_PAYG_NORTHAMERICA = "wireless-data-payg-northamerica" + WIRELESS_DATA_PAYG_OCEANIA = "wireless-data-payg-oceania" + WIRELESS_DATA_QUOTA1 = "wireless-data-quota1" + WIRELESS_DATA_QUOTA1_AFRICA = "wireless-data-quota1-africa" + WIRELESS_DATA_QUOTA1_ASIA = "wireless-data-quota1-asia" + WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota1-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA1_EUROPE = "wireless-data-quota1-europe" + WIRELESS_DATA_QUOTA1_NORTHAMERICA = "wireless-data-quota1-northamerica" + WIRELESS_DATA_QUOTA1_OCEANIA = "wireless-data-quota1-oceania" + WIRELESS_DATA_QUOTA10 = "wireless-data-quota10" + WIRELESS_DATA_QUOTA10_AFRICA = "wireless-data-quota10-africa" + WIRELESS_DATA_QUOTA10_ASIA = "wireless-data-quota10-asia" + WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota10-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA10_EUROPE = "wireless-data-quota10-europe" + WIRELESS_DATA_QUOTA10_NORTHAMERICA = "wireless-data-quota10-northamerica" + WIRELESS_DATA_QUOTA10_OCEANIA = "wireless-data-quota10-oceania" + WIRELESS_DATA_QUOTA50 = "wireless-data-quota50" + WIRELESS_DATA_QUOTA50_AFRICA = "wireless-data-quota50-africa" + WIRELESS_DATA_QUOTA50_ASIA = "wireless-data-quota50-asia" + WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota50-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA50_EUROPE = "wireless-data-quota50-europe" + WIRELESS_DATA_QUOTA50_NORTHAMERICA = "wireless-data-quota50-northamerica" + WIRELESS_DATA_QUOTA50_OCEANIA = "wireless-data-quota50-oceania" + WIRELESS_DATA_QUOTACUSTOM = "wireless-data-quotacustom" + WIRELESS_DATA_QUOTACUSTOM_AFRICA = "wireless-data-quotacustom-africa" + WIRELESS_DATA_QUOTACUSTOM_ASIA = "wireless-data-quotacustom-asia" + WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quotacustom-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_EUROPE = "wireless-data-quotacustom-europe" + WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA = ( + "wireless-data-quotacustom-northamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_OCEANIA = "wireless-data-quotacustom-oceania" + WIRELESS_MRC_PAYG = "wireless-mrc-payg" + WIRELESS_MRC_QUOTA1 = "wireless-mrc-quota1" + WIRELESS_MRC_QUOTA10 = "wireless-mrc-quota10" + WIRELESS_MRC_QUOTA50 = "wireless-mrc-quota50" + WIRELESS_MRC_QUOTACUSTOM = "wireless-mrc-quotacustom" + WIRELESS_ORDERS = "wireless-orders" + WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" + WIRELESS_ORDERS_BULK = "wireless-orders-bulk" + WIRELESS_ORDERS_ESIM = "wireless-orders-esim" + WIRELESS_ORDERS_STARTER = "wireless-orders-starter" + WIRELESS_QUOTAS = "wireless-quotas" + WIRELESS_SMS_AFRICA = "wireless-sms-africa" + WIRELESS_SMS_ASIA = "wireless-sms-asia" + WIRELESS_SMS_CENTRALANDSOUTHAMERICA = "wireless-sms-centralandsouthamerica" + WIRELESS_SMS_EUROPE = "wireless-sms-europe" + WIRELESS_SMS_NORTHAMERICA = "wireless-sms-northamerica" + WIRELESS_SMS_OCEANIA = "wireless-sms-oceania" + WIRELESS_SUPER_SIM = "wireless-super-sim" + WIRELESS_SUPER_SIM_DATA = "wireless-super-sim-data" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA = ( + "wireless-super-sim-data-north-america-usa" + ) + WIRELESS_SUPER_SIM_DATA_PAYG = "wireless-super-sim-data-payg" + WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE = "wireless-super-sim-data-payg-europe" + WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA = ( + "wireless-super-sim-data-payg-north-america" + ) + WIRELESS_SUPER_SIM_HARDWARE = "wireless-super-sim-hardware" + WIRELESS_SUPER_SIM_HARDWARE_BULK = "wireless-super-sim-hardware-bulk" + WIRELESS_SUPER_SIM_SMSCOMMANDS = "wireless-super-sim-smscommands" + WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA = "wireless-super-sim-smscommands-africa" + WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA = "wireless-super-sim-smscommands-asia" + WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA = ( + "wireless-super-sim-smscommands-cent-and-south-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE = "wireless-super-sim-smscommands-europe" + WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA = ( + "wireless-super-sim-smscommands-north-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA = ( + "wireless-super-sim-smscommands-oceania" + ) + WIRELESS_SUPER_SIM_SUBSCRIPTION = "wireless-super-sim-subscription" + WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG = "wireless-super-sim-subscription-payg" + WIRELESS_USAGE = "wireless-usage" + WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" + WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" + WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" + WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-commands-centralandsouthamerica" + ) + WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" + WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" + WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" + WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" + WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" + WIRELESS_USAGE_DATA = "wireless-usage-data" + WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" + WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" + WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-data-centralandsouthamerica" + ) + WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( + "wireless-usage-data-custom-additionalmb" + ) + WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" + WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" + WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" + WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( + "wireless-usage-data-individual-additionalgb" + ) + WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( + "wireless-usage-data-individual-firstgb" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( + "wireless-usage-data-international-roaming-canada" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( + "wireless-usage-data-international-roaming-india" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( + "wireless-usage-data-international-roaming-mexico" + ) + WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" + WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" + WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" + WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" + WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" + WIRELESS_USAGE_MRC = "wireless-usage-mrc" + WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" + WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" + WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" + WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" + WIRELESS_USAGE_SMS = "wireless-usage-sms" + WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + :ivar api_version: The API version used to create the resource. + :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + :ivar category: + :ivar count: The number of usage events, such as the number of calls. + :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + :ivar description: A plain-language description of the usage category. + :ivar end_date: The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar price: The total price of the usage in the currency specified in `price_unit` and associated with the account. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + :ivar start_date: The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar subresource_uris: A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar usage: The amount used to bill usage and measured in units described in `usage_unit`. + :ivar usage_unit: The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.as_of: Optional[str] = payload.get("as_of") + self.category: Optional["YesterdayInstance.Category"] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class YesterdayPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> YesterdayInstance: + """ + Build an instance of YesterdayInstance + + :param payload: Payload response from the API + """ + return YesterdayInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class YesterdayList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the YesterdayList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records/Yesterday.json".format( + **self._solution + ) + + def stream( + self, + category: Union["YesterdayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[YesterdayInstance]: + """ + Streams YesterdayInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "YesterdayInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + category: Union["YesterdayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[YesterdayInstance]: + """ + Asynchronously streams YesterdayInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "YesterdayInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["YesterdayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[YesterdayInstance]: + """ + Lists YesterdayInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "YesterdayInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + category: Union["YesterdayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[YesterdayInstance]: + """ + Asynchronously lists YesterdayInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "YesterdayInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + category: Union["YesterdayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> YesterdayPage: + """ + Retrieve a single page of YesterdayInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of YesterdayInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return YesterdayPage(self._version, response, self._solution) + + async def page_async( + self, + category: Union["YesterdayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> YesterdayPage: + """ + Asynchronously retrieve a single page of YesterdayInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of YesterdayInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return YesterdayPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> YesterdayPage: + """ + Retrieve a specific page of YesterdayInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of YesterdayInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return YesterdayPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> YesterdayPage: + """ + Asynchronously retrieve a specific page of YesterdayInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of YesterdayInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return YesterdayPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/trigger.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/trigger.py new file mode 100644 index 00000000..7f182a01 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/usage/trigger.py @@ -0,0 +1,1611 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TriggerInstance(InstanceResource): + + class Recurring(object): + DAILY = "daily" + MONTHLY = "monthly" + YEARLY = "yearly" + ALLTIME = "alltime" + + class TriggerField(object): + COUNT = "count" + USAGE = "usage" + PRICE = "price" + + class UsageCategory(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" + AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" + ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" + AUTHY_AUTHENTICATIONS = "authy-authentications" + AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" + AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" + AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" + AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" + AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" + CALL_PROGESS_EVENTS = "call-progess-events" + CALLERIDLOOKUPS = "calleridlookups" + CALLS = "calls" + CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" + CALLS_GLOBALCONFERENCE = "calls-globalconference" + CALLS_INBOUND = "calls-inbound" + CALLS_INBOUND_LOCAL = "calls-inbound-local" + CALLS_INBOUND_MOBILE = "calls-inbound-mobile" + CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" + CALLS_OUTBOUND = "calls-outbound" + CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" + CALLS_RECORDINGS = "calls-recordings" + CALLS_SIP = "calls-sip" + CALLS_SIP_INBOUND = "calls-sip-inbound" + CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" + CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" + CONVERSATIONS = "conversations" + CONVERSATIONS_API_REQUESTS = "conversations-api-requests" + CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" + CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" + CONVERSATIONS_EVENTS = "conversations-events" + CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" + CONVERSATIONS_PARTICIPANTS = "conversations-participants" + CPS = "cps" + CREDIT_TRANSFER = "credit-transfer" + EMAIL = "email" + EMERGING_TECH = "emerging-tech" + ENGAGEMENT_SUITE_PACKAGED_PLANS = "engagement-suite-packaged-plans" + ENHANCED_LINE_TYPE_LOOKUPS = "enhanced-line-type-lookups" + ENTERPRISE = "enterprise" + EVENTS = "events" + EXPERIMENT_FRANCE_SMS = "experiment-france-sms" + EXPERIMENT_INDIA_SMS = "experiment-india-sms" + EXPERIMENT_UK_SMS = "experiment-uk-sms" + FAILED_MESSAGE_PROCESSING_FEE = "failed-message-processing-fee" + FLEX = "flex" + FLEX_ACTIVE_USER_HOURS = "flex-active-user-hours" + FLEX_CONCURRENT_USERS = "flex-concurrent-users" + FLEX_CONVERSATIONAL_INSIGHTS = "flex-conversational-insights" + FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES = "flex-conversational-insights-messages" + FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = ( + "flex-conversational-insights-voice-minutes" + ) + FLEX_EMAIL_USAGE = "flex-email-usage" + FLEX_MESSAGING_USAGE = "flex-messaging-usage" + FLEX_PARTNER_SPINSCI = "flex-partner-spinsci" + FLEX_PARTNER_XCELERATE = "flex-partner-xcelerate" + FLEX_RESELLER_ECOSYSTEM = "flex-reseller-ecosystem" + FLEX_UNIQUE_USER = "flex-unique-user" + FLEX_USAGE = "flex-usage" + FLEX_USERS = "flex-users" + FLEX_VOICE_MINUTE = "flex-voice-minute" + FLEX_YTICA = "flex-ytica" + FRAUD_LOOKUPS = "fraud-lookups" + FRONTLINE = "frontline" + FRONTLINE_USERS = "frontline-users" + FUNCTIONS = "functions" + GENERIC_PAY_TRANSACTIONS = "generic-pay-transactions" + GROUP_ROOMS = "group-rooms" + GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" + GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" + GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" + GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" + GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" + GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" + GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" + GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" + IP_MESSAGING = "ip-messaging" + IP_MESSAGING_COMMANDS = "ip-messaging-commands" + IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" + IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" + IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" + IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" + IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" + LINE_STATUS_LOOKUPS = "line-status-lookups" + LIVE_ACTIVITY_LOOKUPS = "live-activity-lookups" + LOOKUP_BUCKET_ADJUSTMENT = "lookup-bucket-adjustment" + LOOKUP_IDENTITY_MATCH = "lookup-identity-match" + LOOKUPS = "lookups" + MARKETPLACE = "marketplace" + MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) + MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" + MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" + MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" + MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" + MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION = "marketplace-deepgram-transcription" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE = ( + "marketplace-deepgram-transcription-base" + ) + MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED = ( + "marketplace-deepgram-transscription-enhanced" + ) + MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( + "marketplace-digital-segment-business-info" + ) + MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( + "marketplace-facebook-offline-conversions" + ) + MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" + MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( + "marketplace-ibm-watson-message-insights" + ) + MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( + "marketplace-ibm-watson-message-sentiment" + ) + MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( + "marketplace-ibm-watson-recording-analysis" + ) + MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" + MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" + MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( + "marketplace-infogroup-dataaxle-bizinfo" + ) + MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( + "marketplace-keen-io-contact-center-analytics" + ) + MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" + MARKETPLACE_MARCHEX_RECORDING_ANALYSIS = ( + "marketplace-marchex-recording-analysis" + ) + MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( + "marketplace-marchex-sentiment-analysis-for-sms" + ) + MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( + "marketplace-marketplace-nextcaller-social-id" + ) + MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( + "marketplace-mobile-commons-opt-out-classifier" + ) + MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( + "marketplace-nexiwave-voicemail-to-text" + ) + MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( + "marketplace-nextcaller-advanced-caller-identification" + ) + MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" + MARKETPLACE_PAY_ADDONS = "marketplace-pay-addons" + MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR = ( + "marketplace-pay-addons-basecommerce-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR = ( + "marketplace-pay-addons-braintree-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR = ( + "marketplace-pay-addons-cardconnect-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR = ( + "marketplace-pay-addons-chase-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplace-pay-addons-shuttle-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplace-pay-addons-stripe-pay-connector" + ) + MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" + MARKETPLACE_POLY_AI_CONNECTOR = "marketplace-poly-ai-connector" + MARKETPLACE_REALPHONEVALIDATION = "marketplace-realphonevalidation" + MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( + "marketplace-remeeting-automatic-speech-recognition" + ) + MARKETPLACE_SPOKE_PHONE_LICENSE_PRO = "marketplace-spoke-phone-license-pro" + MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD = ( + "marketplace-spoke-phone-license-standard" + ) + MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( + "marketplace-tcpa-defense-solutions-blacklist-feed" + ) + MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" + MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION = ( + "marketplace-trestle-solutions-caller-identification" + ) + MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" + MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( + "marketplace-twilio-caller-name-lookup-us" + ) + MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( + "marketplace-twilio-carrier-information-lookup" + ) + MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" + MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" + MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) + MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" + MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( + "marketplace-ytica-contact-center-reporting-analytics" + ) + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplay-pay-addons-shuttle-pay-connector" + ) + MEDIA_COMPOSER_MINUTES = "media-composer-minutes" + MEDIASTORAGE = "mediastorage" + MIN_SPEND_ADJUSTMENTS = "min-spend-adjustments" + MMS = "mms" + MMS_INBOUND = "mms-inbound" + MMS_INBOUND_LONGCODE = "mms-inbound-longcode" + MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" + MMS_INBOUND_TOLL_FREE = "mms-inbound-toll-free" + MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" + MMS_OUTBOUND = "mms-outbound" + MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" + MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" + MMS_OUTBOUND_TOLLFREE = "mms-outbound-tollfree" + MONITOR = "monitor" + MONITOR_READS = "monitor-reads" + MONITOR_STORAGE = "monitor-storage" + MONITOR_WRITES = "monitor-writes" + NOTIFY = "notify" + NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" + NOTIFY_CHANNELS = "notify-channels" + NUMBER_FORMAT_LOOKUPS = "number-format-lookups" + PCHAT = "pchat" + PCHAT_ACTIONS = "pchat-actions" + PCHAT_APS = "pchat-aps" + PCHAT_CONV_MED_STORAGE = "pchat-conv-med-storage" + PCHAT_MESSAGES = "pchat-messages" + PCHAT_NOTIFICATIONS = "pchat-notifications" + PCHAT_READS = "pchat-reads" + PCHAT_USERS = "pchat-users" + PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "peer-to-peer-rooms-participant-minutes" + ) + PFAX = "pfax" + PFAX_MINUTES = "pfax-minutes" + PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" + PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" + PFAX_PAGES = "pfax-pages" + PHONE_QUALITY_SCORE_LOOKUPS = "phone-quality-score-lookups" + PHONENUMBERS = "phonenumbers" + PHONENUMBERS_CPS = "phonenumbers-cps" + PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" + PHONENUMBERS_LOCAL = "phonenumbers-local" + PHONENUMBERS_MOBILE = "phonenumbers-mobile" + PHONENUMBERS_PORTING = "phonenumbers-porting" + PHONENUMBERS_SETUPS = "phonenumbers-setups" + PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" + PREMIUMSUPPORT = "premiumsupport" + PREMIUMSUPPORT_PERCENTAGE_SPEND = "premiumsupport-percentage-spend" + PROGRAMMABLEVOICE_PLATFORM = "programmablevoice-platform" + PROGRAMMABLEVOICECONN_CLIENTSDK = "programmablevoiceconn-clientsdk" + PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND = ( + "programmablevoiceconn-clientsdk-inbound" + ) + PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND = ( + "programmablevoiceconn-clientsdk-outbound" + ) + PROGRAMMABLEVOICECONN_ONNET = "programmablevoiceconn-onnet" + PROGRAMMABLEVOICECONN_ONNET_INBOUND = "programmablevoiceconn-onnet-inbound" + PROGRAMMABLEVOICECONN_ONNET_OUTBOUND = "programmablevoiceconn-onnet-outbound" + PROGRAMMABLEVOICECONN_SIP = "programmablevoiceconn-sip" + PROGRAMMABLEVOICECONN_SIP_INBOUND = "programmablevoiceconn-sip-inbound" + PROGRAMMABLEVOICECONN_SIP_OUTBOUND = "programmablevoiceconn-sip-outbound" + PROGRAMMABLEVOICECONNECTIVITY = "programmablevoiceconnectivity" + PROXY = "proxy" + PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" + PROXY_BUCKET_ADJUSTMENT = "proxy-bucket-adjustment" + PROXY_LICENSES = "proxy-licenses" + PSTNCONNECTIVITY = "pstnconnectivity" + PSTNCONNECTIVITY_INBOUND = "pstnconnectivity-inbound" + PSTNCONNECTIVITY_OUTBOUND = "pstnconnectivity-outbound" + PV = "pv" + PV_BASIC_ROOMS = "pv-basic-rooms" + PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" + PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" + PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" + PV_COMPOSITION_MINUTES = "pv-composition-minutes" + PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" + PV_ROOM_PARTICIPANTS = "pv-room-participants" + PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" + PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" + PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" + PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" + PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" + PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" + PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" + PV_ROOMS = "pv-rooms" + PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" + RCS_MESSAGES = "rcs-messages" + REASSIGNED_NUMBER = "reassigned-number" + RECORDINGS = "recordings" + RECORDINGSTORAGE = "recordingstorage" + SHORTCODES = "shortcodes" + SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" + SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" + SHORTCODES_MPS = "shortcodes-mps" + SHORTCODES_RANDOM = "shortcodes-random" + SHORTCODES_SETUP_FEES = "shortcodes-setup-fees" + SHORTCODES_UK = "shortcodes-uk" + SHORTCODES_VANITY = "shortcodes-vanity" + SIM_SWAP_LOOKUPS = "sim-swap-lookups" + SIP_SECURE_MEDIA = "sip-secure-media" + SMALL_GROUP_ROOMS = "small-group-rooms" + SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" + SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" + SMS = "sms" + SMS_INBOUND = "sms-inbound" + SMS_INBOUND_LONGCODE = "sms-inbound-longcode" + SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" + SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" + SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) + SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" + SMS_OUTBOUND = "sms-outbound" + SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" + SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" + SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" + SPEECH_RECOGNITION = "speech-recognition" + STUDIO_ENGAGEMENTS = "studio-engagements" + SYNC = "sync" + SYNC_ACTIONS = "sync-actions" + SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" + SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" + TASKROUTER_TASKS = "taskrouter-tasks" + TOTALPRICE = "totalprice" + TRANSCRIPTIONS = "transcriptions" + TRUNKING_CPS = "trunking-cps" + TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" + TRUNKING_ORIGINATION = "trunking-origination" + TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" + TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" + TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" + TRUNKING_RECORDINGS = "trunking-recordings" + TRUNKING_SECURE = "trunking-secure" + TRUNKING_TERMINATION = "trunking-termination" + TTS_GOOGLE = "tts-google" + TURNMEGABYTES = "turnmegabytes" + TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" + TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" + TURNMEGABYTES_GERMANY = "turnmegabytes-germany" + TURNMEGABYTES_INDIA = "turnmegabytes-india" + TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" + TURNMEGABYTES_JAPAN = "turnmegabytes-japan" + TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" + TURNMEGABYTES_USEAST = "turnmegabytes-useast" + TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" + TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) + VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" + VOICE_INSIGHTS = "voice-insights" + VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-client-insights-on-demand-minute" + ) + VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-ptsn-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-interface-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-trunking-insights-on-demand-minute" + ) + VOICE_INTELLIGENCE = "voice-intelligence" + VOICE_INTELLIGENCE_EIP_OPERATORS = "voice-intelligence-eip-operators" + VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" + VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" + WDS = "wds" + WIRELESS = "wireless" + WIRELESS_DATA = "wireless-data" + WIRELESS_DATA_PAYG = "wireless-data-payg" + WIRELESS_DATA_PAYG_AFRICA = "wireless-data-payg-africa" + WIRELESS_DATA_PAYG_ASIA = "wireless-data-payg-asia" + WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA = ( + "wireless-data-payg-centralandsouthamerica" + ) + WIRELESS_DATA_PAYG_EUROPE = "wireless-data-payg-europe" + WIRELESS_DATA_PAYG_NORTHAMERICA = "wireless-data-payg-northamerica" + WIRELESS_DATA_PAYG_OCEANIA = "wireless-data-payg-oceania" + WIRELESS_DATA_QUOTA1 = "wireless-data-quota1" + WIRELESS_DATA_QUOTA1_AFRICA = "wireless-data-quota1-africa" + WIRELESS_DATA_QUOTA1_ASIA = "wireless-data-quota1-asia" + WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota1-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA1_EUROPE = "wireless-data-quota1-europe" + WIRELESS_DATA_QUOTA1_NORTHAMERICA = "wireless-data-quota1-northamerica" + WIRELESS_DATA_QUOTA1_OCEANIA = "wireless-data-quota1-oceania" + WIRELESS_DATA_QUOTA10 = "wireless-data-quota10" + WIRELESS_DATA_QUOTA10_AFRICA = "wireless-data-quota10-africa" + WIRELESS_DATA_QUOTA10_ASIA = "wireless-data-quota10-asia" + WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota10-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA10_EUROPE = "wireless-data-quota10-europe" + WIRELESS_DATA_QUOTA10_NORTHAMERICA = "wireless-data-quota10-northamerica" + WIRELESS_DATA_QUOTA10_OCEANIA = "wireless-data-quota10-oceania" + WIRELESS_DATA_QUOTA50 = "wireless-data-quota50" + WIRELESS_DATA_QUOTA50_AFRICA = "wireless-data-quota50-africa" + WIRELESS_DATA_QUOTA50_ASIA = "wireless-data-quota50-asia" + WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota50-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA50_EUROPE = "wireless-data-quota50-europe" + WIRELESS_DATA_QUOTA50_NORTHAMERICA = "wireless-data-quota50-northamerica" + WIRELESS_DATA_QUOTA50_OCEANIA = "wireless-data-quota50-oceania" + WIRELESS_DATA_QUOTACUSTOM = "wireless-data-quotacustom" + WIRELESS_DATA_QUOTACUSTOM_AFRICA = "wireless-data-quotacustom-africa" + WIRELESS_DATA_QUOTACUSTOM_ASIA = "wireless-data-quotacustom-asia" + WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quotacustom-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_EUROPE = "wireless-data-quotacustom-europe" + WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA = ( + "wireless-data-quotacustom-northamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_OCEANIA = "wireless-data-quotacustom-oceania" + WIRELESS_MRC_PAYG = "wireless-mrc-payg" + WIRELESS_MRC_QUOTA1 = "wireless-mrc-quota1" + WIRELESS_MRC_QUOTA10 = "wireless-mrc-quota10" + WIRELESS_MRC_QUOTA50 = "wireless-mrc-quota50" + WIRELESS_MRC_QUOTACUSTOM = "wireless-mrc-quotacustom" + WIRELESS_ORDERS = "wireless-orders" + WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" + WIRELESS_ORDERS_BULK = "wireless-orders-bulk" + WIRELESS_ORDERS_ESIM = "wireless-orders-esim" + WIRELESS_ORDERS_STARTER = "wireless-orders-starter" + WIRELESS_QUOTAS = "wireless-quotas" + WIRELESS_SMS_AFRICA = "wireless-sms-africa" + WIRELESS_SMS_ASIA = "wireless-sms-asia" + WIRELESS_SMS_CENTRALANDSOUTHAMERICA = "wireless-sms-centralandsouthamerica" + WIRELESS_SMS_EUROPE = "wireless-sms-europe" + WIRELESS_SMS_NORTHAMERICA = "wireless-sms-northamerica" + WIRELESS_SMS_OCEANIA = "wireless-sms-oceania" + WIRELESS_SUPER_SIM = "wireless-super-sim" + WIRELESS_SUPER_SIM_DATA = "wireless-super-sim-data" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA = ( + "wireless-super-sim-data-north-america-usa" + ) + WIRELESS_SUPER_SIM_DATA_PAYG = "wireless-super-sim-data-payg" + WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE = "wireless-super-sim-data-payg-europe" + WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA = ( + "wireless-super-sim-data-payg-north-america" + ) + WIRELESS_SUPER_SIM_HARDWARE = "wireless-super-sim-hardware" + WIRELESS_SUPER_SIM_HARDWARE_BULK = "wireless-super-sim-hardware-bulk" + WIRELESS_SUPER_SIM_SMSCOMMANDS = "wireless-super-sim-smscommands" + WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA = "wireless-super-sim-smscommands-africa" + WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA = "wireless-super-sim-smscommands-asia" + WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA = ( + "wireless-super-sim-smscommands-cent-and-south-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE = "wireless-super-sim-smscommands-europe" + WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA = ( + "wireless-super-sim-smscommands-north-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA = ( + "wireless-super-sim-smscommands-oceania" + ) + WIRELESS_SUPER_SIM_SUBSCRIPTION = "wireless-super-sim-subscription" + WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG = "wireless-super-sim-subscription-payg" + WIRELESS_USAGE = "wireless-usage" + WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" + WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" + WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" + WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-commands-centralandsouthamerica" + ) + WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" + WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" + WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" + WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" + WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" + WIRELESS_USAGE_DATA = "wireless-usage-data" + WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" + WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" + WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-data-centralandsouthamerica" + ) + WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( + "wireless-usage-data-custom-additionalmb" + ) + WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" + WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" + WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" + WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( + "wireless-usage-data-individual-additionalgb" + ) + WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( + "wireless-usage-data-individual-firstgb" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( + "wireless-usage-data-international-roaming-canada" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( + "wireless-usage-data-international-roaming-india" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( + "wireless-usage-data-international-roaming-mexico" + ) + WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" + WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" + WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" + WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" + WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" + WIRELESS_USAGE_MRC = "wireless-usage-mrc" + WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" + WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" + WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" + WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" + WIRELESS_USAGE_SMS = "wireless-usage-sms" + WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the trigger monitors. + :ivar api_version: The API version used to create the resource. + :ivar callback_method: The HTTP method we use to call `callback_url`. Can be: `GET` or `POST`. + :ivar callback_url: The URL we call using the `callback_method` when the trigger fires. + :ivar current_value: The current value of the field the trigger is watching. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_fired: The date and time in GMT that the trigger was last fired specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the trigger. + :ivar recurring: + :ivar sid: The unique string that that we created to identify the UsageTrigger resource. + :ivar trigger_by: + :ivar trigger_value: The value at which the trigger will fire. Must be a positive, numeric value. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar usage_category: + :ivar usage_record_uri: The URI of the [UsageRecord](https://www.twilio.com/docs/usage/api/usage-record) resource this trigger watches, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.callback_method: Optional[str] = payload.get("callback_method") + self.callback_url: Optional[str] = payload.get("callback_url") + self.current_value: Optional[str] = payload.get("current_value") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_fired: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_fired") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.recurring: Optional["TriggerInstance.Recurring"] = payload.get("recurring") + self.sid: Optional[str] = payload.get("sid") + self.trigger_by: Optional["TriggerInstance.TriggerField"] = payload.get( + "trigger_by" + ) + self.trigger_value: Optional[str] = payload.get("trigger_value") + self.uri: Optional[str] = payload.get("uri") + self.usage_category: Optional["TriggerInstance.UsageCategory"] = payload.get( + "usage_category" + ) + self.usage_record_uri: Optional[str] = payload.get("usage_record_uri") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[TriggerContext] = None + + @property + def _proxy(self) -> "TriggerContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TriggerContext for this TriggerInstance + """ + if self._context is None: + self._context = TriggerContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TriggerInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TriggerInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "TriggerInstance": + """ + Fetch the TriggerInstance + + + :returns: The fetched TriggerInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TriggerInstance": + """ + Asynchronous coroutine to fetch the TriggerInstance + + + :returns: The fetched TriggerInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "TriggerInstance": + """ + Update the TriggerInstance + + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. + :param callback_url: The URL we should call using `callback_method` when the trigger fires. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated TriggerInstance + """ + return self._proxy.update( + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + ) + + async def update_async( + self, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "TriggerInstance": + """ + Asynchronous coroutine to update the TriggerInstance + + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. + :param callback_url: The URL we should call using `callback_method` when the trigger fires. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated TriggerInstance + """ + return await self._proxy.update_async( + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TriggerContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the TriggerContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageTrigger resources to update. + :param sid: The Twilio-provided string that uniquely identifies the UsageTrigger resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Triggers/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the TriggerInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TriggerInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TriggerInstance: + """ + Fetch the TriggerInstance + + + :returns: The fetched TriggerInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TriggerInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TriggerInstance: + """ + Asynchronous coroutine to fetch the TriggerInstance + + + :returns: The fetched TriggerInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TriggerInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> TriggerInstance: + """ + Update the TriggerInstance + + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. + :param callback_url: The URL we should call using `callback_method` when the trigger fires. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated TriggerInstance + """ + + data = values.of( + { + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TriggerInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> TriggerInstance: + """ + Asynchronous coroutine to update the TriggerInstance + + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. + :param callback_url: The URL we should call using `callback_method` when the trigger fires. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated TriggerInstance + """ + + data = values.of( + { + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TriggerInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TriggerPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TriggerInstance: + """ + Build an instance of TriggerInstance + + :param payload: Payload response from the API + """ + return TriggerInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TriggerList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the TriggerList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageTrigger resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Triggers.json".format( + **self._solution + ) + + def create( + self, + callback_url: str, + trigger_value: str, + usage_category: "TriggerInstance.UsageCategory", + callback_method: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + ) -> TriggerInstance: + """ + Create the TriggerInstance + + :param callback_url: The URL we should call using `callback_method` when the trigger fires. + :param trigger_value: The usage value at which the trigger should fire. For convenience, you can use an offset value such as `+30` to specify a trigger_value that is 30 units more than the current usage value. Be sure to urlencode a `+` as `%2B`. + :param usage_category: + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param recurring: + :param trigger_by: + + :returns: The created TriggerInstance + """ + + data = values.of( + { + "CallbackUrl": callback_url, + "TriggerValue": trigger_value, + "UsageCategory": usage_category, + "CallbackMethod": callback_method, + "FriendlyName": friendly_name, + "Recurring": recurring, + "TriggerBy": trigger_by, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TriggerInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, + callback_url: str, + trigger_value: str, + usage_category: "TriggerInstance.UsageCategory", + callback_method: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + ) -> TriggerInstance: + """ + Asynchronously create the TriggerInstance + + :param callback_url: The URL we should call using `callback_method` when the trigger fires. + :param trigger_value: The usage value at which the trigger should fire. For convenience, you can use an offset value such as `+30` to specify a trigger_value that is 30 units more than the current usage value. Be sure to urlencode a `+` as `%2B`. + :param usage_category: + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param recurring: + :param trigger_by: + + :returns: The created TriggerInstance + """ + + data = values.of( + { + "CallbackUrl": callback_url, + "TriggerValue": trigger_value, + "UsageCategory": usage_category, + "CallbackMethod": callback_method, + "FriendlyName": friendly_name, + "Recurring": recurring, + "TriggerBy": trigger_by, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TriggerInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union["TriggerInstance.UsageCategory", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TriggerInstance]: + """ + Streams TriggerInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "TriggerInstance.Recurring" recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. + :param "TriggerInstance.TriggerField" trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + :param "TriggerInstance.UsageCategory" usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + recurring=recurring, + trigger_by=trigger_by, + usage_category=usage_category, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union["TriggerInstance.UsageCategory", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TriggerInstance]: + """ + Asynchronously streams TriggerInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "TriggerInstance.Recurring" recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. + :param "TriggerInstance.TriggerField" trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + :param "TriggerInstance.UsageCategory" usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + recurring=recurring, + trigger_by=trigger_by, + usage_category=usage_category, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union["TriggerInstance.UsageCategory", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TriggerInstance]: + """ + Lists TriggerInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "TriggerInstance.Recurring" recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. + :param "TriggerInstance.TriggerField" trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + :param "TriggerInstance.UsageCategory" usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + recurring=recurring, + trigger_by=trigger_by, + usage_category=usage_category, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union["TriggerInstance.UsageCategory", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TriggerInstance]: + """ + Asynchronously lists TriggerInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "TriggerInstance.Recurring" recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. + :param "TriggerInstance.TriggerField" trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + :param "TriggerInstance.UsageCategory" usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + recurring=recurring, + trigger_by=trigger_by, + usage_category=usage_category, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union["TriggerInstance.UsageCategory", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TriggerPage: + """ + Retrieve a single page of TriggerInstance records from the API. + Request is executed immediately + + :param recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. + :param trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + :param usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TriggerInstance + """ + data = values.of( + { + "Recurring": recurring, + "TriggerBy": trigger_by, + "UsageCategory": usage_category, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TriggerPage(self._version, response, self._solution) + + async def page_async( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union["TriggerInstance.UsageCategory", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TriggerPage: + """ + Asynchronously retrieve a single page of TriggerInstance records from the API. + Request is executed immediately + + :param recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. + :param trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + :param usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TriggerInstance + """ + data = values.of( + { + "Recurring": recurring, + "TriggerBy": trigger_by, + "UsageCategory": usage_category, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TriggerPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> TriggerPage: + """ + Retrieve a specific page of TriggerInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TriggerInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TriggerPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> TriggerPage: + """ + Asynchronously retrieve a specific page of TriggerInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TriggerInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TriggerPage(self._version, response, self._solution) + + def get(self, sid: str) -> TriggerContext: + """ + Constructs a TriggerContext + + :param sid: The Twilio-provided string that uniquely identifies the UsageTrigger resource to update. + """ + return TriggerContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> TriggerContext: + """ + Constructs a TriggerContext + + :param sid: The Twilio-provided string that uniquely identifies the UsageTrigger resource to update. + """ + return TriggerContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/api/v2010/account/validation_request.py b/venv/Lib/site-packages/twilio/rest/api/v2010/account/validation_request.py new file mode 100644 index 00000000..d92f840e --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/api/v2010/account/validation_request.py @@ -0,0 +1,173 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ValidationRequestInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for the Caller ID. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Caller ID is associated with. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar phone_number: The phone number to verify in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar validation_code: The 6 digit validation code that someone must enter to validate the Caller ID when `phone_number` is called. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.call_sid: Optional[str] = payload.get("call_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.phone_number: Optional[str] = payload.get("phone_number") + self.validation_code: Optional[str] = payload.get("validation_code") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ValidationRequestList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the ValidationRequestList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for the new caller ID resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/OutgoingCallerIds.json".format( + **self._solution + ) + + def create( + self, + phone_number: str, + friendly_name: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + extension: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> ValidationRequestInstance: + """ + Create the ValidationRequestInstance + + :param phone_number: The phone number to verify in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :param friendly_name: A descriptive string that you create to describe the new caller ID resource. It can be up to 64 characters long. The default value is a formatted version of the phone number. + :param call_delay: The number of seconds to delay before initiating the verification call. Can be an integer between `0` and `60`, inclusive. The default is `0`. + :param extension: The digits to dial after connecting the verification call. + :param status_callback: The URL we should call using the `status_callback_method` to send status information about the verification process to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`, and the default is `POST`. + + :returns: The created ValidationRequestInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "FriendlyName": friendly_name, + "CallDelay": call_delay, + "Extension": extension, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ValidationRequestInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, + phone_number: str, + friendly_name: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + extension: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> ValidationRequestInstance: + """ + Asynchronously create the ValidationRequestInstance + + :param phone_number: The phone number to verify in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :param friendly_name: A descriptive string that you create to describe the new caller ID resource. It can be up to 64 characters long. The default value is a formatted version of the phone number. + :param call_delay: The number of seconds to delay before initiating the verification call. Can be an integer between `0` and `60`, inclusive. The default is `0`. + :param extension: The digits to dial after connecting the verification call. + :param status_callback: The URL we should call using the `status_callback_method` to send status information about the verification process to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`, and the default is `POST`. + + :returns: The created ValidationRequestInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "FriendlyName": friendly_name, + "CallDelay": call_delay, + "Extension": extension, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ValidationRequestInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/assistants/AssistantsBase.py b/venv/Lib/site-packages/twilio/rest/assistants/AssistantsBase.py new file mode 100644 index 00000000..a9c9e9af --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/assistants/AssistantsBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.assistants.v1 import V1 + + +class AssistantsBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Assistants Domain + + :returns: Domain for Assistants + """ + super().__init__(twilio, "https://assistants.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Assistants + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/assistants/__init__.py b/venv/Lib/site-packages/twilio/rest/assistants/__init__.py new file mode 100644 index 00000000..889daf9d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/assistants/__init__.py @@ -0,0 +1,56 @@ +from warnings import warn + +from twilio.rest.assistants.AssistantsBase import AssistantsBase +from twilio.rest.assistants.v1.assistant import AssistantList +from twilio.rest.assistants.v1.knowledge import KnowledgeList +from twilio.rest.assistants.v1.policy import PolicyList +from twilio.rest.assistants.v1.session import SessionList +from twilio.rest.assistants.v1.tool import ToolList + + +class Assistants(AssistantsBase): + + @property + def assistants(self) -> AssistantList: + warn( + "assistants is deprecated. Use v1.assistants instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.assistants + + @property + def knowledge(self) -> KnowledgeList: + warn( + "knowledge is deprecated. Use v1.knowledge instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.knowledge + + @property + def policies(self) -> PolicyList: + warn( + "policies is deprecated. Use v1.policies instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.policies + + @property + def sessions(self) -> SessionList: + warn( + "sessions is deprecated. Use v1.sessions instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.sessions + + @property + def tools(self) -> ToolList: + warn( + "tools is deprecated. Use v1.tools instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.tools diff --git a/venv/Lib/site-packages/twilio/rest/assistants/__pycache__/AssistantsBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/assistants/__pycache__/AssistantsBase.cpython-312.pyc new file mode 100644 index 00000000..b2ed9f3e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/assistants/__pycache__/AssistantsBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/assistants/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/assistants/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..3fc55a39 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/assistants/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/assistants/v1/__init__.py new file mode 100644 index 00000000..546ad145 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/assistants/v1/__init__.py @@ -0,0 +1,75 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.assistants.v1.assistant import AssistantList +from twilio.rest.assistants.v1.knowledge import KnowledgeList +from twilio.rest.assistants.v1.policy import PolicyList +from twilio.rest.assistants.v1.session import SessionList +from twilio.rest.assistants.v1.tool import ToolList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Assistants + + :param domain: The Twilio.assistants domain + """ + super().__init__(domain, "v1") + self._assistants: Optional[AssistantList] = None + self._knowledge: Optional[KnowledgeList] = None + self._policies: Optional[PolicyList] = None + self._sessions: Optional[SessionList] = None + self._tools: Optional[ToolList] = None + + @property + def assistants(self) -> AssistantList: + if self._assistants is None: + self._assistants = AssistantList(self) + return self._assistants + + @property + def knowledge(self) -> KnowledgeList: + if self._knowledge is None: + self._knowledge = KnowledgeList(self) + return self._knowledge + + @property + def policies(self) -> PolicyList: + if self._policies is None: + self._policies = PolicyList(self) + return self._policies + + @property + def sessions(self) -> SessionList: + if self._sessions is None: + self._sessions = SessionList(self) + return self._sessions + + @property + def tools(self) -> ToolList: + if self._tools is None: + self._tools = ToolList(self) + return self._tools + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/assistants/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..b20174e4 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/assistants/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/__pycache__/policy.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/assistants/v1/__pycache__/policy.cpython-312.pyc new file mode 100644 index 00000000..7e7537f9 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/assistants/v1/__pycache__/policy.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/__pycache__/tool.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/assistants/v1/__pycache__/tool.cpython-312.pyc new file mode 100644 index 00000000..9c729527 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/assistants/v1/__pycache__/tool.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/__init__.py b/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/__init__.py new file mode 100644 index 00000000..8ab22a5d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/__init__.py @@ -0,0 +1,1036 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.assistants.v1.assistant.assistants_knowledge import ( + AssistantsKnowledgeList, +) +from twilio.rest.assistants.v1.assistant.assistants_tool import AssistantsToolList +from twilio.rest.assistants.v1.assistant.feedback import FeedbackList +from twilio.rest.assistants.v1.assistant.message import MessageList + + +class AssistantInstance(InstanceResource): + + class AssistantsV1ServiceCreateAssistantRequest(object): + """ + :ivar customer_ai: + :ivar name: The name of the assistant. + :ivar owner: The owner/company of the assistant. + :ivar personality_prompt: The personality prompt to be used for assistant. + :ivar segment_credential: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_ai: Optional[AssistantList.AssistantsV1ServiceCustomerAi] = ( + payload.get("customer_ai") + ) + self.name: Optional[str] = payload.get("name") + self.owner: Optional[str] = payload.get("owner") + self.personality_prompt: Optional[str] = payload.get("personality_prompt") + self.segment_credential: Optional[ + AssistantList.AssistantsV1ServiceSegmentCredential + ] = payload.get("segment_credential") + + def to_dict(self): + return { + "customer_ai": ( + self.customer_ai.to_dict() if self.customer_ai is not None else None + ), + "name": self.name, + "owner": self.owner, + "personality_prompt": self.personality_prompt, + "segment_credential": ( + self.segment_credential.to_dict() + if self.segment_credential is not None + else None + ), + } + + class AssistantsV1ServiceCustomerAi(object): + """ + :ivar perception_engine_enabled: True if the perception engine is enabled. + :ivar personalization_engine_enabled: True if the personalization engine is enabled. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.perception_engine_enabled: Optional[bool] = payload.get( + "perception_engine_enabled" + ) + self.personalization_engine_enabled: Optional[bool] = payload.get( + "personalization_engine_enabled" + ) + + def to_dict(self): + return { + "perception_engine_enabled": self.perception_engine_enabled, + "personalization_engine_enabled": self.personalization_engine_enabled, + } + + class AssistantsV1ServiceSegmentCredential(object): + """ + :ivar profile_api_key: The profile API key. + :ivar space_id: The space ID. + :ivar write_key: The write key. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.profile_api_key: Optional[str] = payload.get("profile_api_key") + self.space_id: Optional[str] = payload.get("space_id") + self.write_key: Optional[str] = payload.get("write_key") + + def to_dict(self): + return { + "profile_api_key": self.profile_api_key, + "space_id": self.space_id, + "write_key": self.write_key, + } + + class AssistantsV1ServiceUpdateAssistantRequest(object): + """ + :ivar customer_ai: + :ivar name: The name of the assistant. + :ivar owner: The owner/company of the assistant. + :ivar personality_prompt: The personality prompt to be used for assistant. + :ivar segment_credential: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_ai: Optional[AssistantList.AssistantsV1ServiceCustomerAi] = ( + payload.get("customer_ai") + ) + self.name: Optional[str] = payload.get("name") + self.owner: Optional[str] = payload.get("owner") + self.personality_prompt: Optional[str] = payload.get("personality_prompt") + self.segment_credential: Optional[ + AssistantList.AssistantsV1ServiceSegmentCredential + ] = payload.get("segment_credential") + + def to_dict(self): + return { + "customer_ai": ( + self.customer_ai.to_dict() if self.customer_ai is not None else None + ), + "name": self.name, + "owner": self.owner, + "personality_prompt": self.personality_prompt, + "segment_credential": ( + self.segment_credential.to_dict() + if self.segment_credential is not None + else None + ), + } + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Assistant resource. + :ivar customer_ai: The Personalization and Perception Engine settings. + :ivar id: The Assistant ID. + :ivar model: The default model used by the assistant. + :ivar name: The name of the assistant. + :ivar owner: The owner/company of the assistant. + :ivar url: The url of the assistant resource. + :ivar personality_prompt: The personality prompt to be used for assistant. + :ivar date_created: The date and time in GMT when the Assistant was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Assistant was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar knowledge: The list of knowledge sources associated with the assistant. + :ivar tools: The list of tools associated with the assistant. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], id: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.customer_ai: Optional[Dict[str, object]] = payload.get("customer_ai") + self.id: Optional[str] = payload.get("id") + self.model: Optional[str] = payload.get("model") + self.name: Optional[str] = payload.get("name") + self.owner: Optional[str] = payload.get("owner") + self.url: Optional[str] = payload.get("url") + self.personality_prompt: Optional[str] = payload.get("personality_prompt") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.knowledge: Optional[List[str]] = payload.get("knowledge") + self.tools: Optional[List[str]] = payload.get("tools") + + self._solution = { + "id": id or self.id, + } + self._context: Optional[AssistantContext] = None + + @property + def _proxy(self) -> "AssistantContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AssistantContext for this AssistantInstance + """ + if self._context is None: + self._context = AssistantContext( + self._version, + id=self._solution["id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AssistantInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AssistantInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AssistantInstance": + """ + Fetch the AssistantInstance + + + :returns: The fetched AssistantInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AssistantInstance": + """ + Asynchronous coroutine to fetch the AssistantInstance + + + :returns: The fetched AssistantInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + assistants_v1_service_update_assistant_request: Union[ + AssistantsV1ServiceUpdateAssistantRequest, object + ] = values.unset, + ) -> "AssistantInstance": + """ + Update the AssistantInstance + + :param assistants_v1_service_update_assistant_request: + + :returns: The updated AssistantInstance + """ + return self._proxy.update( + assistants_v1_service_update_assistant_request=assistants_v1_service_update_assistant_request, + ) + + async def update_async( + self, + assistants_v1_service_update_assistant_request: Union[ + AssistantsV1ServiceUpdateAssistantRequest, object + ] = values.unset, + ) -> "AssistantInstance": + """ + Asynchronous coroutine to update the AssistantInstance + + :param assistants_v1_service_update_assistant_request: + + :returns: The updated AssistantInstance + """ + return await self._proxy.update_async( + assistants_v1_service_update_assistant_request=assistants_v1_service_update_assistant_request, + ) + + @property + def assistants_knowledge(self) -> AssistantsKnowledgeList: + """ + Access the assistants_knowledge + """ + return self._proxy.assistants_knowledge + + @property + def assistants_tools(self) -> AssistantsToolList: + """ + Access the assistants_tools + """ + return self._proxy.assistants_tools + + @property + def feedbacks(self) -> FeedbackList: + """ + Access the feedbacks + """ + return self._proxy.feedbacks + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AssistantContext(InstanceContext): + + class AssistantsV1ServiceCreateAssistantRequest(object): + """ + :ivar customer_ai: + :ivar name: The name of the assistant. + :ivar owner: The owner/company of the assistant. + :ivar personality_prompt: The personality prompt to be used for assistant. + :ivar segment_credential: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_ai: Optional[AssistantList.AssistantsV1ServiceCustomerAi] = ( + payload.get("customer_ai") + ) + self.name: Optional[str] = payload.get("name") + self.owner: Optional[str] = payload.get("owner") + self.personality_prompt: Optional[str] = payload.get("personality_prompt") + self.segment_credential: Optional[ + AssistantList.AssistantsV1ServiceSegmentCredential + ] = payload.get("segment_credential") + + def to_dict(self): + return { + "customer_ai": ( + self.customer_ai.to_dict() if self.customer_ai is not None else None + ), + "name": self.name, + "owner": self.owner, + "personality_prompt": self.personality_prompt, + "segment_credential": ( + self.segment_credential.to_dict() + if self.segment_credential is not None + else None + ), + } + + class AssistantsV1ServiceCustomerAi(object): + """ + :ivar perception_engine_enabled: True if the perception engine is enabled. + :ivar personalization_engine_enabled: True if the personalization engine is enabled. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.perception_engine_enabled: Optional[bool] = payload.get( + "perception_engine_enabled" + ) + self.personalization_engine_enabled: Optional[bool] = payload.get( + "personalization_engine_enabled" + ) + + def to_dict(self): + return { + "perception_engine_enabled": self.perception_engine_enabled, + "personalization_engine_enabled": self.personalization_engine_enabled, + } + + class AssistantsV1ServiceSegmentCredential(object): + """ + :ivar profile_api_key: The profile API key. + :ivar space_id: The space ID. + :ivar write_key: The write key. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.profile_api_key: Optional[str] = payload.get("profile_api_key") + self.space_id: Optional[str] = payload.get("space_id") + self.write_key: Optional[str] = payload.get("write_key") + + def to_dict(self): + return { + "profile_api_key": self.profile_api_key, + "space_id": self.space_id, + "write_key": self.write_key, + } + + class AssistantsV1ServiceUpdateAssistantRequest(object): + """ + :ivar customer_ai: + :ivar name: The name of the assistant. + :ivar owner: The owner/company of the assistant. + :ivar personality_prompt: The personality prompt to be used for assistant. + :ivar segment_credential: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_ai: Optional[AssistantList.AssistantsV1ServiceCustomerAi] = ( + payload.get("customer_ai") + ) + self.name: Optional[str] = payload.get("name") + self.owner: Optional[str] = payload.get("owner") + self.personality_prompt: Optional[str] = payload.get("personality_prompt") + self.segment_credential: Optional[ + AssistantList.AssistantsV1ServiceSegmentCredential + ] = payload.get("segment_credential") + + def to_dict(self): + return { + "customer_ai": ( + self.customer_ai.to_dict() if self.customer_ai is not None else None + ), + "name": self.name, + "owner": self.owner, + "personality_prompt": self.personality_prompt, + "segment_credential": ( + self.segment_credential.to_dict() + if self.segment_credential is not None + else None + ), + } + + def __init__(self, version: Version, id: str): + """ + Initialize the AssistantContext + + :param version: Version that contains the resource + :param id: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Assistants/{id}".format(**self._solution) + + self._assistants_knowledge: Optional[AssistantsKnowledgeList] = None + self._assistants_tools: Optional[AssistantsToolList] = None + self._feedbacks: Optional[FeedbackList] = None + self._messages: Optional[MessageList] = None + + def delete(self) -> bool: + """ + Deletes the AssistantInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AssistantInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AssistantInstance: + """ + Fetch the AssistantInstance + + + :returns: The fetched AssistantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AssistantInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_async(self) -> AssistantInstance: + """ + Asynchronous coroutine to fetch the AssistantInstance + + + :returns: The fetched AssistantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AssistantInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def update( + self, + assistants_v1_service_update_assistant_request: Union[ + AssistantsV1ServiceUpdateAssistantRequest, object + ] = values.unset, + ) -> AssistantInstance: + """ + Update the AssistantInstance + + :param assistants_v1_service_update_assistant_request: + + :returns: The updated AssistantInstance + """ + data = assistants_v1_service_update_assistant_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + return AssistantInstance(self._version, payload, id=self._solution["id"]) + + async def update_async( + self, + assistants_v1_service_update_assistant_request: Union[ + AssistantsV1ServiceUpdateAssistantRequest, object + ] = values.unset, + ) -> AssistantInstance: + """ + Asynchronous coroutine to update the AssistantInstance + + :param assistants_v1_service_update_assistant_request: + + :returns: The updated AssistantInstance + """ + data = assistants_v1_service_update_assistant_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + return AssistantInstance(self._version, payload, id=self._solution["id"]) + + @property + def assistants_knowledge(self) -> AssistantsKnowledgeList: + """ + Access the assistants_knowledge + """ + if self._assistants_knowledge is None: + self._assistants_knowledge = AssistantsKnowledgeList( + self._version, + self._solution["id"], + ) + return self._assistants_knowledge + + @property + def assistants_tools(self) -> AssistantsToolList: + """ + Access the assistants_tools + """ + if self._assistants_tools is None: + self._assistants_tools = AssistantsToolList( + self._version, + self._solution["id"], + ) + return self._assistants_tools + + @property + def feedbacks(self) -> FeedbackList: + """ + Access the feedbacks + """ + if self._feedbacks is None: + self._feedbacks = FeedbackList( + self._version, + self._solution["id"], + ) + return self._feedbacks + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + if self._messages is None: + self._messages = MessageList( + self._version, + self._solution["id"], + ) + return self._messages + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AssistantPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AssistantInstance: + """ + Build an instance of AssistantInstance + + :param payload: Payload response from the API + """ + return AssistantInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AssistantList(ListResource): + + class AssistantsV1ServiceCreateAssistantRequest(object): + """ + :ivar customer_ai: + :ivar name: The name of the assistant. + :ivar owner: The owner/company of the assistant. + :ivar personality_prompt: The personality prompt to be used for assistant. + :ivar segment_credential: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_ai: Optional[AssistantList.AssistantsV1ServiceCustomerAi] = ( + payload.get("customer_ai") + ) + self.name: Optional[str] = payload.get("name") + self.owner: Optional[str] = payload.get("owner") + self.personality_prompt: Optional[str] = payload.get("personality_prompt") + self.segment_credential: Optional[ + AssistantList.AssistantsV1ServiceSegmentCredential + ] = payload.get("segment_credential") + + def to_dict(self): + return { + "customer_ai": ( + self.customer_ai.to_dict() if self.customer_ai is not None else None + ), + "name": self.name, + "owner": self.owner, + "personality_prompt": self.personality_prompt, + "segment_credential": ( + self.segment_credential.to_dict() + if self.segment_credential is not None + else None + ), + } + + class AssistantsV1ServiceCustomerAi(object): + """ + :ivar perception_engine_enabled: True if the perception engine is enabled. + :ivar personalization_engine_enabled: True if the personalization engine is enabled. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.perception_engine_enabled: Optional[bool] = payload.get( + "perception_engine_enabled" + ) + self.personalization_engine_enabled: Optional[bool] = payload.get( + "personalization_engine_enabled" + ) + + def to_dict(self): + return { + "perception_engine_enabled": self.perception_engine_enabled, + "personalization_engine_enabled": self.personalization_engine_enabled, + } + + class AssistantsV1ServiceSegmentCredential(object): + """ + :ivar profile_api_key: The profile API key. + :ivar space_id: The space ID. + :ivar write_key: The write key. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.profile_api_key: Optional[str] = payload.get("profile_api_key") + self.space_id: Optional[str] = payload.get("space_id") + self.write_key: Optional[str] = payload.get("write_key") + + def to_dict(self): + return { + "profile_api_key": self.profile_api_key, + "space_id": self.space_id, + "write_key": self.write_key, + } + + class AssistantsV1ServiceUpdateAssistantRequest(object): + """ + :ivar customer_ai: + :ivar name: The name of the assistant. + :ivar owner: The owner/company of the assistant. + :ivar personality_prompt: The personality prompt to be used for assistant. + :ivar segment_credential: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_ai: Optional[AssistantList.AssistantsV1ServiceCustomerAi] = ( + payload.get("customer_ai") + ) + self.name: Optional[str] = payload.get("name") + self.owner: Optional[str] = payload.get("owner") + self.personality_prompt: Optional[str] = payload.get("personality_prompt") + self.segment_credential: Optional[ + AssistantList.AssistantsV1ServiceSegmentCredential + ] = payload.get("segment_credential") + + def to_dict(self): + return { + "customer_ai": ( + self.customer_ai.to_dict() if self.customer_ai is not None else None + ), + "name": self.name, + "owner": self.owner, + "personality_prompt": self.personality_prompt, + "segment_credential": ( + self.segment_credential.to_dict() + if self.segment_credential is not None + else None + ), + } + + def __init__(self, version: Version): + """ + Initialize the AssistantList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Assistants" + + def create( + self, + assistants_v1_service_create_assistant_request: AssistantsV1ServiceCreateAssistantRequest, + ) -> AssistantInstance: + """ + Create the AssistantInstance + + :param assistants_v1_service_create_assistant_request: + + :returns: The created AssistantInstance + """ + data = assistants_v1_service_create_assistant_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AssistantInstance(self._version, payload) + + async def create_async( + self, + assistants_v1_service_create_assistant_request: AssistantsV1ServiceCreateAssistantRequest, + ) -> AssistantInstance: + """ + Asynchronously create the AssistantInstance + + :param assistants_v1_service_create_assistant_request: + + :returns: The created AssistantInstance + """ + data = assistants_v1_service_create_assistant_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AssistantInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AssistantInstance]: + """ + Streams AssistantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AssistantInstance]: + """ + Asynchronously streams AssistantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssistantInstance]: + """ + Lists AssistantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssistantInstance]: + """ + Asynchronously lists AssistantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssistantPage: + """ + Retrieve a single page of AssistantInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssistantInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssistantPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssistantPage: + """ + Asynchronously retrieve a single page of AssistantInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssistantInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssistantPage(self._version, response) + + def get_page(self, target_url: str) -> AssistantPage: + """ + Retrieve a specific page of AssistantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssistantInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AssistantPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AssistantPage: + """ + Asynchronously retrieve a specific page of AssistantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssistantInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AssistantPage(self._version, response) + + def get(self, id: str) -> AssistantContext: + """ + Constructs a AssistantContext + + :param id: + """ + return AssistantContext(self._version, id=id) + + def __call__(self, id: str) -> AssistantContext: + """ + Constructs a AssistantContext + + :param id: + """ + return AssistantContext(self._version, id=id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..491c5085 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/__pycache__/assistants_knowledge.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/__pycache__/assistants_knowledge.cpython-312.pyc new file mode 100644 index 00000000..9cb85e67 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/__pycache__/assistants_knowledge.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/__pycache__/assistants_tool.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/__pycache__/assistants_tool.cpython-312.pyc new file mode 100644 index 00000000..2fd2f5f2 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/__pycache__/assistants_tool.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/__pycache__/feedback.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/__pycache__/feedback.cpython-312.pyc new file mode 100644 index 00000000..12832c5f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/__pycache__/feedback.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/__pycache__/message.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/__pycache__/message.cpython-312.pyc new file mode 100644 index 00000000..93ef9268 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/__pycache__/message.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/assistants_knowledge.py b/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/assistants_knowledge.py new file mode 100644 index 00000000..681d7178 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/assistants_knowledge.py @@ -0,0 +1,520 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AssistantsKnowledgeInstance(InstanceResource): + """ + :ivar description: The type of knowledge source. + :ivar id: The description of knowledge. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Knowledge resource. + :ivar knowledge_source_details: The details of the knowledge source based on the type. + :ivar name: The name of the knowledge source. + :ivar status: The status of processing the knowledge source ('QUEUED', 'PROCESSING', 'COMPLETED', 'FAILED') + :ivar type: The type of knowledge source ('Web', 'Database', 'Text', 'File') + :ivar url: The url of the knowledge resource. + :ivar embedding_model: The embedding model to be used for the knowledge source. + :ivar date_created: The date and time in GMT when the Knowledge was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Knowledge was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + assistant_id: str, + id: Optional[str] = None, + ): + super().__init__(version) + + self.description: Optional[str] = payload.get("description") + self.id: Optional[str] = payload.get("id") + self.account_sid: Optional[str] = payload.get("account_sid") + self.knowledge_source_details: Optional[Dict[str, object]] = payload.get( + "knowledge_source_details" + ) + self.name: Optional[str] = payload.get("name") + self.status: Optional[str] = payload.get("status") + self.type: Optional[str] = payload.get("type") + self.url: Optional[str] = payload.get("url") + self.embedding_model: Optional[str] = payload.get("embedding_model") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "assistant_id": assistant_id, + "id": id or self.id, + } + self._context: Optional[AssistantsKnowledgeContext] = None + + @property + def _proxy(self) -> "AssistantsKnowledgeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AssistantsKnowledgeContext for this AssistantsKnowledgeInstance + """ + if self._context is None: + self._context = AssistantsKnowledgeContext( + self._version, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + return self._context + + def create(self) -> "AssistantsKnowledgeInstance": + """ + Create the AssistantsKnowledgeInstance + + + :returns: The created AssistantsKnowledgeInstance + """ + return self._proxy.create() + + async def create_async(self) -> "AssistantsKnowledgeInstance": + """ + Asynchronous coroutine to create the AssistantsKnowledgeInstance + + + :returns: The created AssistantsKnowledgeInstance + """ + return await self._proxy.create_async() + + def delete(self) -> bool: + """ + Deletes the AssistantsKnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AssistantsKnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AssistantsKnowledgeContext(InstanceContext): + + def __init__(self, version: Version, assistant_id: str, id: str): + """ + Initialize the AssistantsKnowledgeContext + + :param version: Version that contains the resource + :param assistant_id: The assistant ID. + :param id: The knowledge ID. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "assistant_id": assistant_id, + "id": id, + } + self._uri = "/Assistants/{assistant_id}/Knowledge/{id}".format(**self._solution) + + def create(self) -> AssistantsKnowledgeInstance: + """ + Create the AssistantsKnowledgeInstance + + + :returns: The created AssistantsKnowledgeInstance + """ + data = values.of({}) + + payload = self._version.create(method="POST", uri=self._uri, data=data) + + return AssistantsKnowledgeInstance( + self._version, + payload, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + + async def create_async(self) -> AssistantsKnowledgeInstance: + """ + Asynchronous coroutine to create the AssistantsKnowledgeInstance + + + :returns: The created AssistantsKnowledgeInstance + """ + data = values.of({}) + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data + ) + + return AssistantsKnowledgeInstance( + self._version, + payload, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + + def delete(self) -> bool: + """ + Deletes the AssistantsKnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AssistantsKnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AssistantsKnowledgePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AssistantsKnowledgeInstance: + """ + Build an instance of AssistantsKnowledgeInstance + + :param payload: Payload response from the API + """ + return AssistantsKnowledgeInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AssistantsKnowledgeList(ListResource): + + def __init__(self, version: Version, assistant_id: str): + """ + Initialize the AssistantsKnowledgeList + + :param version: Version that contains the resource + :param assistant_id: The assistant ID. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "assistant_id": assistant_id, + } + self._uri = "/Assistants/{assistant_id}/Knowledge".format(**self._solution) + + def create(self) -> AssistantsKnowledgeInstance: + """ + Create the AssistantsKnowledgeInstance + + + :returns: The created AssistantsKnowledgeInstance + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + payload = self._version.create(method="POST", uri=self._uri, headers=headers) + + return AssistantsKnowledgeInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + + async def create_async(self) -> AssistantsKnowledgeInstance: + """ + Asynchronously create the AssistantsKnowledgeInstance + + + :returns: The created AssistantsKnowledgeInstance + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + payload = await self._version.create_async( + method="POST", uri=self._uri, headers=headers + ) + + return AssistantsKnowledgeInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AssistantsKnowledgeInstance]: + """ + Streams AssistantsKnowledgeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AssistantsKnowledgeInstance]: + """ + Asynchronously streams AssistantsKnowledgeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssistantsKnowledgeInstance]: + """ + Lists AssistantsKnowledgeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssistantsKnowledgeInstance]: + """ + Asynchronously lists AssistantsKnowledgeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssistantsKnowledgePage: + """ + Retrieve a single page of AssistantsKnowledgeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssistantsKnowledgeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssistantsKnowledgePage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssistantsKnowledgePage: + """ + Asynchronously retrieve a single page of AssistantsKnowledgeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssistantsKnowledgeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssistantsKnowledgePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AssistantsKnowledgePage: + """ + Retrieve a specific page of AssistantsKnowledgeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssistantsKnowledgeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AssistantsKnowledgePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AssistantsKnowledgePage: + """ + Asynchronously retrieve a specific page of AssistantsKnowledgeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssistantsKnowledgeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AssistantsKnowledgePage(self._version, response, self._solution) + + def get(self, id: str) -> AssistantsKnowledgeContext: + """ + Constructs a AssistantsKnowledgeContext + + :param id: The knowledge ID. + """ + return AssistantsKnowledgeContext( + self._version, assistant_id=self._solution["assistant_id"], id=id + ) + + def __call__(self, id: str) -> AssistantsKnowledgeContext: + """ + Constructs a AssistantsKnowledgeContext + + :param id: The knowledge ID. + """ + return AssistantsKnowledgeContext( + self._version, assistant_id=self._solution["assistant_id"], id=id + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/assistants_tool.py b/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/assistants_tool.py new file mode 100644 index 00000000..ed02410d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/assistants_tool.py @@ -0,0 +1,518 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AssistantsToolInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Tool resource. + :ivar description: The description of the tool. + :ivar enabled: True if the tool is enabled. + :ivar id: The tool ID. + :ivar meta: The metadata related to method, url, input_schema to used with the Tool. + :ivar name: The name of the tool. + :ivar requires_auth: The authentication requirement for the tool. + :ivar type: The type of the tool. ('WEBHOOK') + :ivar url: The url of the tool resource. + :ivar date_created: The date and time in GMT when the Tool was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Tool was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + assistant_id: str, + id: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.description: Optional[str] = payload.get("description") + self.enabled: Optional[bool] = payload.get("enabled") + self.id: Optional[str] = payload.get("id") + self.meta: Optional[Dict[str, object]] = payload.get("meta") + self.name: Optional[str] = payload.get("name") + self.requires_auth: Optional[bool] = payload.get("requires_auth") + self.type: Optional[str] = payload.get("type") + self.url: Optional[str] = payload.get("url") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "assistant_id": assistant_id, + "id": id or self.id, + } + self._context: Optional[AssistantsToolContext] = None + + @property + def _proxy(self) -> "AssistantsToolContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AssistantsToolContext for this AssistantsToolInstance + """ + if self._context is None: + self._context = AssistantsToolContext( + self._version, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + return self._context + + def create(self) -> "AssistantsToolInstance": + """ + Create the AssistantsToolInstance + + + :returns: The created AssistantsToolInstance + """ + return self._proxy.create() + + async def create_async(self) -> "AssistantsToolInstance": + """ + Asynchronous coroutine to create the AssistantsToolInstance + + + :returns: The created AssistantsToolInstance + """ + return await self._proxy.create_async() + + def delete(self) -> bool: + """ + Deletes the AssistantsToolInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AssistantsToolInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AssistantsToolContext(InstanceContext): + + def __init__(self, version: Version, assistant_id: str, id: str): + """ + Initialize the AssistantsToolContext + + :param version: Version that contains the resource + :param assistant_id: The assistant ID. + :param id: The tool ID. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "assistant_id": assistant_id, + "id": id, + } + self._uri = "/Assistants/{assistant_id}/Tools/{id}".format(**self._solution) + + def create(self) -> AssistantsToolInstance: + """ + Create the AssistantsToolInstance + + + :returns: The created AssistantsToolInstance + """ + data = values.of({}) + + payload = self._version.create(method="POST", uri=self._uri, data=data) + + return AssistantsToolInstance( + self._version, + payload, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + + async def create_async(self) -> AssistantsToolInstance: + """ + Asynchronous coroutine to create the AssistantsToolInstance + + + :returns: The created AssistantsToolInstance + """ + data = values.of({}) + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data + ) + + return AssistantsToolInstance( + self._version, + payload, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + + def delete(self) -> bool: + """ + Deletes the AssistantsToolInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AssistantsToolInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AssistantsToolPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AssistantsToolInstance: + """ + Build an instance of AssistantsToolInstance + + :param payload: Payload response from the API + """ + return AssistantsToolInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AssistantsToolList(ListResource): + + def __init__(self, version: Version, assistant_id: str): + """ + Initialize the AssistantsToolList + + :param version: Version that contains the resource + :param assistant_id: The assistant ID. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "assistant_id": assistant_id, + } + self._uri = "/Assistants/{assistant_id}/Tools".format(**self._solution) + + def create(self) -> AssistantsToolInstance: + """ + Create the AssistantsToolInstance + + + :returns: The created AssistantsToolInstance + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + payload = self._version.create(method="POST", uri=self._uri, headers=headers) + + return AssistantsToolInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + + async def create_async(self) -> AssistantsToolInstance: + """ + Asynchronously create the AssistantsToolInstance + + + :returns: The created AssistantsToolInstance + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + payload = await self._version.create_async( + method="POST", uri=self._uri, headers=headers + ) + + return AssistantsToolInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AssistantsToolInstance]: + """ + Streams AssistantsToolInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AssistantsToolInstance]: + """ + Asynchronously streams AssistantsToolInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssistantsToolInstance]: + """ + Lists AssistantsToolInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssistantsToolInstance]: + """ + Asynchronously lists AssistantsToolInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssistantsToolPage: + """ + Retrieve a single page of AssistantsToolInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssistantsToolInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssistantsToolPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssistantsToolPage: + """ + Asynchronously retrieve a single page of AssistantsToolInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssistantsToolInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssistantsToolPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AssistantsToolPage: + """ + Retrieve a specific page of AssistantsToolInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssistantsToolInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AssistantsToolPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AssistantsToolPage: + """ + Asynchronously retrieve a specific page of AssistantsToolInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssistantsToolInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AssistantsToolPage(self._version, response, self._solution) + + def get(self, id: str) -> AssistantsToolContext: + """ + Constructs a AssistantsToolContext + + :param id: The tool ID. + """ + return AssistantsToolContext( + self._version, assistant_id=self._solution["assistant_id"], id=id + ) + + def __call__(self, id: str) -> AssistantsToolContext: + """ + Constructs a AssistantsToolContext + + :param id: The tool ID. + """ + return AssistantsToolContext( + self._version, assistant_id=self._solution["assistant_id"], id=id + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/feedback.py b/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/feedback.py new file mode 100644 index 00000000..77c6d405 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/feedback.py @@ -0,0 +1,404 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class FeedbackInstance(InstanceResource): + + class AssistantsV1ServiceCreateFeedbackRequest(object): + """ + :ivar message_id: The message ID. + :ivar score: The score to be given(0-1). + :ivar session_id: The Session ID. + :ivar text: The text to be given as feedback. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.message_id: Optional[str] = payload.get("message_id") + self.score: Optional[float] = payload.get("score") + self.session_id: Optional[str] = payload.get("session_id") + self.text: Optional[str] = payload.get("text") + + def to_dict(self): + return { + "message_id": self.message_id, + "score": self.score, + "session_id": self.session_id, + "text": self.text, + } + + """ + :ivar assistant_id: The Assistant ID. + :ivar id: The Feedback ID. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Feedback. + :ivar user_sid: The SID of the User created the Feedback. + :ivar message_id: The Message ID. + :ivar score: The Score to provide as Feedback (0-1) + :ivar session_id: The Session ID. + :ivar text: The text to be given as feedback. + :ivar date_created: The date and time in GMT when the Feedback was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Feedback was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], id: str): + super().__init__(version) + + self.assistant_id: Optional[str] = payload.get("assistant_id") + self.id: Optional[str] = payload.get("id") + self.account_sid: Optional[str] = payload.get("account_sid") + self.user_sid: Optional[str] = payload.get("user_sid") + self.message_id: Optional[str] = payload.get("message_id") + self.score: Optional[float] = payload.get("score") + self.session_id: Optional[str] = payload.get("session_id") + self.text: Optional[str] = payload.get("text") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "id": id, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FeedbackPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> FeedbackInstance: + """ + Build an instance of FeedbackInstance + + :param payload: Payload response from the API + """ + return FeedbackInstance(self._version, payload, id=self._solution["id"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class FeedbackList(ListResource): + + class AssistantsV1ServiceCreateFeedbackRequest(object): + """ + :ivar message_id: The message ID. + :ivar score: The score to be given(0-1). + :ivar session_id: The Session ID. + :ivar text: The text to be given as feedback. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.message_id: Optional[str] = payload.get("message_id") + self.score: Optional[float] = payload.get("score") + self.session_id: Optional[str] = payload.get("session_id") + self.text: Optional[str] = payload.get("text") + + def to_dict(self): + return { + "message_id": self.message_id, + "score": self.score, + "session_id": self.session_id, + "text": self.text, + } + + def __init__(self, version: Version, id: str): + """ + Initialize the FeedbackList + + :param version: Version that contains the resource + :param id: The assistant ID. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Assistants/{id}/Feedbacks".format(**self._solution) + + def create( + self, + assistants_v1_service_create_feedback_request: AssistantsV1ServiceCreateFeedbackRequest, + ) -> FeedbackInstance: + """ + Create the FeedbackInstance + + :param assistants_v1_service_create_feedback_request: + + :returns: The created FeedbackInstance + """ + data = assistants_v1_service_create_feedback_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FeedbackInstance(self._version, payload, id=self._solution["id"]) + + async def create_async( + self, + assistants_v1_service_create_feedback_request: AssistantsV1ServiceCreateFeedbackRequest, + ) -> FeedbackInstance: + """ + Asynchronously create the FeedbackInstance + + :param assistants_v1_service_create_feedback_request: + + :returns: The created FeedbackInstance + """ + data = assistants_v1_service_create_feedback_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FeedbackInstance(self._version, payload, id=self._solution["id"]) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FeedbackInstance]: + """ + Streams FeedbackInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FeedbackInstance]: + """ + Asynchronously streams FeedbackInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FeedbackInstance]: + """ + Lists FeedbackInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FeedbackInstance]: + """ + Asynchronously lists FeedbackInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FeedbackPage: + """ + Retrieve a single page of FeedbackInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FeedbackInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FeedbackPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FeedbackPage: + """ + Asynchronously retrieve a single page of FeedbackInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FeedbackInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FeedbackPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> FeedbackPage: + """ + Retrieve a specific page of FeedbackInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FeedbackInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return FeedbackPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> FeedbackPage: + """ + Asynchronously retrieve a specific page of FeedbackInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FeedbackInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return FeedbackPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/message.py b/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/message.py new file mode 100644 index 00000000..11d73776 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/assistants/v1/assistant/message.py @@ -0,0 +1,186 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class MessageInstance(InstanceResource): + + class AssistantsV1ServiceAssistantSendMessageRequest(object): + """ + :ivar identity: The unique identity of user for the session. + :ivar session_id: The unique name for the session. + :ivar body: The query to ask the assistant. + :ivar webhook: The webhook url to call after the assistant has generated a response or report an error. + :ivar mode: one of the modes 'chat', 'email' or 'voice' + """ + + def __init__(self, payload: Dict[str, Any]): + + self.identity: Optional[str] = payload.get("identity") + self.session_id: Optional[str] = payload.get("session_id") + self.body: Optional[str] = payload.get("body") + self.webhook: Optional[str] = payload.get("webhook") + self.mode: Optional[str] = payload.get("mode") + + def to_dict(self): + return { + "identity": self.identity, + "session_id": self.session_id, + "body": self.body, + "webhook": self.webhook, + "mode": self.mode, + } + + """ + :ivar status: success or failure based on whether the request successfully generated a response. + :ivar flagged: If successful, this property will denote whether the response was flagged or not. + :ivar aborted: This property will denote whether the request was aborted or not. + :ivar session_id: The unique name for the session. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that sent the Message. + :ivar body: If successful, the body of the generated response + :ivar error: The error message if generation was not successful + """ + + def __init__(self, version: Version, payload: Dict[str, Any], id: str): + super().__init__(version) + + self.status: Optional[str] = payload.get("status") + self.flagged: Optional[bool] = payload.get("flagged") + self.aborted: Optional[bool] = payload.get("aborted") + self.session_id: Optional[str] = payload.get("session_id") + self.account_sid: Optional[str] = payload.get("account_sid") + self.body: Optional[str] = payload.get("body") + self.error: Optional[str] = payload.get("error") + + self._solution = { + "id": id, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MessageList(ListResource): + + class AssistantsV1ServiceAssistantSendMessageRequest(object): + """ + :ivar identity: The unique identity of user for the session. + :ivar session_id: The unique name for the session. + :ivar body: The query to ask the assistant. + :ivar webhook: The webhook url to call after the assistant has generated a response or report an error. + :ivar mode: one of the modes 'chat', 'email' or 'voice' + """ + + def __init__(self, payload: Dict[str, Any]): + + self.identity: Optional[str] = payload.get("identity") + self.session_id: Optional[str] = payload.get("session_id") + self.body: Optional[str] = payload.get("body") + self.webhook: Optional[str] = payload.get("webhook") + self.mode: Optional[str] = payload.get("mode") + + def to_dict(self): + return { + "identity": self.identity, + "session_id": self.session_id, + "body": self.body, + "webhook": self.webhook, + "mode": self.mode, + } + + def __init__(self, version: Version, id: str): + """ + Initialize the MessageList + + :param version: Version that contains the resource + :param id: the Assistant ID. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Assistants/{id}/Messages".format(**self._solution) + + def create( + self, + assistants_v1_service_assistant_send_message_request: AssistantsV1ServiceAssistantSendMessageRequest, + ) -> MessageInstance: + """ + Create the MessageInstance + + :param assistants_v1_service_assistant_send_message_request: + + :returns: The created MessageInstance + """ + data = assistants_v1_service_assistant_send_message_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance(self._version, payload, id=self._solution["id"]) + + async def create_async( + self, + assistants_v1_service_assistant_send_message_request: AssistantsV1ServiceAssistantSendMessageRequest, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param assistants_v1_service_assistant_send_message_request: + + :returns: The created MessageInstance + """ + data = assistants_v1_service_assistant_send_message_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance(self._version, payload, id=self._solution["id"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/knowledge/__init__.py b/venv/Lib/site-packages/twilio/rest/assistants/v1/knowledge/__init__.py new file mode 100644 index 00000000..7d616f86 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/assistants/v1/knowledge/__init__.py @@ -0,0 +1,962 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.assistants.v1.knowledge.chunk import ChunkList +from twilio.rest.assistants.v1.knowledge.knowledge_status import KnowledgeStatusList + + +class KnowledgeInstance(InstanceResource): + + class AssistantsV1ServiceCreateKnowledgeRequest(object): + """ + :ivar assistant_id: The Assistant ID. + :ivar description: The description of the knowledge source. + :ivar knowledge_source_details: The details of the knowledge source based on the type. + :ivar name: The name of the tool. + :ivar policy: + :ivar type: The type of the knowledge source. + :ivar embedding_model: The embedding model to be used for the knowledge source. It's required for 'Database' type but disallowed for other types. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.assistant_id: Optional[str] = payload.get("assistant_id") + self.description: Optional[str] = payload.get("description") + self.knowledge_source_details: Optional[Dict[str, object]] = payload.get( + "knowledge_source_details" + ) + self.name: Optional[str] = payload.get("name") + self.policy: Optional[ + KnowledgeList.AssistantsV1ServiceCreatePolicyRequest + ] = payload.get("policy") + self.type: Optional[str] = payload.get("type") + self.embedding_model: Optional[str] = payload.get("embedding_model") + + def to_dict(self): + return { + "assistant_id": self.assistant_id, + "description": self.description, + "knowledge_source_details": self.knowledge_source_details, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + "embedding_model": self.embedding_model, + } + + class AssistantsV1ServiceCreatePolicyRequest(object): + """ + :ivar description: The description of the policy. + :ivar id: The Policy ID. + :ivar name: The name of the policy. + :ivar policy_details: + :ivar type: The description of the policy. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.description: Optional[str] = payload.get("description") + self.id: Optional[str] = payload.get("id") + self.name: Optional[str] = payload.get("name") + self.policy_details: Optional[Dict[str, object]] = payload.get( + "policy_details" + ) + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "description": self.description, + "id": self.id, + "name": self.name, + "policy_details": self.policy_details, + "type": self.type, + } + + class AssistantsV1ServiceUpdateKnowledgeRequest(object): + """ + :ivar description: The description of the knowledge source. + :ivar knowledge_source_details: The details of the knowledge source based on the type. + :ivar name: The name of the knowledge source. + :ivar policy: + :ivar type: The description of the knowledge source. + :ivar embedding_model: The embedding model to be used for the knowledge source. It's only applicable to 'Database' type. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.description: Optional[str] = payload.get("description") + self.knowledge_source_details: Optional[Dict[str, object]] = payload.get( + "knowledge_source_details" + ) + self.name: Optional[str] = payload.get("name") + self.policy: Optional[ + KnowledgeList.AssistantsV1ServiceCreatePolicyRequest + ] = payload.get("policy") + self.type: Optional[str] = payload.get("type") + self.embedding_model: Optional[str] = payload.get("embedding_model") + + def to_dict(self): + return { + "description": self.description, + "knowledge_source_details": self.knowledge_source_details, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + "embedding_model": self.embedding_model, + } + + """ + :ivar description: The type of knowledge source. + :ivar id: The description of knowledge. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Knowledge resource. + :ivar knowledge_source_details: The details of the knowledge source based on the type. + :ivar name: The name of the knowledge source. + :ivar status: The status of processing the knowledge source ('QUEUED', 'PROCESSING', 'COMPLETED', 'FAILED') + :ivar type: The type of knowledge source ('Web', 'Database', 'Text', 'File') + :ivar url: The url of the knowledge resource. + :ivar embedding_model: The embedding model to be used for the knowledge source. + :ivar date_created: The date and time in GMT when the Knowledge was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Knowledge was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], id: Optional[str] = None + ): + super().__init__(version) + + self.description: Optional[str] = payload.get("description") + self.id: Optional[str] = payload.get("id") + self.account_sid: Optional[str] = payload.get("account_sid") + self.knowledge_source_details: Optional[Dict[str, object]] = payload.get( + "knowledge_source_details" + ) + self.name: Optional[str] = payload.get("name") + self.status: Optional[str] = payload.get("status") + self.type: Optional[str] = payload.get("type") + self.url: Optional[str] = payload.get("url") + self.embedding_model: Optional[str] = payload.get("embedding_model") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "id": id or self.id, + } + self._context: Optional[KnowledgeContext] = None + + @property + def _proxy(self) -> "KnowledgeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: KnowledgeContext for this KnowledgeInstance + """ + if self._context is None: + self._context = KnowledgeContext( + self._version, + id=self._solution["id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the KnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the KnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "KnowledgeInstance": + """ + Fetch the KnowledgeInstance + + + :returns: The fetched KnowledgeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "KnowledgeInstance": + """ + Asynchronous coroutine to fetch the KnowledgeInstance + + + :returns: The fetched KnowledgeInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + assistants_v1_service_update_knowledge_request: Union[ + AssistantsV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> "KnowledgeInstance": + """ + Update the KnowledgeInstance + + :param assistants_v1_service_update_knowledge_request: + + :returns: The updated KnowledgeInstance + """ + return self._proxy.update( + assistants_v1_service_update_knowledge_request=assistants_v1_service_update_knowledge_request, + ) + + async def update_async( + self, + assistants_v1_service_update_knowledge_request: Union[ + AssistantsV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> "KnowledgeInstance": + """ + Asynchronous coroutine to update the KnowledgeInstance + + :param assistants_v1_service_update_knowledge_request: + + :returns: The updated KnowledgeInstance + """ + return await self._proxy.update_async( + assistants_v1_service_update_knowledge_request=assistants_v1_service_update_knowledge_request, + ) + + @property + def chunks(self) -> ChunkList: + """ + Access the chunks + """ + return self._proxy.chunks + + @property + def knowledge_status(self) -> KnowledgeStatusList: + """ + Access the knowledge_status + """ + return self._proxy.knowledge_status + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class KnowledgeContext(InstanceContext): + + class AssistantsV1ServiceCreateKnowledgeRequest(object): + """ + :ivar assistant_id: The Assistant ID. + :ivar description: The description of the knowledge source. + :ivar knowledge_source_details: The details of the knowledge source based on the type. + :ivar name: The name of the tool. + :ivar policy: + :ivar type: The type of the knowledge source. + :ivar embedding_model: The embedding model to be used for the knowledge source. It's required for 'Database' type but disallowed for other types. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.assistant_id: Optional[str] = payload.get("assistant_id") + self.description: Optional[str] = payload.get("description") + self.knowledge_source_details: Optional[Dict[str, object]] = payload.get( + "knowledge_source_details" + ) + self.name: Optional[str] = payload.get("name") + self.policy: Optional[ + KnowledgeList.AssistantsV1ServiceCreatePolicyRequest + ] = payload.get("policy") + self.type: Optional[str] = payload.get("type") + self.embedding_model: Optional[str] = payload.get("embedding_model") + + def to_dict(self): + return { + "assistant_id": self.assistant_id, + "description": self.description, + "knowledge_source_details": self.knowledge_source_details, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + "embedding_model": self.embedding_model, + } + + class AssistantsV1ServiceCreatePolicyRequest(object): + """ + :ivar description: The description of the policy. + :ivar id: The Policy ID. + :ivar name: The name of the policy. + :ivar policy_details: + :ivar type: The description of the policy. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.description: Optional[str] = payload.get("description") + self.id: Optional[str] = payload.get("id") + self.name: Optional[str] = payload.get("name") + self.policy_details: Optional[Dict[str, object]] = payload.get( + "policy_details" + ) + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "description": self.description, + "id": self.id, + "name": self.name, + "policy_details": self.policy_details, + "type": self.type, + } + + class AssistantsV1ServiceUpdateKnowledgeRequest(object): + """ + :ivar description: The description of the knowledge source. + :ivar knowledge_source_details: The details of the knowledge source based on the type. + :ivar name: The name of the knowledge source. + :ivar policy: + :ivar type: The description of the knowledge source. + :ivar embedding_model: The embedding model to be used for the knowledge source. It's only applicable to 'Database' type. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.description: Optional[str] = payload.get("description") + self.knowledge_source_details: Optional[Dict[str, object]] = payload.get( + "knowledge_source_details" + ) + self.name: Optional[str] = payload.get("name") + self.policy: Optional[ + KnowledgeList.AssistantsV1ServiceCreatePolicyRequest + ] = payload.get("policy") + self.type: Optional[str] = payload.get("type") + self.embedding_model: Optional[str] = payload.get("embedding_model") + + def to_dict(self): + return { + "description": self.description, + "knowledge_source_details": self.knowledge_source_details, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + "embedding_model": self.embedding_model, + } + + def __init__(self, version: Version, id: str): + """ + Initialize the KnowledgeContext + + :param version: Version that contains the resource + :param id: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Knowledge/{id}".format(**self._solution) + + self._chunks: Optional[ChunkList] = None + self._knowledge_status: Optional[KnowledgeStatusList] = None + + def delete(self) -> bool: + """ + Deletes the KnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the KnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> KnowledgeInstance: + """ + Fetch the KnowledgeInstance + + + :returns: The fetched KnowledgeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return KnowledgeInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_async(self) -> KnowledgeInstance: + """ + Asynchronous coroutine to fetch the KnowledgeInstance + + + :returns: The fetched KnowledgeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return KnowledgeInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def update( + self, + assistants_v1_service_update_knowledge_request: Union[ + AssistantsV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> KnowledgeInstance: + """ + Update the KnowledgeInstance + + :param assistants_v1_service_update_knowledge_request: + + :returns: The updated KnowledgeInstance + """ + data = assistants_v1_service_update_knowledge_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + return KnowledgeInstance(self._version, payload, id=self._solution["id"]) + + async def update_async( + self, + assistants_v1_service_update_knowledge_request: Union[ + AssistantsV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> KnowledgeInstance: + """ + Asynchronous coroutine to update the KnowledgeInstance + + :param assistants_v1_service_update_knowledge_request: + + :returns: The updated KnowledgeInstance + """ + data = assistants_v1_service_update_knowledge_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + return KnowledgeInstance(self._version, payload, id=self._solution["id"]) + + @property + def chunks(self) -> ChunkList: + """ + Access the chunks + """ + if self._chunks is None: + self._chunks = ChunkList( + self._version, + self._solution["id"], + ) + return self._chunks + + @property + def knowledge_status(self) -> KnowledgeStatusList: + """ + Access the knowledge_status + """ + if self._knowledge_status is None: + self._knowledge_status = KnowledgeStatusList( + self._version, + self._solution["id"], + ) + return self._knowledge_status + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class KnowledgePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> KnowledgeInstance: + """ + Build an instance of KnowledgeInstance + + :param payload: Payload response from the API + """ + return KnowledgeInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class KnowledgeList(ListResource): + + class AssistantsV1ServiceCreateKnowledgeRequest(object): + """ + :ivar assistant_id: The Assistant ID. + :ivar description: The description of the knowledge source. + :ivar knowledge_source_details: The details of the knowledge source based on the type. + :ivar name: The name of the tool. + :ivar policy: + :ivar type: The type of the knowledge source. + :ivar embedding_model: The embedding model to be used for the knowledge source. It's required for 'Database' type but disallowed for other types. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.assistant_id: Optional[str] = payload.get("assistant_id") + self.description: Optional[str] = payload.get("description") + self.knowledge_source_details: Optional[Dict[str, object]] = payload.get( + "knowledge_source_details" + ) + self.name: Optional[str] = payload.get("name") + self.policy: Optional[ + KnowledgeList.AssistantsV1ServiceCreatePolicyRequest + ] = payload.get("policy") + self.type: Optional[str] = payload.get("type") + self.embedding_model: Optional[str] = payload.get("embedding_model") + + def to_dict(self): + return { + "assistant_id": self.assistant_id, + "description": self.description, + "knowledge_source_details": self.knowledge_source_details, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + "embedding_model": self.embedding_model, + } + + class AssistantsV1ServiceCreatePolicyRequest(object): + """ + :ivar description: The description of the policy. + :ivar id: The Policy ID. + :ivar name: The name of the policy. + :ivar policy_details: + :ivar type: The description of the policy. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.description: Optional[str] = payload.get("description") + self.id: Optional[str] = payload.get("id") + self.name: Optional[str] = payload.get("name") + self.policy_details: Optional[Dict[str, object]] = payload.get( + "policy_details" + ) + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "description": self.description, + "id": self.id, + "name": self.name, + "policy_details": self.policy_details, + "type": self.type, + } + + class AssistantsV1ServiceUpdateKnowledgeRequest(object): + """ + :ivar description: The description of the knowledge source. + :ivar knowledge_source_details: The details of the knowledge source based on the type. + :ivar name: The name of the knowledge source. + :ivar policy: + :ivar type: The description of the knowledge source. + :ivar embedding_model: The embedding model to be used for the knowledge source. It's only applicable to 'Database' type. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.description: Optional[str] = payload.get("description") + self.knowledge_source_details: Optional[Dict[str, object]] = payload.get( + "knowledge_source_details" + ) + self.name: Optional[str] = payload.get("name") + self.policy: Optional[ + KnowledgeList.AssistantsV1ServiceCreatePolicyRequest + ] = payload.get("policy") + self.type: Optional[str] = payload.get("type") + self.embedding_model: Optional[str] = payload.get("embedding_model") + + def to_dict(self): + return { + "description": self.description, + "knowledge_source_details": self.knowledge_source_details, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + "embedding_model": self.embedding_model, + } + + def __init__(self, version: Version): + """ + Initialize the KnowledgeList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Knowledge" + + def create( + self, + assistants_v1_service_create_knowledge_request: AssistantsV1ServiceCreateKnowledgeRequest, + ) -> KnowledgeInstance: + """ + Create the KnowledgeInstance + + :param assistants_v1_service_create_knowledge_request: + + :returns: The created KnowledgeInstance + """ + data = assistants_v1_service_create_knowledge_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return KnowledgeInstance(self._version, payload) + + async def create_async( + self, + assistants_v1_service_create_knowledge_request: AssistantsV1ServiceCreateKnowledgeRequest, + ) -> KnowledgeInstance: + """ + Asynchronously create the KnowledgeInstance + + :param assistants_v1_service_create_knowledge_request: + + :returns: The created KnowledgeInstance + """ + data = assistants_v1_service_create_knowledge_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return KnowledgeInstance(self._version, payload) + + def stream( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[KnowledgeInstance]: + """ + Streams KnowledgeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str assistant_id: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(assistant_id=assistant_id, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[KnowledgeInstance]: + """ + Asynchronously streams KnowledgeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str assistant_id: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + assistant_id=assistant_id, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[KnowledgeInstance]: + """ + Lists KnowledgeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str assistant_id: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + assistant_id=assistant_id, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[KnowledgeInstance]: + """ + Asynchronously lists KnowledgeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str assistant_id: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + assistant_id=assistant_id, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + assistant_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> KnowledgePage: + """ + Retrieve a single page of KnowledgeInstance records from the API. + Request is executed immediately + + :param assistant_id: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of KnowledgeInstance + """ + data = values.of( + { + "AssistantId": assistant_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return KnowledgePage(self._version, response) + + async def page_async( + self, + assistant_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> KnowledgePage: + """ + Asynchronously retrieve a single page of KnowledgeInstance records from the API. + Request is executed immediately + + :param assistant_id: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of KnowledgeInstance + """ + data = values.of( + { + "AssistantId": assistant_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return KnowledgePage(self._version, response) + + def get_page(self, target_url: str) -> KnowledgePage: + """ + Retrieve a specific page of KnowledgeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of KnowledgeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return KnowledgePage(self._version, response) + + async def get_page_async(self, target_url: str) -> KnowledgePage: + """ + Asynchronously retrieve a specific page of KnowledgeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of KnowledgeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return KnowledgePage(self._version, response) + + def get(self, id: str) -> KnowledgeContext: + """ + Constructs a KnowledgeContext + + :param id: + """ + return KnowledgeContext(self._version, id=id) + + def __call__(self, id: str) -> KnowledgeContext: + """ + Constructs a KnowledgeContext + + :param id: + """ + return KnowledgeContext(self._version, id=id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/knowledge/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/assistants/v1/knowledge/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..3c691b0c Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/assistants/v1/knowledge/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/knowledge/__pycache__/chunk.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/assistants/v1/knowledge/__pycache__/chunk.cpython-312.pyc new file mode 100644 index 00000000..df41ab12 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/assistants/v1/knowledge/__pycache__/chunk.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/knowledge/__pycache__/knowledge_status.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/assistants/v1/knowledge/__pycache__/knowledge_status.cpython-312.pyc new file mode 100644 index 00000000..d571d632 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/assistants/v1/knowledge/__pycache__/knowledge_status.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/knowledge/chunk.py b/venv/Lib/site-packages/twilio/rest/assistants/v1/knowledge/chunk.py new file mode 100644 index 00000000..be90a762 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/assistants/v1/knowledge/chunk.py @@ -0,0 +1,297 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ChunkInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Knowledge resource. + :ivar content: The chunk content. + :ivar metadata: The metadata of the chunk. + :ivar date_created: The date and time in GMT when the Chunk was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Chunk was updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], id: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.content: Optional[str] = payload.get("content") + self.metadata: Optional[Dict[str, object]] = payload.get("metadata") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "id": id, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ChunkPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ChunkInstance: + """ + Build an instance of ChunkInstance + + :param payload: Payload response from the API + """ + return ChunkInstance(self._version, payload, id=self._solution["id"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ChunkList(ListResource): + + def __init__(self, version: Version, id: str): + """ + Initialize the ChunkList + + :param version: Version that contains the resource + :param id: The knowledge ID. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Knowledge/{id}/Chunks".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChunkInstance]: + """ + Streams ChunkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ChunkInstance]: + """ + Asynchronously streams ChunkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChunkInstance]: + """ + Lists ChunkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChunkInstance]: + """ + Asynchronously lists ChunkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChunkPage: + """ + Retrieve a single page of ChunkInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChunkInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChunkPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChunkPage: + """ + Asynchronously retrieve a single page of ChunkInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChunkInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChunkPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ChunkPage: + """ + Retrieve a specific page of ChunkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChunkInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ChunkPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ChunkPage: + """ + Asynchronously retrieve a specific page of ChunkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChunkInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChunkPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/knowledge/knowledge_status.py b/venv/Lib/site-packages/twilio/rest/assistants/v1/knowledge/knowledge_status.py new file mode 100644 index 00000000..fedbcaad --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/assistants/v1/knowledge/knowledge_status.py @@ -0,0 +1,196 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class KnowledgeStatusInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Knowledge resource. + :ivar status: The status of processing the knowledge source ('QUEUED', 'PROCESSING', 'COMPLETED', 'FAILED') + :ivar last_status: The last status of processing the knowledge source ('QUEUED', 'PROCESSING', 'COMPLETED', 'FAILED') + :ivar date_updated: The date and time in GMT when the Knowledge was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], id: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.status: Optional[str] = payload.get("status") + self.last_status: Optional[str] = payload.get("last_status") + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "id": id, + } + self._context: Optional[KnowledgeStatusContext] = None + + @property + def _proxy(self) -> "KnowledgeStatusContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: KnowledgeStatusContext for this KnowledgeStatusInstance + """ + if self._context is None: + self._context = KnowledgeStatusContext( + self._version, + id=self._solution["id"], + ) + return self._context + + def fetch(self) -> "KnowledgeStatusInstance": + """ + Fetch the KnowledgeStatusInstance + + + :returns: The fetched KnowledgeStatusInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "KnowledgeStatusInstance": + """ + Asynchronous coroutine to fetch the KnowledgeStatusInstance + + + :returns: The fetched KnowledgeStatusInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class KnowledgeStatusContext(InstanceContext): + + def __init__(self, version: Version, id: str): + """ + Initialize the KnowledgeStatusContext + + :param version: Version that contains the resource + :param id: the Knowledge ID. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Knowledge/{id}/Status".format(**self._solution) + + def fetch(self) -> KnowledgeStatusInstance: + """ + Fetch the KnowledgeStatusInstance + + + :returns: The fetched KnowledgeStatusInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return KnowledgeStatusInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_async(self) -> KnowledgeStatusInstance: + """ + Asynchronous coroutine to fetch the KnowledgeStatusInstance + + + :returns: The fetched KnowledgeStatusInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return KnowledgeStatusInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class KnowledgeStatusList(ListResource): + + def __init__(self, version: Version, id: str): + """ + Initialize the KnowledgeStatusList + + :param version: Version that contains the resource + :param id: the Knowledge ID. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + + def get(self) -> KnowledgeStatusContext: + """ + Constructs a KnowledgeStatusContext + + """ + return KnowledgeStatusContext(self._version, id=self._solution["id"]) + + def __call__(self) -> KnowledgeStatusContext: + """ + Constructs a KnowledgeStatusContext + + """ + return KnowledgeStatusContext(self._version, id=self._solution["id"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/policy.py b/venv/Lib/site-packages/twilio/rest/assistants/v1/policy.py new file mode 100644 index 00000000..63854fb8 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/assistants/v1/policy.py @@ -0,0 +1,332 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class PolicyInstance(InstanceResource): + """ + :ivar id: The Policy ID. + :ivar name: The name of the policy. + :ivar description: The description of the policy. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Policy resource. + :ivar user_sid: The SID of the User that created the Policy resource. + :ivar type: The type of the policy. + :ivar policy_details: The details of the policy based on the type. + :ivar date_created: The date and time in GMT when the Policy was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Policy was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.name: Optional[str] = payload.get("name") + self.description: Optional[str] = payload.get("description") + self.account_sid: Optional[str] = payload.get("account_sid") + self.user_sid: Optional[str] = payload.get("user_sid") + self.type: Optional[str] = payload.get("type") + self.policy_details: Optional[Dict[str, object]] = payload.get("policy_details") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class PolicyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PolicyInstance: + """ + Build an instance of PolicyInstance + + :param payload: Payload response from the API + """ + return PolicyInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class PolicyList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PolicyList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Policies" + + def stream( + self, + tool_id: Union[str, object] = values.unset, + knowledge_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PolicyInstance]: + """ + Streams PolicyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str tool_id: The tool ID. + :param str knowledge_id: The knowledge ID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + tool_id=tool_id, knowledge_id=knowledge_id, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + tool_id: Union[str, object] = values.unset, + knowledge_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PolicyInstance]: + """ + Asynchronously streams PolicyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str tool_id: The tool ID. + :param str knowledge_id: The knowledge ID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + tool_id=tool_id, knowledge_id=knowledge_id, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + tool_id: Union[str, object] = values.unset, + knowledge_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PolicyInstance]: + """ + Lists PolicyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str tool_id: The tool ID. + :param str knowledge_id: The knowledge ID. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + tool_id=tool_id, + knowledge_id=knowledge_id, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + tool_id: Union[str, object] = values.unset, + knowledge_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PolicyInstance]: + """ + Asynchronously lists PolicyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str tool_id: The tool ID. + :param str knowledge_id: The knowledge ID. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + tool_id=tool_id, + knowledge_id=knowledge_id, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + tool_id: Union[str, object] = values.unset, + knowledge_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PolicyPage: + """ + Retrieve a single page of PolicyInstance records from the API. + Request is executed immediately + + :param tool_id: The tool ID. + :param knowledge_id: The knowledge ID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PolicyInstance + """ + data = values.of( + { + "ToolId": tool_id, + "KnowledgeId": knowledge_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PolicyPage(self._version, response) + + async def page_async( + self, + tool_id: Union[str, object] = values.unset, + knowledge_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PolicyPage: + """ + Asynchronously retrieve a single page of PolicyInstance records from the API. + Request is executed immediately + + :param tool_id: The tool ID. + :param knowledge_id: The knowledge ID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PolicyInstance + """ + data = values.of( + { + "ToolId": tool_id, + "KnowledgeId": knowledge_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PolicyPage(self._version, response) + + def get_page(self, target_url: str) -> PolicyPage: + """ + Retrieve a specific page of PolicyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PolicyInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PolicyPage(self._version, response) + + async def get_page_async(self, target_url: str) -> PolicyPage: + """ + Asynchronously retrieve a specific page of PolicyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PolicyInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PolicyPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/session/__init__.py b/venv/Lib/site-packages/twilio/rest/assistants/v1/session/__init__.py new file mode 100644 index 00000000..3f0054ea --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/assistants/v1/session/__init__.py @@ -0,0 +1,439 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.assistants.v1.session.message import MessageList + + +class SessionInstance(InstanceResource): + """ + :ivar id: The Session ID. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Session resource. + :ivar assistant_id: The Assistant ID. + :ivar verified: True if the session is verified. + :ivar identity: The unique identity of user for the session. + :ivar date_created: The date and time in GMT when the Session was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Session was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], id: Optional[str] = None + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.account_sid: Optional[str] = payload.get("account_sid") + self.assistant_id: Optional[str] = payload.get("assistant_id") + self.verified: Optional[bool] = payload.get("verified") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "id": id or self.id, + } + self._context: Optional[SessionContext] = None + + @property + def _proxy(self) -> "SessionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SessionContext for this SessionInstance + """ + if self._context is None: + self._context = SessionContext( + self._version, + id=self._solution["id"], + ) + return self._context + + def fetch(self) -> "SessionInstance": + """ + Fetch the SessionInstance + + + :returns: The fetched SessionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SessionInstance": + """ + Asynchronous coroutine to fetch the SessionInstance + + + :returns: The fetched SessionInstance + """ + return await self._proxy.fetch_async() + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SessionContext(InstanceContext): + + def __init__(self, version: Version, id: str): + """ + Initialize the SessionContext + + :param version: Version that contains the resource + :param id: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Sessions/{id}".format(**self._solution) + + self._messages: Optional[MessageList] = None + + def fetch(self) -> SessionInstance: + """ + Fetch the SessionInstance + + + :returns: The fetched SessionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SessionInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_async(self) -> SessionInstance: + """ + Asynchronous coroutine to fetch the SessionInstance + + + :returns: The fetched SessionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SessionInstance( + self._version, + payload, + id=self._solution["id"], + ) + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + if self._messages is None: + self._messages = MessageList( + self._version, + self._solution["id"], + ) + return self._messages + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SessionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SessionInstance: + """ + Build an instance of SessionInstance + + :param payload: Payload response from the API + """ + return SessionInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SessionList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SessionList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Sessions" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SessionInstance]: + """ + Streams SessionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SessionInstance]: + """ + Asynchronously streams SessionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SessionInstance]: + """ + Lists SessionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SessionInstance]: + """ + Asynchronously lists SessionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SessionPage: + """ + Retrieve a single page of SessionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SessionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SessionPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SessionPage: + """ + Asynchronously retrieve a single page of SessionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SessionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SessionPage(self._version, response) + + def get_page(self, target_url: str) -> SessionPage: + """ + Retrieve a specific page of SessionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SessionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SessionPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SessionPage: + """ + Asynchronously retrieve a specific page of SessionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SessionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SessionPage(self._version, response) + + def get(self, id: str) -> SessionContext: + """ + Constructs a SessionContext + + :param id: + """ + return SessionContext(self._version, id=id) + + def __call__(self, id: str) -> SessionContext: + """ + Constructs a SessionContext + + :param id: + """ + return SessionContext(self._version, id=id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/session/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/assistants/v1/session/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..224b28a3 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/assistants/v1/session/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/session/__pycache__/message.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/assistants/v1/session/__pycache__/message.cpython-312.pyc new file mode 100644 index 00000000..be972724 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/assistants/v1/session/__pycache__/message.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/session/message.py b/venv/Lib/site-packages/twilio/rest/assistants/v1/session/message.py new file mode 100644 index 00000000..a7ea5ca2 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/assistants/v1/session/message.py @@ -0,0 +1,309 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MessageInstance(InstanceResource): + """ + :ivar id: The message ID. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Message resource. + :ivar assistant_id: The Assistant ID. + :ivar session_id: The Session ID. + :ivar identity: The identity of the user. + :ivar role: The role of the user associated with the message. + :ivar content: The content of the message. + :ivar meta: The metadata of the message. + :ivar date_created: The date and time in GMT when the Message was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Message was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], session_id: str): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.account_sid: Optional[str] = payload.get("account_sid") + self.assistant_id: Optional[str] = payload.get("assistant_id") + self.session_id: Optional[str] = payload.get("session_id") + self.identity: Optional[str] = payload.get("identity") + self.role: Optional[str] = payload.get("role") + self.content: Optional[Dict[str, object]] = payload.get("content") + self.meta: Optional[Dict[str, object]] = payload.get("meta") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "session_id": session_id, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MessagePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: + """ + Build an instance of MessageInstance + + :param payload: Payload response from the API + """ + return MessageInstance( + self._version, payload, session_id=self._solution["session_id"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MessageList(ListResource): + + def __init__(self, version: Version, session_id: str): + """ + Initialize the MessageList + + :param version: Version that contains the resource + :param session_id: Session id or name + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "session_id": session_id, + } + self._uri = "/Sessions/{session_id}/Messages".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: + """ + Streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessageInstance]: + """ + Asynchronously streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Asynchronously lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MessagePage: + """ + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MessagePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MessagePage: + """ + Asynchronously retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagePage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/assistants/v1/tool.py b/venv/Lib/site-packages/twilio/rest/assistants/v1/tool.py new file mode 100644 index 00000000..648faca5 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/assistants/v1/tool.py @@ -0,0 +1,916 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ToolInstance(InstanceResource): + + class AssistantsV1ServiceCreatePolicyRequest(object): + """ + :ivar description: The description of the policy. + :ivar id: The Policy ID. + :ivar name: The name of the policy. + :ivar policy_details: + :ivar type: The description of the policy. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.description: Optional[str] = payload.get("description") + self.id: Optional[str] = payload.get("id") + self.name: Optional[str] = payload.get("name") + self.policy_details: Optional[Dict[str, object]] = payload.get( + "policy_details" + ) + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "description": self.description, + "id": self.id, + "name": self.name, + "policy_details": self.policy_details, + "type": self.type, + } + + class AssistantsV1ServiceCreateToolRequest(object): + """ + :ivar assistant_id: The Assistant ID. + :ivar description: The description of the tool. + :ivar enabled: True if the tool is enabled. + :ivar meta: The metadata related to method, url, input_schema to used with the Tool. + :ivar name: The name of the tool. + :ivar policy: + :ivar type: The description of the tool. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.assistant_id: Optional[str] = payload.get("assistant_id") + self.description: Optional[str] = payload.get("description") + self.enabled: Optional[bool] = payload.get("enabled") + self.meta: Optional[Dict[str, object]] = payload.get("meta") + self.name: Optional[str] = payload.get("name") + self.policy: Optional[ToolList.AssistantsV1ServiceCreatePolicyRequest] = ( + payload.get("policy") + ) + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "assistant_id": self.assistant_id, + "description": self.description, + "enabled": self.enabled, + "meta": self.meta, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + } + + class AssistantsV1ServiceUpdateToolRequest(object): + """ + :ivar assistant_id: The Assistant ID. + :ivar description: The description of the tool. + :ivar enabled: True if the tool is enabled. + :ivar meta: The metadata related to method, url, input_schema to used with the Tool. + :ivar name: The name of the tool. + :ivar policy: + :ivar type: The type of the tool. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.assistant_id: Optional[str] = payload.get("assistant_id") + self.description: Optional[str] = payload.get("description") + self.enabled: Optional[bool] = payload.get("enabled") + self.meta: Optional[Dict[str, object]] = payload.get("meta") + self.name: Optional[str] = payload.get("name") + self.policy: Optional[ToolList.AssistantsV1ServiceCreatePolicyRequest] = ( + payload.get("policy") + ) + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "assistant_id": self.assistant_id, + "description": self.description, + "enabled": self.enabled, + "meta": self.meta, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + } + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Tool resource. + :ivar description: The description of the tool. + :ivar enabled: True if the tool is enabled. + :ivar id: The tool ID. + :ivar meta: The metadata related to method, url, input_schema to used with the Tool. + :ivar name: The name of the tool. + :ivar requires_auth: The authentication requirement for the tool. + :ivar type: The type of the tool. ('WEBHOOK') + :ivar url: The url of the tool resource. + :ivar date_created: The date and time in GMT when the Tool was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Tool was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar policies: The Policies associated with the tool. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], id: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.description: Optional[str] = payload.get("description") + self.enabled: Optional[bool] = payload.get("enabled") + self.id: Optional[str] = payload.get("id") + self.meta: Optional[Dict[str, object]] = payload.get("meta") + self.name: Optional[str] = payload.get("name") + self.requires_auth: Optional[bool] = payload.get("requires_auth") + self.type: Optional[str] = payload.get("type") + self.url: Optional[str] = payload.get("url") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.policies: Optional[List[str]] = payload.get("policies") + + self._solution = { + "id": id or self.id, + } + self._context: Optional[ToolContext] = None + + @property + def _proxy(self) -> "ToolContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ToolContext for this ToolInstance + """ + if self._context is None: + self._context = ToolContext( + self._version, + id=self._solution["id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ToolInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ToolInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ToolInstance": + """ + Fetch the ToolInstance + + + :returns: The fetched ToolInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ToolInstance": + """ + Asynchronous coroutine to fetch the ToolInstance + + + :returns: The fetched ToolInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + assistants_v1_service_update_tool_request: Union[ + AssistantsV1ServiceUpdateToolRequest, object + ] = values.unset, + ) -> "ToolInstance": + """ + Update the ToolInstance + + :param assistants_v1_service_update_tool_request: + + :returns: The updated ToolInstance + """ + return self._proxy.update( + assistants_v1_service_update_tool_request=assistants_v1_service_update_tool_request, + ) + + async def update_async( + self, + assistants_v1_service_update_tool_request: Union[ + AssistantsV1ServiceUpdateToolRequest, object + ] = values.unset, + ) -> "ToolInstance": + """ + Asynchronous coroutine to update the ToolInstance + + :param assistants_v1_service_update_tool_request: + + :returns: The updated ToolInstance + """ + return await self._proxy.update_async( + assistants_v1_service_update_tool_request=assistants_v1_service_update_tool_request, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ToolContext(InstanceContext): + + class AssistantsV1ServiceCreatePolicyRequest(object): + """ + :ivar description: The description of the policy. + :ivar id: The Policy ID. + :ivar name: The name of the policy. + :ivar policy_details: + :ivar type: The description of the policy. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.description: Optional[str] = payload.get("description") + self.id: Optional[str] = payload.get("id") + self.name: Optional[str] = payload.get("name") + self.policy_details: Optional[Dict[str, object]] = payload.get( + "policy_details" + ) + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "description": self.description, + "id": self.id, + "name": self.name, + "policy_details": self.policy_details, + "type": self.type, + } + + class AssistantsV1ServiceCreateToolRequest(object): + """ + :ivar assistant_id: The Assistant ID. + :ivar description: The description of the tool. + :ivar enabled: True if the tool is enabled. + :ivar meta: The metadata related to method, url, input_schema to used with the Tool. + :ivar name: The name of the tool. + :ivar policy: + :ivar type: The description of the tool. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.assistant_id: Optional[str] = payload.get("assistant_id") + self.description: Optional[str] = payload.get("description") + self.enabled: Optional[bool] = payload.get("enabled") + self.meta: Optional[Dict[str, object]] = payload.get("meta") + self.name: Optional[str] = payload.get("name") + self.policy: Optional[ToolList.AssistantsV1ServiceCreatePolicyRequest] = ( + payload.get("policy") + ) + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "assistant_id": self.assistant_id, + "description": self.description, + "enabled": self.enabled, + "meta": self.meta, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + } + + class AssistantsV1ServiceUpdateToolRequest(object): + """ + :ivar assistant_id: The Assistant ID. + :ivar description: The description of the tool. + :ivar enabled: True if the tool is enabled. + :ivar meta: The metadata related to method, url, input_schema to used with the Tool. + :ivar name: The name of the tool. + :ivar policy: + :ivar type: The type of the tool. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.assistant_id: Optional[str] = payload.get("assistant_id") + self.description: Optional[str] = payload.get("description") + self.enabled: Optional[bool] = payload.get("enabled") + self.meta: Optional[Dict[str, object]] = payload.get("meta") + self.name: Optional[str] = payload.get("name") + self.policy: Optional[ToolList.AssistantsV1ServiceCreatePolicyRequest] = ( + payload.get("policy") + ) + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "assistant_id": self.assistant_id, + "description": self.description, + "enabled": self.enabled, + "meta": self.meta, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + } + + def __init__(self, version: Version, id: str): + """ + Initialize the ToolContext + + :param version: Version that contains the resource + :param id: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Tools/{id}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the ToolInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ToolInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ToolInstance: + """ + Fetch the ToolInstance + + + :returns: The fetched ToolInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ToolInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_async(self) -> ToolInstance: + """ + Asynchronous coroutine to fetch the ToolInstance + + + :returns: The fetched ToolInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ToolInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def update( + self, + assistants_v1_service_update_tool_request: Union[ + AssistantsV1ServiceUpdateToolRequest, object + ] = values.unset, + ) -> ToolInstance: + """ + Update the ToolInstance + + :param assistants_v1_service_update_tool_request: + + :returns: The updated ToolInstance + """ + data = assistants_v1_service_update_tool_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + return ToolInstance(self._version, payload, id=self._solution["id"]) + + async def update_async( + self, + assistants_v1_service_update_tool_request: Union[ + AssistantsV1ServiceUpdateToolRequest, object + ] = values.unset, + ) -> ToolInstance: + """ + Asynchronous coroutine to update the ToolInstance + + :param assistants_v1_service_update_tool_request: + + :returns: The updated ToolInstance + """ + data = assistants_v1_service_update_tool_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + return ToolInstance(self._version, payload, id=self._solution["id"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ToolPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ToolInstance: + """ + Build an instance of ToolInstance + + :param payload: Payload response from the API + """ + return ToolInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ToolList(ListResource): + + class AssistantsV1ServiceCreatePolicyRequest(object): + """ + :ivar description: The description of the policy. + :ivar id: The Policy ID. + :ivar name: The name of the policy. + :ivar policy_details: + :ivar type: The description of the policy. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.description: Optional[str] = payload.get("description") + self.id: Optional[str] = payload.get("id") + self.name: Optional[str] = payload.get("name") + self.policy_details: Optional[Dict[str, object]] = payload.get( + "policy_details" + ) + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "description": self.description, + "id": self.id, + "name": self.name, + "policy_details": self.policy_details, + "type": self.type, + } + + class AssistantsV1ServiceCreateToolRequest(object): + """ + :ivar assistant_id: The Assistant ID. + :ivar description: The description of the tool. + :ivar enabled: True if the tool is enabled. + :ivar meta: The metadata related to method, url, input_schema to used with the Tool. + :ivar name: The name of the tool. + :ivar policy: + :ivar type: The description of the tool. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.assistant_id: Optional[str] = payload.get("assistant_id") + self.description: Optional[str] = payload.get("description") + self.enabled: Optional[bool] = payload.get("enabled") + self.meta: Optional[Dict[str, object]] = payload.get("meta") + self.name: Optional[str] = payload.get("name") + self.policy: Optional[ToolList.AssistantsV1ServiceCreatePolicyRequest] = ( + payload.get("policy") + ) + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "assistant_id": self.assistant_id, + "description": self.description, + "enabled": self.enabled, + "meta": self.meta, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + } + + class AssistantsV1ServiceUpdateToolRequest(object): + """ + :ivar assistant_id: The Assistant ID. + :ivar description: The description of the tool. + :ivar enabled: True if the tool is enabled. + :ivar meta: The metadata related to method, url, input_schema to used with the Tool. + :ivar name: The name of the tool. + :ivar policy: + :ivar type: The type of the tool. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.assistant_id: Optional[str] = payload.get("assistant_id") + self.description: Optional[str] = payload.get("description") + self.enabled: Optional[bool] = payload.get("enabled") + self.meta: Optional[Dict[str, object]] = payload.get("meta") + self.name: Optional[str] = payload.get("name") + self.policy: Optional[ToolList.AssistantsV1ServiceCreatePolicyRequest] = ( + payload.get("policy") + ) + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "assistant_id": self.assistant_id, + "description": self.description, + "enabled": self.enabled, + "meta": self.meta, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + } + + def __init__(self, version: Version): + """ + Initialize the ToolList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Tools" + + def create( + self, + assistants_v1_service_create_tool_request: AssistantsV1ServiceCreateToolRequest, + ) -> ToolInstance: + """ + Create the ToolInstance + + :param assistants_v1_service_create_tool_request: + + :returns: The created ToolInstance + """ + data = assistants_v1_service_create_tool_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ToolInstance(self._version, payload) + + async def create_async( + self, + assistants_v1_service_create_tool_request: AssistantsV1ServiceCreateToolRequest, + ) -> ToolInstance: + """ + Asynchronously create the ToolInstance + + :param assistants_v1_service_create_tool_request: + + :returns: The created ToolInstance + """ + data = assistants_v1_service_create_tool_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ToolInstance(self._version, payload) + + def stream( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ToolInstance]: + """ + Streams ToolInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str assistant_id: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(assistant_id=assistant_id, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ToolInstance]: + """ + Asynchronously streams ToolInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str assistant_id: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + assistant_id=assistant_id, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ToolInstance]: + """ + Lists ToolInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str assistant_id: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + assistant_id=assistant_id, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ToolInstance]: + """ + Asynchronously lists ToolInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str assistant_id: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + assistant_id=assistant_id, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + assistant_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ToolPage: + """ + Retrieve a single page of ToolInstance records from the API. + Request is executed immediately + + :param assistant_id: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ToolInstance + """ + data = values.of( + { + "AssistantId": assistant_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ToolPage(self._version, response) + + async def page_async( + self, + assistant_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ToolPage: + """ + Asynchronously retrieve a single page of ToolInstance records from the API. + Request is executed immediately + + :param assistant_id: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ToolInstance + """ + data = values.of( + { + "AssistantId": assistant_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ToolPage(self._version, response) + + def get_page(self, target_url: str) -> ToolPage: + """ + Retrieve a specific page of ToolInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ToolInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ToolPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ToolPage: + """ + Asynchronously retrieve a specific page of ToolInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ToolInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ToolPage(self._version, response) + + def get(self, id: str) -> ToolContext: + """ + Constructs a ToolContext + + :param id: + """ + return ToolContext(self._version, id=id) + + def __call__(self, id: str) -> ToolContext: + """ + Constructs a ToolContext + + :param id: + """ + return ToolContext(self._version, id=id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/bulkexports/BulkexportsBase.py b/venv/Lib/site-packages/twilio/rest/bulkexports/BulkexportsBase.py new file mode 100644 index 00000000..cbca4c53 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/bulkexports/BulkexportsBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.bulkexports.v1 import V1 + + +class BulkexportsBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Bulkexports Domain + + :returns: Domain for Bulkexports + """ + super().__init__(twilio, "https://bulkexports.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Bulkexports + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/bulkexports/__init__.py b/venv/Lib/site-packages/twilio/rest/bulkexports/__init__.py new file mode 100644 index 00000000..3a28fb57 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/bulkexports/__init__.py @@ -0,0 +1,25 @@ +from warnings import warn + +from twilio.rest.bulkexports.BulkexportsBase import BulkexportsBase +from twilio.rest.bulkexports.v1.export import ExportList +from twilio.rest.bulkexports.v1.export_configuration import ExportConfigurationList + + +class Bulkexports(BulkexportsBase): + @property + def exports(self) -> ExportList: + warn( + "exports is deprecated. Use v1.exports instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.exports + + @property + def export_configuration(self) -> ExportConfigurationList: + warn( + "export_configuration is deprecated. Use v1.export_configuration instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.export_configuration diff --git a/venv/Lib/site-packages/twilio/rest/bulkexports/__pycache__/BulkexportsBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/bulkexports/__pycache__/BulkexportsBase.cpython-312.pyc new file mode 100644 index 00000000..c7ab3d93 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/bulkexports/__pycache__/BulkexportsBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/bulkexports/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/bulkexports/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..8528cf98 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/bulkexports/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/bulkexports/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/bulkexports/v1/__init__.py new file mode 100644 index 00000000..a888fb48 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/bulkexports/v1/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Bulkexports + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.bulkexports.v1.export import ExportList +from twilio.rest.bulkexports.v1.export_configuration import ExportConfigurationList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Bulkexports + + :param domain: The Twilio.bulkexports domain + """ + super().__init__(domain, "v1") + self._exports: Optional[ExportList] = None + self._export_configuration: Optional[ExportConfigurationList] = None + + @property + def exports(self) -> ExportList: + if self._exports is None: + self._exports = ExportList(self) + return self._exports + + @property + def export_configuration(self) -> ExportConfigurationList: + if self._export_configuration is None: + self._export_configuration = ExportConfigurationList(self) + return self._export_configuration + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/bulkexports/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/bulkexports/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..3bb28821 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/bulkexports/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/bulkexports/v1/__pycache__/export_configuration.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/bulkexports/v1/__pycache__/export_configuration.cpython-312.pyc new file mode 100644 index 00000000..b5fd5282 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/bulkexports/v1/__pycache__/export_configuration.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export/__init__.py b/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export/__init__.py new file mode 100644 index 00000000..0ebf3a45 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export/__init__.py @@ -0,0 +1,250 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Bulkexports + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.bulkexports.v1.export.day import DayList +from twilio.rest.bulkexports.v1.export.export_custom_job import ExportCustomJobList +from twilio.rest.bulkexports.v1.export.job import JobList + + +class ExportInstance(InstanceResource): + """ + :ivar resource_type: The type of communication – Messages, Calls, Conferences, and Participants + :ivar url: The URL of this resource. + :ivar links: Contains a dictionary of URL links to nested resources of this Export. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + resource_type: Optional[str] = None, + ): + super().__init__(version) + + self.resource_type: Optional[str] = payload.get("resource_type") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "resource_type": resource_type or self.resource_type, + } + self._context: Optional[ExportContext] = None + + @property + def _proxy(self) -> "ExportContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ExportContext for this ExportInstance + """ + if self._context is None: + self._context = ExportContext( + self._version, + resource_type=self._solution["resource_type"], + ) + return self._context + + def fetch(self) -> "ExportInstance": + """ + Fetch the ExportInstance + + + :returns: The fetched ExportInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ExportInstance": + """ + Asynchronous coroutine to fetch the ExportInstance + + + :returns: The fetched ExportInstance + """ + return await self._proxy.fetch_async() + + @property + def days(self) -> DayList: + """ + Access the days + """ + return self._proxy.days + + @property + def export_custom_jobs(self) -> ExportCustomJobList: + """ + Access the export_custom_jobs + """ + return self._proxy.export_custom_jobs + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ExportContext(InstanceContext): + + def __init__(self, version: Version, resource_type: str): + """ + Initialize the ExportContext + + :param version: Version that contains the resource + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants + """ + super().__init__(version) + + # Path Solution + self._solution = { + "resource_type": resource_type, + } + self._uri = "/Exports/{resource_type}".format(**self._solution) + + self._days: Optional[DayList] = None + self._export_custom_jobs: Optional[ExportCustomJobList] = None + + def fetch(self) -> ExportInstance: + """ + Fetch the ExportInstance + + + :returns: The fetched ExportInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ExportInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + ) + + async def fetch_async(self) -> ExportInstance: + """ + Asynchronous coroutine to fetch the ExportInstance + + + :returns: The fetched ExportInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ExportInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + ) + + @property + def days(self) -> DayList: + """ + Access the days + """ + if self._days is None: + self._days = DayList( + self._version, + self._solution["resource_type"], + ) + return self._days + + @property + def export_custom_jobs(self) -> ExportCustomJobList: + """ + Access the export_custom_jobs + """ + if self._export_custom_jobs is None: + self._export_custom_jobs = ExportCustomJobList( + self._version, + self._solution["resource_type"], + ) + return self._export_custom_jobs + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ExportList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ExportList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Exports" + + self._jobs: Optional[JobList] = None + + @property + def jobs(self) -> JobList: + """ + Access the jobs + """ + if self._jobs is None: + self._jobs = JobList(self._version) + return self._jobs + + def get(self, resource_type: str) -> ExportContext: + """ + Constructs a ExportContext + + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants + """ + return ExportContext(self._version, resource_type=resource_type) + + def __call__(self, resource_type: str) -> ExportContext: + """ + Constructs a ExportContext + + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants + """ + return ExportContext(self._version, resource_type=resource_type) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..0a36e35b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export/__pycache__/day.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export/__pycache__/day.cpython-312.pyc new file mode 100644 index 00000000..dcdecb6b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export/__pycache__/day.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export/__pycache__/export_custom_job.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export/__pycache__/export_custom_job.cpython-312.pyc new file mode 100644 index 00000000..d16158c8 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export/__pycache__/export_custom_job.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export/__pycache__/job.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export/__pycache__/job.cpython-312.pyc new file mode 100644 index 00000000..596d669d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export/__pycache__/job.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export/day.py b/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export/day.py new file mode 100644 index 00000000..f4b2a065 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export/day.py @@ -0,0 +1,431 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Bulkexports + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DayInstance(InstanceResource): + """ + :ivar redirect_to: + :ivar day: The ISO 8601 format date of the resources in the file, for a UTC day + :ivar size: The size of the day's data file in bytes + :ivar create_date: The ISO 8601 format date when resources is created + :ivar friendly_name: The friendly name specified when creating the job + :ivar resource_type: The type of communication – Messages, Calls, Conferences, and Participants + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + resource_type: str, + day: Optional[str] = None, + ): + super().__init__(version) + + self.redirect_to: Optional[str] = payload.get("redirect_to") + self.day: Optional[str] = payload.get("day") + self.size: Optional[int] = deserialize.integer(payload.get("size")) + self.create_date: Optional[str] = payload.get("create_date") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.resource_type: Optional[str] = payload.get("resource_type") + + self._solution = { + "resource_type": resource_type, + "day": day or self.day, + } + self._context: Optional[DayContext] = None + + @property + def _proxy(self) -> "DayContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DayContext for this DayInstance + """ + if self._context is None: + self._context = DayContext( + self._version, + resource_type=self._solution["resource_type"], + day=self._solution["day"], + ) + return self._context + + def fetch(self) -> "DayInstance": + """ + Fetch the DayInstance + + + :returns: The fetched DayInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DayInstance": + """ + Asynchronous coroutine to fetch the DayInstance + + + :returns: The fetched DayInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DayContext(InstanceContext): + + def __init__(self, version: Version, resource_type: str, day: str): + """ + Initialize the DayContext + + :param version: Version that contains the resource + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants + :param day: The ISO 8601 format date of the resources in the file, for a UTC day + """ + super().__init__(version) + + # Path Solution + self._solution = { + "resource_type": resource_type, + "day": day, + } + self._uri = "/Exports/{resource_type}/Days/{day}".format(**self._solution) + + def fetch(self) -> DayInstance: + """ + Fetch the DayInstance + + + :returns: The fetched DayInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DayInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + day=self._solution["day"], + ) + + async def fetch_async(self) -> DayInstance: + """ + Asynchronous coroutine to fetch the DayInstance + + + :returns: The fetched DayInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DayInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + day=self._solution["day"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DayPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DayInstance: + """ + Build an instance of DayInstance + + :param payload: Payload response from the API + """ + return DayInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class DayList(ListResource): + + def __init__(self, version: Version, resource_type: str): + """ + Initialize the DayList + + :param version: Version that contains the resource + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "resource_type": resource_type, + } + self._uri = "/Exports/{resource_type}/Days".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DayInstance]: + """ + Streams DayInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DayInstance]: + """ + Asynchronously streams DayInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DayInstance]: + """ + Lists DayInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DayInstance]: + """ + Asynchronously lists DayInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DayPage: + """ + Retrieve a single page of DayInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DayInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DayPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DayPage: + """ + Asynchronously retrieve a single page of DayInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DayInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DayPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DayPage: + """ + Retrieve a specific page of DayInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DayInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DayPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DayPage: + """ + Asynchronously retrieve a specific page of DayInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DayInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DayPage(self._version, response, self._solution) + + def get(self, day: str) -> DayContext: + """ + Constructs a DayContext + + :param day: The ISO 8601 format date of the resources in the file, for a UTC day + """ + return DayContext( + self._version, resource_type=self._solution["resource_type"], day=day + ) + + def __call__(self, day: str) -> DayContext: + """ + Constructs a DayContext + + :param day: The ISO 8601 format date of the resources in the file, for a UTC day + """ + return DayContext( + self._version, resource_type=self._solution["resource_type"], day=day + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export/export_custom_job.py b/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export/export_custom_job.py new file mode 100644 index 00000000..72d0e9b3 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export/export_custom_job.py @@ -0,0 +1,400 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Bulkexports + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ExportCustomJobInstance(InstanceResource): + """ + :ivar friendly_name: The friendly name specified when creating the job + :ivar resource_type: The type of communication – Messages, Calls, Conferences, and Participants + :ivar start_day: The start day for the custom export specified when creating the job + :ivar end_day: The end day for the export specified when creating the job + :ivar webhook_url: The optional webhook url called on completion of the job. If this is supplied, `WebhookMethod` must also be supplied. + :ivar webhook_method: This is the method used to call the webhook on completion of the job. If this is supplied, `WebhookUrl` must also be supplied. + :ivar email: The optional email to send the completion notification to + :ivar job_sid: The unique job_sid returned when the custom export was created + :ivar details: The details of a job which is an object that contains an array of status grouped by `status` state. Each `status` object has a `status` string, a count which is the number of days in that `status`, and list of days in that `status`. The day strings are in the format yyyy-MM-dd. As an example, a currently running job may have a status object for COMPLETED and a `status` object for SUBMITTED each with its own count and list of days. + :ivar job_queue_position: This is the job position from the 1st in line. Your queue position will never increase. As jobs ahead of yours in the queue are processed, the queue position number will decrease + :ivar estimated_completion_time: this is the time estimated until your job is complete. This is calculated each time you request the job list. The time is calculated based on the current rate of job completion (which may vary) and your job queue position + """ + + def __init__(self, version: Version, payload: Dict[str, Any], resource_type: str): + super().__init__(version) + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.resource_type: Optional[str] = payload.get("resource_type") + self.start_day: Optional[str] = payload.get("start_day") + self.end_day: Optional[str] = payload.get("end_day") + self.webhook_url: Optional[str] = payload.get("webhook_url") + self.webhook_method: Optional[str] = payload.get("webhook_method") + self.email: Optional[str] = payload.get("email") + self.job_sid: Optional[str] = payload.get("job_sid") + self.details: Optional[Dict[str, object]] = payload.get("details") + self.job_queue_position: Optional[str] = payload.get("job_queue_position") + self.estimated_completion_time: Optional[str] = payload.get( + "estimated_completion_time" + ) + + self._solution = { + "resource_type": resource_type, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ExportCustomJobPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ExportCustomJobInstance: + """ + Build an instance of ExportCustomJobInstance + + :param payload: Payload response from the API + """ + return ExportCustomJobInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ExportCustomJobList(ListResource): + + def __init__(self, version: Version, resource_type: str): + """ + Initialize the ExportCustomJobList + + :param version: Version that contains the resource + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "resource_type": resource_type, + } + self._uri = "/Exports/{resource_type}/Jobs".format(**self._solution) + + def create( + self, + start_day: str, + end_day: str, + friendly_name: str, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ExportCustomJobInstance: + """ + Create the ExportCustomJobInstance + + :param start_day: The start day for the custom export specified as a string in the format of yyyy-mm-dd + :param end_day: The end day for the custom export specified as a string in the format of yyyy-mm-dd. End day is inclusive and must be 2 days earlier than the current UTC day. + :param friendly_name: The friendly name specified when creating the job + :param webhook_url: The optional webhook url called on completion of the job. If this is supplied, `WebhookMethod` must also be supplied. If you set neither webhook nor email, you will have to check your job's status manually. + :param webhook_method: This is the method used to call the webhook on completion of the job. If this is supplied, `WebhookUrl` must also be supplied. + :param email: The optional email to send the completion notification to. You can set both webhook, and email, or one or the other. If you set neither, the job will run but you will have to query to determine your job's status. + + :returns: The created ExportCustomJobInstance + """ + + data = values.of( + { + "StartDay": start_day, + "EndDay": end_day, + "FriendlyName": friendly_name, + "WebhookUrl": webhook_url, + "WebhookMethod": webhook_method, + "Email": email, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExportCustomJobInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + + async def create_async( + self, + start_day: str, + end_day: str, + friendly_name: str, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ExportCustomJobInstance: + """ + Asynchronously create the ExportCustomJobInstance + + :param start_day: The start day for the custom export specified as a string in the format of yyyy-mm-dd + :param end_day: The end day for the custom export specified as a string in the format of yyyy-mm-dd. End day is inclusive and must be 2 days earlier than the current UTC day. + :param friendly_name: The friendly name specified when creating the job + :param webhook_url: The optional webhook url called on completion of the job. If this is supplied, `WebhookMethod` must also be supplied. If you set neither webhook nor email, you will have to check your job's status manually. + :param webhook_method: This is the method used to call the webhook on completion of the job. If this is supplied, `WebhookUrl` must also be supplied. + :param email: The optional email to send the completion notification to. You can set both webhook, and email, or one or the other. If you set neither, the job will run but you will have to query to determine your job's status. + + :returns: The created ExportCustomJobInstance + """ + + data = values.of( + { + "StartDay": start_day, + "EndDay": end_day, + "FriendlyName": friendly_name, + "WebhookUrl": webhook_url, + "WebhookMethod": webhook_method, + "Email": email, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExportCustomJobInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ExportCustomJobInstance]: + """ + Streams ExportCustomJobInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ExportCustomJobInstance]: + """ + Asynchronously streams ExportCustomJobInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExportCustomJobInstance]: + """ + Lists ExportCustomJobInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExportCustomJobInstance]: + """ + Asynchronously lists ExportCustomJobInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ExportCustomJobPage: + """ + Retrieve a single page of ExportCustomJobInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ExportCustomJobInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExportCustomJobPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ExportCustomJobPage: + """ + Asynchronously retrieve a single page of ExportCustomJobInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ExportCustomJobInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExportCustomJobPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ExportCustomJobPage: + """ + Retrieve a specific page of ExportCustomJobInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ExportCustomJobInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ExportCustomJobPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ExportCustomJobPage: + """ + Asynchronously retrieve a specific page of ExportCustomJobInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ExportCustomJobInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ExportCustomJobPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export/job.py b/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export/job.py new file mode 100644 index 00000000..5358ffa8 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export/job.py @@ -0,0 +1,253 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Bulkexports + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class JobInstance(InstanceResource): + """ + :ivar resource_type: The type of communication – Messages, Calls, Conferences, and Participants + :ivar friendly_name: The friendly name specified when creating the job + :ivar details: The details of a job which is an object that contains an array of status grouped by `status` state. Each `status` object has a `status` string, a count which is the number of days in that `status`, and list of days in that `status`. The day strings are in the format yyyy-MM-dd. As an example, a currently running job may have a status object for COMPLETED and a `status` object for SUBMITTED each with its own count and list of days. + :ivar start_day: The start time for the export specified when creating the job + :ivar end_day: The end time for the export specified when creating the job + :ivar job_sid: The job_sid returned when the export was created + :ivar webhook_url: The optional webhook url called on completion + :ivar webhook_method: This is the method used to call the webhook + :ivar email: The optional email to send the completion notification to + :ivar url: + :ivar job_queue_position: This is the job position from the 1st in line. Your queue position will never increase. As jobs ahead of yours in the queue are processed, the queue position number will decrease + :ivar estimated_completion_time: this is the time estimated until your job is complete. This is calculated each time you request the job list. The time is calculated based on the current rate of job completion (which may vary) and your job queue position + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], job_sid: Optional[str] = None + ): + super().__init__(version) + + self.resource_type: Optional[str] = payload.get("resource_type") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.details: Optional[Dict[str, object]] = payload.get("details") + self.start_day: Optional[str] = payload.get("start_day") + self.end_day: Optional[str] = payload.get("end_day") + self.job_sid: Optional[str] = payload.get("job_sid") + self.webhook_url: Optional[str] = payload.get("webhook_url") + self.webhook_method: Optional[str] = payload.get("webhook_method") + self.email: Optional[str] = payload.get("email") + self.url: Optional[str] = payload.get("url") + self.job_queue_position: Optional[str] = payload.get("job_queue_position") + self.estimated_completion_time: Optional[str] = payload.get( + "estimated_completion_time" + ) + + self._solution = { + "job_sid": job_sid or self.job_sid, + } + self._context: Optional[JobContext] = None + + @property + def _proxy(self) -> "JobContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: JobContext for this JobInstance + """ + if self._context is None: + self._context = JobContext( + self._version, + job_sid=self._solution["job_sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the JobInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the JobInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "JobInstance": + """ + Fetch the JobInstance + + + :returns: The fetched JobInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "JobInstance": + """ + Asynchronous coroutine to fetch the JobInstance + + + :returns: The fetched JobInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class JobContext(InstanceContext): + + def __init__(self, version: Version, job_sid: str): + """ + Initialize the JobContext + + :param version: Version that contains the resource + :param job_sid: The unique string that that we created to identify the Bulk Export job + """ + super().__init__(version) + + # Path Solution + self._solution = { + "job_sid": job_sid, + } + self._uri = "/Exports/Jobs/{job_sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the JobInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the JobInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> JobInstance: + """ + Fetch the JobInstance + + + :returns: The fetched JobInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return JobInstance( + self._version, + payload, + job_sid=self._solution["job_sid"], + ) + + async def fetch_async(self) -> JobInstance: + """ + Asynchronous coroutine to fetch the JobInstance + + + :returns: The fetched JobInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return JobInstance( + self._version, + payload, + job_sid=self._solution["job_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class JobList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the JobList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, job_sid: str) -> JobContext: + """ + Constructs a JobContext + + :param job_sid: The unique string that that we created to identify the Bulk Export job + """ + return JobContext(self._version, job_sid=job_sid) + + def __call__(self, job_sid: str) -> JobContext: + """ + Constructs a JobContext + + :param job_sid: The unique string that that we created to identify the Bulk Export job + """ + return JobContext(self._version, job_sid=job_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export_configuration.py b/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export_configuration.py new file mode 100644 index 00000000..20764276 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/bulkexports/v1/export_configuration.py @@ -0,0 +1,312 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Bulkexports + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ExportConfigurationInstance(InstanceResource): + """ + :ivar enabled: If true, Twilio will automatically generate every day's file when the day is over. + :ivar webhook_url: Stores the URL destination for the method specified in webhook_method. + :ivar webhook_method: Sets whether Twilio should call a webhook URL when the automatic generation is complete, using GET or POST. The actual destination is set in the webhook_url + :ivar resource_type: The type of communication – Messages, Calls, Conferences, and Participants + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + resource_type: Optional[str] = None, + ): + super().__init__(version) + + self.enabled: Optional[bool] = payload.get("enabled") + self.webhook_url: Optional[str] = payload.get("webhook_url") + self.webhook_method: Optional[str] = payload.get("webhook_method") + self.resource_type: Optional[str] = payload.get("resource_type") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "resource_type": resource_type or self.resource_type, + } + self._context: Optional[ExportConfigurationContext] = None + + @property + def _proxy(self) -> "ExportConfigurationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ExportConfigurationContext for this ExportConfigurationInstance + """ + if self._context is None: + self._context = ExportConfigurationContext( + self._version, + resource_type=self._solution["resource_type"], + ) + return self._context + + def fetch(self) -> "ExportConfigurationInstance": + """ + Fetch the ExportConfigurationInstance + + + :returns: The fetched ExportConfigurationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ExportConfigurationInstance": + """ + Asynchronous coroutine to fetch the ExportConfigurationInstance + + + :returns: The fetched ExportConfigurationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> "ExportConfigurationInstance": + """ + Update the ExportConfigurationInstance + + :param enabled: If true, Twilio will automatically generate every day's file when the day is over. + :param webhook_url: Stores the URL destination for the method specified in webhook_method. + :param webhook_method: Sets whether Twilio should call a webhook URL when the automatic generation is complete, using GET or POST. The actual destination is set in the webhook_url + + :returns: The updated ExportConfigurationInstance + """ + return self._proxy.update( + enabled=enabled, + webhook_url=webhook_url, + webhook_method=webhook_method, + ) + + async def update_async( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> "ExportConfigurationInstance": + """ + Asynchronous coroutine to update the ExportConfigurationInstance + + :param enabled: If true, Twilio will automatically generate every day's file when the day is over. + :param webhook_url: Stores the URL destination for the method specified in webhook_method. + :param webhook_method: Sets whether Twilio should call a webhook URL when the automatic generation is complete, using GET or POST. The actual destination is set in the webhook_url + + :returns: The updated ExportConfigurationInstance + """ + return await self._proxy.update_async( + enabled=enabled, + webhook_url=webhook_url, + webhook_method=webhook_method, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ExportConfigurationContext(InstanceContext): + + def __init__(self, version: Version, resource_type: str): + """ + Initialize the ExportConfigurationContext + + :param version: Version that contains the resource + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants + """ + super().__init__(version) + + # Path Solution + self._solution = { + "resource_type": resource_type, + } + self._uri = "/Exports/{resource_type}/Configuration".format(**self._solution) + + def fetch(self) -> ExportConfigurationInstance: + """ + Fetch the ExportConfigurationInstance + + + :returns: The fetched ExportConfigurationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ExportConfigurationInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + ) + + async def fetch_async(self) -> ExportConfigurationInstance: + """ + Asynchronous coroutine to fetch the ExportConfigurationInstance + + + :returns: The fetched ExportConfigurationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ExportConfigurationInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + ) + + def update( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> ExportConfigurationInstance: + """ + Update the ExportConfigurationInstance + + :param enabled: If true, Twilio will automatically generate every day's file when the day is over. + :param webhook_url: Stores the URL destination for the method specified in webhook_method. + :param webhook_method: Sets whether Twilio should call a webhook URL when the automatic generation is complete, using GET or POST. The actual destination is set in the webhook_url + + :returns: The updated ExportConfigurationInstance + """ + + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + "WebhookUrl": webhook_url, + "WebhookMethod": webhook_method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExportConfigurationInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + + async def update_async( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> ExportConfigurationInstance: + """ + Asynchronous coroutine to update the ExportConfigurationInstance + + :param enabled: If true, Twilio will automatically generate every day's file when the day is over. + :param webhook_url: Stores the URL destination for the method specified in webhook_method. + :param webhook_method: Sets whether Twilio should call a webhook URL when the automatic generation is complete, using GET or POST. The actual destination is set in the webhook_url + + :returns: The updated ExportConfigurationInstance + """ + + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + "WebhookUrl": webhook_url, + "WebhookMethod": webhook_method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExportConfigurationInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ExportConfigurationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ExportConfigurationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, resource_type: str) -> ExportConfigurationContext: + """ + Constructs a ExportConfigurationContext + + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants + """ + return ExportConfigurationContext(self._version, resource_type=resource_type) + + def __call__(self, resource_type: str) -> ExportConfigurationContext: + """ + Constructs a ExportConfigurationContext + + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants + """ + return ExportConfigurationContext(self._version, resource_type=resource_type) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/ChatBase.py b/venv/Lib/site-packages/twilio/rest/chat/ChatBase.py new file mode 100644 index 00000000..6d8656da --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/ChatBase.py @@ -0,0 +1,66 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.chat.v1 import V1 +from twilio.rest.chat.v2 import V2 +from twilio.rest.chat.v3 import V3 + + +class ChatBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Chat Domain + + :returns: Domain for Chat + """ + super().__init__(twilio, "https://chat.twilio.com") + self._v1: Optional[V1] = None + self._v2: Optional[V2] = None + self._v3: Optional[V3] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Chat + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Chat + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + @property + def v3(self) -> V3: + """ + :returns: Versions v3 of Chat + """ + if self._v3 is None: + self._v3 = V3(self) + return self._v3 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/__init__.py b/venv/Lib/site-packages/twilio/rest/chat/__init__.py new file mode 100644 index 00000000..9608a0fd --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/__init__.py @@ -0,0 +1,35 @@ +from warnings import warn + +from twilio.rest.chat.ChatBase import ChatBase +from twilio.rest.chat.v2.credential import CredentialList +from twilio.rest.chat.v2.service import ServiceList +from twilio.rest.chat.v3.channel import ChannelList + + +class Chat(ChatBase): + @property + def credentials(self) -> CredentialList: + warn( + "credentials is deprecated. Use v2.credentials instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.credentials + + @property + def services(self) -> ServiceList: + warn( + "services is deprecated. Use v2.services instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.services + + @property + def channels(self) -> ChannelList: + warn( + "channels is deprecated. Use v3.channels instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v3.channels diff --git a/venv/Lib/site-packages/twilio/rest/chat/__pycache__/ChatBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/__pycache__/ChatBase.cpython-312.pyc new file mode 100644 index 00000000..2d69d80f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/__pycache__/ChatBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..dbc72f04 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/chat/v1/__init__.py new file mode 100644 index 00000000..d0ade9ee --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v1/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.chat.v1.credential import CredentialList +from twilio.rest.chat.v1.service import ServiceList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Chat + + :param domain: The Twilio.chat domain + """ + super().__init__(domain, "v1") + self._credentials: Optional[CredentialList] = None + self._services: Optional[ServiceList] = None + + @property + def credentials(self) -> CredentialList: + if self._credentials is None: + self._credentials = CredentialList(self) + return self._credentials + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..45ca2c6d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v1/__pycache__/credential.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v1/__pycache__/credential.cpython-312.pyc new file mode 100644 index 00000000..b43f677e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v1/__pycache__/credential.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v1/credential.py b/venv/Lib/site-packages/twilio/rest/chat/v1/credential.py new file mode 100644 index 00000000..3bd48b11 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v1/credential.py @@ -0,0 +1,711 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CredentialInstance(InstanceResource): + + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: The unique string that we created to identify the Credential resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Credential resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the Credential resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["CredentialInstance.PushService"] = payload.get("type") + self.sandbox: Optional[str] = payload.get("sandbox") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CredentialContext] = None + + @property + def _proxy(self) -> "CredentialContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CredentialInstance": + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CredentialInstance": + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CredentialContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialInstance: + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: + """ + Build an instance of CredentialInstance + + :param payload: Payload response from the API + """ + return CredentialInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CredentialList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CredentialList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Credentials" + + def create( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Create the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload) + + async def create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialInstance]: + """ + Streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialInstance]: + """ + Asynchronously streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Asynchronously lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Asynchronously retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response) + + def get_page(self, target_url: str) -> CredentialPage: + """ + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CredentialPage: + """ + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response) + + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. + """ + return CredentialContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. + """ + return CredentialContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/v1/service/__init__.py b/venv/Lib/site-packages/twilio/rest/chat/v1/service/__init__.py new file mode 100644 index 00000000..26fde402 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v1/service/__init__.py @@ -0,0 +1,1359 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.chat.v1.service.channel import ChannelList +from twilio.rest.chat.v1.service.role import RoleList +from twilio.rest.chat.v1.service.user import UserList + + +class ServiceInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Service resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Service resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar default_service_role_sid: The service role assigned to users when they are added to the service. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :ivar default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :ivar default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :ivar read_status_enabled: Whether the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature is enabled. The default is `true`. + :ivar reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) is enabled for this Service instance. The default is `false`. + :ivar typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :ivar consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :ivar limits: An object that describes the limits of the service instance. The `limits` object contains `channel_members` to describe the members/channel limit and `user_channels` to describe the channels/user limit. `channel_members` can be 1,000 or less, with a default of 250. `user_channels` can be 1,000 or less, with a default value of 100. + :ivar webhooks: An object that contains information about the webhooks configured for this service. + :ivar pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :ivar post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :ivar webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :ivar webhook_filters: The list of WebHook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :ivar notifications: The notification configuration for the Service instance. See [Push Notification Configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more information. + :ivar url: The absolute URL of the Service resource. + :ivar links: The absolute URLs of the Service's [Channels](https://www.twilio.com/docs/chat/api/channels), [Roles](https://www.twilio.com/docs/chat/api/roles), and [Users](https://www.twilio.com/docs/chat/api/users). + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.default_service_role_sid: Optional[str] = payload.get( + "default_service_role_sid" + ) + self.default_channel_role_sid: Optional[str] = payload.get( + "default_channel_role_sid" + ) + self.default_channel_creator_role_sid: Optional[str] = payload.get( + "default_channel_creator_role_sid" + ) + self.read_status_enabled: Optional[bool] = payload.get("read_status_enabled") + self.reachability_enabled: Optional[bool] = payload.get("reachability_enabled") + self.typing_indicator_timeout: Optional[int] = deserialize.integer( + payload.get("typing_indicator_timeout") + ) + self.consumption_report_interval: Optional[int] = deserialize.integer( + payload.get("consumption_report_interval") + ) + self.limits: Optional[Dict[str, object]] = payload.get("limits") + self.webhooks: Optional[Dict[str, object]] = payload.get("webhooks") + self.pre_webhook_url: Optional[str] = payload.get("pre_webhook_url") + self.post_webhook_url: Optional[str] = payload.get("post_webhook_url") + self.webhook_method: Optional[str] = payload.get("webhook_method") + self.webhook_filters: Optional[List[str]] = payload.get("webhook_filters") + self.notifications: Optional[Dict[str, object]] = payload.get("notifications") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of WebHook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhooks_on_message_send_url: The URL of the webhook to call in response to the `on_message_send` event using the `webhooks.on_message_send.method` HTTP method. + :param webhooks_on_message_send_method: The HTTP method to use when calling the `webhooks.on_message_send.url`. + :param webhooks_on_message_update_url: The URL of the webhook to call in response to the `on_message_update` event using the `webhooks.on_message_update.method` HTTP method. + :param webhooks_on_message_update_method: The HTTP method to use when calling the `webhooks.on_message_update.url`. + :param webhooks_on_message_remove_url: The URL of the webhook to call in response to the `on_message_remove` event using the `webhooks.on_message_remove.method` HTTP method. + :param webhooks_on_message_remove_method: The HTTP method to use when calling the `webhooks.on_message_remove.url`. + :param webhooks_on_channel_add_url: The URL of the webhook to call in response to the `on_channel_add` event using the `webhooks.on_channel_add.method` HTTP method. + :param webhooks_on_channel_add_method: The HTTP method to use when calling the `webhooks.on_channel_add.url`. + :param webhooks_on_channel_destroy_url: The URL of the webhook to call in response to the `on_channel_destroy` event using the `webhooks.on_channel_destroy.method` HTTP method. + :param webhooks_on_channel_destroy_method: The HTTP method to use when calling the `webhooks.on_channel_destroy.url`. + :param webhooks_on_channel_update_url: The URL of the webhook to call in response to the `on_channel_update` event using the `webhooks.on_channel_update.method` HTTP method. + :param webhooks_on_channel_update_method: The HTTP method to use when calling the `webhooks.on_channel_update.url`. + :param webhooks_on_member_add_url: The URL of the webhook to call in response to the `on_member_add` event using the `webhooks.on_member_add.method` HTTP method. + :param webhooks_on_member_add_method: The HTTP method to use when calling the `webhooks.on_member_add.url`. + :param webhooks_on_member_remove_url: The URL of the webhook to call in response to the `on_member_remove` event using the `webhooks.on_member_remove.method` HTTP method. + :param webhooks_on_member_remove_method: The HTTP method to use when calling the `webhooks.on_member_remove.url`. + :param webhooks_on_message_sent_url: The URL of the webhook to call in response to the `on_message_sent` event using the `webhooks.on_message_sent.method` HTTP method. + :param webhooks_on_message_sent_method: The URL of the webhook to call in response to the `on_message_sent` event`. + :param webhooks_on_message_updated_url: The URL of the webhook to call in response to the `on_message_updated` event using the `webhooks.on_message_updated.method` HTTP method. + :param webhooks_on_message_updated_method: The HTTP method to use when calling the `webhooks.on_message_updated.url`. + :param webhooks_on_message_removed_url: The URL of the webhook to call in response to the `on_message_removed` event using the `webhooks.on_message_removed.method` HTTP method. + :param webhooks_on_message_removed_method: The HTTP method to use when calling the `webhooks.on_message_removed.url`. + :param webhooks_on_channel_added_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_added.method` HTTP method. + :param webhooks_on_channel_added_method: The URL of the webhook to call in response to the `on_channel_added` event`. + :param webhooks_on_channel_destroyed_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_destroyed.method` HTTP method. + :param webhooks_on_channel_destroyed_method: The HTTP method to use when calling the `webhooks.on_channel_destroyed.url`. + :param webhooks_on_channel_updated_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_channel_updated_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_added_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_member_added_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_removed_url: The URL of the webhook to call in response to the `on_member_removed` event using the `webhooks.on_member_removed.method` HTTP method. + :param webhooks_on_member_removed_method: The HTTP method to use when calling the `webhooks.on_member_removed.url`. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of WebHook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhooks_on_message_send_url: The URL of the webhook to call in response to the `on_message_send` event using the `webhooks.on_message_send.method` HTTP method. + :param webhooks_on_message_send_method: The HTTP method to use when calling the `webhooks.on_message_send.url`. + :param webhooks_on_message_update_url: The URL of the webhook to call in response to the `on_message_update` event using the `webhooks.on_message_update.method` HTTP method. + :param webhooks_on_message_update_method: The HTTP method to use when calling the `webhooks.on_message_update.url`. + :param webhooks_on_message_remove_url: The URL of the webhook to call in response to the `on_message_remove` event using the `webhooks.on_message_remove.method` HTTP method. + :param webhooks_on_message_remove_method: The HTTP method to use when calling the `webhooks.on_message_remove.url`. + :param webhooks_on_channel_add_url: The URL of the webhook to call in response to the `on_channel_add` event using the `webhooks.on_channel_add.method` HTTP method. + :param webhooks_on_channel_add_method: The HTTP method to use when calling the `webhooks.on_channel_add.url`. + :param webhooks_on_channel_destroy_url: The URL of the webhook to call in response to the `on_channel_destroy` event using the `webhooks.on_channel_destroy.method` HTTP method. + :param webhooks_on_channel_destroy_method: The HTTP method to use when calling the `webhooks.on_channel_destroy.url`. + :param webhooks_on_channel_update_url: The URL of the webhook to call in response to the `on_channel_update` event using the `webhooks.on_channel_update.method` HTTP method. + :param webhooks_on_channel_update_method: The HTTP method to use when calling the `webhooks.on_channel_update.url`. + :param webhooks_on_member_add_url: The URL of the webhook to call in response to the `on_member_add` event using the `webhooks.on_member_add.method` HTTP method. + :param webhooks_on_member_add_method: The HTTP method to use when calling the `webhooks.on_member_add.url`. + :param webhooks_on_member_remove_url: The URL of the webhook to call in response to the `on_member_remove` event using the `webhooks.on_member_remove.method` HTTP method. + :param webhooks_on_member_remove_method: The HTTP method to use when calling the `webhooks.on_member_remove.url`. + :param webhooks_on_message_sent_url: The URL of the webhook to call in response to the `on_message_sent` event using the `webhooks.on_message_sent.method` HTTP method. + :param webhooks_on_message_sent_method: The URL of the webhook to call in response to the `on_message_sent` event`. + :param webhooks_on_message_updated_url: The URL of the webhook to call in response to the `on_message_updated` event using the `webhooks.on_message_updated.method` HTTP method. + :param webhooks_on_message_updated_method: The HTTP method to use when calling the `webhooks.on_message_updated.url`. + :param webhooks_on_message_removed_url: The URL of the webhook to call in response to the `on_message_removed` event using the `webhooks.on_message_removed.method` HTTP method. + :param webhooks_on_message_removed_method: The HTTP method to use when calling the `webhooks.on_message_removed.url`. + :param webhooks_on_channel_added_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_added.method` HTTP method. + :param webhooks_on_channel_added_method: The URL of the webhook to call in response to the `on_channel_added` event`. + :param webhooks_on_channel_destroyed_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_destroyed.method` HTTP method. + :param webhooks_on_channel_destroyed_method: The HTTP method to use when calling the `webhooks.on_channel_destroyed.url`. + :param webhooks_on_channel_updated_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_channel_updated_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_added_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_member_added_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_removed_url: The URL of the webhook to call in response to the `on_member_removed` event using the `webhooks.on_member_removed.method` HTTP method. + :param webhooks_on_member_removed_method: The HTTP method to use when calling the `webhooks.on_member_removed.url`. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + return self._proxy.channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + return self._proxy.roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + return self._proxy.users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._channels: Optional[ChannelList] = None + self._roles: Optional[RoleList] = None + self._users: Optional[UserList] = None + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of WebHook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhooks_on_message_send_url: The URL of the webhook to call in response to the `on_message_send` event using the `webhooks.on_message_send.method` HTTP method. + :param webhooks_on_message_send_method: The HTTP method to use when calling the `webhooks.on_message_send.url`. + :param webhooks_on_message_update_url: The URL of the webhook to call in response to the `on_message_update` event using the `webhooks.on_message_update.method` HTTP method. + :param webhooks_on_message_update_method: The HTTP method to use when calling the `webhooks.on_message_update.url`. + :param webhooks_on_message_remove_url: The URL of the webhook to call in response to the `on_message_remove` event using the `webhooks.on_message_remove.method` HTTP method. + :param webhooks_on_message_remove_method: The HTTP method to use when calling the `webhooks.on_message_remove.url`. + :param webhooks_on_channel_add_url: The URL of the webhook to call in response to the `on_channel_add` event using the `webhooks.on_channel_add.method` HTTP method. + :param webhooks_on_channel_add_method: The HTTP method to use when calling the `webhooks.on_channel_add.url`. + :param webhooks_on_channel_destroy_url: The URL of the webhook to call in response to the `on_channel_destroy` event using the `webhooks.on_channel_destroy.method` HTTP method. + :param webhooks_on_channel_destroy_method: The HTTP method to use when calling the `webhooks.on_channel_destroy.url`. + :param webhooks_on_channel_update_url: The URL of the webhook to call in response to the `on_channel_update` event using the `webhooks.on_channel_update.method` HTTP method. + :param webhooks_on_channel_update_method: The HTTP method to use when calling the `webhooks.on_channel_update.url`. + :param webhooks_on_member_add_url: The URL of the webhook to call in response to the `on_member_add` event using the `webhooks.on_member_add.method` HTTP method. + :param webhooks_on_member_add_method: The HTTP method to use when calling the `webhooks.on_member_add.url`. + :param webhooks_on_member_remove_url: The URL of the webhook to call in response to the `on_member_remove` event using the `webhooks.on_member_remove.method` HTTP method. + :param webhooks_on_member_remove_method: The HTTP method to use when calling the `webhooks.on_member_remove.url`. + :param webhooks_on_message_sent_url: The URL of the webhook to call in response to the `on_message_sent` event using the `webhooks.on_message_sent.method` HTTP method. + :param webhooks_on_message_sent_method: The URL of the webhook to call in response to the `on_message_sent` event`. + :param webhooks_on_message_updated_url: The URL of the webhook to call in response to the `on_message_updated` event using the `webhooks.on_message_updated.method` HTTP method. + :param webhooks_on_message_updated_method: The HTTP method to use when calling the `webhooks.on_message_updated.url`. + :param webhooks_on_message_removed_url: The URL of the webhook to call in response to the `on_message_removed` event using the `webhooks.on_message_removed.method` HTTP method. + :param webhooks_on_message_removed_method: The HTTP method to use when calling the `webhooks.on_message_removed.url`. + :param webhooks_on_channel_added_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_added.method` HTTP method. + :param webhooks_on_channel_added_method: The URL of the webhook to call in response to the `on_channel_added` event`. + :param webhooks_on_channel_destroyed_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_destroyed.method` HTTP method. + :param webhooks_on_channel_destroyed_method: The HTTP method to use when calling the `webhooks.on_channel_destroyed.url`. + :param webhooks_on_channel_updated_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_channel_updated_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_added_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_member_added_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_removed_url: The URL of the webhook to call in response to the `on_member_removed` event using the `webhooks.on_member_removed.method` HTTP method. + :param webhooks_on_member_removed_method: The HTTP method to use when calling the `webhooks.on_member_removed.url`. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Webhooks.OnMessageSend.Url": webhooks_on_message_send_url, + "Webhooks.OnMessageSend.Method": webhooks_on_message_send_method, + "Webhooks.OnMessageUpdate.Url": webhooks_on_message_update_url, + "Webhooks.OnMessageUpdate.Method": webhooks_on_message_update_method, + "Webhooks.OnMessageRemove.Url": webhooks_on_message_remove_url, + "Webhooks.OnMessageRemove.Method": webhooks_on_message_remove_method, + "Webhooks.OnChannelAdd.Url": webhooks_on_channel_add_url, + "Webhooks.OnChannelAdd.Method": webhooks_on_channel_add_method, + "Webhooks.OnChannelDestroy.Url": webhooks_on_channel_destroy_url, + "Webhooks.OnChannelDestroy.Method": webhooks_on_channel_destroy_method, + "Webhooks.OnChannelUpdate.Url": webhooks_on_channel_update_url, + "Webhooks.OnChannelUpdate.Method": webhooks_on_channel_update_method, + "Webhooks.OnMemberAdd.Url": webhooks_on_member_add_url, + "Webhooks.OnMemberAdd.Method": webhooks_on_member_add_method, + "Webhooks.OnMemberRemove.Url": webhooks_on_member_remove_url, + "Webhooks.OnMemberRemove.Method": webhooks_on_member_remove_method, + "Webhooks.OnMessageSent.Url": webhooks_on_message_sent_url, + "Webhooks.OnMessageSent.Method": webhooks_on_message_sent_method, + "Webhooks.OnMessageUpdated.Url": webhooks_on_message_updated_url, + "Webhooks.OnMessageUpdated.Method": webhooks_on_message_updated_method, + "Webhooks.OnMessageRemoved.Url": webhooks_on_message_removed_url, + "Webhooks.OnMessageRemoved.Method": webhooks_on_message_removed_method, + "Webhooks.OnChannelAdded.Url": webhooks_on_channel_added_url, + "Webhooks.OnChannelAdded.Method": webhooks_on_channel_added_method, + "Webhooks.OnChannelDestroyed.Url": webhooks_on_channel_destroyed_url, + "Webhooks.OnChannelDestroyed.Method": webhooks_on_channel_destroyed_method, + "Webhooks.OnChannelUpdated.Url": webhooks_on_channel_updated_url, + "Webhooks.OnChannelUpdated.Method": webhooks_on_channel_updated_method, + "Webhooks.OnMemberAdded.Url": webhooks_on_member_added_url, + "Webhooks.OnMemberAdded.Method": webhooks_on_member_added_method, + "Webhooks.OnMemberRemoved.Url": webhooks_on_member_removed_url, + "Webhooks.OnMemberRemoved.Method": webhooks_on_member_removed_method, + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of WebHook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhooks_on_message_send_url: The URL of the webhook to call in response to the `on_message_send` event using the `webhooks.on_message_send.method` HTTP method. + :param webhooks_on_message_send_method: The HTTP method to use when calling the `webhooks.on_message_send.url`. + :param webhooks_on_message_update_url: The URL of the webhook to call in response to the `on_message_update` event using the `webhooks.on_message_update.method` HTTP method. + :param webhooks_on_message_update_method: The HTTP method to use when calling the `webhooks.on_message_update.url`. + :param webhooks_on_message_remove_url: The URL of the webhook to call in response to the `on_message_remove` event using the `webhooks.on_message_remove.method` HTTP method. + :param webhooks_on_message_remove_method: The HTTP method to use when calling the `webhooks.on_message_remove.url`. + :param webhooks_on_channel_add_url: The URL of the webhook to call in response to the `on_channel_add` event using the `webhooks.on_channel_add.method` HTTP method. + :param webhooks_on_channel_add_method: The HTTP method to use when calling the `webhooks.on_channel_add.url`. + :param webhooks_on_channel_destroy_url: The URL of the webhook to call in response to the `on_channel_destroy` event using the `webhooks.on_channel_destroy.method` HTTP method. + :param webhooks_on_channel_destroy_method: The HTTP method to use when calling the `webhooks.on_channel_destroy.url`. + :param webhooks_on_channel_update_url: The URL of the webhook to call in response to the `on_channel_update` event using the `webhooks.on_channel_update.method` HTTP method. + :param webhooks_on_channel_update_method: The HTTP method to use when calling the `webhooks.on_channel_update.url`. + :param webhooks_on_member_add_url: The URL of the webhook to call in response to the `on_member_add` event using the `webhooks.on_member_add.method` HTTP method. + :param webhooks_on_member_add_method: The HTTP method to use when calling the `webhooks.on_member_add.url`. + :param webhooks_on_member_remove_url: The URL of the webhook to call in response to the `on_member_remove` event using the `webhooks.on_member_remove.method` HTTP method. + :param webhooks_on_member_remove_method: The HTTP method to use when calling the `webhooks.on_member_remove.url`. + :param webhooks_on_message_sent_url: The URL of the webhook to call in response to the `on_message_sent` event using the `webhooks.on_message_sent.method` HTTP method. + :param webhooks_on_message_sent_method: The URL of the webhook to call in response to the `on_message_sent` event`. + :param webhooks_on_message_updated_url: The URL of the webhook to call in response to the `on_message_updated` event using the `webhooks.on_message_updated.method` HTTP method. + :param webhooks_on_message_updated_method: The HTTP method to use when calling the `webhooks.on_message_updated.url`. + :param webhooks_on_message_removed_url: The URL of the webhook to call in response to the `on_message_removed` event using the `webhooks.on_message_removed.method` HTTP method. + :param webhooks_on_message_removed_method: The HTTP method to use when calling the `webhooks.on_message_removed.url`. + :param webhooks_on_channel_added_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_added.method` HTTP method. + :param webhooks_on_channel_added_method: The URL of the webhook to call in response to the `on_channel_added` event`. + :param webhooks_on_channel_destroyed_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_destroyed.method` HTTP method. + :param webhooks_on_channel_destroyed_method: The HTTP method to use when calling the `webhooks.on_channel_destroyed.url`. + :param webhooks_on_channel_updated_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_channel_updated_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_added_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_member_added_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_removed_url: The URL of the webhook to call in response to the `on_member_removed` event using the `webhooks.on_member_removed.method` HTTP method. + :param webhooks_on_member_removed_method: The HTTP method to use when calling the `webhooks.on_member_removed.url`. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Webhooks.OnMessageSend.Url": webhooks_on_message_send_url, + "Webhooks.OnMessageSend.Method": webhooks_on_message_send_method, + "Webhooks.OnMessageUpdate.Url": webhooks_on_message_update_url, + "Webhooks.OnMessageUpdate.Method": webhooks_on_message_update_method, + "Webhooks.OnMessageRemove.Url": webhooks_on_message_remove_url, + "Webhooks.OnMessageRemove.Method": webhooks_on_message_remove_method, + "Webhooks.OnChannelAdd.Url": webhooks_on_channel_add_url, + "Webhooks.OnChannelAdd.Method": webhooks_on_channel_add_method, + "Webhooks.OnChannelDestroy.Url": webhooks_on_channel_destroy_url, + "Webhooks.OnChannelDestroy.Method": webhooks_on_channel_destroy_method, + "Webhooks.OnChannelUpdate.Url": webhooks_on_channel_update_url, + "Webhooks.OnChannelUpdate.Method": webhooks_on_channel_update_method, + "Webhooks.OnMemberAdd.Url": webhooks_on_member_add_url, + "Webhooks.OnMemberAdd.Method": webhooks_on_member_add_method, + "Webhooks.OnMemberRemove.Url": webhooks_on_member_remove_url, + "Webhooks.OnMemberRemove.Method": webhooks_on_member_remove_method, + "Webhooks.OnMessageSent.Url": webhooks_on_message_sent_url, + "Webhooks.OnMessageSent.Method": webhooks_on_message_sent_method, + "Webhooks.OnMessageUpdated.Url": webhooks_on_message_updated_url, + "Webhooks.OnMessageUpdated.Method": webhooks_on_message_updated_method, + "Webhooks.OnMessageRemoved.Url": webhooks_on_message_removed_url, + "Webhooks.OnMessageRemoved.Method": webhooks_on_message_removed_method, + "Webhooks.OnChannelAdded.Url": webhooks_on_channel_added_url, + "Webhooks.OnChannelAdded.Method": webhooks_on_channel_added_method, + "Webhooks.OnChannelDestroyed.Url": webhooks_on_channel_destroyed_url, + "Webhooks.OnChannelDestroyed.Method": webhooks_on_channel_destroyed_method, + "Webhooks.OnChannelUpdated.Url": webhooks_on_channel_updated_url, + "Webhooks.OnChannelUpdated.Method": webhooks_on_channel_updated_method, + "Webhooks.OnMemberAdded.Url": webhooks_on_member_added_url, + "Webhooks.OnMemberAdded.Method": webhooks_on_member_added_method, + "Webhooks.OnMemberRemoved.Url": webhooks_on_member_removed_url, + "Webhooks.OnMemberRemoved.Method": webhooks_on_member_removed_method, + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + if self._channels is None: + self._channels = ChannelList( + self._version, + self._solution["sid"], + ) + return self._channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + if self._roles is None: + self._roles = RoleList( + self._version, + self._solution["sid"], + ) + return self._roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + if self._users is None: + self._users = UserList( + self._version, + self._solution["sid"], + ) + return self._users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def create(self, friendly_name: str) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async(self, friendly_name: str) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/v1/service/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v1/service/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..25478620 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v1/service/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v1/service/__pycache__/role.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v1/service/__pycache__/role.cpython-312.pyc new file mode 100644 index 00000000..6518b4db Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v1/service/__pycache__/role.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v1/service/channel/__init__.py b/venv/Lib/site-packages/twilio/rest/chat/v1/service/channel/__init__.py new file mode 100644 index 00000000..ffe42c0b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v1/service/channel/__init__.py @@ -0,0 +1,790 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.chat.v1.service.channel.invite import InviteList +from twilio.rest.chat.v1.service.channel.member import MemberList +from twilio.rest.chat.v1.service.channel.message import MessageList + + +class ChannelInstance(InstanceResource): + + class ChannelType(object): + PUBLIC = "public" + PRIVATE = "private" + + """ + :ivar sid: The unique string that we created to identify the Channel resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Channel resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :ivar attributes: The JSON string that stores application-specific data. **Note** If this property has been assigned a value, it's only displayed in a FETCH action that returns a single resource; otherwise, it's null. If the attributes have not been set, `{}` is returned. + :ivar type: + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar created_by: The `identity` of the User that created the channel. If the Channel was created by using the API, the value is `system`. + :ivar members_count: The number of Members in the Channel. + :ivar messages_count: The number of Messages in the Channel. + :ivar url: The absolute URL of the Channel resource. + :ivar links: The absolute URLs of the [Members](https://www.twilio.com/docs/chat/api/members), [Messages](https://www.twilio.com/docs/chat/api/messages) , [Invites](https://www.twilio.com/docs/chat/api/invites) and, if it exists, the last [Message](https://www.twilio.com/docs/chat/api/messages) for the Channel. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.attributes: Optional[str] = payload.get("attributes") + self.type: Optional["ChannelInstance.ChannelType"] = payload.get("type") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + self.members_count: Optional[int] = deserialize.integer( + payload.get("members_count") + ) + self.messages_count: Optional[int] = deserialize.integer( + payload.get("messages_count") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ChannelContext] = None + + @property + def _proxy(self) -> "ChannelContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ChannelContext for this ChannelInstance + """ + if self._context is None: + self._context = ChannelContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ChannelInstance": + """ + Fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ChannelInstance": + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Update the ChannelInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated ChannelInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Asynchronous coroutine to update the ChannelInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated ChannelInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + ) + + @property + def invites(self) -> InviteList: + """ + Access the invites + """ + return self._proxy.invites + + @property + def members(self) -> MemberList: + """ + Access the members + """ + return self._proxy.members + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ChannelContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the ChannelContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to update the resource from. + :param sid: The Twilio-provided string that uniquely identifies the Channel resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Channels/{sid}".format(**self._solution) + + self._invites: Optional[InviteList] = None + self._members: Optional[MemberList] = None + self._messages: Optional[MessageList] = None + + def delete(self) -> bool: + """ + Deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChannelInstance: + """ + Fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ChannelInstance: + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Update the ChannelInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronous coroutine to update the ChannelInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def invites(self) -> InviteList: + """ + Access the invites + """ + if self._invites is None: + self._invites = InviteList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._invites + + @property + def members(self) -> MemberList: + """ + Access the members + """ + if self._members is None: + self._members = MemberList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._members + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + if self._messages is None: + self._messages = MessageList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._messages + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: + """ + Build an instance of ChannelInstance + + :param payload: Payload response from the API + """ + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ChannelList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the ChannelList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Channels".format(**self._solution) + + def create( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> ChannelInstance: + """ + Create the ChannelInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param type: + + :returns: The created ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "Type": type, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronously create the ChannelInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param type: + + :returns: The created ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "Type": type, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChannelInstance]: + """ + Streams ChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(type=type, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ChannelInstance]: + """ + Asynchronously streams ChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(type=type, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: + """ + Lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + type=type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: + """ + Asynchronously lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + type=type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: + """ + Retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, self._solution) + + async def page_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: + """ + Asynchronously retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ChannelPage: + """ + Retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ChannelPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ChannelPage: + """ + Asynchronously retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelPage(self._version, response, self._solution) + + def get(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: The Twilio-provided string that uniquely identifies the Channel resource to update. + """ + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: The Twilio-provided string that uniquely identifies the Channel resource to update. + """ + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/v1/service/channel/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v1/service/channel/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..83ce4409 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v1/service/channel/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v1/service/channel/__pycache__/invite.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v1/service/channel/__pycache__/invite.cpython-312.pyc new file mode 100644 index 00000000..b1215606 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v1/service/channel/__pycache__/invite.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v1/service/channel/__pycache__/member.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v1/service/channel/__pycache__/member.cpython-312.pyc new file mode 100644 index 00000000..6b30da3b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v1/service/channel/__pycache__/member.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v1/service/channel/__pycache__/message.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v1/service/channel/__pycache__/message.cpython-312.pyc new file mode 100644 index 00000000..6b3ec688 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v1/service/channel/__pycache__/message.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v1/service/channel/invite.py b/venv/Lib/site-packages/twilio/rest/chat/v1/service/channel/invite.py new file mode 100644 index 00000000..e5cd4ebe --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v1/service/channel/invite.py @@ -0,0 +1,598 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InviteInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Invite resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Invite resource. + :ivar channel_sid: The SID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the resource belongs to. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + :ivar identity: The application-defined string that uniquely identifies the resource's [User](https://www.twilio.com/docs/api/chat/rest/users) within the [Service](https://www.twilio.com/docs/api/chat/rest/services). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more info. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the resource. + :ivar created_by: The `identity` of the User that created the invite. + :ivar url: The absolute URL of the Invite resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.created_by: Optional[str] = payload.get("created_by") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[InviteContext] = None + + @property + def _proxy(self) -> "InviteContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InviteContext for this InviteInstance + """ + if self._context is None: + self._context = InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "InviteInstance": + """ + Fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InviteInstance": + """ + Asynchronous coroutine to fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InviteContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the InviteContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to fetch the resource from. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the resource to fetch belongs to. + :param sid: The Twilio-provided string that uniquely identifies the Invite resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Invites/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> InviteInstance: + """ + Fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> InviteInstance: + """ + Asynchronous coroutine to fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InvitePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: + """ + Build an instance of InviteInstance + + :param payload: Payload response from the API + """ + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class InviteList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the InviteList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to read the resources from. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the resources to read belong to. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Invites".format( + **self._solution + ) + + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Create the InviteInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more info. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new member. + + :returns: The created InviteInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Asynchronously create the InviteInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more info. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new member. + + :returns: The created InviteInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InviteInstance]: + """ + Streams InviteInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InviteInstance]: + """ + Asynchronously streams InviteInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: + """ + Lists InviteInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: + """ + Asynchronously lists InviteInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InvitePage: + """ + Retrieve a single page of InviteInstance records from the API. + Request is executed immediately + + :param identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InviteInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InvitePage(self._version, response, self._solution) + + async def page_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InvitePage: + """ + Asynchronously retrieve a single page of InviteInstance records from the API. + Request is executed immediately + + :param identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InviteInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InvitePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> InvitePage: + """ + Retrieve a specific page of InviteInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InviteInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InvitePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> InvitePage: + """ + Asynchronously retrieve a specific page of InviteInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InviteInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InvitePage(self._version, response, self._solution) + + def get(self, sid: str) -> InviteContext: + """ + Constructs a InviteContext + + :param sid: The Twilio-provided string that uniquely identifies the Invite resource to fetch. + """ + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InviteContext: + """ + Constructs a InviteContext + + :param sid: The Twilio-provided string that uniquely identifies the Invite resource to fetch. + """ + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/v1/service/channel/member.py b/venv/Lib/site-packages/twilio/rest/chat/v1/service/channel/member.py new file mode 100644 index 00000000..1262703d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v1/service/channel/member.py @@ -0,0 +1,716 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MemberInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Member resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Member resource. + :ivar channel_sid: The unique ID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) for the member. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + :ivar identity: The application-defined string that uniquely identifies the resource's [User](https://www.twilio.com/docs/api/chat/rest/users) within the [Service](https://www.twilio.com/docs/api/chat/rest/services). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more info. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the member. + :ivar last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) in the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) that the Member has read. + :ivar last_consumption_timestamp: The ISO 8601 timestamp string that represents the date-time of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) read event for the Member within the [Channel](https://www.twilio.com/docs/api/chat/rest/channels). + :ivar url: The absolute URL of the Member resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.last_consumed_message_index: Optional[int] = deserialize.integer( + payload.get("last_consumed_message_index") + ) + self.last_consumption_timestamp: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("last_consumption_timestamp")) + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[MemberContext] = None + + @property + def _proxy(self) -> "MemberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MemberContext for this MemberInstance + """ + if self._context is None: + self._context = MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the MemberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MemberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "MemberInstance": + """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MemberInstance": + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> "MemberInstance": + """ + Update the MemberInstance + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) that the Member has read within the [Channel](https://www.twilio.com/docs/api/chat/rest/channels). + + :returns: The updated MemberInstance + """ + return self._proxy.update( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + ) + + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> "MemberInstance": + """ + Asynchronous coroutine to update the MemberInstance + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) that the Member has read within the [Channel](https://www.twilio.com/docs/api/chat/rest/channels). + + :returns: The updated MemberInstance + """ + return await self._proxy.update_async( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MemberContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the MemberContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to update the resource from. + :param channel_sid: The unique ID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the member to update belongs to. Can be the Channel resource's `sid` or `unique_name`. + :param sid: The Twilio-provided string that uniquely identifies the Member resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Members/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the MemberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MemberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MemberInstance: + """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MemberInstance: + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> MemberInstance: + """ + Update the MemberInstance + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) that the Member has read within the [Channel](https://www.twilio.com/docs/api/chat/rest/channels). + + :returns: The updated MemberInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> MemberInstance: + """ + Asynchronous coroutine to update the MemberInstance + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) that the Member has read within the [Channel](https://www.twilio.com/docs/api/chat/rest/channels). + + :returns: The updated MemberInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MemberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: + """ + Build an instance of MemberInstance + + :param payload: Payload response from the API + """ + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MemberList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MemberList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to read the resources from. + :param channel_sid: The unique ID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the members to read belong to. Can be the Channel resource's `sid` or `unique_name` value. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Members".format( + **self._solution + ) + + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> MemberInstance: + """ + Create the MemberInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/services). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + + :returns: The created MemberInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> MemberInstance: + """ + Asynchronously create the MemberInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/services). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + + :returns: The created MemberInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MemberInstance]: + """ + Streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MemberInstance]: + """ + Asynchronously streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: + """ + Lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: + """ + Asynchronously lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: + """ + Retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, self._solution) + + async def page_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: + """ + Asynchronously retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MemberPage: + """ + Retrieve a specific page of MemberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MemberPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MemberPage: + """ + Asynchronously retrieve a specific page of MemberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MemberPage(self._version, response, self._solution) + + def get(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param sid: The Twilio-provided string that uniquely identifies the Member resource to update. + """ + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param sid: The Twilio-provided string that uniquely identifies the Member resource to update. + """ + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/v1/service/channel/message.py b/venv/Lib/site-packages/twilio/rest/chat/v1/service/channel/message.py new file mode 100644 index 00000000..e7cfc921 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v1/service/channel/message.py @@ -0,0 +1,731 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MessageInstance(InstanceResource): + + class OrderType(object): + ASC = "asc" + DESC = "desc" + + """ + :ivar sid: The unique string that we created to identify the Message resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Message resource. + :ivar attributes: The JSON string that stores application-specific data. **Note** If this property has been assigned a value, it's only displayed in a FETCH action that returns a single resource; otherwise, it's null. If the attributes have not been set, `{}` is returned. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + :ivar to: The SID of the [Channel](https://www.twilio.com/docs/chat/api/channels) that the message was sent to. + :ivar channel_sid: The unique ID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the Message resource belongs to. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar was_edited: Whether the message has been edited since it was created. + :ivar _from: The [identity](https://www.twilio.com/docs/api/chat/guides/identity) of the message's author. The default value is `system`. + :ivar body: The content of the message. + :ivar index: The index of the message within the [Channel](https://www.twilio.com/docs/chat/api/channels). + :ivar url: The absolute URL of the Message resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.attributes: Optional[str] = payload.get("attributes") + self.service_sid: Optional[str] = payload.get("service_sid") + self.to: Optional[str] = payload.get("to") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.was_edited: Optional[bool] = payload.get("was_edited") + self._from: Optional[str] = payload.get("from") + self.body: Optional[str] = payload.get("body") + self.index: Optional[int] = deserialize.integer(payload.get("index")) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[MessageContext] = None + + @property + def _proxy(self) -> "MessageContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MessageContext for this MessageInstance + """ + if self._context is None: + self._context = MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "MessageInstance": + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MessageInstance": + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Update the MessageInstance + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated MessageInstance + """ + return self._proxy.update( + body=body, + attributes=attributes, + ) + + async def update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Asynchronous coroutine to update the MessageInstance + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated MessageInstance + """ + return await self._proxy.update_async( + body=body, + attributes=attributes, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MessageContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the MessageContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to update the resource from. + :param channel_sid: The unique ID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the message belongs to. Can be the Channel's `sid` or `unique_name`. + :param sid: The Twilio-provided string that uniquely identifies the Message resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Messages/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Update the MessageInstance + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Body": body, + "Attributes": attributes, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronous coroutine to update the MessageInstance + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Body": body, + "Attributes": attributes, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MessagePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: + """ + Build an instance of MessageInstance + + :param payload: Payload response from the API + """ + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MessageList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MessageList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to read the resources from. + :param channel_sid: The unique ID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the message to read belongs to. Can be the Channel's `sid` or `unique_name`. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Messages".format( + **self._solution + ) + + def create( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Create the MessageInstance + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param from_: The [identity](https://www.twilio.com/docs/api/chat/guides/identity) of the new message's author. The default value is `system`. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The created MessageInstance + """ + + data = values.of( + { + "Body": body, + "From": from_, + "Attributes": attributes, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param from_: The [identity](https://www.twilio.com/docs/api/chat/guides/identity) of the new message's author. The default value is `system`. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The created MessageInstance + """ + + data = values.of( + { + "Body": body, + "From": from_, + "Attributes": attributes, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: + """ + Streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(order=order, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessageInstance]: + """ + Asynchronously streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(order=order, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + order=order, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Asynchronously lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + order=order, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + async def page_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MessagePage: + """ + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MessagePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MessagePage: + """ + Asynchronously retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagePage(self._version, response, self._solution) + + def get(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: The Twilio-provided string that uniquely identifies the Message resource to update. + """ + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: The Twilio-provided string that uniquely identifies the Message resource to update. + """ + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/v1/service/role.py b/venv/Lib/site-packages/twilio/rest/chat/v1/service/role.py new file mode 100644 index 00000000..d81cbd55 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v1/service/role.py @@ -0,0 +1,645 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RoleInstance(InstanceResource): + + class RoleType(object): + CHANNEL = "channel" + DEPLOYMENT = "deployment" + + """ + :ivar sid: The unique string that we created to identify the Role resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Role resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar permissions: An array of the permissions the role has been granted, formatted as a JSON string. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the Role resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["RoleInstance.RoleType"] = payload.get("type") + self.permissions: Optional[List[str]] = payload.get("permissions") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[RoleContext] = None + + @property + def _proxy(self) -> "RoleContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RoleContext for this RoleInstance + """ + if self._context is None: + self._context = RoleContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RoleInstance": + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RoleInstance": + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + return await self._proxy.fetch_async() + + def update(self, permission: List[str]) -> "RoleInstance": + """ + Update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: The updated RoleInstance + """ + return self._proxy.update( + permission=permission, + ) + + async def update_async(self, permission: List[str]) -> "RoleInstance": + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: The updated RoleInstance + """ + return await self._proxy.update_async( + permission=permission, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RoleContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the RoleContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to update the resource from. + :param sid: The Twilio-provided string that uniquely identifies the Role resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Roles/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RoleInstance: + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update(self, permission: List[str]) -> RoleInstance: + """ + Update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: The updated RoleInstance + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, permission: List[str]) -> RoleInstance: + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: The updated RoleInstance + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RolePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: + """ + Build an instance of RoleInstance + + :param payload: Payload response from the API + """ + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RoleList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the RoleList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Roles".format(**self._solution) + + def create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: The created RoleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Asynchronously create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: The created RoleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoleInstance]: + """ + Streams RoleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RoleInstance]: + """ + Asynchronously streams RoleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: + """ + Lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: + """ + Asynchronously lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePage: + """ + Retrieve a single page of RoleInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePage: + """ + Asynchronously retrieve a single page of RoleInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RolePage: + """ + Retrieve a specific page of RoleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RolePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RolePage: + """ + Asynchronously retrieve a specific page of RoleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RolePage(self._version, response, self._solution) + + def get(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: The Twilio-provided string that uniquely identifies the Role resource to update. + """ + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: The Twilio-provided string that uniquely identifies the Role resource to update. + """ + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/v1/service/user/__init__.py b/venv/Lib/site-packages/twilio/rest/chat/v1/service/user/__init__.py new file mode 100644 index 00000000..c6b90095 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v1/service/user/__init__.py @@ -0,0 +1,723 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.chat.v1.service.user.user_channel import UserChannelList + + +class UserInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the User resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the User resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + :ivar attributes: The JSON string that stores application-specific data. **Note** If this property has been assigned a value, it's only displayed in a FETCH action that returns a single resource; otherwise, it's null. If the attributes have not been set, `{}` is returned. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the user. + :ivar identity: The application-defined string that uniquely identifies the resource's User within the [Service](https://www.twilio.com/docs/api/chat/rest/services). This value is often a username or an email address. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more info. + :ivar is_online: Whether the User is actively connected to the Service instance and online. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service's `reachability_enabled` is `false`, if the User has never been online for the Service instance, even if the Service's `reachability_enabled` is `true`. + :ivar is_notifiable: Whether the User has a potentially valid Push Notification registration (APN or GCM) for the Service instance. If at least one registration exists, `true`; otherwise `false`. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service's `reachability_enabled` is `false`, and if the User has never had a notification registration, even if the Service's `reachability_enabled` is `true`. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar joined_channels_count: The number of Channels this User is a Member of. + :ivar links: The absolute URLs of the [Channel](https://www.twilio.com/docs/chat/api/channels) and [Binding](https://www.twilio.com/docs/chat/rest/bindings-resource) resources related to the user. + :ivar url: The absolute URL of the User resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.attributes: Optional[str] = payload.get("attributes") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.role_sid: Optional[str] = payload.get("role_sid") + self.identity: Optional[str] = payload.get("identity") + self.is_online: Optional[bool] = payload.get("is_online") + self.is_notifiable: Optional[bool] = payload.get("is_notifiable") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.joined_channels_count: Optional[int] = deserialize.integer( + payload.get("joined_channels_count") + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[UserContext] = None + + @property + def _proxy(self) -> "UserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserContext for this UserInstance + """ + if self._context is None: + self._context = UserContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "UserInstance": + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserInstance": + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Update the UserInstance + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to this user. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: The updated UserInstance + """ + return self._proxy.update( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Asynchronous coroutine to update the UserInstance + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to this user. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: The updated UserInstance + """ + return await self._proxy.update_async( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + @property + def user_channels(self) -> UserChannelList: + """ + Access the user_channels + """ + return self._proxy.user_channels + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the UserContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to update the resource from. + :param sid: The Twilio-provided string that uniquely identifies the User resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Users/{sid}".format(**self._solution) + + self._user_channels: Optional[UserChannelList] = None + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Update the UserInstance + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to this user. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: The updated UserInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to this user. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: The updated UserInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def user_channels(self) -> UserChannelList: + """ + Access the user_channels + """ + if self._user_channels is None: + self._user_channels = UserChannelList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._user_channels + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: + """ + Build an instance of UserInstance + + :param payload: Payload response from the API + """ + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class UserList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the UserList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Users".format(**self._solution) + + def create( + self, + identity: str, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Create the UserInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). This value is often a username or email address. See the Identity documentation for more details. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. + + :returns: The created UserInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + identity: str, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). This value is often a username or email address. See the Identity documentation for more details. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. + + :returns: The created UserInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserInstance]: + """ + Streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserInstance]: + """ + Asynchronously streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Asynchronously lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Asynchronously retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserPage: + """ + Retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserPage: + """ + Asynchronously retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserPage(self._version, response, self._solution) + + def get(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: The Twilio-provided string that uniquely identifies the User resource to update. + """ + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: The Twilio-provided string that uniquely identifies the User resource to update. + """ + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/v1/service/user/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v1/service/user/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..4ec51577 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v1/service/user/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v1/service/user/__pycache__/user_channel.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v1/service/user/__pycache__/user_channel.cpython-312.pyc new file mode 100644 index 00000000..1a62f1c9 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v1/service/user/__pycache__/user_channel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v1/service/user/user_channel.py b/venv/Lib/site-packages/twilio/rest/chat/v1/service/user/user_channel.py new file mode 100644 index 00000000..b7f35aa9 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v1/service/user/user_channel.py @@ -0,0 +1,322 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UserChannelInstance(InstanceResource): + + class ChannelStatus(object): + JOINED = "joined" + INVITED = "invited" + NOT_PARTICIPATING = "not_participating" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the User Channel resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + :ivar channel_sid: The SID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the resource belongs to. + :ivar member_sid: The SID of a [Member](https://www.twilio.com/docs/api/chat/rest/members) that represents the User on the Channel. + :ivar status: + :ivar last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) in the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) that the Member has read. + :ivar unread_messages_count: The number of unread Messages in the Channel for the User. Note that retrieving messages on a client endpoint does not mean that messages are consumed or read. See [Consumption Horizon feature](/docs/api/chat/guides/consumption-horizon) to learn how to mark messages as consumed. + :ivar links: The absolute URLs of the [Members](https://www.twilio.com/docs/chat/api/members), [Messages](https://www.twilio.com/docs/chat/api/messages) , [Invites](https://www.twilio.com/docs/chat/api/invites) and, if it exists, the last [Message](https://www.twilio.com/docs/chat/api/messages) for the Channel. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], service_sid: str, user_sid: str + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.member_sid: Optional[str] = payload.get("member_sid") + self.status: Optional["UserChannelInstance.ChannelStatus"] = payload.get( + "status" + ) + self.last_consumed_message_index: Optional[int] = deserialize.integer( + payload.get("last_consumed_message_index") + ) + self.unread_messages_count: Optional[int] = deserialize.integer( + payload.get("unread_messages_count") + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: + """ + Build an instance of UserChannelInstance + + :param payload: Payload response from the API + """ + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class UserChannelList(ListResource): + + def __init__(self, version: Version, service_sid: str, user_sid: str): + """ + Initialize the UserChannelList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to read the resources from. + :param user_sid: The SID of the [User](https://www.twilio.com/docs/api/chat/rest/users) to read the User Channel resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + } + self._uri = "/Services/{service_sid}/Users/{user_sid}/Channels".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserChannelInstance]: + """ + Streams UserChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserChannelInstance]: + """ + Asynchronously streams UserChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: + """ + Lists UserChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: + """ + Asynchronously lists UserChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserChannelPage: + """ + Retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserChannelPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserChannelPage: + """ + Asynchronously retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserChannelPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserChannelPage: + """ + Retrieve a specific page of UserChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserChannelPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserChannelPage: + """ + Asynchronously retrieve a specific page of UserChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserChannelPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/__init__.py b/venv/Lib/site-packages/twilio/rest/chat/v2/__init__.py new file mode 100644 index 00000000..e949532d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v2/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.chat.v2.credential import CredentialList +from twilio.rest.chat.v2.service import ServiceList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Chat + + :param domain: The Twilio.chat domain + """ + super().__init__(domain, "v2") + self._credentials: Optional[CredentialList] = None + self._services: Optional[ServiceList] = None + + @property + def credentials(self) -> CredentialList: + if self._credentials is None: + self._credentials = CredentialList(self) + return self._credentials + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v2/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..663f8d52 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v2/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/__pycache__/credential.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v2/__pycache__/credential.cpython-312.pyc new file mode 100644 index 00000000..0e9d3dc8 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v2/__pycache__/credential.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/credential.py b/venv/Lib/site-packages/twilio/rest/chat/v2/credential.py new file mode 100644 index 00000000..5479abec --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v2/credential.py @@ -0,0 +1,711 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CredentialInstance(InstanceResource): + + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: The unique string that we created to identify the Credential resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Credential resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Credential resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["CredentialInstance.PushService"] = payload.get("type") + self.sandbox: Optional[str] = payload.get("sandbox") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CredentialContext] = None + + @property + def _proxy(self) -> "CredentialContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CredentialInstance": + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CredentialInstance": + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CredentialContext + + :param version: Version that contains the resource + :param sid: The SID of the Credential resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialInstance: + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: + """ + Build an instance of CredentialInstance + + :param payload: Payload response from the API + """ + return CredentialInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CredentialList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CredentialList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Credentials" + + def create( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Create the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload) + + async def create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialInstance]: + """ + Streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialInstance]: + """ + Asynchronously streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Asynchronously lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Asynchronously retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response) + + def get_page(self, target_url: str) -> CredentialPage: + """ + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CredentialPage: + """ + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response) + + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: The SID of the Credential resource to update. + """ + return CredentialContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: The SID of the Credential resource to update. + """ + return CredentialContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/service/__init__.py b/venv/Lib/site-packages/twilio/rest/chat/v2/service/__init__.py new file mode 100644 index 00000000..90a6c6cd --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v2/service/__init__.py @@ -0,0 +1,1128 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.chat.v2.service.binding import BindingList +from twilio.rest.chat.v2.service.channel import ChannelList +from twilio.rest.chat.v2.service.role import RoleList +from twilio.rest.chat.v2.service.user import UserList + + +class ServiceInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Service resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar default_service_role_sid: The service role assigned to users when they are added to the service. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :ivar default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :ivar default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :ivar read_status_enabled: Whether the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature is enabled. The default is `true`. + :ivar reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) is enabled for this Service instance. The default is `false`. + :ivar typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :ivar consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :ivar limits: An object that describes the limits of the service instance. The `limits` object contains `channel_members` to describe the members/channel limit and `user_channels` to describe the channels/user limit. `channel_members` can be 1,000 or less, with a default of 250. `user_channels` can be 1,000 or less, with a default value of 100. + :ivar pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :ivar post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :ivar webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :ivar webhook_filters: The list of webhook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :ivar pre_webhook_retry_count: The number of times to retry a call to the `pre_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. Default retry count is 0 times, which means the call won't be retried. + :ivar post_webhook_retry_count: The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won't be retried. + :ivar notifications: The notification configuration for the Service instance. See [Push Notification Configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :ivar media: An object that describes the properties of media that the service supports. The object contains the `size_limit_mb` property, which describes the size of the largest media file in MB; and the `compatibility_message` property, which contains the message text to send when a media message does not have any text. + :ivar url: The absolute URL of the Service resource. + :ivar links: The absolute URLs of the Service's [Channels](https://www.twilio.com/docs/chat/channels), [Roles](https://www.twilio.com/docs/chat/rest/role-resource), [Bindings](https://www.twilio.com/docs/chat/rest/binding-resource), and [Users](https://www.twilio.com/docs/chat/rest/user-resource). + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.default_service_role_sid: Optional[str] = payload.get( + "default_service_role_sid" + ) + self.default_channel_role_sid: Optional[str] = payload.get( + "default_channel_role_sid" + ) + self.default_channel_creator_role_sid: Optional[str] = payload.get( + "default_channel_creator_role_sid" + ) + self.read_status_enabled: Optional[bool] = payload.get("read_status_enabled") + self.reachability_enabled: Optional[bool] = payload.get("reachability_enabled") + self.typing_indicator_timeout: Optional[int] = deserialize.integer( + payload.get("typing_indicator_timeout") + ) + self.consumption_report_interval: Optional[int] = deserialize.integer( + payload.get("consumption_report_interval") + ) + self.limits: Optional[Dict[str, object]] = payload.get("limits") + self.pre_webhook_url: Optional[str] = payload.get("pre_webhook_url") + self.post_webhook_url: Optional[str] = payload.get("post_webhook_url") + self.webhook_method: Optional[str] = payload.get("webhook_method") + self.webhook_filters: Optional[List[str]] = payload.get("webhook_filters") + self.pre_webhook_retry_count: Optional[int] = deserialize.integer( + payload.get("pre_webhook_retry_count") + ) + self.post_webhook_retry_count: Optional[int] = deserialize.integer( + payload.get("post_webhook_retry_count") + ) + self.notifications: Optional[Dict[str, object]] = payload.get("notifications") + self.media: Optional[Dict[str, object]] = payload.get("media") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. The default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_sound: The name of the sound to play when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. The default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_added_to_channel_sound: The name of the sound to play when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. The default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_removed_from_channel_sound: The name of the sound to play to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. The default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param notifications_invited_to_channel_sound: The name of the sound to play when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of webhook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + :param media_compatibility_message: The message to send when a media message has no text. Can be used as placeholder message. + :param pre_webhook_retry_count: The number of times to retry a call to the `pre_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. Default retry count is 0 times, which means the call won't be retried. + :param post_webhook_retry_count: The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won't be retried. + :param notifications_log_enabled: Whether to log notifications. The default is `false`. + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. The default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_sound: The name of the sound to play when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. The default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_added_to_channel_sound: The name of the sound to play when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. The default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_removed_from_channel_sound: The name of the sound to play to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. The default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param notifications_invited_to_channel_sound: The name of the sound to play when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of webhook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + :param media_compatibility_message: The message to send when a media message has no text. Can be used as placeholder message. + :param pre_webhook_retry_count: The number of times to retry a call to the `pre_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. Default retry count is 0 times, which means the call won't be retried. + :param post_webhook_retry_count: The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won't be retried. + :param notifications_log_enabled: Whether to log notifications. The default is `false`. + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, + ) + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + return self._proxy.bindings + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + return self._proxy.channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + return self._proxy.roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + return self._proxy.users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: The SID of the Service resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._bindings: Optional[BindingList] = None + self._channels: Optional[ChannelList] = None + self._roles: Optional[RoleList] = None + self._users: Optional[UserList] = None + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. The default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_sound: The name of the sound to play when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. The default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_added_to_channel_sound: The name of the sound to play when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. The default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_removed_from_channel_sound: The name of the sound to play to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. The default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param notifications_invited_to_channel_sound: The name of the sound to play when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of webhook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + :param media_compatibility_message: The message to send when a media message has no text. Can be used as placeholder message. + :param pre_webhook_retry_count: The number of times to retry a call to the `pre_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. Default retry count is 0 times, which means the call won't be retried. + :param post_webhook_retry_count: The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won't be retried. + :param notifications_log_enabled: Whether to log notifications. The default is `false`. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.NewMessage.Sound": notifications_new_message_sound, + "Notifications.NewMessage.BadgeCountEnabled": serialize.boolean_to_string( + notifications_new_message_badge_count_enabled + ), + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.AddedToChannel.Sound": notifications_added_to_channel_sound, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.RemovedFromChannel.Sound": notifications_removed_from_channel_sound, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "Notifications.InvitedToChannel.Sound": notifications_invited_to_channel_sound, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + "Media.CompatibilityMessage": media_compatibility_message, + "PreWebhookRetryCount": pre_webhook_retry_count, + "PostWebhookRetryCount": post_webhook_retry_count, + "Notifications.LogEnabled": serialize.boolean_to_string( + notifications_log_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. The default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_sound: The name of the sound to play when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. The default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_added_to_channel_sound: The name of the sound to play when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. The default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_removed_from_channel_sound: The name of the sound to play to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. The default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param notifications_invited_to_channel_sound: The name of the sound to play when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of webhook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + :param media_compatibility_message: The message to send when a media message has no text. Can be used as placeholder message. + :param pre_webhook_retry_count: The number of times to retry a call to the `pre_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. Default retry count is 0 times, which means the call won't be retried. + :param post_webhook_retry_count: The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won't be retried. + :param notifications_log_enabled: Whether to log notifications. The default is `false`. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.NewMessage.Sound": notifications_new_message_sound, + "Notifications.NewMessage.BadgeCountEnabled": serialize.boolean_to_string( + notifications_new_message_badge_count_enabled + ), + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.AddedToChannel.Sound": notifications_added_to_channel_sound, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.RemovedFromChannel.Sound": notifications_removed_from_channel_sound, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "Notifications.InvitedToChannel.Sound": notifications_invited_to_channel_sound, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + "Media.CompatibilityMessage": media_compatibility_message, + "PreWebhookRetryCount": pre_webhook_retry_count, + "PostWebhookRetryCount": post_webhook_retry_count, + "Notifications.LogEnabled": serialize.boolean_to_string( + notifications_log_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + if self._bindings is None: + self._bindings = BindingList( + self._version, + self._solution["sid"], + ) + return self._bindings + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + if self._channels is None: + self._channels = ChannelList( + self._version, + self._solution["sid"], + ) + return self._channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + if self._roles is None: + self._roles = RoleList( + self._version, + self._solution["sid"], + ) + return self._roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + if self._users is None: + self._users = UserList( + self._version, + self._solution["sid"], + ) + return self._users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def create(self, friendly_name: str) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async(self, friendly_name: str) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The SID of the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The SID of the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/service/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v2/service/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..22927500 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v2/service/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/service/__pycache__/binding.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v2/service/__pycache__/binding.cpython-312.pyc new file mode 100644 index 00000000..271df665 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v2/service/__pycache__/binding.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/service/__pycache__/role.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v2/service/__pycache__/role.cpython-312.pyc new file mode 100644 index 00000000..8a9c9b6f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v2/service/__pycache__/role.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/service/binding.py b/venv/Lib/site-packages/twilio/rest/chat/v2/service/binding.py new file mode 100644 index 00000000..125f4b93 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v2/service/binding.py @@ -0,0 +1,536 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class BindingInstance(InstanceResource): + + class BindingType(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: The unique string that we created to identify the Binding resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Binding resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Binding resource is associated with. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar endpoint: The unique endpoint identifier for the Binding. The format of this value depends on the `binding_type`. + :ivar identity: The application-defined string that uniquely identifies the resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :ivar credential_sid: The SID of the [Credential](https://www.twilio.com/docs/chat/rest/credential-resource) for the binding. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :ivar binding_type: + :ivar message_types: The [Programmable Chat message types](https://www.twilio.com/docs/chat/push-notification-configuration#push-types) the binding is subscribed to. + :ivar url: The absolute URL of the Binding resource. + :ivar links: The absolute URLs of the Binding's [User](https://www.twilio.com/docs/chat/rest/user-resource). + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.endpoint: Optional[str] = payload.get("endpoint") + self.identity: Optional[str] = payload.get("identity") + self.credential_sid: Optional[str] = payload.get("credential_sid") + self.binding_type: Optional["BindingInstance.BindingType"] = payload.get( + "binding_type" + ) + self.message_types: Optional[List[str]] = payload.get("message_types") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[BindingContext] = None + + @property + def _proxy(self) -> "BindingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BindingContext for this BindingInstance + """ + if self._context is None: + self._context = BindingContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "BindingInstance": + """ + Fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BindingInstance": + """ + Asynchronous coroutine to fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BindingContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the BindingContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to fetch the Binding resource from. + :param sid: The SID of the Binding resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Bindings/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> BindingInstance: + """ + Fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> BindingInstance: + """ + Asynchronous coroutine to fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BindingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> BindingInstance: + """ + Build an instance of BindingInstance + + :param payload: Payload response from the API + """ + return BindingInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class BindingList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the BindingList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the Binding resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Bindings".format(**self._solution) + + def stream( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BindingInstance]: + """ + Streams BindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BindingInstance]: + """ + Asynchronously streams BindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BindingInstance]: + """ + Lists BindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BindingInstance]: + """ + Asynchronously lists BindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BindingPage: + """ + Retrieve a single page of BindingInstance records from the API. + Request is executed immediately + + :param binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BindingInstance + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BindingPage(self._version, response, self._solution) + + async def page_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BindingPage: + """ + Asynchronously retrieve a single page of BindingInstance records from the API. + Request is executed immediately + + :param binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BindingInstance + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BindingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> BindingPage: + """ + Retrieve a specific page of BindingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BindingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return BindingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> BindingPage: + """ + Asynchronously retrieve a specific page of BindingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BindingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return BindingPage(self._version, response, self._solution) + + def get(self, sid: str) -> BindingContext: + """ + Constructs a BindingContext + + :param sid: The SID of the Binding resource to fetch. + """ + return BindingContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> BindingContext: + """ + Constructs a BindingContext + + :param sid: The SID of the Binding resource to fetch. + """ + return BindingContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/__init__.py b/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/__init__.py new file mode 100644 index 00000000..36d08a38 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/__init__.py @@ -0,0 +1,962 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.chat.v2.service.channel.invite import InviteList +from twilio.rest.chat.v2.service.channel.member import MemberList +from twilio.rest.chat.v2.service.channel.message import MessageList +from twilio.rest.chat.v2.service.channel.webhook import WebhookList + + +class ChannelInstance(InstanceResource): + + class ChannelType(object): + PUBLIC = "public" + PRIVATE = "private" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: The unique string that we created to identify the Channel resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Channel resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Channel resource is associated with. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :ivar attributes: The JSON string that stores application-specific data. If attributes have not been set, `{}` is returned. + :ivar type: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar created_by: The `identity` of the User that created the channel. If the Channel was created by using the API, the value is `system`. + :ivar members_count: The number of Members in the Channel. + :ivar messages_count: The number of Messages that have been passed in the Channel. + :ivar url: The absolute URL of the Channel resource. + :ivar links: The absolute URLs of the [Members](https://www.twilio.com/docs/chat/rest/member-resource), [Messages](https://www.twilio.com/docs/chat/rest/message-resource), [Invites](https://www.twilio.com/docs/chat/rest/invite-resource), Webhooks and, if it exists, the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) for the Channel. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.attributes: Optional[str] = payload.get("attributes") + self.type: Optional["ChannelInstance.ChannelType"] = payload.get("type") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + self.members_count: Optional[int] = deserialize.integer( + payload.get("members_count") + ) + self.messages_count: Optional[int] = deserialize.integer( + payload.get("messages_count") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ChannelContext] = None + + @property + def _proxy(self) -> "ChannelContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ChannelContext for this ChannelInstance + """ + if self._context is None: + self._context = ChannelContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "ChannelInstance": + """ + Fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ChannelInstance": + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 256 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 256 characters or less in length and unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: The updated ChannelInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Asynchronous coroutine to update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 256 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 256 characters or less in length and unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: The updated ChannelInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + + @property + def invites(self) -> InviteList: + """ + Access the invites + """ + return self._proxy.invites + + @property + def members(self) -> MemberList: + """ + Access the members + """ + return self._proxy.members + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages + + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + return self._proxy.webhooks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ChannelContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the ChannelContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to update the Channel resource in. + :param sid: The SID of the Channel resource to update. This value can be either the `sid` or the `unique_name` of the Channel resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Channels/{sid}".format(**self._solution) + + self._invites: Optional[InviteList] = None + self._members: Optional[MemberList] = None + self._messages: Optional[MessageList] = None + self._webhooks: Optional[WebhookList] = None + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChannelInstance: + """ + Fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ChannelInstance: + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 256 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 256 characters or less in length and unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: The updated ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "CreatedBy": created_by, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronous coroutine to update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 256 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 256 characters or less in length and unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: The updated ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "CreatedBy": created_by, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def invites(self) -> InviteList: + """ + Access the invites + """ + if self._invites is None: + self._invites = InviteList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._invites + + @property + def members(self) -> MemberList: + """ + Access the members + """ + if self._members is None: + self._members = MemberList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._members + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + if self._messages is None: + self._messages = MessageList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._messages + + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + if self._webhooks is None: + self._webhooks = WebhookList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._webhooks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: + """ + Build an instance of ChannelInstance + + :param payload: Payload response from the API + """ + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ChannelList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the ChannelList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the Channel resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Channels".format(**self._solution) + + def create( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Create the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the Channel resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param type: + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used in cases where a Channel is being recreated from a backup/separate source and where a Message was previously updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: The created ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "Type": type, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "CreatedBy": created_by, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronously create the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the Channel resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param type: + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used in cases where a Channel is being recreated from a backup/separate source and where a Message was previously updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: The created ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "Type": type, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "CreatedBy": created_by, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChannelInstance]: + """ + Streams ChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(type=type, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ChannelInstance]: + """ + Asynchronously streams ChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(type=type, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: + """ + Lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + type=type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: + """ + Asynchronously lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + type=type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: + """ + Retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, self._solution) + + async def page_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: + """ + Asynchronously retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ChannelPage: + """ + Retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ChannelPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ChannelPage: + """ + Asynchronously retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelPage(self._version, response, self._solution) + + def get(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: The SID of the Channel resource to update. This value can be either the `sid` or the `unique_name` of the Channel resource to update. + """ + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: The SID of the Channel resource to update. This value can be either the `sid` or the `unique_name` of the Channel resource to update. + """ + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..c04e7427 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/__pycache__/invite.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/__pycache__/invite.cpython-312.pyc new file mode 100644 index 00000000..ab421e9f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/__pycache__/invite.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/__pycache__/member.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/__pycache__/member.cpython-312.pyc new file mode 100644 index 00000000..8954b798 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/__pycache__/member.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/__pycache__/message.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/__pycache__/message.cpython-312.pyc new file mode 100644 index 00000000..31d66a0e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/__pycache__/message.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/__pycache__/webhook.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/__pycache__/webhook.cpython-312.pyc new file mode 100644 index 00000000..bd4c0cb9 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/__pycache__/webhook.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/invite.py b/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/invite.py new file mode 100644 index 00000000..7c7f9f62 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/invite.py @@ -0,0 +1,598 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InviteInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Invite resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Invite resource. + :ivar channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Invite resource belongs to. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Invite resource is associated with. + :ivar identity: The application-defined string that uniquely identifies the resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the resource. + :ivar created_by: The `identity` of the User that created the invite. + :ivar url: The absolute URL of the Invite resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.created_by: Optional[str] = payload.get("created_by") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[InviteContext] = None + + @property + def _proxy(self) -> "InviteContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InviteContext for this InviteInstance + """ + if self._context is None: + self._context = InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "InviteInstance": + """ + Fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InviteInstance": + """ + Asynchronous coroutine to fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InviteContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the InviteContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to fetch the Invite resource from. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Invite resource to fetch belongs to. This value can be the Channel resource's `sid` or `unique_name`. + :param sid: The SID of the Invite resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Invites/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> InviteInstance: + """ + Fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> InviteInstance: + """ + Asynchronous coroutine to fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InvitePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: + """ + Build an instance of InviteInstance + + :param payload: Payload response from the API + """ + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class InviteList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the InviteList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the Invite resources from. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Invite resources to read belong to. This value can be the Channel resource's `sid` or `unique_name`. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Invites".format( + **self._solution + ) + + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Create the InviteInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the new member. + + :returns: The created InviteInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Asynchronously create the InviteInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the new member. + + :returns: The created InviteInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InviteInstance]: + """ + Streams InviteInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InviteInstance]: + """ + Asynchronously streams InviteInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: + """ + Lists InviteInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: + """ + Asynchronously lists InviteInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InvitePage: + """ + Retrieve a single page of InviteInstance records from the API. + Request is executed immediately + + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InviteInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InvitePage(self._version, response, self._solution) + + async def page_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InvitePage: + """ + Asynchronously retrieve a single page of InviteInstance records from the API. + Request is executed immediately + + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InviteInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InvitePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> InvitePage: + """ + Retrieve a specific page of InviteInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InviteInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InvitePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> InvitePage: + """ + Asynchronously retrieve a specific page of InviteInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InviteInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InvitePage(self._version, response, self._solution) + + def get(self, sid: str) -> InviteContext: + """ + Constructs a InviteContext + + :param sid: The SID of the Invite resource to fetch. + """ + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InviteContext: + """ + Constructs a InviteContext + + :param sid: The SID of the Invite resource to fetch. + """ + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/member.py b/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/member.py new file mode 100644 index 00000000..f07cb218 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/member.py @@ -0,0 +1,905 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MemberInstance(InstanceResource): + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: The unique string that we created to identify the Member resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Member resource. + :ivar channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Member resource belongs to. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Member resource is associated with. + :ivar identity: The application-defined string that uniquely identifies the resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the member. + :ivar last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + :ivar last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :ivar url: The absolute URL of the Member resource. + :ivar attributes: The JSON string that stores application-specific data. If attributes have not been set, `{}` is returned. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.last_consumed_message_index: Optional[int] = deserialize.integer( + payload.get("last_consumed_message_index") + ) + self.last_consumption_timestamp: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("last_consumption_timestamp")) + ) + self.url: Optional[str] = payload.get("url") + self.attributes: Optional[str] = payload.get("attributes") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[MemberContext] = None + + @property + def _proxy(self) -> "MemberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MemberContext for this MemberInstance + """ + if self._context is None: + self._context = MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "MemberInstance": + """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MemberInstance": + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MemberInstance": + """ + Update the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) that the Member has read within the [Channel](https://www.twilio.com/docs/chat/channels). + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated MemberInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MemberInstance": + """ + Asynchronous coroutine to update the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) that the Member has read within the [Channel](https://www.twilio.com/docs/chat/channels). + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated MemberInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MemberContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the MemberContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to update the Member resource in. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Member resource to update belongs to. This value can be the Channel resource's `sid` or `unique_name`. + :param sid: The SID of the Member resource to update. This value can be either the Member's `sid` or its `identity` value. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Members/{sid}".format( + **self._solution + ) + ) + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MemberInstance: + """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MemberInstance: + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MemberInstance: + """ + Update the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) that the Member has read within the [Channel](https://www.twilio.com/docs/chat/channels). + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated MemberInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MemberInstance: + """ + Asynchronous coroutine to update the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) that the Member has read within the [Channel](https://www.twilio.com/docs/chat/channels). + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated MemberInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MemberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: + """ + Build an instance of MemberInstance + + :param payload: Payload response from the API + """ + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MemberList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MemberList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the Member resources from. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Member resources to read belong to. This value can be the Channel resource's `sid` or `unique_name`. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Members".format( + **self._solution + ) + + def create( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MemberInstance: + """ + Create the MemberInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. This parameter should only be used when recreating a Member from a backup/separate source. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used when a Member is being recreated from a backup/separate source and where a Member was previously updated. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The created MemberInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MemberInstance: + """ + Asynchronously create the MemberInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. This parameter should only be used when recreating a Member from a backup/separate source. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used when a Member is being recreated from a backup/separate source and where a Member was previously updated. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The created MemberInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MemberInstance]: + """ + Streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MemberInstance]: + """ + Asynchronously streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: + """ + Lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: + """ + Asynchronously lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: + """ + Retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, self._solution) + + async def page_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: + """ + Asynchronously retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MemberPage: + """ + Retrieve a specific page of MemberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MemberPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MemberPage: + """ + Asynchronously retrieve a specific page of MemberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MemberPage(self._version, response, self._solution) + + def get(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param sid: The SID of the Member resource to update. This value can be either the Member's `sid` or its `identity` value. + """ + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param sid: The SID of the Member resource to update. This value can be either the Member's `sid` or its `identity` value. + """ + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/message.py b/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/message.py new file mode 100644 index 00000000..d0bf2e5a --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/message.py @@ -0,0 +1,905 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MessageInstance(InstanceResource): + + class OrderType(object): + ASC = "asc" + DESC = "desc" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: The unique string that we created to identify the Message resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Message resource. + :ivar attributes: The JSON string that stores application-specific data. If attributes have not been set, `{}` is returned. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Message resource is associated with. + :ivar to: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) that the message was sent to. + :ivar channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Message resource belongs to. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :ivar was_edited: Whether the message has been edited since it was created. + :ivar _from: The [Identity](https://www.twilio.com/docs/chat/identity) of the message's author. The default value is `system`. + :ivar body: The content of the message. + :ivar index: The index of the message within the [Channel](https://www.twilio.com/docs/chat/channels). Indices may skip numbers, but will always be in order of when the message was received. + :ivar type: The Message type. Can be: `text` or `media`. + :ivar media: An object that describes the Message's media, if the message contains media. The object contains these fields: `content_type` with the MIME type of the media, `filename` with the name of the media, `sid` with the SID of the Media resource, and `size` with the media object's file size in bytes. If the Message has no media, this value is `null`. + :ivar url: The absolute URL of the Message resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.attributes: Optional[str] = payload.get("attributes") + self.service_sid: Optional[str] = payload.get("service_sid") + self.to: Optional[str] = payload.get("to") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.last_updated_by: Optional[str] = payload.get("last_updated_by") + self.was_edited: Optional[bool] = payload.get("was_edited") + self._from: Optional[str] = payload.get("from") + self.body: Optional[str] = payload.get("body") + self.index: Optional[int] = deserialize.integer(payload.get("index")) + self.type: Optional[str] = payload.get("type") + self.media: Optional[Dict[str, object]] = payload.get("media") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[MessageContext] = None + + @property + def _proxy(self) -> "MessageContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MessageContext for this MessageInstance + """ + if self._context is None: + self._context = MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "MessageInstance": + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MessageInstance": + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the message's author. + + :returns: The updated MessageInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Asynchronous coroutine to update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the message's author. + + :returns: The updated MessageInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MessageContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the MessageContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to update the Message resource in. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Message resource to update belongs to. This value can be the Channel resource's `sid` or `unique_name`. + :param sid: The SID of the Message resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Messages/{sid}".format( + **self._solution + ) + ) + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the message's author. + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Body": body, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "LastUpdatedBy": last_updated_by, + "From": from_, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronous coroutine to update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the message's author. + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Body": body, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "LastUpdatedBy": last_updated_by, + "From": from_, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MessagePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: + """ + Build an instance of MessageInstance + + :param payload: Payload response from the API + """ + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MessageList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MessageList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the Message resources from. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Message resource to read belongs to. This value can be the Channel resource's `sid` or `unique_name`. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Messages".format( + **self._solution + ) + + def create( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the new message's author. The default value is `system`. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param media_sid: The SID of the [Media](https://www.twilio.com/docs/chat/rest/media) to attach to the new Message. + + :returns: The created MessageInstance + """ + + data = values.of( + { + "From": from_, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "LastUpdatedBy": last_updated_by, + "Body": body, + "MediaSid": media_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the new message's author. The default value is `system`. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param media_sid: The SID of the [Media](https://www.twilio.com/docs/chat/rest/media) to attach to the new Message. + + :returns: The created MessageInstance + """ + + data = values.of( + { + "From": from_, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "LastUpdatedBy": last_updated_by, + "Body": body, + "MediaSid": media_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: + """ + Streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(order=order, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessageInstance]: + """ + Asynchronously streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(order=order, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + order=order, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Asynchronously lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + order=order, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + async def page_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MessagePage: + """ + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MessagePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MessagePage: + """ + Asynchronously retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagePage(self._version, response, self._solution) + + def get(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: The SID of the Message resource to update. + """ + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: The SID of the Message resource to update. + """ + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/webhook.py b/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/webhook.py new file mode 100644 index 00000000..3e31df42 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v2/service/channel/webhook.py @@ -0,0 +1,800 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class WebhookInstance(InstanceResource): + + class Method(object): + GET = "GET" + POST = "POST" + + class Type(object): + WEBHOOK = "webhook" + TRIGGER = "trigger" + STUDIO = "studio" + + """ + :ivar sid: The unique string that we created to identify the Channel Webhook resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Channel Webhook resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Channel Webhook resource is associated with. + :ivar channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Channel Webhook resource belongs to. + :ivar type: The type of webhook. Can be: `webhook`, `studio`, or `trigger`. + :ivar url: The absolute URL of the Channel Webhook resource. + :ivar configuration: The JSON string that describes how the channel webhook is configured. The configuration object contains the `url`, `method`, `filters`, and `retry_count` values that are configured by the create and update actions. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.type: Optional[str] = payload.get("type") + self.url: Optional[str] = payload.get("url") + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[WebhookContext] = None + + @property + def _proxy(self) -> "WebhookContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WebhookContext for this WebhookInstance + """ + if self._context is None: + self._context = WebhookContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "WebhookInstance": + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "WebhookInstance": + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> "WebhookInstance": + """ + Update the WebhookInstance + + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` = `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + + :returns: The updated WebhookInstance + """ + return self._proxy.update( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + + async def update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> "WebhookInstance": + """ + Asynchronous coroutine to update the WebhookInstance + + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` = `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + + :returns: The updated WebhookInstance + """ + return await self._proxy.update_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WebhookContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the WebhookContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) with the Channel that has the Webhook resource to update. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Channel Webhook resource to update belongs to. This value can be the Channel resource's `sid` or `unique_name`. + :param sid: The SID of the Channel Webhook resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Webhooks/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Update the WebhookInstance + + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` = `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + "Configuration.RetryCount": configuration_retry_count, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronous coroutine to update the WebhookInstance + + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` = `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + "Configuration.RetryCount": configuration_retry_count, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WebhookPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: + """ + Build an instance of WebhookInstance + + :param payload: Payload response from the API + """ + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class WebhookList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the WebhookList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) with the Channel to read the resources from. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Channel Webhook resources to read belong to. This value can be the Channel resource's `sid` or `unique_name`. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Webhooks".format( + **self._solution + ) + + def create( + self, + type: "WebhookInstance.Type", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Create the WebhookInstance + + :param type: + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` is `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + + :returns: The created WebhookInstance + """ + + data = values.of( + { + "Type": type, + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + "Configuration.RetryCount": configuration_retry_count, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, + type: "WebhookInstance.Type", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronously create the WebhookInstance + + :param type: + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` is `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + + :returns: The created WebhookInstance + """ + + data = values.of( + { + "Type": type, + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + "Configuration.RetryCount": configuration_retry_count, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WebhookInstance]: + """ + Streams WebhookInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WebhookInstance]: + """ + Asynchronously streams WebhookInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: + """ + Lists WebhookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: + """ + Asynchronously lists WebhookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebhookPage: + """ + Retrieve a single page of WebhookInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebhookInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebhookPage: + """ + Asynchronously retrieve a single page of WebhookInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebhookInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> WebhookPage: + """ + Retrieve a specific page of WebhookInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebhookInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return WebhookPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> WebhookPage: + """ + Asynchronously retrieve a specific page of WebhookInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebhookInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return WebhookPage(self._version, response, self._solution) + + def get(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: The SID of the Channel Webhook resource to update. + """ + return WebhookContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: The SID of the Channel Webhook resource to update. + """ + return WebhookContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/service/role.py b/venv/Lib/site-packages/twilio/rest/chat/v2/service/role.py new file mode 100644 index 00000000..fef06436 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v2/service/role.py @@ -0,0 +1,645 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RoleInstance(InstanceResource): + + class RoleType(object): + CHANNEL = "channel" + DEPLOYMENT = "deployment" + + """ + :ivar sid: The unique string that we created to identify the Role resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Role resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Role resource is associated with. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar permissions: An array of the permissions the role has been granted. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Role resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["RoleInstance.RoleType"] = payload.get("type") + self.permissions: Optional[List[str]] = payload.get("permissions") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[RoleContext] = None + + @property + def _proxy(self) -> "RoleContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RoleContext for this RoleInstance + """ + if self._context is None: + self._context = RoleContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RoleInstance": + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RoleInstance": + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + return await self._proxy.fetch_async() + + def update(self, permission: List[str]) -> "RoleInstance": + """ + Update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + return self._proxy.update( + permission=permission, + ) + + async def update_async(self, permission: List[str]) -> "RoleInstance": + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + return await self._proxy.update_async( + permission=permission, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RoleContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the RoleContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to update the Role resource in. + :param sid: The SID of the Role resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Roles/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RoleInstance: + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update(self, permission: List[str]) -> RoleInstance: + """ + Update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, permission: List[str]) -> RoleInstance: + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RolePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: + """ + Build an instance of RoleInstance + + :param payload: Payload response from the API + """ + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RoleList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the RoleList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the Role resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Roles".format(**self._solution) + + def create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: The created RoleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Asynchronously create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: The created RoleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoleInstance]: + """ + Streams RoleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RoleInstance]: + """ + Asynchronously streams RoleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: + """ + Lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: + """ + Asynchronously lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePage: + """ + Retrieve a single page of RoleInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePage: + """ + Asynchronously retrieve a single page of RoleInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RolePage: + """ + Retrieve a specific page of RoleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RolePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RolePage: + """ + Asynchronously retrieve a specific page of RoleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RolePage(self._version, response, self._solution) + + def get(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: The SID of the Role resource to update. + """ + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: The SID of the Role resource to update. + """ + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/service/user/__init__.py b/venv/Lib/site-packages/twilio/rest/chat/v2/service/user/__init__.py new file mode 100644 index 00000000..9fbde6fe --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v2/service/user/__init__.py @@ -0,0 +1,804 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.chat.v2.service.user.user_binding import UserBindingList +from twilio.rest.chat.v2.service.user.user_channel import UserChannelList + + +class UserInstance(InstanceResource): + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: The unique string that we created to identify the User resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the User resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the User resource is associated with. + :ivar attributes: The JSON string that stores application-specific data. If attributes have not been set, `{}` is returned. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the user. + :ivar identity: The application-defined string that uniquely identifies the resource's User within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). This value is often a username or an email address, and is case-sensitive. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :ivar is_online: Whether the User is actively connected to the Service instance and online. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service's `reachability_enabled` is `false`, if the User has never been online for the Service instance, even if the Service's `reachability_enabled` is `true`. + :ivar is_notifiable: Whether the User has a potentially valid Push Notification registration (APN or GCM) for the Service instance. If at least one registration exists, `true`; otherwise `false`. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service's `reachability_enabled` is `false`, and if the User has never had a notification registration, even if the Service's `reachability_enabled` is `true`. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar joined_channels_count: The number of Channels the User is a Member of. + :ivar links: The absolute URLs of the [Channel](https://www.twilio.com/docs/chat/channels) and [Binding](https://www.twilio.com/docs/chat/rest/binding-resource) resources related to the user. + :ivar url: The absolute URL of the User resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.attributes: Optional[str] = payload.get("attributes") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.role_sid: Optional[str] = payload.get("role_sid") + self.identity: Optional[str] = payload.get("identity") + self.is_online: Optional[bool] = payload.get("is_online") + self.is_notifiable: Optional[bool] = payload.get("is_notifiable") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.joined_channels_count: Optional[int] = deserialize.integer( + payload.get("joined_channels_count") + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[UserContext] = None + + @property + def _proxy(self) -> "UserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserContext for this UserInstance + """ + if self._context is None: + self._context = UserContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "UserInstance": + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserInstance": + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: The updated UserInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Asynchronous coroutine to update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: The updated UserInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + @property + def user_bindings(self) -> UserBindingList: + """ + Access the user_bindings + """ + return self._proxy.user_bindings + + @property + def user_channels(self) -> UserChannelList: + """ + Access the user_channels + """ + return self._proxy.user_channels + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the UserContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to update the User resource in. + :param sid: The SID of the User resource to update. This value can be either the `sid` or the `identity` of the User resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Users/{sid}".format(**self._solution) + + self._user_bindings: Optional[UserBindingList] = None + self._user_channels: Optional[UserChannelList] = None + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: The updated UserInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: The updated UserInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def user_bindings(self) -> UserBindingList: + """ + Access the user_bindings + """ + if self._user_bindings is None: + self._user_bindings = UserBindingList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._user_bindings + + @property + def user_channels(self) -> UserChannelList: + """ + Access the user_channels + """ + if self._user_channels is None: + self._user_channels = UserChannelList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._user_channels + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: + """ + Build an instance of UserInstance + + :param payload: Payload response from the API + """ + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class UserList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the UserList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the User resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Users".format(**self._solution) + + def create( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Create the UserInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). This value is often a username or email address. See the Identity documentation for more info. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the new User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. + + :returns: The created UserInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). This value is often a username or email address. See the Identity documentation for more info. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the new User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. + + :returns: The created UserInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserInstance]: + """ + Streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserInstance]: + """ + Asynchronously streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Asynchronously lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Asynchronously retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserPage: + """ + Retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserPage: + """ + Asynchronously retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserPage(self._version, response, self._solution) + + def get(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: The SID of the User resource to update. This value can be either the `sid` or the `identity` of the User resource to update. + """ + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: The SID of the User resource to update. This value can be either the `sid` or the `identity` of the User resource to update. + """ + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/service/user/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v2/service/user/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..925d0e6f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v2/service/user/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/service/user/__pycache__/user_binding.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v2/service/user/__pycache__/user_binding.cpython-312.pyc new file mode 100644 index 00000000..6e43af16 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v2/service/user/__pycache__/user_binding.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/service/user/__pycache__/user_channel.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v2/service/user/__pycache__/user_channel.cpython-312.pyc new file mode 100644 index 00000000..6cccc1e4 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v2/service/user/__pycache__/user_channel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/service/user/user_binding.py b/venv/Lib/site-packages/twilio/rest/chat/v2/service/user/user_binding.py new file mode 100644 index 00000000..8d79c551 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v2/service/user/user_binding.py @@ -0,0 +1,552 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UserBindingInstance(InstanceResource): + + class BindingType(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: The unique string that we created to identify the User Binding resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the User Binding resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the User Binding resource is associated with. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar endpoint: The unique endpoint identifier for the User Binding. The format of the value depends on the `binding_type`. + :ivar identity: The application-defined string that uniquely identifies the resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :ivar user_sid: The SID of the [User](https://www.twilio.com/docs/chat/rest/user-resource) with the User Binding resource. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :ivar credential_sid: The SID of the [Credential](https://www.twilio.com/docs/chat/rest/credential-resource) for the binding. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :ivar binding_type: + :ivar message_types: The [Programmable Chat message types](https://www.twilio.com/docs/chat/push-notification-configuration#push-types) the binding is subscribed to. + :ivar url: The absolute URL of the User Binding resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + user_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.endpoint: Optional[str] = payload.get("endpoint") + self.identity: Optional[str] = payload.get("identity") + self.user_sid: Optional[str] = payload.get("user_sid") + self.credential_sid: Optional[str] = payload.get("credential_sid") + self.binding_type: Optional["UserBindingInstance.BindingType"] = payload.get( + "binding_type" + ) + self.message_types: Optional[List[str]] = payload.get("message_types") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "sid": sid or self.sid, + } + self._context: Optional[UserBindingContext] = None + + @property + def _proxy(self) -> "UserBindingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserBindingContext for this UserBindingInstance + """ + if self._context is None: + self._context = UserBindingContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UserBindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserBindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "UserBindingInstance": + """ + Fetch the UserBindingInstance + + + :returns: The fetched UserBindingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserBindingInstance": + """ + Asynchronous coroutine to fetch the UserBindingInstance + + + :returns: The fetched UserBindingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserBindingContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, user_sid: str, sid: str): + """ + Initialize the UserBindingContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to fetch the User Binding resource from. + :param user_sid: The SID of the [User](https://www.twilio.com/docs/chat/rest/user-resource) with the User Binding resource to fetch. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param sid: The SID of the User Binding resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Users/{user_sid}/Bindings/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the UserBindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserBindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserBindingInstance: + """ + Fetch the UserBindingInstance + + + :returns: The fetched UserBindingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> UserBindingInstance: + """ + Asynchronous coroutine to fetch the UserBindingInstance + + + :returns: The fetched UserBindingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserBindingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserBindingInstance: + """ + Build an instance of UserBindingInstance + + :param payload: Payload response from the API + """ + return UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class UserBindingList(ListResource): + + def __init__(self, version: Version, service_sid: str, user_sid: str): + """ + Initialize the UserBindingList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the User Binding resources from. + :param user_sid: The SID of the [User](https://www.twilio.com/docs/chat/rest/user-resource) with the User Binding resources to read. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + } + self._uri = "/Services/{service_sid}/Users/{user_sid}/Bindings".format( + **self._solution + ) + + def stream( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserBindingInstance]: + """ + Streams UserBindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["UserBindingInstance.BindingType"] binding_type: The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(binding_type=binding_type, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserBindingInstance]: + """ + Asynchronously streams UserBindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["UserBindingInstance.BindingType"] binding_type: The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + binding_type=binding_type, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserBindingInstance]: + """ + Lists UserBindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["UserBindingInstance.BindingType"] binding_type: The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + binding_type=binding_type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserBindingInstance]: + """ + Asynchronously lists UserBindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["UserBindingInstance.BindingType"] binding_type: The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + binding_type=binding_type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserBindingPage: + """ + Retrieve a single page of UserBindingInstance records from the API. + Request is executed immediately + + :param binding_type: The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserBindingInstance + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserBindingPage(self._version, response, self._solution) + + async def page_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserBindingPage: + """ + Asynchronously retrieve a single page of UserBindingInstance records from the API. + Request is executed immediately + + :param binding_type: The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserBindingInstance + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserBindingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserBindingPage: + """ + Retrieve a specific page of UserBindingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserBindingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserBindingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserBindingPage: + """ + Asynchronously retrieve a specific page of UserBindingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserBindingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserBindingPage(self._version, response, self._solution) + + def get(self, sid: str) -> UserBindingContext: + """ + Constructs a UserBindingContext + + :param sid: The SID of the User Binding resource to fetch. + """ + return UserBindingContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> UserBindingContext: + """ + Constructs a UserBindingContext + + :param sid: The SID of the User Binding resource to fetch. + """ + return UserBindingContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/v2/service/user/user_channel.py b/venv/Lib/site-packages/twilio/rest/chat/v2/service/user/user_channel.py new file mode 100644 index 00000000..9fab3573 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v2/service/user/user_channel.py @@ -0,0 +1,708 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UserChannelInstance(InstanceResource): + + class ChannelStatus(object): + JOINED = "joined" + INVITED = "invited" + NOT_PARTICIPATING = "not_participating" + + class NotificationLevel(object): + DEFAULT = "default" + MUTED = "muted" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the User Channel resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the User Channel resource is associated with. + :ivar channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the User Channel resource belongs to. + :ivar user_sid: The SID of the [User](https://www.twilio.com/docs/chat/rest/user-resource) the User Channel belongs to. + :ivar member_sid: The SID of a [Member](https://www.twilio.com/docs/chat/rest/member-resource) that represents the User on the Channel. + :ivar status: + :ivar last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + :ivar unread_messages_count: The number of unread Messages in the Channel for the User. Note that retrieving messages on a client endpoint does not mean that messages are consumed or read. See [Consumption Horizon feature](https://www.twilio.com/docs/chat/consumption-horizon) to learn how to mark messages as consumed. + :ivar links: The absolute URLs of the [Members](https://www.twilio.com/docs/chat/rest/member-resource), [Messages](https://www.twilio.com/docs/chat/rest/message-resource) , [Invites](https://www.twilio.com/docs/chat/rest/invite-resource) and, if it exists, the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) for the Channel. + :ivar url: The absolute URL of the User Channel resource. + :ivar notification_level: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + user_sid: str, + channel_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.user_sid: Optional[str] = payload.get("user_sid") + self.member_sid: Optional[str] = payload.get("member_sid") + self.status: Optional["UserChannelInstance.ChannelStatus"] = payload.get( + "status" + ) + self.last_consumed_message_index: Optional[int] = deserialize.integer( + payload.get("last_consumed_message_index") + ) + self.unread_messages_count: Optional[int] = deserialize.integer( + payload.get("unread_messages_count") + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + self.url: Optional[str] = payload.get("url") + self.notification_level: Optional["UserChannelInstance.NotificationLevel"] = ( + payload.get("notification_level") + ) + + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "channel_sid": channel_sid or self.channel_sid, + } + self._context: Optional[UserChannelContext] = None + + @property + def _proxy(self) -> "UserChannelContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserChannelContext for this UserChannelInstance + """ + if self._context is None: + self._context = UserChannelContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the UserChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the UserChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "UserChannelInstance": + """ + Fetch the UserChannelInstance + + + :returns: The fetched UserChannelInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserChannelInstance": + """ + Asynchronous coroutine to fetch the UserChannelInstance + + + :returns: The fetched UserChannelInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> "UserChannelInstance": + """ + Update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + + :returns: The updated UserChannelInstance + """ + return self._proxy.update( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + + async def update_async( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> "UserChannelInstance": + """ + Asynchronous coroutine to update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + + :returns: The updated UserChannelInstance + """ + return await self._proxy.update_async( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserChannelContext(InstanceContext): + + def __init__( + self, version: Version, service_sid: str, user_sid: str, channel_sid: str + ): + """ + Initialize the UserChannelContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to update the User Channel resource in. + :param user_sid: The SID of the [User](https://www.twilio.com/docs/chat/rest/user-resource) to update the User Channel resource from. This value can be either the `sid` or the `identity` of the User resource. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) with the User Channel resource to update. This value can be the Channel resource's `sid` or `unique_name`. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "channel_sid": channel_sid, + } + self._uri = ( + "/Services/{service_sid}/Users/{user_sid}/Channels/{channel_sid}".format( + **self._solution + ) + ) + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the UserChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the UserChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserChannelInstance: + """ + Fetch the UserChannelInstance + + + :returns: The fetched UserChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def fetch_async(self) -> UserChannelInstance: + """ + Asynchronous coroutine to fetch the UserChannelInstance + + + :returns: The fetched UserChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def update( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> UserChannelInstance: + """ + Update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + + :returns: The updated UserChannelInstance + """ + + data = values.of( + { + "NotificationLevel": notification_level, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def update_async( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> UserChannelInstance: + """ + Asynchronous coroutine to update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + + :returns: The updated UserChannelInstance + """ + + data = values.of( + { + "NotificationLevel": notification_level, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: + """ + Build an instance of UserChannelInstance + + :param payload: Payload response from the API + """ + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class UserChannelList(ListResource): + + def __init__(self, version: Version, service_sid: str, user_sid: str): + """ + Initialize the UserChannelList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the User Channel resources from. + :param user_sid: The SID of the [User](https://www.twilio.com/docs/chat/rest/user-resource) to read the User Channel resources from. This value can be either the `sid` or the `identity` of the User resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + } + self._uri = "/Services/{service_sid}/Users/{user_sid}/Channels".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserChannelInstance]: + """ + Streams UserChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserChannelInstance]: + """ + Asynchronously streams UserChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: + """ + Lists UserChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: + """ + Asynchronously lists UserChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserChannelPage: + """ + Retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserChannelPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserChannelPage: + """ + Asynchronously retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserChannelPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserChannelPage: + """ + Retrieve a specific page of UserChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserChannelPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserChannelPage: + """ + Asynchronously retrieve a specific page of UserChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserChannelPage(self._version, response, self._solution) + + def get(self, channel_sid: str) -> UserChannelContext: + """ + Constructs a UserChannelContext + + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) with the User Channel resource to update. This value can be the Channel resource's `sid` or `unique_name`. + """ + return UserChannelContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=channel_sid, + ) + + def __call__(self, channel_sid: str) -> UserChannelContext: + """ + Constructs a UserChannelContext + + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) with the User Channel resource to update. This value can be the Channel resource's `sid` or `unique_name`. + """ + return UserChannelContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=channel_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/v3/__init__.py b/venv/Lib/site-packages/twilio/rest/chat/v3/__init__.py new file mode 100644 index 00000000..582dc440 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v3/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.chat.v3.channel import ChannelList + + +class V3(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V3 version of Chat + + :param domain: The Twilio.chat domain + """ + super().__init__(domain, "v3") + self._channels: Optional[ChannelList] = None + + @property + def channels(self) -> ChannelList: + if self._channels is None: + self._channels = ChannelList(self) + return self._channels + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/chat/v3/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v3/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..4a4f6f15 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v3/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v3/__pycache__/channel.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/chat/v3/__pycache__/channel.cpython-312.pyc new file mode 100644 index 00000000..3211bc0e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/chat/v3/__pycache__/channel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/chat/v3/channel.py b/venv/Lib/site-packages/twilio/rest/chat/v3/channel.py new file mode 100644 index 00000000..4682838f --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/chat/v3/channel.py @@ -0,0 +1,325 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ChannelInstance(InstanceResource): + + class ChannelType(object): + PUBLIC = "public" + PRIVATE = "private" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: The unique string that we created to identify the Channel resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Channel resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Channel resource is associated with. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :ivar attributes: The JSON string that stores application-specific data. If attributes have not been set, `{}` is returned. + :ivar type: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar created_by: The `identity` of the User that created the channel. If the Channel was created by using the API, the value is `system`. + :ivar members_count: The number of Members in the Channel. + :ivar messages_count: The number of Messages that have been passed in the Channel. + :ivar messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this channel belongs to. + :ivar url: The absolute URL of the Channel resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: Optional[str] = None, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.attributes: Optional[str] = payload.get("attributes") + self.type: Optional["ChannelInstance.ChannelType"] = payload.get("type") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + self.members_count: Optional[int] = deserialize.integer( + payload.get("members_count") + ) + self.messages_count: Optional[int] = deserialize.integer( + payload.get("messages_count") + ) + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid or self.service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ChannelContext] = None + + @property + def _proxy(self) -> "ChannelContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ChannelContext for this ChannelInstance + """ + if self._context is None: + self._context = ChannelContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param type: + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this channel belongs to. + + :returns: The updated ChannelInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + type=type, + messaging_service_sid=messaging_service_sid, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Asynchronous coroutine to update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param type: + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this channel belongs to. + + :returns: The updated ChannelInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + type=type, + messaging_service_sid=messaging_service_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ChannelContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the ChannelContext + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param sid: A 34 character string that uniquely identifies this Channel. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Channels/{sid}".format(**self._solution) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param type: + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this channel belongs to. + + :returns: The updated ChannelInstance + """ + + data = values.of( + { + "Type": type, + "MessagingServiceSid": messaging_service_sid, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronous coroutine to update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param type: + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this channel belongs to. + + :returns: The updated ChannelInstance + """ + + data = values.of( + { + "Type": type, + "MessagingServiceSid": messaging_service_sid, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ChannelList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ChannelList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, service_sid: str, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param service_sid: The unique SID identifier of the Service. + :param sid: A 34 character string that uniquely identifies this Channel. + """ + return ChannelContext(self._version, service_sid=service_sid, sid=sid) + + def __call__(self, service_sid: str, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param service_sid: The unique SID identifier of the Service. + :param sid: A 34 character string that uniquely identifies this Channel. + """ + return ChannelContext(self._version, service_sid=service_sid, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/content/ContentBase.py b/venv/Lib/site-packages/twilio/rest/content/ContentBase.py new file mode 100644 index 00000000..8a1ccd5d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/content/ContentBase.py @@ -0,0 +1,55 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.content.v1 import V1 +from twilio.rest.content.v2 import V2 + + +class ContentBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Content Domain + + :returns: Domain for Content + """ + super().__init__(twilio, "https://content.twilio.com") + self._v1: Optional[V1] = None + self._v2: Optional[V2] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Content + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Content + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/content/__init__.py b/venv/Lib/site-packages/twilio/rest/content/__init__.py new file mode 100644 index 00000000..7663bd71 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/content/__init__.py @@ -0,0 +1,35 @@ +from warnings import warn + +from twilio.rest.content.ContentBase import ContentBase +from twilio.rest.content.v1.content import ContentList +from twilio.rest.content.v1.content_and_approvals import ContentAndApprovalsList +from twilio.rest.content.v1.legacy_content import LegacyContentList + + +class Content(ContentBase): + @property + def contents(self) -> ContentList: + warn( + "contents is deprecated. Use v1.contents instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.contents + + @property + def content_and_approvals(self) -> ContentAndApprovalsList: + warn( + "content_and_approvals is deprecated. Use v1.content_and_approvals instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.content_and_approvals + + @property + def legacy_contents(self) -> LegacyContentList: + warn( + "legacy_contents is deprecated. Use v1.legacy_contents instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.legacy_contents diff --git a/venv/Lib/site-packages/twilio/rest/content/__pycache__/ContentBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/content/__pycache__/ContentBase.cpython-312.pyc new file mode 100644 index 00000000..bd32dd00 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/content/__pycache__/ContentBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/content/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/content/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..db0a0192 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/content/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/content/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/content/v1/__init__.py new file mode 100644 index 00000000..1410fe47 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/content/v1/__init__.py @@ -0,0 +1,59 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Content + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.content.v1.content import ContentList +from twilio.rest.content.v1.content_and_approvals import ContentAndApprovalsList +from twilio.rest.content.v1.legacy_content import LegacyContentList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Content + + :param domain: The Twilio.content domain + """ + super().__init__(domain, "v1") + self._contents: Optional[ContentList] = None + self._content_and_approvals: Optional[ContentAndApprovalsList] = None + self._legacy_contents: Optional[LegacyContentList] = None + + @property + def contents(self) -> ContentList: + if self._contents is None: + self._contents = ContentList(self) + return self._contents + + @property + def content_and_approvals(self) -> ContentAndApprovalsList: + if self._content_and_approvals is None: + self._content_and_approvals = ContentAndApprovalsList(self) + return self._content_and_approvals + + @property + def legacy_contents(self) -> LegacyContentList: + if self._legacy_contents is None: + self._legacy_contents = LegacyContentList(self) + return self._legacy_contents + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/content/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/content/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..43407a63 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/content/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/content/v1/__pycache__/content_and_approvals.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/content/v1/__pycache__/content_and_approvals.cpython-312.pyc new file mode 100644 index 00000000..f54ec1d4 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/content/v1/__pycache__/content_and_approvals.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/content/v1/__pycache__/legacy_content.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/content/v1/__pycache__/legacy_content.cpython-312.pyc new file mode 100644 index 00000000..658f0cbe Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/content/v1/__pycache__/legacy_content.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/content/v1/content/__init__.py b/venv/Lib/site-packages/twilio/rest/content/v1/content/__init__.py new file mode 100644 index 00000000..44cc6a67 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/content/v1/content/__init__.py @@ -0,0 +1,2766 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Content + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.content.v1.content.approval_create import ApprovalCreateList +from twilio.rest.content.v1.content.approval_fetch import ApprovalFetchList + + +class ContentInstance(InstanceResource): + + class AuthenticationAction(object): + """ + :ivar type: + :ivar copy_code_text: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.AuthenticationActionType"] = ( + payload.get("type") + ) + self.copy_code_text: Optional[str] = payload.get("copy_code_text") + + def to_dict(self): + return { + "type": self.type, + "copy_code_text": self.copy_code_text, + } + + class CallToActionAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar code: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CallToActionActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + self.url: Optional[str] = payload.get("url") + self.phone: Optional[str] = payload.get("phone") + self.code: Optional[str] = payload.get("code") + self.id: Optional[str] = payload.get("id") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "code": self.code, + "id": self.id, + } + + class CardAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar id: + :ivar code: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CardActionType"] = payload.get("type") + self.title: Optional[str] = payload.get("title") + self.url: Optional[str] = payload.get("url") + self.phone: Optional[str] = payload.get("phone") + self.id: Optional[str] = payload.get("id") + self.code: Optional[str] = payload.get("code") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "id": self.id, + "code": self.code, + } + + class CarouselAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CarouselActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + self.url: Optional[str] = payload.get("url") + self.phone: Optional[str] = payload.get("phone") + self.id: Optional[str] = payload.get("id") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "id": self.id, + } + + class CarouselCard(object): + """ + :ivar title: + :ivar body: + :ivar media: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.body: Optional[str] = payload.get("body") + self.media: Optional[str] = payload.get("media") + self.actions: Optional[List[ContentList.CarouselAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "title": self.title, + "body": self.body, + "media": self.media, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class CatalogItem(object): + """ + :ivar id: + :ivar section_title: + :ivar name: + :ivar media_url: + :ivar price: + :ivar description: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.section_title: Optional[str] = payload.get("section_title") + self.name: Optional[str] = payload.get("name") + self.media_url: Optional[str] = payload.get("media_url") + self.price: Optional[float] = payload.get("price") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "id": self.id, + "section_title": self.section_title, + "name": self.name, + "media_url": self.media_url, + "price": self.price, + "description": self.description, + } + + class ContentCreateRequest(object): + """ + :ivar friendly_name: User defined name of the content + :ivar variables: Key value pairs of variable name to value + :ivar language: Language code for the content + :ivar types: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.variables: Optional[dict[str, str]] = payload.get("variables") + self.language: Optional[str] = payload.get("language") + self.types: Optional[ContentList.Types] = payload.get("types") + + def to_dict(self): + return { + "friendly_name": self.friendly_name, + "variables": self.variables, + "language": self.language, + "types": self.types.to_dict() if self.types is not None else None, + } + + class FlowsPage(object): + """ + :ivar id: + :ivar next_page_id: + :ivar title: + :ivar subtitle: + :ivar layout: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.next_page_id: Optional[str] = payload.get("next_page_id") + self.title: Optional[str] = payload.get("title") + self.subtitle: Optional[str] = payload.get("subtitle") + self.layout: Optional[List[ContentList.FlowsPageComponent]] = payload.get( + "layout" + ) + + def to_dict(self): + return { + "id": self.id, + "next_page_id": self.next_page_id, + "title": self.title, + "subtitle": self.subtitle, + "layout": ( + [layout.to_dict() for layout in self.layout] + if self.layout is not None + else None + ), + } + + class FlowsPageComponent(object): + """ + :ivar label: + :ivar type: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.label: Optional[str] = payload.get("label") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "label": self.label, + "type": self.type, + } + + class ListItem(object): + """ + :ivar id: + :ivar item: + :ivar description: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.item: Optional[str] = payload.get("item") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "id": self.id, + "item": self.item, + "description": self.description, + } + + class QuickReplyAction(object): + """ + :ivar type: + :ivar title: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.QuickReplyActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + self.id: Optional[str] = payload.get("id") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "id": self.id, + } + + class TwilioCallToAction(object): + """ + :ivar body: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.actions: Optional[List[ContentList.CallToActionAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class TwilioCard(object): + """ + :ivar title: + :ivar subtitle: + :ivar media: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.subtitle: Optional[str] = payload.get("subtitle") + self.media: Optional[List[str]] = payload.get("media") + self.actions: Optional[List[ContentList.CardAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "title": self.title, + "subtitle": self.subtitle, + "media": self.media, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class TwilioCarousel(object): + """ + :ivar body: + :ivar cards: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.cards: Optional[List[ContentList.CarouselCard]] = payload.get("cards") + + def to_dict(self): + return { + "body": self.body, + "cards": ( + [cards.to_dict() for cards in self.cards] + if self.cards is not None + else None + ), + } + + class TwilioCatalog(object): + """ + :ivar title: + :ivar body: + :ivar subtitle: + :ivar id: + :ivar items: + :ivar dynamic_items: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.body: Optional[str] = payload.get("body") + self.subtitle: Optional[str] = payload.get("subtitle") + self.id: Optional[str] = payload.get("id") + self.items: Optional[List[ContentList.CatalogItem]] = payload.get("items") + self.dynamic_items: Optional[str] = payload.get("dynamic_items") + + def to_dict(self): + return { + "title": self.title, + "body": self.body, + "subtitle": self.subtitle, + "id": self.id, + "items": ( + [items.to_dict() for items in self.items] + if self.items is not None + else None + ), + "dynamic_items": self.dynamic_items, + } + + class TwilioFlows(object): + """ + :ivar body: + :ivar button_text: + :ivar subtitle: + :ivar media_url: + :ivar pages: + :ivar type: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.button_text: Optional[str] = payload.get("button_text") + self.subtitle: Optional[str] = payload.get("subtitle") + self.media_url: Optional[str] = payload.get("media_url") + self.pages: Optional[List[ContentList.FlowsPage]] = payload.get("pages") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "body": self.body, + "button_text": self.button_text, + "subtitle": self.subtitle, + "media_url": self.media_url, + "pages": ( + [pages.to_dict() for pages in self.pages] + if self.pages is not None + else None + ), + "type": self.type, + } + + class TwilioListPicker(object): + """ + :ivar body: + :ivar button: + :ivar items: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.button: Optional[str] = payload.get("button") + self.items: Optional[List[ContentList.ListItem]] = payload.get("items") + + def to_dict(self): + return { + "body": self.body, + "button": self.button, + "items": ( + [items.to_dict() for items in self.items] + if self.items is not None + else None + ), + } + + class TwilioLocation(object): + """ + :ivar latitude: + :ivar longitude: + :ivar label: + :ivar id: + :ivar address: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.latitude: Optional[float] = payload.get("latitude") + self.longitude: Optional[float] = payload.get("longitude") + self.label: Optional[str] = payload.get("label") + self.id: Optional[str] = payload.get("id") + self.address: Optional[str] = payload.get("address") + + def to_dict(self): + return { + "latitude": self.latitude, + "longitude": self.longitude, + "label": self.label, + "id": self.id, + "address": self.address, + } + + class TwilioMedia(object): + """ + :ivar body: + :ivar media: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.media: Optional[List[str]] = payload.get("media") + + def to_dict(self): + return { + "body": self.body, + "media": self.media, + } + + class TwilioQuickReply(object): + """ + :ivar body: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.actions: Optional[List[ContentList.QuickReplyAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class TwilioSchedule(object): + """ + :ivar id: + :ivar title: + :ivar time_slots: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.title: Optional[str] = payload.get("title") + self.time_slots: Optional[str] = payload.get("time_slots") + + def to_dict(self): + return { + "id": self.id, + "title": self.title, + "time_slots": self.time_slots, + } + + class TwilioText(object): + """ + :ivar body: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + + def to_dict(self): + return { + "body": self.body, + } + + class Types(object): + """ + :ivar twilio_text: + :ivar twilio_media: + :ivar twilio_location: + :ivar twilio_list_picker: + :ivar twilio_call_to_action: + :ivar twilio_quick_reply: + :ivar twilio_card: + :ivar twilio_catalog: + :ivar twilio_carousel: + :ivar twilio_flows: + :ivar twilio_schedule: + :ivar whatsapp_card: + :ivar whatsapp_authentication: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.twilio_text: Optional[ContentList.TwilioText] = payload.get( + "twilio_text" + ) + self.twilio_media: Optional[ContentList.TwilioMedia] = payload.get( + "twilio_media" + ) + self.twilio_location: Optional[ContentList.TwilioLocation] = payload.get( + "twilio_location" + ) + self.twilio_list_picker: Optional[ContentList.TwilioListPicker] = ( + payload.get("twilio_list_picker") + ) + self.twilio_call_to_action: Optional[ContentList.TwilioCallToAction] = ( + payload.get("twilio_call_to_action") + ) + self.twilio_quick_reply: Optional[ContentList.TwilioQuickReply] = ( + payload.get("twilio_quick_reply") + ) + self.twilio_card: Optional[ContentList.TwilioCard] = payload.get( + "twilio_card" + ) + self.twilio_catalog: Optional[ContentList.TwilioCatalog] = payload.get( + "twilio_catalog" + ) + self.twilio_carousel: Optional[ContentList.TwilioCarousel] = payload.get( + "twilio_carousel" + ) + self.twilio_flows: Optional[ContentList.TwilioFlows] = payload.get( + "twilio_flows" + ) + self.twilio_schedule: Optional[ContentList.TwilioSchedule] = payload.get( + "twilio_schedule" + ) + self.whatsapp_card: Optional[ContentList.WhatsappCard] = payload.get( + "whatsapp_card" + ) + self.whatsapp_authentication: Optional[ + ContentList.WhatsappAuthentication + ] = payload.get("whatsapp_authentication") + + def to_dict(self): + return { + "twilio_text": ( + self.twilio_text.to_dict() if self.twilio_text is not None else None + ), + "twilio_media": ( + self.twilio_media.to_dict() + if self.twilio_media is not None + else None + ), + "twilio_location": ( + self.twilio_location.to_dict() + if self.twilio_location is not None + else None + ), + "twilio_list_picker": ( + self.twilio_list_picker.to_dict() + if self.twilio_list_picker is not None + else None + ), + "twilio_call_to_action": ( + self.twilio_call_to_action.to_dict() + if self.twilio_call_to_action is not None + else None + ), + "twilio_quick_reply": ( + self.twilio_quick_reply.to_dict() + if self.twilio_quick_reply is not None + else None + ), + "twilio_card": ( + self.twilio_card.to_dict() if self.twilio_card is not None else None + ), + "twilio_catalog": ( + self.twilio_catalog.to_dict() + if self.twilio_catalog is not None + else None + ), + "twilio_carousel": ( + self.twilio_carousel.to_dict() + if self.twilio_carousel is not None + else None + ), + "twilio_flows": ( + self.twilio_flows.to_dict() + if self.twilio_flows is not None + else None + ), + "twilio_schedule": ( + self.twilio_schedule.to_dict() + if self.twilio_schedule is not None + else None + ), + "whatsapp_card": ( + self.whatsapp_card.to_dict() + if self.whatsapp_card is not None + else None + ), + "whatsapp_authentication": ( + self.whatsapp_authentication.to_dict() + if self.whatsapp_authentication is not None + else None + ), + } + + class WhatsappAuthentication(object): + """ + :ivar add_security_recommendation: + :ivar code_expiration_minutes: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.add_security_recommendation: Optional[bool] = payload.get( + "add_security_recommendation" + ) + self.code_expiration_minutes: Optional[float] = payload.get( + "code_expiration_minutes" + ) + self.actions: Optional[List[ContentList.AuthenticationAction]] = ( + payload.get("actions") + ) + + def to_dict(self): + return { + "add_security_recommendation": self.add_security_recommendation, + "code_expiration_minutes": self.code_expiration_minutes, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class WhatsappCard(object): + """ + :ivar body: + :ivar footer: + :ivar media: + :ivar header_text: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.footer: Optional[str] = payload.get("footer") + self.media: Optional[List[str]] = payload.get("media") + self.header_text: Optional[str] = payload.get("header_text") + self.actions: Optional[List[ContentList.CardAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "footer": self.footer, + "media": self.media, + "header_text": self.header_text, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class AuthenticationActionType(object): + COPY_CODE = "COPY_CODE" + + class CallToActionActionType(object): + URL = "URL" + PHONE_NUMBER = "PHONE_NUMBER" + COPY_CODE = "COPY_CODE" + VOICE_CALL = "VOICE_CALL" + VOICE_CALL_REQUEST = "VOICE_CALL_REQUEST" + + class CardActionType(object): + URL = "URL" + PHONE_NUMBER = "PHONE_NUMBER" + QUICK_REPLY = "QUICK_REPLY" + COPY_CODE = "COPY_CODE" + VOICE_CALL = "VOICE_CALL" + + class CarouselActionType(object): + URL = "URL" + PHONE_NUMBER = "PHONE_NUMBER" + QUICK_REPLY = "QUICK_REPLY" + + class QuickReplyActionType(object): + QUICK_REPLY = "QUICK_REPLY" + + """ + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar sid: The unique string that that we created to identify the Content resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/usage/api/account) that created Content resource. + :ivar friendly_name: A string name used to describe the Content resource. Not visible to the end recipient. + :ivar language: Two-letter (ISO 639-1) language code (e.g., en) identifying the language the Content resource is in. + :ivar variables: Defines the default placeholder values for variables included in the Content resource. e.g. {\"1\": \"Customer_Name\"}. + :ivar types: The [Content types](https://www.twilio.com/docs/content-api/content-types-overview) (e.g. twilio/text) for this Content resource. + :ivar url: The URL of the resource, relative to `https://content.twilio.com`. + :ivar links: A list of links related to the Content resource, such as approval_fetch and approval_create + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.language: Optional[str] = payload.get("language") + self.variables: Optional[Dict[str, object]] = payload.get("variables") + self.types: Optional[Dict[str, object]] = payload.get("types") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ContentContext] = None + + @property + def _proxy(self) -> "ContentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ContentContext for this ContentInstance + """ + if self._context is None: + self._context = ContentContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ContentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ContentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ContentInstance": + """ + Fetch the ContentInstance + + + :returns: The fetched ContentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ContentInstance": + """ + Asynchronous coroutine to fetch the ContentInstance + + + :returns: The fetched ContentInstance + """ + return await self._proxy.fetch_async() + + @property + def approval_create(self) -> ApprovalCreateList: + """ + Access the approval_create + """ + return self._proxy.approval_create + + @property + def approval_fetch(self) -> ApprovalFetchList: + """ + Access the approval_fetch + """ + return self._proxy.approval_fetch + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ContentContext(InstanceContext): + + class AuthenticationAction(object): + """ + :ivar type: + :ivar copy_code_text: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.AuthenticationActionType"] = ( + payload.get("type") + ) + self.copy_code_text: Optional[str] = payload.get("copy_code_text") + + def to_dict(self): + return { + "type": self.type, + "copy_code_text": self.copy_code_text, + } + + class CallToActionAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar code: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CallToActionActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + self.url: Optional[str] = payload.get("url") + self.phone: Optional[str] = payload.get("phone") + self.code: Optional[str] = payload.get("code") + self.id: Optional[str] = payload.get("id") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "code": self.code, + "id": self.id, + } + + class CardAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar id: + :ivar code: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CardActionType"] = payload.get("type") + self.title: Optional[str] = payload.get("title") + self.url: Optional[str] = payload.get("url") + self.phone: Optional[str] = payload.get("phone") + self.id: Optional[str] = payload.get("id") + self.code: Optional[str] = payload.get("code") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "id": self.id, + "code": self.code, + } + + class CarouselAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CarouselActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + self.url: Optional[str] = payload.get("url") + self.phone: Optional[str] = payload.get("phone") + self.id: Optional[str] = payload.get("id") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "id": self.id, + } + + class CarouselCard(object): + """ + :ivar title: + :ivar body: + :ivar media: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.body: Optional[str] = payload.get("body") + self.media: Optional[str] = payload.get("media") + self.actions: Optional[List[ContentList.CarouselAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "title": self.title, + "body": self.body, + "media": self.media, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class CatalogItem(object): + """ + :ivar id: + :ivar section_title: + :ivar name: + :ivar media_url: + :ivar price: + :ivar description: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.section_title: Optional[str] = payload.get("section_title") + self.name: Optional[str] = payload.get("name") + self.media_url: Optional[str] = payload.get("media_url") + self.price: Optional[float] = payload.get("price") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "id": self.id, + "section_title": self.section_title, + "name": self.name, + "media_url": self.media_url, + "price": self.price, + "description": self.description, + } + + class ContentCreateRequest(object): + """ + :ivar friendly_name: User defined name of the content + :ivar variables: Key value pairs of variable name to value + :ivar language: Language code for the content + :ivar types: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.variables: Optional[dict[str, str]] = payload.get("variables") + self.language: Optional[str] = payload.get("language") + self.types: Optional[ContentList.Types] = payload.get("types") + + def to_dict(self): + return { + "friendly_name": self.friendly_name, + "variables": self.variables, + "language": self.language, + "types": self.types.to_dict() if self.types is not None else None, + } + + class FlowsPage(object): + """ + :ivar id: + :ivar next_page_id: + :ivar title: + :ivar subtitle: + :ivar layout: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.next_page_id: Optional[str] = payload.get("next_page_id") + self.title: Optional[str] = payload.get("title") + self.subtitle: Optional[str] = payload.get("subtitle") + self.layout: Optional[List[ContentList.FlowsPageComponent]] = payload.get( + "layout" + ) + + def to_dict(self): + return { + "id": self.id, + "next_page_id": self.next_page_id, + "title": self.title, + "subtitle": self.subtitle, + "layout": ( + [layout.to_dict() for layout in self.layout] + if self.layout is not None + else None + ), + } + + class FlowsPageComponent(object): + """ + :ivar label: + :ivar type: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.label: Optional[str] = payload.get("label") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "label": self.label, + "type": self.type, + } + + class ListItem(object): + """ + :ivar id: + :ivar item: + :ivar description: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.item: Optional[str] = payload.get("item") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "id": self.id, + "item": self.item, + "description": self.description, + } + + class QuickReplyAction(object): + """ + :ivar type: + :ivar title: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.QuickReplyActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + self.id: Optional[str] = payload.get("id") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "id": self.id, + } + + class TwilioCallToAction(object): + """ + :ivar body: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.actions: Optional[List[ContentList.CallToActionAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class TwilioCard(object): + """ + :ivar title: + :ivar subtitle: + :ivar media: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.subtitle: Optional[str] = payload.get("subtitle") + self.media: Optional[List[str]] = payload.get("media") + self.actions: Optional[List[ContentList.CardAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "title": self.title, + "subtitle": self.subtitle, + "media": self.media, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class TwilioCarousel(object): + """ + :ivar body: + :ivar cards: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.cards: Optional[List[ContentList.CarouselCard]] = payload.get("cards") + + def to_dict(self): + return { + "body": self.body, + "cards": ( + [cards.to_dict() for cards in self.cards] + if self.cards is not None + else None + ), + } + + class TwilioCatalog(object): + """ + :ivar title: + :ivar body: + :ivar subtitle: + :ivar id: + :ivar items: + :ivar dynamic_items: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.body: Optional[str] = payload.get("body") + self.subtitle: Optional[str] = payload.get("subtitle") + self.id: Optional[str] = payload.get("id") + self.items: Optional[List[ContentList.CatalogItem]] = payload.get("items") + self.dynamic_items: Optional[str] = payload.get("dynamic_items") + + def to_dict(self): + return { + "title": self.title, + "body": self.body, + "subtitle": self.subtitle, + "id": self.id, + "items": ( + [items.to_dict() for items in self.items] + if self.items is not None + else None + ), + "dynamic_items": self.dynamic_items, + } + + class TwilioFlows(object): + """ + :ivar body: + :ivar button_text: + :ivar subtitle: + :ivar media_url: + :ivar pages: + :ivar type: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.button_text: Optional[str] = payload.get("button_text") + self.subtitle: Optional[str] = payload.get("subtitle") + self.media_url: Optional[str] = payload.get("media_url") + self.pages: Optional[List[ContentList.FlowsPage]] = payload.get("pages") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "body": self.body, + "button_text": self.button_text, + "subtitle": self.subtitle, + "media_url": self.media_url, + "pages": ( + [pages.to_dict() for pages in self.pages] + if self.pages is not None + else None + ), + "type": self.type, + } + + class TwilioListPicker(object): + """ + :ivar body: + :ivar button: + :ivar items: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.button: Optional[str] = payload.get("button") + self.items: Optional[List[ContentList.ListItem]] = payload.get("items") + + def to_dict(self): + return { + "body": self.body, + "button": self.button, + "items": ( + [items.to_dict() for items in self.items] + if self.items is not None + else None + ), + } + + class TwilioLocation(object): + """ + :ivar latitude: + :ivar longitude: + :ivar label: + :ivar id: + :ivar address: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.latitude: Optional[float] = payload.get("latitude") + self.longitude: Optional[float] = payload.get("longitude") + self.label: Optional[str] = payload.get("label") + self.id: Optional[str] = payload.get("id") + self.address: Optional[str] = payload.get("address") + + def to_dict(self): + return { + "latitude": self.latitude, + "longitude": self.longitude, + "label": self.label, + "id": self.id, + "address": self.address, + } + + class TwilioMedia(object): + """ + :ivar body: + :ivar media: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.media: Optional[List[str]] = payload.get("media") + + def to_dict(self): + return { + "body": self.body, + "media": self.media, + } + + class TwilioQuickReply(object): + """ + :ivar body: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.actions: Optional[List[ContentList.QuickReplyAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class TwilioSchedule(object): + """ + :ivar id: + :ivar title: + :ivar time_slots: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.title: Optional[str] = payload.get("title") + self.time_slots: Optional[str] = payload.get("time_slots") + + def to_dict(self): + return { + "id": self.id, + "title": self.title, + "time_slots": self.time_slots, + } + + class TwilioText(object): + """ + :ivar body: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + + def to_dict(self): + return { + "body": self.body, + } + + class Types(object): + """ + :ivar twilio_text: + :ivar twilio_media: + :ivar twilio_location: + :ivar twilio_list_picker: + :ivar twilio_call_to_action: + :ivar twilio_quick_reply: + :ivar twilio_card: + :ivar twilio_catalog: + :ivar twilio_carousel: + :ivar twilio_flows: + :ivar twilio_schedule: + :ivar whatsapp_card: + :ivar whatsapp_authentication: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.twilio_text: Optional[ContentList.TwilioText] = payload.get( + "twilio_text" + ) + self.twilio_media: Optional[ContentList.TwilioMedia] = payload.get( + "twilio_media" + ) + self.twilio_location: Optional[ContentList.TwilioLocation] = payload.get( + "twilio_location" + ) + self.twilio_list_picker: Optional[ContentList.TwilioListPicker] = ( + payload.get("twilio_list_picker") + ) + self.twilio_call_to_action: Optional[ContentList.TwilioCallToAction] = ( + payload.get("twilio_call_to_action") + ) + self.twilio_quick_reply: Optional[ContentList.TwilioQuickReply] = ( + payload.get("twilio_quick_reply") + ) + self.twilio_card: Optional[ContentList.TwilioCard] = payload.get( + "twilio_card" + ) + self.twilio_catalog: Optional[ContentList.TwilioCatalog] = payload.get( + "twilio_catalog" + ) + self.twilio_carousel: Optional[ContentList.TwilioCarousel] = payload.get( + "twilio_carousel" + ) + self.twilio_flows: Optional[ContentList.TwilioFlows] = payload.get( + "twilio_flows" + ) + self.twilio_schedule: Optional[ContentList.TwilioSchedule] = payload.get( + "twilio_schedule" + ) + self.whatsapp_card: Optional[ContentList.WhatsappCard] = payload.get( + "whatsapp_card" + ) + self.whatsapp_authentication: Optional[ + ContentList.WhatsappAuthentication + ] = payload.get("whatsapp_authentication") + + def to_dict(self): + return { + "twilio_text": ( + self.twilio_text.to_dict() if self.twilio_text is not None else None + ), + "twilio_media": ( + self.twilio_media.to_dict() + if self.twilio_media is not None + else None + ), + "twilio_location": ( + self.twilio_location.to_dict() + if self.twilio_location is not None + else None + ), + "twilio_list_picker": ( + self.twilio_list_picker.to_dict() + if self.twilio_list_picker is not None + else None + ), + "twilio_call_to_action": ( + self.twilio_call_to_action.to_dict() + if self.twilio_call_to_action is not None + else None + ), + "twilio_quick_reply": ( + self.twilio_quick_reply.to_dict() + if self.twilio_quick_reply is not None + else None + ), + "twilio_card": ( + self.twilio_card.to_dict() if self.twilio_card is not None else None + ), + "twilio_catalog": ( + self.twilio_catalog.to_dict() + if self.twilio_catalog is not None + else None + ), + "twilio_carousel": ( + self.twilio_carousel.to_dict() + if self.twilio_carousel is not None + else None + ), + "twilio_flows": ( + self.twilio_flows.to_dict() + if self.twilio_flows is not None + else None + ), + "twilio_schedule": ( + self.twilio_schedule.to_dict() + if self.twilio_schedule is not None + else None + ), + "whatsapp_card": ( + self.whatsapp_card.to_dict() + if self.whatsapp_card is not None + else None + ), + "whatsapp_authentication": ( + self.whatsapp_authentication.to_dict() + if self.whatsapp_authentication is not None + else None + ), + } + + class WhatsappAuthentication(object): + """ + :ivar add_security_recommendation: + :ivar code_expiration_minutes: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.add_security_recommendation: Optional[bool] = payload.get( + "add_security_recommendation" + ) + self.code_expiration_minutes: Optional[float] = payload.get( + "code_expiration_minutes" + ) + self.actions: Optional[List[ContentList.AuthenticationAction]] = ( + payload.get("actions") + ) + + def to_dict(self): + return { + "add_security_recommendation": self.add_security_recommendation, + "code_expiration_minutes": self.code_expiration_minutes, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class WhatsappCard(object): + """ + :ivar body: + :ivar footer: + :ivar media: + :ivar header_text: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.footer: Optional[str] = payload.get("footer") + self.media: Optional[List[str]] = payload.get("media") + self.header_text: Optional[str] = payload.get("header_text") + self.actions: Optional[List[ContentList.CardAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "footer": self.footer, + "media": self.media, + "header_text": self.header_text, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + def __init__(self, version: Version, sid: str): + """ + Initialize the ContentContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Content resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Content/{sid}".format(**self._solution) + + self._approval_create: Optional[ApprovalCreateList] = None + self._approval_fetch: Optional[ApprovalFetchList] = None + + def delete(self) -> bool: + """ + Deletes the ContentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ContentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ContentInstance: + """ + Fetch the ContentInstance + + + :returns: The fetched ContentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ContentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ContentInstance: + """ + Asynchronous coroutine to fetch the ContentInstance + + + :returns: The fetched ContentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ContentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + @property + def approval_create(self) -> ApprovalCreateList: + """ + Access the approval_create + """ + if self._approval_create is None: + self._approval_create = ApprovalCreateList( + self._version, + self._solution["sid"], + ) + return self._approval_create + + @property + def approval_fetch(self) -> ApprovalFetchList: + """ + Access the approval_fetch + """ + if self._approval_fetch is None: + self._approval_fetch = ApprovalFetchList( + self._version, + self._solution["sid"], + ) + return self._approval_fetch + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ContentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ContentInstance: + """ + Build an instance of ContentInstance + + :param payload: Payload response from the API + """ + return ContentInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ContentList(ListResource): + + class AuthenticationAction(object): + """ + :ivar type: + :ivar copy_code_text: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.AuthenticationActionType"] = ( + payload.get("type") + ) + self.copy_code_text: Optional[str] = payload.get("copy_code_text") + + def to_dict(self): + return { + "type": self.type, + "copy_code_text": self.copy_code_text, + } + + class CallToActionAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar code: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CallToActionActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + self.url: Optional[str] = payload.get("url") + self.phone: Optional[str] = payload.get("phone") + self.code: Optional[str] = payload.get("code") + self.id: Optional[str] = payload.get("id") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "code": self.code, + "id": self.id, + } + + class CardAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar id: + :ivar code: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CardActionType"] = payload.get("type") + self.title: Optional[str] = payload.get("title") + self.url: Optional[str] = payload.get("url") + self.phone: Optional[str] = payload.get("phone") + self.id: Optional[str] = payload.get("id") + self.code: Optional[str] = payload.get("code") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "id": self.id, + "code": self.code, + } + + class CarouselAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CarouselActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + self.url: Optional[str] = payload.get("url") + self.phone: Optional[str] = payload.get("phone") + self.id: Optional[str] = payload.get("id") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "id": self.id, + } + + class CarouselCard(object): + """ + :ivar title: + :ivar body: + :ivar media: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.body: Optional[str] = payload.get("body") + self.media: Optional[str] = payload.get("media") + self.actions: Optional[List[ContentList.CarouselAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "title": self.title, + "body": self.body, + "media": self.media, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class CatalogItem(object): + """ + :ivar id: + :ivar section_title: + :ivar name: + :ivar media_url: + :ivar price: + :ivar description: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.section_title: Optional[str] = payload.get("section_title") + self.name: Optional[str] = payload.get("name") + self.media_url: Optional[str] = payload.get("media_url") + self.price: Optional[float] = payload.get("price") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "id": self.id, + "section_title": self.section_title, + "name": self.name, + "media_url": self.media_url, + "price": self.price, + "description": self.description, + } + + class ContentCreateRequest(object): + """ + :ivar friendly_name: User defined name of the content + :ivar variables: Key value pairs of variable name to value + :ivar language: Language code for the content + :ivar types: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.variables: Optional[dict[str, str]] = payload.get("variables") + self.language: Optional[str] = payload.get("language") + self.types: Optional[ContentList.Types] = payload.get("types") + + def to_dict(self): + return { + "friendly_name": self.friendly_name, + "variables": self.variables, + "language": self.language, + "types": self.types.to_dict() if self.types is not None else None, + } + + class FlowsPage(object): + """ + :ivar id: + :ivar next_page_id: + :ivar title: + :ivar subtitle: + :ivar layout: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.next_page_id: Optional[str] = payload.get("next_page_id") + self.title: Optional[str] = payload.get("title") + self.subtitle: Optional[str] = payload.get("subtitle") + self.layout: Optional[List[ContentList.FlowsPageComponent]] = payload.get( + "layout" + ) + + def to_dict(self): + return { + "id": self.id, + "next_page_id": self.next_page_id, + "title": self.title, + "subtitle": self.subtitle, + "layout": ( + [layout.to_dict() for layout in self.layout] + if self.layout is not None + else None + ), + } + + class FlowsPageComponent(object): + """ + :ivar label: + :ivar type: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.label: Optional[str] = payload.get("label") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "label": self.label, + "type": self.type, + } + + class ListItem(object): + """ + :ivar id: + :ivar item: + :ivar description: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.item: Optional[str] = payload.get("item") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "id": self.id, + "item": self.item, + "description": self.description, + } + + class QuickReplyAction(object): + """ + :ivar type: + :ivar title: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.QuickReplyActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + self.id: Optional[str] = payload.get("id") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "id": self.id, + } + + class TwilioCallToAction(object): + """ + :ivar body: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.actions: Optional[List[ContentList.CallToActionAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class TwilioCard(object): + """ + :ivar title: + :ivar subtitle: + :ivar media: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.subtitle: Optional[str] = payload.get("subtitle") + self.media: Optional[List[str]] = payload.get("media") + self.actions: Optional[List[ContentList.CardAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "title": self.title, + "subtitle": self.subtitle, + "media": self.media, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class TwilioCarousel(object): + """ + :ivar body: + :ivar cards: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.cards: Optional[List[ContentList.CarouselCard]] = payload.get("cards") + + def to_dict(self): + return { + "body": self.body, + "cards": ( + [cards.to_dict() for cards in self.cards] + if self.cards is not None + else None + ), + } + + class TwilioCatalog(object): + """ + :ivar title: + :ivar body: + :ivar subtitle: + :ivar id: + :ivar items: + :ivar dynamic_items: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.body: Optional[str] = payload.get("body") + self.subtitle: Optional[str] = payload.get("subtitle") + self.id: Optional[str] = payload.get("id") + self.items: Optional[List[ContentList.CatalogItem]] = payload.get("items") + self.dynamic_items: Optional[str] = payload.get("dynamic_items") + + def to_dict(self): + return { + "title": self.title, + "body": self.body, + "subtitle": self.subtitle, + "id": self.id, + "items": ( + [items.to_dict() for items in self.items] + if self.items is not None + else None + ), + "dynamic_items": self.dynamic_items, + } + + class TwilioFlows(object): + """ + :ivar body: + :ivar button_text: + :ivar subtitle: + :ivar media_url: + :ivar pages: + :ivar type: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.button_text: Optional[str] = payload.get("button_text") + self.subtitle: Optional[str] = payload.get("subtitle") + self.media_url: Optional[str] = payload.get("media_url") + self.pages: Optional[List[ContentList.FlowsPage]] = payload.get("pages") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "body": self.body, + "button_text": self.button_text, + "subtitle": self.subtitle, + "media_url": self.media_url, + "pages": ( + [pages.to_dict() for pages in self.pages] + if self.pages is not None + else None + ), + "type": self.type, + } + + class TwilioListPicker(object): + """ + :ivar body: + :ivar button: + :ivar items: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.button: Optional[str] = payload.get("button") + self.items: Optional[List[ContentList.ListItem]] = payload.get("items") + + def to_dict(self): + return { + "body": self.body, + "button": self.button, + "items": ( + [items.to_dict() for items in self.items] + if self.items is not None + else None + ), + } + + class TwilioLocation(object): + """ + :ivar latitude: + :ivar longitude: + :ivar label: + :ivar id: + :ivar address: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.latitude: Optional[float] = payload.get("latitude") + self.longitude: Optional[float] = payload.get("longitude") + self.label: Optional[str] = payload.get("label") + self.id: Optional[str] = payload.get("id") + self.address: Optional[str] = payload.get("address") + + def to_dict(self): + return { + "latitude": self.latitude, + "longitude": self.longitude, + "label": self.label, + "id": self.id, + "address": self.address, + } + + class TwilioMedia(object): + """ + :ivar body: + :ivar media: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.media: Optional[List[str]] = payload.get("media") + + def to_dict(self): + return { + "body": self.body, + "media": self.media, + } + + class TwilioQuickReply(object): + """ + :ivar body: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.actions: Optional[List[ContentList.QuickReplyAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class TwilioSchedule(object): + """ + :ivar id: + :ivar title: + :ivar time_slots: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.title: Optional[str] = payload.get("title") + self.time_slots: Optional[str] = payload.get("time_slots") + + def to_dict(self): + return { + "id": self.id, + "title": self.title, + "time_slots": self.time_slots, + } + + class TwilioText(object): + """ + :ivar body: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + + def to_dict(self): + return { + "body": self.body, + } + + class Types(object): + """ + :ivar twilio_text: + :ivar twilio_media: + :ivar twilio_location: + :ivar twilio_list_picker: + :ivar twilio_call_to_action: + :ivar twilio_quick_reply: + :ivar twilio_card: + :ivar twilio_catalog: + :ivar twilio_carousel: + :ivar twilio_flows: + :ivar twilio_schedule: + :ivar whatsapp_card: + :ivar whatsapp_authentication: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.twilio_text: Optional[ContentList.TwilioText] = payload.get( + "twilio_text" + ) + self.twilio_media: Optional[ContentList.TwilioMedia] = payload.get( + "twilio_media" + ) + self.twilio_location: Optional[ContentList.TwilioLocation] = payload.get( + "twilio_location" + ) + self.twilio_list_picker: Optional[ContentList.TwilioListPicker] = ( + payload.get("twilio_list_picker") + ) + self.twilio_call_to_action: Optional[ContentList.TwilioCallToAction] = ( + payload.get("twilio_call_to_action") + ) + self.twilio_quick_reply: Optional[ContentList.TwilioQuickReply] = ( + payload.get("twilio_quick_reply") + ) + self.twilio_card: Optional[ContentList.TwilioCard] = payload.get( + "twilio_card" + ) + self.twilio_catalog: Optional[ContentList.TwilioCatalog] = payload.get( + "twilio_catalog" + ) + self.twilio_carousel: Optional[ContentList.TwilioCarousel] = payload.get( + "twilio_carousel" + ) + self.twilio_flows: Optional[ContentList.TwilioFlows] = payload.get( + "twilio_flows" + ) + self.twilio_schedule: Optional[ContentList.TwilioSchedule] = payload.get( + "twilio_schedule" + ) + self.whatsapp_card: Optional[ContentList.WhatsappCard] = payload.get( + "whatsapp_card" + ) + self.whatsapp_authentication: Optional[ + ContentList.WhatsappAuthentication + ] = payload.get("whatsapp_authentication") + + def to_dict(self): + return { + "twilio_text": ( + self.twilio_text.to_dict() if self.twilio_text is not None else None + ), + "twilio_media": ( + self.twilio_media.to_dict() + if self.twilio_media is not None + else None + ), + "twilio_location": ( + self.twilio_location.to_dict() + if self.twilio_location is not None + else None + ), + "twilio_list_picker": ( + self.twilio_list_picker.to_dict() + if self.twilio_list_picker is not None + else None + ), + "twilio_call_to_action": ( + self.twilio_call_to_action.to_dict() + if self.twilio_call_to_action is not None + else None + ), + "twilio_quick_reply": ( + self.twilio_quick_reply.to_dict() + if self.twilio_quick_reply is not None + else None + ), + "twilio_card": ( + self.twilio_card.to_dict() if self.twilio_card is not None else None + ), + "twilio_catalog": ( + self.twilio_catalog.to_dict() + if self.twilio_catalog is not None + else None + ), + "twilio_carousel": ( + self.twilio_carousel.to_dict() + if self.twilio_carousel is not None + else None + ), + "twilio_flows": ( + self.twilio_flows.to_dict() + if self.twilio_flows is not None + else None + ), + "twilio_schedule": ( + self.twilio_schedule.to_dict() + if self.twilio_schedule is not None + else None + ), + "whatsapp_card": ( + self.whatsapp_card.to_dict() + if self.whatsapp_card is not None + else None + ), + "whatsapp_authentication": ( + self.whatsapp_authentication.to_dict() + if self.whatsapp_authentication is not None + else None + ), + } + + class WhatsappAuthentication(object): + """ + :ivar add_security_recommendation: + :ivar code_expiration_minutes: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.add_security_recommendation: Optional[bool] = payload.get( + "add_security_recommendation" + ) + self.code_expiration_minutes: Optional[float] = payload.get( + "code_expiration_minutes" + ) + self.actions: Optional[List[ContentList.AuthenticationAction]] = ( + payload.get("actions") + ) + + def to_dict(self): + return { + "add_security_recommendation": self.add_security_recommendation, + "code_expiration_minutes": self.code_expiration_minutes, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class WhatsappCard(object): + """ + :ivar body: + :ivar footer: + :ivar media: + :ivar header_text: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.footer: Optional[str] = payload.get("footer") + self.media: Optional[List[str]] = payload.get("media") + self.header_text: Optional[str] = payload.get("header_text") + self.actions: Optional[List[ContentList.CardAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "footer": self.footer, + "media": self.media, + "header_text": self.header_text, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + def __init__(self, version: Version): + """ + Initialize the ContentList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Content" + + def create(self, content_create_request: ContentCreateRequest) -> ContentInstance: + """ + Create the ContentInstance + + :param content_create_request: + + :returns: The created ContentInstance + """ + data = content_create_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ContentInstance(self._version, payload) + + async def create_async( + self, content_create_request: ContentCreateRequest + ) -> ContentInstance: + """ + Asynchronously create the ContentInstance + + :param content_create_request: + + :returns: The created ContentInstance + """ + data = content_create_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ContentInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ContentInstance]: + """ + Streams ContentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ContentInstance]: + """ + Asynchronously streams ContentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ContentInstance]: + """ + Lists ContentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ContentInstance]: + """ + Asynchronously lists ContentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ContentPage: + """ + Retrieve a single page of ContentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ContentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ContentPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ContentPage: + """ + Asynchronously retrieve a single page of ContentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ContentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ContentPage(self._version, response) + + def get_page(self, target_url: str) -> ContentPage: + """ + Retrieve a specific page of ContentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ContentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ContentPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ContentPage: + """ + Asynchronously retrieve a specific page of ContentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ContentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ContentPage(self._version, response) + + def get(self, sid: str) -> ContentContext: + """ + Constructs a ContentContext + + :param sid: The Twilio-provided string that uniquely identifies the Content resource to fetch. + """ + return ContentContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ContentContext: + """ + Constructs a ContentContext + + :param sid: The Twilio-provided string that uniquely identifies the Content resource to fetch. + """ + return ContentContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/content/v1/content/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/content/v1/content/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..3365a1af Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/content/v1/content/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/content/v1/content/__pycache__/approval_create.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/content/v1/content/__pycache__/approval_create.cpython-312.pyc new file mode 100644 index 00000000..839c1d1e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/content/v1/content/__pycache__/approval_create.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/content/v1/content/__pycache__/approval_fetch.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/content/v1/content/__pycache__/approval_fetch.cpython-312.pyc new file mode 100644 index 00000000..9dc56124 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/content/v1/content/__pycache__/approval_fetch.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/content/v1/content/approval_create.py b/venv/Lib/site-packages/twilio/rest/content/v1/content/approval_create.py new file mode 100644 index 00000000..9f34064e --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/content/v1/content/approval_create.py @@ -0,0 +1,172 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Content + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ApprovalCreateInstance(InstanceResource): + + class ContentApprovalRequest(object): + """ + :ivar name: Name of the template. + :ivar category: A WhatsApp recognized template category. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.category: Optional[str] = payload.get("category") + + def to_dict(self): + return { + "name": self.name, + "category": self.category, + } + + """ + :ivar name: + :ivar category: + :ivar content_type: + :ivar status: + :ivar rejection_reason: + :ivar allow_category_change: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], content_sid: str): + super().__init__(version) + + self.name: Optional[str] = payload.get("name") + self.category: Optional[str] = payload.get("category") + self.content_type: Optional[str] = payload.get("content_type") + self.status: Optional[str] = payload.get("status") + self.rejection_reason: Optional[str] = payload.get("rejection_reason") + self.allow_category_change: Optional[bool] = payload.get( + "allow_category_change" + ) + + self._solution = { + "content_sid": content_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ApprovalCreateList(ListResource): + + class ContentApprovalRequest(object): + """ + :ivar name: Name of the template. + :ivar category: A WhatsApp recognized template category. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.category: Optional[str] = payload.get("category") + + def to_dict(self): + return { + "name": self.name, + "category": self.category, + } + + def __init__(self, version: Version, content_sid: str): + """ + Initialize the ApprovalCreateList + + :param version: Version that contains the resource + :param content_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "content_sid": content_sid, + } + self._uri = "/Content/{content_sid}/ApprovalRequests/whatsapp".format( + **self._solution + ) + + def create( + self, content_approval_request: ContentApprovalRequest + ) -> ApprovalCreateInstance: + """ + Create the ApprovalCreateInstance + + :param content_approval_request: + + :returns: The created ApprovalCreateInstance + """ + data = content_approval_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ApprovalCreateInstance( + self._version, payload, content_sid=self._solution["content_sid"] + ) + + async def create_async( + self, content_approval_request: ContentApprovalRequest + ) -> ApprovalCreateInstance: + """ + Asynchronously create the ApprovalCreateInstance + + :param content_approval_request: + + :returns: The created ApprovalCreateInstance + """ + data = content_approval_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ApprovalCreateInstance( + self._version, payload, content_sid=self._solution["content_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/content/v1/content/approval_fetch.py b/venv/Lib/site-packages/twilio/rest/content/v1/content/approval_fetch.py new file mode 100644 index 00000000..d3d00e50 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/content/v1/content/approval_fetch.py @@ -0,0 +1,193 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Content + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ApprovalFetchInstance(InstanceResource): + """ + :ivar sid: The unique string that that we created to identify the Content resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/usage/api/account) that created Content resource. + :ivar whatsapp: Contains the whatsapp approval information for the Content resource, with fields such as approval status, rejection reason, and category, amongst others. + :ivar url: The URL of the resource, relative to `https://content.twilio.com`. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.whatsapp: Optional[Dict[str, object]] = payload.get("whatsapp") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid, + } + self._context: Optional[ApprovalFetchContext] = None + + @property + def _proxy(self) -> "ApprovalFetchContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ApprovalFetchContext for this ApprovalFetchInstance + """ + if self._context is None: + self._context = ApprovalFetchContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "ApprovalFetchInstance": + """ + Fetch the ApprovalFetchInstance + + + :returns: The fetched ApprovalFetchInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ApprovalFetchInstance": + """ + Asynchronous coroutine to fetch the ApprovalFetchInstance + + + :returns: The fetched ApprovalFetchInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ApprovalFetchContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ApprovalFetchContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Content resource whose approval information to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Content/{sid}/ApprovalRequests".format(**self._solution) + + def fetch(self) -> ApprovalFetchInstance: + """ + Fetch the ApprovalFetchInstance + + + :returns: The fetched ApprovalFetchInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ApprovalFetchInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ApprovalFetchInstance: + """ + Asynchronous coroutine to fetch the ApprovalFetchInstance + + + :returns: The fetched ApprovalFetchInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ApprovalFetchInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ApprovalFetchList(ListResource): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ApprovalFetchList + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Content resource whose approval information to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + + def get(self) -> ApprovalFetchContext: + """ + Constructs a ApprovalFetchContext + + """ + return ApprovalFetchContext(self._version, sid=self._solution["sid"]) + + def __call__(self) -> ApprovalFetchContext: + """ + Constructs a ApprovalFetchContext + + """ + return ApprovalFetchContext(self._version, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/content/v1/content_and_approvals.py b/venv/Lib/site-packages/twilio/rest/content/v1/content_and_approvals.py new file mode 100644 index 00000000..c2a21066 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/content/v1/content_and_approvals.py @@ -0,0 +1,298 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Content + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ContentAndApprovalsInstance(InstanceResource): + """ + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar sid: The unique string that that we created to identify the Content resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/usage/api/account) that created Content resource. + :ivar friendly_name: A string name used to describe the Content resource. Not visible to the end recipient. + :ivar language: Two-letter (ISO 639-1) language code (e.g., en) identifying the language the Content resource is in. + :ivar variables: Defines the default placeholder values for variables included in the Content resource. e.g. {\"1\": \"Customer_Name\"}. + :ivar types: The [Content types](https://www.twilio.com/docs/content-api/content-types-overview) (e.g. twilio/text) for this Content resource. + :ivar approval_requests: The submitted information and approval request status of the Content resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.language: Optional[str] = payload.get("language") + self.variables: Optional[Dict[str, object]] = payload.get("variables") + self.types: Optional[Dict[str, object]] = payload.get("types") + self.approval_requests: Optional[Dict[str, object]] = payload.get( + "approval_requests" + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class ContentAndApprovalsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ContentAndApprovalsInstance: + """ + Build an instance of ContentAndApprovalsInstance + + :param payload: Payload response from the API + """ + return ContentAndApprovalsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ContentAndApprovalsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ContentAndApprovalsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ContentAndApprovals" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ContentAndApprovalsInstance]: + """ + Streams ContentAndApprovalsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ContentAndApprovalsInstance]: + """ + Asynchronously streams ContentAndApprovalsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ContentAndApprovalsInstance]: + """ + Lists ContentAndApprovalsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ContentAndApprovalsInstance]: + """ + Asynchronously lists ContentAndApprovalsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ContentAndApprovalsPage: + """ + Retrieve a single page of ContentAndApprovalsInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ContentAndApprovalsInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ContentAndApprovalsPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ContentAndApprovalsPage: + """ + Asynchronously retrieve a single page of ContentAndApprovalsInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ContentAndApprovalsInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ContentAndApprovalsPage(self._version, response) + + def get_page(self, target_url: str) -> ContentAndApprovalsPage: + """ + Retrieve a specific page of ContentAndApprovalsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ContentAndApprovalsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ContentAndApprovalsPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ContentAndApprovalsPage: + """ + Asynchronously retrieve a specific page of ContentAndApprovalsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ContentAndApprovalsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ContentAndApprovalsPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/content/v1/legacy_content.py b/venv/Lib/site-packages/twilio/rest/content/v1/legacy_content.py new file mode 100644 index 00000000..d32778e7 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/content/v1/legacy_content.py @@ -0,0 +1,300 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Content + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class LegacyContentInstance(InstanceResource): + """ + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar sid: The unique string that that we created to identify the Content resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/usage/api/account) that created Content resource. + :ivar friendly_name: A string name used to describe the Content resource. Not visible to the end recipient. + :ivar language: Two-letter (ISO 639-1) language code (e.g., en) identifying the language the Content resource is in. + :ivar variables: Defines the default placeholder values for variables included in the Content resource. e.g. {\"1\": \"Customer_Name\"}. + :ivar types: The [Content types](https://www.twilio.com/docs/content-api/content-types-overview) (e.g. twilio/text) for this Content resource. + :ivar legacy_template_name: The string name of the legacy content template associated with this Content resource, unique across all template names for its account. Only lowercase letters, numbers and underscores are allowed + :ivar legacy_body: The string body field of the legacy content template associated with this Content resource + :ivar url: The URL of the resource, relative to `https://content.twilio.com`. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.language: Optional[str] = payload.get("language") + self.variables: Optional[Dict[str, object]] = payload.get("variables") + self.types: Optional[Dict[str, object]] = payload.get("types") + self.legacy_template_name: Optional[str] = payload.get("legacy_template_name") + self.legacy_body: Optional[str] = payload.get("legacy_body") + self.url: Optional[str] = payload.get("url") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class LegacyContentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> LegacyContentInstance: + """ + Build an instance of LegacyContentInstance + + :param payload: Payload response from the API + """ + return LegacyContentInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class LegacyContentList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the LegacyContentList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/LegacyContent" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[LegacyContentInstance]: + """ + Streams LegacyContentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[LegacyContentInstance]: + """ + Asynchronously streams LegacyContentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[LegacyContentInstance]: + """ + Lists LegacyContentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[LegacyContentInstance]: + """ + Asynchronously lists LegacyContentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> LegacyContentPage: + """ + Retrieve a single page of LegacyContentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of LegacyContentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LegacyContentPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> LegacyContentPage: + """ + Asynchronously retrieve a single page of LegacyContentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of LegacyContentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LegacyContentPage(self._version, response) + + def get_page(self, target_url: str) -> LegacyContentPage: + """ + Retrieve a specific page of LegacyContentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of LegacyContentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return LegacyContentPage(self._version, response) + + async def get_page_async(self, target_url: str) -> LegacyContentPage: + """ + Asynchronously retrieve a specific page of LegacyContentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of LegacyContentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return LegacyContentPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/content/v2/__init__.py b/venv/Lib/site-packages/twilio/rest/content/v2/__init__.py new file mode 100644 index 00000000..ca6d8bcd --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/content/v2/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Content + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.content.v2.content import ContentList +from twilio.rest.content.v2.content_and_approvals import ContentAndApprovalsList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Content + + :param domain: The Twilio.content domain + """ + super().__init__(domain, "v2") + self._contents: Optional[ContentList] = None + self._content_and_approvals: Optional[ContentAndApprovalsList] = None + + @property + def contents(self) -> ContentList: + if self._contents is None: + self._contents = ContentList(self) + return self._contents + + @property + def content_and_approvals(self) -> ContentAndApprovalsList: + if self._content_and_approvals is None: + self._content_and_approvals = ContentAndApprovalsList(self) + return self._content_and_approvals + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/content/v2/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/content/v2/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..94ef771c Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/content/v2/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/content/v2/__pycache__/content.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/content/v2/__pycache__/content.cpython-312.pyc new file mode 100644 index 00000000..4b36d6cf Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/content/v2/__pycache__/content.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/content/v2/__pycache__/content_and_approvals.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/content/v2/__pycache__/content_and_approvals.cpython-312.pyc new file mode 100644 index 00000000..0032f7aa Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/content/v2/__pycache__/content_and_approvals.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/content/v2/content.py b/venv/Lib/site-packages/twilio/rest/content/v2/content.py new file mode 100644 index 00000000..c2e2db7d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/content/v2/content.py @@ -0,0 +1,464 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Content + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ContentInstance(InstanceResource): + """ + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar sid: The unique string that that we created to identify the Content resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/usage/api/account) that created Content resource. + :ivar friendly_name: A string name used to describe the Content resource. Not visible to the end recipient. + :ivar language: Two-letter (ISO 639-1) language code (e.g., en) identifying the language the Content resource is in. + :ivar variables: Defines the default placeholder values for variables included in the Content resource. e.g. {\"1\": \"Customer_Name\"}. + :ivar types: The [Content types](https://www.twilio.com/docs/content/content-types-overview) (e.g. twilio/text) for this Content resource. + :ivar url: The URL of the resource, relative to `https://content.twilio.com`. + :ivar links: A list of links related to the Content resource, such as approval_fetch and approval_create + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.language: Optional[str] = payload.get("language") + self.variables: Optional[Dict[str, object]] = payload.get("variables") + self.types: Optional[Dict[str, object]] = payload.get("types") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class ContentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ContentInstance: + """ + Build an instance of ContentInstance + + :param payload: Payload response from the API + """ + return ContentInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ContentList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ContentList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Content" + + def stream( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ContentInstance]: + """ + Streams ContentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ContentInstance]: + """ + Asynchronously streams ContentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ContentInstance]: + """ + Lists ContentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ContentInstance]: + """ + Asynchronously lists ContentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ContentPage: + """ + Retrieve a single page of ContentInstance records from the API. + Request is executed immediately + + :param sort_by_date: Whether to sort by ascending or descending date updated + :param sort_by_content_name: Whether to sort by ascending or descending content name + :param date_created_after: Filter by >=[date-time] + :param date_created_before: Filter by <=[date-time] + :param content_name: Filter by Regex Pattern in content name + :param content: Filter by Regex Pattern in template content + :param language: Filter by array of valid language(s) + :param content_type: Filter by array of contentType(s) + :param channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ContentInstance + """ + data = values.of( + { + "SortByDate": sort_by_date, + "SortByContentName": sort_by_content_name, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "ContentName": content_name, + "Content": content, + "Language": serialize.map(language, lambda e: e), + "ContentType": serialize.map(content_type, lambda e: e), + "ChannelEligibility": serialize.map(channel_eligibility, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ContentPage(self._version, response) + + async def page_async( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ContentPage: + """ + Asynchronously retrieve a single page of ContentInstance records from the API. + Request is executed immediately + + :param sort_by_date: Whether to sort by ascending or descending date updated + :param sort_by_content_name: Whether to sort by ascending or descending content name + :param date_created_after: Filter by >=[date-time] + :param date_created_before: Filter by <=[date-time] + :param content_name: Filter by Regex Pattern in content name + :param content: Filter by Regex Pattern in template content + :param language: Filter by array of valid language(s) + :param content_type: Filter by array of contentType(s) + :param channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ContentInstance + """ + data = values.of( + { + "SortByDate": sort_by_date, + "SortByContentName": sort_by_content_name, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "ContentName": content_name, + "Content": content, + "Language": serialize.map(language, lambda e: e), + "ContentType": serialize.map(content_type, lambda e: e), + "ChannelEligibility": serialize.map(channel_eligibility, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ContentPage(self._version, response) + + def get_page(self, target_url: str) -> ContentPage: + """ + Retrieve a specific page of ContentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ContentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ContentPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ContentPage: + """ + Asynchronously retrieve a specific page of ContentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ContentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ContentPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/content/v2/content_and_approvals.py b/venv/Lib/site-packages/twilio/rest/content/v2/content_and_approvals.py new file mode 100644 index 00000000..823bcfe0 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/content/v2/content_and_approvals.py @@ -0,0 +1,464 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Content + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ContentAndApprovalsInstance(InstanceResource): + """ + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar sid: The unique string that that we created to identify the Content resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/usage/api/account) that created Content resource. + :ivar friendly_name: A string name used to describe the Content resource. Not visible to the end recipient. + :ivar language: Two-letter (ISO 639-1) language code (e.g., en) identifying the language the Content resource is in. + :ivar variables: Defines the default placeholder values for variables included in the Content resource. e.g. {\"1\": \"Customer_Name\"}. + :ivar types: The [Content types](https://www.twilio.com/docs/content/content-types-overview) (e.g. twilio/text) for this Content resource. + :ivar approval_requests: The submitted information and approval request status of the Content resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.language: Optional[str] = payload.get("language") + self.variables: Optional[Dict[str, object]] = payload.get("variables") + self.types: Optional[Dict[str, object]] = payload.get("types") + self.approval_requests: Optional[Dict[str, object]] = payload.get( + "approval_requests" + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class ContentAndApprovalsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ContentAndApprovalsInstance: + """ + Build an instance of ContentAndApprovalsInstance + + :param payload: Payload response from the API + """ + return ContentAndApprovalsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ContentAndApprovalsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ContentAndApprovalsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ContentAndApprovals" + + def stream( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ContentAndApprovalsInstance]: + """ + Streams ContentAndApprovalsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ContentAndApprovalsInstance]: + """ + Asynchronously streams ContentAndApprovalsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ContentAndApprovalsInstance]: + """ + Lists ContentAndApprovalsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ContentAndApprovalsInstance]: + """ + Asynchronously lists ContentAndApprovalsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ContentAndApprovalsPage: + """ + Retrieve a single page of ContentAndApprovalsInstance records from the API. + Request is executed immediately + + :param sort_by_date: Whether to sort by ascending or descending date updated + :param sort_by_content_name: Whether to sort by ascending or descending content name + :param date_created_after: Filter by >=[date-time] + :param date_created_before: Filter by <=[date-time] + :param content_name: Filter by Regex Pattern in content name + :param content: Filter by Regex Pattern in template content + :param language: Filter by array of valid language(s) + :param content_type: Filter by array of contentType(s) + :param channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ContentAndApprovalsInstance + """ + data = values.of( + { + "SortByDate": sort_by_date, + "SortByContentName": sort_by_content_name, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "ContentName": content_name, + "Content": content, + "Language": serialize.map(language, lambda e: e), + "ContentType": serialize.map(content_type, lambda e: e), + "ChannelEligibility": serialize.map(channel_eligibility, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ContentAndApprovalsPage(self._version, response) + + async def page_async( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ContentAndApprovalsPage: + """ + Asynchronously retrieve a single page of ContentAndApprovalsInstance records from the API. + Request is executed immediately + + :param sort_by_date: Whether to sort by ascending or descending date updated + :param sort_by_content_name: Whether to sort by ascending or descending content name + :param date_created_after: Filter by >=[date-time] + :param date_created_before: Filter by <=[date-time] + :param content_name: Filter by Regex Pattern in content name + :param content: Filter by Regex Pattern in template content + :param language: Filter by array of valid language(s) + :param content_type: Filter by array of contentType(s) + :param channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ContentAndApprovalsInstance + """ + data = values.of( + { + "SortByDate": sort_by_date, + "SortByContentName": sort_by_content_name, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "ContentName": content_name, + "Content": content, + "Language": serialize.map(language, lambda e: e), + "ContentType": serialize.map(content_type, lambda e: e), + "ChannelEligibility": serialize.map(channel_eligibility, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ContentAndApprovalsPage(self._version, response) + + def get_page(self, target_url: str) -> ContentAndApprovalsPage: + """ + Retrieve a specific page of ContentAndApprovalsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ContentAndApprovalsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ContentAndApprovalsPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ContentAndApprovalsPage: + """ + Asynchronously retrieve a specific page of ContentAndApprovalsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ContentAndApprovalsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ContentAndApprovalsPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/ConversationsBase.py b/venv/Lib/site-packages/twilio/rest/conversations/ConversationsBase.py new file mode 100644 index 00000000..89043083 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/ConversationsBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.conversations.v1 import V1 + + +class ConversationsBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Conversations Domain + + :returns: Domain for Conversations + """ + super().__init__(twilio, "https://conversations.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Conversations + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/__init__.py b/venv/Lib/site-packages/twilio/rest/conversations/__init__.py new file mode 100644 index 00000000..d60cb426 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/__init__.py @@ -0,0 +1,87 @@ +from warnings import warn + +from twilio.rest.conversations.ConversationsBase import ConversationsBase +from twilio.rest.conversations.v1.address_configuration import AddressConfigurationList +from twilio.rest.conversations.v1.configuration import ConfigurationList +from twilio.rest.conversations.v1.conversation import ConversationList +from twilio.rest.conversations.v1.credential import CredentialList +from twilio.rest.conversations.v1.participant_conversation import ( + ParticipantConversationList, +) +from twilio.rest.conversations.v1.role import RoleList +from twilio.rest.conversations.v1.service import ServiceList +from twilio.rest.conversations.v1.user import UserList + + +class Conversations(ConversationsBase): + @property + def configuration(self) -> ConfigurationList: + warn( + "configuration is deprecated. Use v1.configuration instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.configuration + + @property + def address_configurations(self) -> AddressConfigurationList: + warn( + "address_configurations is deprecated. Use v1.address_configurations instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.address_configurations + + @property + def conversations(self) -> ConversationList: + warn( + "conversations is deprecated. Use v1.conversations instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.conversations + + @property + def credentials(self) -> CredentialList: + warn( + "credentials is deprecated. Use v1.credentials instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.credentials + + @property + def participant_conversations(self) -> ParticipantConversationList: + warn( + "participant_conversations is deprecated. Use v1.participant_conversations instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.participant_conversations + + @property + def roles(self) -> RoleList: + warn( + "roles is deprecated. Use v1.roles instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.roles + + @property + def services(self) -> ServiceList: + warn( + "services is deprecated. Use v1.services instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.services + + @property + def users(self) -> UserList: + warn( + "users is deprecated. Use v1.users instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.users diff --git a/venv/Lib/site-packages/twilio/rest/conversations/__pycache__/ConversationsBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/__pycache__/ConversationsBase.cpython-312.pyc new file mode 100644 index 00000000..7e5499a1 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/__pycache__/ConversationsBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..975a8282 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/__init__.py new file mode 100644 index 00000000..1ec6c22a --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/__init__.py @@ -0,0 +1,115 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.conversations.v1.address_configuration import AddressConfigurationList +from twilio.rest.conversations.v1.configuration import ConfigurationList +from twilio.rest.conversations.v1.conversation import ConversationList +from twilio.rest.conversations.v1.conversation_with_participants import ( + ConversationWithParticipantsList, +) +from twilio.rest.conversations.v1.credential import CredentialList +from twilio.rest.conversations.v1.participant_conversation import ( + ParticipantConversationList, +) +from twilio.rest.conversations.v1.role import RoleList +from twilio.rest.conversations.v1.service import ServiceList +from twilio.rest.conversations.v1.user import UserList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Conversations + + :param domain: The Twilio.conversations domain + """ + super().__init__(domain, "v1") + self._address_configurations: Optional[AddressConfigurationList] = None + self._configuration: Optional[ConfigurationList] = None + self._conversations: Optional[ConversationList] = None + self._conversation_with_participants: Optional[ + ConversationWithParticipantsList + ] = None + self._credentials: Optional[CredentialList] = None + self._participant_conversations: Optional[ParticipantConversationList] = None + self._roles: Optional[RoleList] = None + self._services: Optional[ServiceList] = None + self._users: Optional[UserList] = None + + @property + def address_configurations(self) -> AddressConfigurationList: + if self._address_configurations is None: + self._address_configurations = AddressConfigurationList(self) + return self._address_configurations + + @property + def configuration(self) -> ConfigurationList: + if self._configuration is None: + self._configuration = ConfigurationList(self) + return self._configuration + + @property + def conversations(self) -> ConversationList: + if self._conversations is None: + self._conversations = ConversationList(self) + return self._conversations + + @property + def conversation_with_participants(self) -> ConversationWithParticipantsList: + if self._conversation_with_participants is None: + self._conversation_with_participants = ConversationWithParticipantsList( + self + ) + return self._conversation_with_participants + + @property + def credentials(self) -> CredentialList: + if self._credentials is None: + self._credentials = CredentialList(self) + return self._credentials + + @property + def participant_conversations(self) -> ParticipantConversationList: + if self._participant_conversations is None: + self._participant_conversations = ParticipantConversationList(self) + return self._participant_conversations + + @property + def roles(self) -> RoleList: + if self._roles is None: + self._roles = RoleList(self) + return self._roles + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + @property + def users(self) -> UserList: + if self._users is None: + self._users = UserList(self) + return self._users + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..7b558e33 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/__pycache__/address_configuration.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/__pycache__/address_configuration.cpython-312.pyc new file mode 100644 index 00000000..b123ecc1 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/__pycache__/address_configuration.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/__pycache__/conversation_with_participants.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/__pycache__/conversation_with_participants.cpython-312.pyc new file mode 100644 index 00000000..96ac24d0 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/__pycache__/conversation_with_participants.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/__pycache__/credential.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/__pycache__/credential.cpython-312.pyc new file mode 100644 index 00000000..92fb4bd1 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/__pycache__/credential.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/__pycache__/participant_conversation.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/__pycache__/participant_conversation.cpython-312.pyc new file mode 100644 index 00000000..fb56d172 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/__pycache__/participant_conversation.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/__pycache__/role.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/__pycache__/role.cpython-312.pyc new file mode 100644 index 00000000..a5344996 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/__pycache__/role.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/address_configuration.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/address_configuration.py new file mode 100644 index 00000000..c12e3c71 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/address_configuration.py @@ -0,0 +1,859 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AddressConfigurationInstance(InstanceResource): + + class AutoCreationType(object): + WEBHOOK = "webhook" + STUDIO = "studio" + DEFAULT = "default" + + class Method(object): + GET = "GET" + POST = "POST" + + class Type(object): + SMS = "sms" + WHATSAPP = "whatsapp" + MESSENGER = "messenger" + GBM = "gbm" + EMAIL = "email" + RCS = "rcs" + APPLE = "apple" + CHAT = "chat" + + """ + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) the address belongs to + :ivar type: Type of Address, value can be `whatsapp` or `sms`. + :ivar address: The unique address to be configured. The address can be a whatsapp address or phone number + :ivar friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :ivar auto_creation: Auto Creation configuration for the address. + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + :ivar url: An absolute API resource URL for this address configuration. + :ivar address_country: An ISO 3166-1 alpha-2n country code which the address belongs to. This is currently only applicable to short code addresses. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.type: Optional[str] = payload.get("type") + self.address: Optional[str] = payload.get("address") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.auto_creation: Optional[Dict[str, object]] = payload.get("auto_creation") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.address_country: Optional[str] = payload.get("address_country") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[AddressConfigurationContext] = None + + @property + def _proxy(self) -> "AddressConfigurationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AddressConfigurationContext for this AddressConfigurationInstance + """ + if self._context is None: + self._context = AddressConfigurationContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AddressConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AddressConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AddressConfigurationInstance": + """ + Fetch the AddressConfigurationInstance + + + :returns: The fetched AddressConfigurationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AddressConfigurationInstance": + """ + Asynchronous coroutine to fetch the AddressConfigurationInstance + + + :returns: The fetched AddressConfigurationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + ) -> "AddressConfigurationInstance": + """ + Update the AddressConfigurationInstance + + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + + :returns: The updated AddressConfigurationInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + auto_creation_enabled=auto_creation_enabled, + auto_creation_type=auto_creation_type, + auto_creation_conversation_service_sid=auto_creation_conversation_service_sid, + auto_creation_webhook_url=auto_creation_webhook_url, + auto_creation_webhook_method=auto_creation_webhook_method, + auto_creation_webhook_filters=auto_creation_webhook_filters, + auto_creation_studio_flow_sid=auto_creation_studio_flow_sid, + auto_creation_studio_retry_count=auto_creation_studio_retry_count, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + ) -> "AddressConfigurationInstance": + """ + Asynchronous coroutine to update the AddressConfigurationInstance + + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + + :returns: The updated AddressConfigurationInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + auto_creation_enabled=auto_creation_enabled, + auto_creation_type=auto_creation_type, + auto_creation_conversation_service_sid=auto_creation_conversation_service_sid, + auto_creation_webhook_url=auto_creation_webhook_url, + auto_creation_webhook_method=auto_creation_webhook_method, + auto_creation_webhook_filters=auto_creation_webhook_filters, + auto_creation_studio_flow_sid=auto_creation_studio_flow_sid, + auto_creation_studio_retry_count=auto_creation_studio_retry_count, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class AddressConfigurationContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the AddressConfigurationContext + + :param version: Version that contains the resource + :param sid: The SID of the Address Configuration resource. This value can be either the `sid` or the `address` of the configuration + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Configuration/Addresses/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the AddressConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AddressConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AddressConfigurationInstance: + """ + Fetch the AddressConfigurationInstance + + + :returns: The fetched AddressConfigurationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AddressConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AddressConfigurationInstance: + """ + Asynchronous coroutine to fetch the AddressConfigurationInstance + + + :returns: The fetched AddressConfigurationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AddressConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + ) -> AddressConfigurationInstance: + """ + Update the AddressConfigurationInstance + + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + + :returns: The updated AddressConfigurationInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "AutoCreation.Enabled": serialize.boolean_to_string( + auto_creation_enabled + ), + "AutoCreation.Type": auto_creation_type, + "AutoCreation.ConversationServiceSid": auto_creation_conversation_service_sid, + "AutoCreation.WebhookUrl": auto_creation_webhook_url, + "AutoCreation.WebhookMethod": auto_creation_webhook_method, + "AutoCreation.WebhookFilters": serialize.map( + auto_creation_webhook_filters, lambda e: e + ), + "AutoCreation.StudioFlowSid": auto_creation_studio_flow_sid, + "AutoCreation.StudioRetryCount": auto_creation_studio_retry_count, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AddressConfigurationInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + ) -> AddressConfigurationInstance: + """ + Asynchronous coroutine to update the AddressConfigurationInstance + + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + + :returns: The updated AddressConfigurationInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "AutoCreation.Enabled": serialize.boolean_to_string( + auto_creation_enabled + ), + "AutoCreation.Type": auto_creation_type, + "AutoCreation.ConversationServiceSid": auto_creation_conversation_service_sid, + "AutoCreation.WebhookUrl": auto_creation_webhook_url, + "AutoCreation.WebhookMethod": auto_creation_webhook_method, + "AutoCreation.WebhookFilters": serialize.map( + auto_creation_webhook_filters, lambda e: e + ), + "AutoCreation.StudioFlowSid": auto_creation_studio_flow_sid, + "AutoCreation.StudioRetryCount": auto_creation_studio_retry_count, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AddressConfigurationInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class AddressConfigurationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AddressConfigurationInstance: + """ + Build an instance of AddressConfigurationInstance + + :param payload: Payload response from the API + """ + return AddressConfigurationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AddressConfigurationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AddressConfigurationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Configuration/Addresses" + + def create( + self, + type: "AddressConfigurationInstance.Type", + address: str, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + address_country: Union[str, object] = values.unset, + ) -> AddressConfigurationInstance: + """ + Create the AddressConfigurationInstance + + :param type: + :param address: The unique address to be configured. The address can be a whatsapp address or phone number + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + :param address_country: An ISO 3166-1 alpha-2n country code which the address belongs to. This is currently only applicable to short code addresses. + + :returns: The created AddressConfigurationInstance + """ + + data = values.of( + { + "Type": type, + "Address": address, + "FriendlyName": friendly_name, + "AutoCreation.Enabled": serialize.boolean_to_string( + auto_creation_enabled + ), + "AutoCreation.Type": auto_creation_type, + "AutoCreation.ConversationServiceSid": auto_creation_conversation_service_sid, + "AutoCreation.WebhookUrl": auto_creation_webhook_url, + "AutoCreation.WebhookMethod": auto_creation_webhook_method, + "AutoCreation.WebhookFilters": serialize.map( + auto_creation_webhook_filters, lambda e: e + ), + "AutoCreation.StudioFlowSid": auto_creation_studio_flow_sid, + "AutoCreation.StudioRetryCount": auto_creation_studio_retry_count, + "AddressCountry": address_country, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AddressConfigurationInstance(self._version, payload) + + async def create_async( + self, + type: "AddressConfigurationInstance.Type", + address: str, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + address_country: Union[str, object] = values.unset, + ) -> AddressConfigurationInstance: + """ + Asynchronously create the AddressConfigurationInstance + + :param type: + :param address: The unique address to be configured. The address can be a whatsapp address or phone number + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + :param address_country: An ISO 3166-1 alpha-2n country code which the address belongs to. This is currently only applicable to short code addresses. + + :returns: The created AddressConfigurationInstance + """ + + data = values.of( + { + "Type": type, + "Address": address, + "FriendlyName": friendly_name, + "AutoCreation.Enabled": serialize.boolean_to_string( + auto_creation_enabled + ), + "AutoCreation.Type": auto_creation_type, + "AutoCreation.ConversationServiceSid": auto_creation_conversation_service_sid, + "AutoCreation.WebhookUrl": auto_creation_webhook_url, + "AutoCreation.WebhookMethod": auto_creation_webhook_method, + "AutoCreation.WebhookFilters": serialize.map( + auto_creation_webhook_filters, lambda e: e + ), + "AutoCreation.StudioFlowSid": auto_creation_studio_flow_sid, + "AutoCreation.StudioRetryCount": auto_creation_studio_retry_count, + "AddressCountry": address_country, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AddressConfigurationInstance(self._version, payload) + + def stream( + self, + type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AddressConfigurationInstance]: + """ + Streams AddressConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str type: Filter the address configurations by its type. This value can be one of: `whatsapp`, `sms`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(type=type, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AddressConfigurationInstance]: + """ + Asynchronously streams AddressConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str type: Filter the address configurations by its type. This value can be one of: `whatsapp`, `sms`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(type=type, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AddressConfigurationInstance]: + """ + Lists AddressConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str type: Filter the address configurations by its type. This value can be one of: `whatsapp`, `sms`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + type=type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AddressConfigurationInstance]: + """ + Asynchronously lists AddressConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str type: Filter the address configurations by its type. This value can be one of: `whatsapp`, `sms`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + type=type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AddressConfigurationPage: + """ + Retrieve a single page of AddressConfigurationInstance records from the API. + Request is executed immediately + + :param type: Filter the address configurations by its type. This value can be one of: `whatsapp`, `sms`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AddressConfigurationInstance + """ + data = values.of( + { + "Type": type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AddressConfigurationPage(self._version, response) + + async def page_async( + self, + type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AddressConfigurationPage: + """ + Asynchronously retrieve a single page of AddressConfigurationInstance records from the API. + Request is executed immediately + + :param type: Filter the address configurations by its type. This value can be one of: `whatsapp`, `sms`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AddressConfigurationInstance + """ + data = values.of( + { + "Type": type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AddressConfigurationPage(self._version, response) + + def get_page(self, target_url: str) -> AddressConfigurationPage: + """ + Retrieve a specific page of AddressConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AddressConfigurationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AddressConfigurationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AddressConfigurationPage: + """ + Asynchronously retrieve a specific page of AddressConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AddressConfigurationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AddressConfigurationPage(self._version, response) + + def get(self, sid: str) -> AddressConfigurationContext: + """ + Constructs a AddressConfigurationContext + + :param sid: The SID of the Address Configuration resource. This value can be either the `sid` or the `address` of the configuration + """ + return AddressConfigurationContext(self._version, sid=sid) + + def __call__(self, sid: str) -> AddressConfigurationContext: + """ + Constructs a AddressConfigurationContext + + :param sid: The SID of the Address Configuration resource. This value can be either the `sid` or the `address` of the configuration + """ + return AddressConfigurationContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/configuration/__init__.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/configuration/__init__.py new file mode 100644 index 00000000..58408235 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/configuration/__init__.py @@ -0,0 +1,325 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.conversations.v1.configuration.webhook import WebhookList + + +class ConfigurationInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this configuration. + :ivar default_chat_service_sid: The SID of the default [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) used when creating a conversation. + :ivar default_messaging_service_sid: The SID of the default [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) used when creating a conversation. + :ivar default_inactive_timer: Default ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :ivar default_closed_timer: Default ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :ivar url: An absolute API resource URL for this global configuration. + :ivar links: Contains absolute API resource URLs to access the webhook and default service configurations. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.default_chat_service_sid: Optional[str] = payload.get( + "default_chat_service_sid" + ) + self.default_messaging_service_sid: Optional[str] = payload.get( + "default_messaging_service_sid" + ) + self.default_inactive_timer: Optional[str] = payload.get( + "default_inactive_timer" + ) + self.default_closed_timer: Optional[str] = payload.get("default_closed_timer") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._context: Optional[ConfigurationContext] = None + + @property + def _proxy(self) -> "ConfigurationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConfigurationContext for this ConfigurationInstance + """ + if self._context is None: + self._context = ConfigurationContext( + self._version, + ) + return self._context + + def fetch(self) -> "ConfigurationInstance": + """ + Fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConfigurationInstance": + """ + Asynchronous coroutine to fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + default_chat_service_sid: Union[str, object] = values.unset, + default_messaging_service_sid: Union[str, object] = values.unset, + default_inactive_timer: Union[str, object] = values.unset, + default_closed_timer: Union[str, object] = values.unset, + ) -> "ConfigurationInstance": + """ + Update the ConfigurationInstance + + :param default_chat_service_sid: The SID of the default [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) to use when creating a conversation. + :param default_messaging_service_sid: The SID of the default [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to use when creating a conversation. + :param default_inactive_timer: Default ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param default_closed_timer: Default ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + + :returns: The updated ConfigurationInstance + """ + return self._proxy.update( + default_chat_service_sid=default_chat_service_sid, + default_messaging_service_sid=default_messaging_service_sid, + default_inactive_timer=default_inactive_timer, + default_closed_timer=default_closed_timer, + ) + + async def update_async( + self, + default_chat_service_sid: Union[str, object] = values.unset, + default_messaging_service_sid: Union[str, object] = values.unset, + default_inactive_timer: Union[str, object] = values.unset, + default_closed_timer: Union[str, object] = values.unset, + ) -> "ConfigurationInstance": + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param default_chat_service_sid: The SID of the default [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) to use when creating a conversation. + :param default_messaging_service_sid: The SID of the default [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to use when creating a conversation. + :param default_inactive_timer: Default ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param default_closed_timer: Default ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + + :returns: The updated ConfigurationInstance + """ + return await self._proxy.update_async( + default_chat_service_sid=default_chat_service_sid, + default_messaging_service_sid=default_messaging_service_sid, + default_inactive_timer=default_inactive_timer, + default_closed_timer=default_closed_timer, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class ConfigurationContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the ConfigurationContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/Configuration" + + def fetch(self) -> ConfigurationInstance: + """ + Fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ConfigurationInstance( + self._version, + payload, + ) + + async def fetch_async(self) -> ConfigurationInstance: + """ + Asynchronous coroutine to fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ConfigurationInstance( + self._version, + payload, + ) + + def update( + self, + default_chat_service_sid: Union[str, object] = values.unset, + default_messaging_service_sid: Union[str, object] = values.unset, + default_inactive_timer: Union[str, object] = values.unset, + default_closed_timer: Union[str, object] = values.unset, + ) -> ConfigurationInstance: + """ + Update the ConfigurationInstance + + :param default_chat_service_sid: The SID of the default [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) to use when creating a conversation. + :param default_messaging_service_sid: The SID of the default [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to use when creating a conversation. + :param default_inactive_timer: Default ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param default_closed_timer: Default ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + + :returns: The updated ConfigurationInstance + """ + + data = values.of( + { + "DefaultChatServiceSid": default_chat_service_sid, + "DefaultMessagingServiceSid": default_messaging_service_sid, + "DefaultInactiveTimer": default_inactive_timer, + "DefaultClosedTimer": default_closed_timer, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConfigurationInstance(self._version, payload) + + async def update_async( + self, + default_chat_service_sid: Union[str, object] = values.unset, + default_messaging_service_sid: Union[str, object] = values.unset, + default_inactive_timer: Union[str, object] = values.unset, + default_closed_timer: Union[str, object] = values.unset, + ) -> ConfigurationInstance: + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param default_chat_service_sid: The SID of the default [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) to use when creating a conversation. + :param default_messaging_service_sid: The SID of the default [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to use when creating a conversation. + :param default_inactive_timer: Default ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param default_closed_timer: Default ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + + :returns: The updated ConfigurationInstance + """ + + data = values.of( + { + "DefaultChatServiceSid": default_chat_service_sid, + "DefaultMessagingServiceSid": default_messaging_service_sid, + "DefaultInactiveTimer": default_inactive_timer, + "DefaultClosedTimer": default_closed_timer, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConfigurationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class ConfigurationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ConfigurationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._webhooks: Optional[WebhookList] = None + + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + if self._webhooks is None: + self._webhooks = WebhookList(self._version) + return self._webhooks + + def get(self) -> ConfigurationContext: + """ + Constructs a ConfigurationContext + + """ + return ConfigurationContext(self._version) + + def __call__(self) -> ConfigurationContext: + """ + Constructs a ConfigurationContext + + """ + return ConfigurationContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/configuration/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/configuration/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..196583b9 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/configuration/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/configuration/__pycache__/webhook.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/configuration/__pycache__/webhook.cpython-312.pyc new file mode 100644 index 00000000..133b1395 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/configuration/__pycache__/webhook.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/configuration/webhook.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/configuration/webhook.py new file mode 100644 index 00000000..f471c879 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/configuration/webhook.py @@ -0,0 +1,327 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WebhookInstance(InstanceResource): + + class Method(object): + GET = "GET" + POST = "POST" + + class Target(object): + WEBHOOK = "webhook" + FLEX = "flex" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar method: + :ivar filters: The list of webhook event triggers that are enabled for this Service: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onMessageAdd`, `onMessageUpdate`, `onMessageRemove`, `onConversationUpdated`, `onConversationRemoved`, `onConversationAdd`, `onConversationAdded`, `onConversationRemove`, `onConversationUpdate`, `onConversationStateUpdated`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onParticipantAdd`, `onParticipantRemove`, `onParticipantUpdate`, `onDeliveryUpdated`, `onUserAdded`, `onUserUpdate`, `onUserUpdated` + :ivar pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :ivar post_webhook_url: The absolute url the post-event webhook request should be sent to. + :ivar target: + :ivar url: An absolute API resource API resource URL for this webhook. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.method: Optional["WebhookInstance.Method"] = payload.get("method") + self.filters: Optional[List[str]] = payload.get("filters") + self.pre_webhook_url: Optional[str] = payload.get("pre_webhook_url") + self.post_webhook_url: Optional[str] = payload.get("post_webhook_url") + self.target: Optional["WebhookInstance.Target"] = payload.get("target") + self.url: Optional[str] = payload.get("url") + + self._context: Optional[WebhookContext] = None + + @property + def _proxy(self) -> "WebhookContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WebhookContext for this WebhookInstance + """ + if self._context is None: + self._context = WebhookContext( + self._version, + ) + return self._context + + def fetch(self) -> "WebhookInstance": + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "WebhookInstance": + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + method: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + target: Union["WebhookInstance.Target", object] = values.unset, + ) -> "WebhookInstance": + """ + Update the WebhookInstance + + :param method: The HTTP method to be used when sending a webhook request. + :param filters: The list of webhook event triggers that are enabled for this Service: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onMessageAdd`, `onMessageUpdate`, `onMessageRemove`, `onConversationUpdated`, `onConversationRemoved`, `onConversationAdd`, `onConversationAdded`, `onConversationRemove`, `onConversationUpdate`, `onConversationStateUpdated`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onParticipantAdd`, `onParticipantRemove`, `onParticipantUpdate`, `onDeliveryUpdated`, `onUserAdded`, `onUserUpdate`, `onUserUpdated` + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param target: + + :returns: The updated WebhookInstance + """ + return self._proxy.update( + method=method, + filters=filters, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + target=target, + ) + + async def update_async( + self, + method: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + target: Union["WebhookInstance.Target", object] = values.unset, + ) -> "WebhookInstance": + """ + Asynchronous coroutine to update the WebhookInstance + + :param method: The HTTP method to be used when sending a webhook request. + :param filters: The list of webhook event triggers that are enabled for this Service: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onMessageAdd`, `onMessageUpdate`, `onMessageRemove`, `onConversationUpdated`, `onConversationRemoved`, `onConversationAdd`, `onConversationAdded`, `onConversationRemove`, `onConversationUpdate`, `onConversationStateUpdated`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onParticipantAdd`, `onParticipantRemove`, `onParticipantUpdate`, `onDeliveryUpdated`, `onUserAdded`, `onUserUpdate`, `onUserUpdated` + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param target: + + :returns: The updated WebhookInstance + """ + return await self._proxy.update_async( + method=method, + filters=filters, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + target=target, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class WebhookContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the WebhookContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/Configuration/Webhooks" + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WebhookInstance( + self._version, + payload, + ) + + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + ) + + def update( + self, + method: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + target: Union["WebhookInstance.Target", object] = values.unset, + ) -> WebhookInstance: + """ + Update the WebhookInstance + + :param method: The HTTP method to be used when sending a webhook request. + :param filters: The list of webhook event triggers that are enabled for this Service: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onMessageAdd`, `onMessageUpdate`, `onMessageRemove`, `onConversationUpdated`, `onConversationRemoved`, `onConversationAdd`, `onConversationAdded`, `onConversationRemove`, `onConversationUpdate`, `onConversationStateUpdated`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onParticipantAdd`, `onParticipantRemove`, `onParticipantUpdate`, `onDeliveryUpdated`, `onUserAdded`, `onUserUpdate`, `onUserUpdated` + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param target: + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "Method": method, + "Filters": serialize.map(filters, lambda e: e), + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "Target": target, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance(self._version, payload) + + async def update_async( + self, + method: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + target: Union["WebhookInstance.Target", object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronous coroutine to update the WebhookInstance + + :param method: The HTTP method to be used when sending a webhook request. + :param filters: The list of webhook event triggers that are enabled for this Service: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onMessageAdd`, `onMessageUpdate`, `onMessageRemove`, `onConversationUpdated`, `onConversationRemoved`, `onConversationAdd`, `onConversationAdded`, `onConversationRemove`, `onConversationUpdate`, `onConversationStateUpdated`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onParticipantAdd`, `onParticipantRemove`, `onParticipantUpdate`, `onDeliveryUpdated`, `onUserAdded`, `onUserUpdate`, `onUserUpdated` + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param target: + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "Method": method, + "Filters": serialize.map(filters, lambda e: e), + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "Target": target, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class WebhookList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the WebhookList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> WebhookContext: + """ + Constructs a WebhookContext + + """ + return WebhookContext(self._version) + + def __call__(self) -> WebhookContext: + """ + Constructs a WebhookContext + + """ + return WebhookContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/__init__.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/__init__.py new file mode 100644 index 00000000..d1f08cc2 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/__init__.py @@ -0,0 +1,1025 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.conversations.v1.conversation.message import MessageList +from twilio.rest.conversations.v1.conversation.participant import ParticipantList +from twilio.rest.conversations.v1.conversation.webhook import WebhookList + + +class ConversationInstance(InstanceResource): + + class State(object): + INACTIVE = "inactive" + ACTIVE = "active" + CLOSED = "closed" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + :ivar messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :ivar attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + :ivar state: + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + :ivar timers: Timer date values representing state update for this conversation. + :ivar url: An absolute API resource URL for this conversation. + :ivar links: Contains absolute URLs to access the [participants](https://www.twilio.com/docs/conversations/api/conversation-participant-resource), [messages](https://www.twilio.com/docs/conversations/api/conversation-message-resource) and [webhooks](https://www.twilio.com/docs/conversations/api/conversation-scoped-webhook-resource) of this conversation. + :ivar bindings: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.attributes: Optional[str] = payload.get("attributes") + self.state: Optional["ConversationInstance.State"] = payload.get("state") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.timers: Optional[Dict[str, object]] = payload.get("timers") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.bindings: Optional[Dict[str, object]] = payload.get("bindings") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ConversationContext] = None + + @property + def _proxy(self) -> "ConversationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConversationContext for this ConversationInstance + """ + if self._context is None: + self._context = ConversationContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "ConversationInstance": + """ + Fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConversationInstance": + """ + Asynchronous coroutine to fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> "ConversationInstance": + """ + Update the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The updated ConversationInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> "ConversationInstance": + """ + Asynchronous coroutine to update the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The updated ConversationInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages + + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + return self._proxy.participants + + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + return self._proxy.webhooks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConversationContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ConversationContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this resource. Can also be the `unique_name` of the Conversation. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Conversations/{sid}".format(**self._solution) + + self._messages: Optional[MessageList] = None + self._participants: Optional[ParticipantList] = None + self._webhooks: Optional[WebhookList] = None + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConversationInstance: + """ + Fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ConversationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ConversationInstance: + """ + Asynchronous coroutine to fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ConversationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ConversationInstance: + """ + Update the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The updated ConversationInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MessagingServiceSid": messaging_service_sid, + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "UniqueName": unique_name, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConversationInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ConversationInstance: + """ + Asynchronous coroutine to update the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The updated ConversationInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MessagingServiceSid": messaging_service_sid, + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "UniqueName": unique_name, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConversationInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + if self._messages is None: + self._messages = MessageList( + self._version, + self._solution["sid"], + ) + return self._messages + + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + if self._participants is None: + self._participants = ParticipantList( + self._version, + self._solution["sid"], + ) + return self._participants + + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + if self._webhooks is None: + self._webhooks = WebhookList( + self._version, + self._solution["sid"], + ) + return self._webhooks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConversationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ConversationInstance: + """ + Build an instance of ConversationInstance + + :param payload: Payload response from the API + """ + return ConversationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ConversationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ConversationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Conversations" + + def create( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ConversationInstance: + """ + Create the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The created ConversationInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "MessagingServiceSid": messaging_service_sid, + "Attributes": attributes, + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConversationInstance(self._version, payload) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ConversationInstance: + """ + Asynchronously create the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The created ConversationInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "MessagingServiceSid": messaging_service_sid, + "Attributes": attributes, + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConversationInstance(self._version, payload) + + def stream( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConversationInstance]: + """ + Streams ConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param str end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param "ConversationInstance.State" state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + start_date=start_date, + end_date=end_date, + state=state, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConversationInstance]: + """ + Asynchronously streams ConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param str end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param "ConversationInstance.State" state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + start_date=start_date, + end_date=end_date, + state=state, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConversationInstance]: + """ + Lists ConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param str end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param "ConversationInstance.State" state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + start_date=start_date, + end_date=end_date, + state=state, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConversationInstance]: + """ + Asynchronously lists ConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param str end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param "ConversationInstance.State" state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + start_date=start_date, + end_date=end_date, + state=state, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConversationPage: + """ + Retrieve a single page of ConversationInstance records from the API. + Request is executed immediately + + :param start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConversationInstance + """ + data = values.of( + { + "StartDate": start_date, + "EndDate": end_date, + "State": state, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConversationPage(self._version, response) + + async def page_async( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConversationPage: + """ + Asynchronously retrieve a single page of ConversationInstance records from the API. + Request is executed immediately + + :param start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConversationInstance + """ + data = values.of( + { + "StartDate": start_date, + "EndDate": end_date, + "State": state, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConversationPage(self._version, response) + + def get_page(self, target_url: str) -> ConversationPage: + """ + Retrieve a specific page of ConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConversationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConversationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ConversationPage: + """ + Asynchronously retrieve a specific page of ConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConversationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConversationPage(self._version, response) + + def get(self, sid: str) -> ConversationContext: + """ + Constructs a ConversationContext + + :param sid: A 34 character string that uniquely identifies this resource. Can also be the `unique_name` of the Conversation. + """ + return ConversationContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ConversationContext: + """ + Constructs a ConversationContext + + :param sid: A 34 character string that uniquely identifies this resource. Can also be the `unique_name` of the Conversation. + """ + return ConversationContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..e41e85df Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/__pycache__/participant.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/__pycache__/participant.cpython-312.pyc new file mode 100644 index 00000000..e8b971b4 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/__pycache__/participant.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/__pycache__/webhook.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/__pycache__/webhook.cpython-312.pyc new file mode 100644 index 00000000..39d679a8 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/__pycache__/webhook.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/message/__init__.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/message/__init__.py new file mode 100644 index 00000000..04e7fdf2 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/message/__init__.py @@ -0,0 +1,912 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.conversations.v1.conversation.message.delivery_receipt import ( + DeliveryReceiptList, +) + + +class MessageInstance(InstanceResource): + + class OrderType(object): + ASC = "asc" + DESC = "desc" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this message. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar index: The index of the message within the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource). Indices may skip numbers, but will always be in order of when the message was received. + :ivar author: The channel specific identifier of the message's author. Defaults to `system`. + :ivar body: The content of the message, can be up to 1,600 characters long. + :ivar media: An array of objects that describe the Message's media, if the message contains media. Each object contains these fields: `content_type` with the MIME type of the media, `filename` with the name of the media, `sid` with the SID of the Media resource, and `size` with the media object's file size in bytes. If the Message has no media, this value is `null`. + :ivar attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + :ivar participant_sid: The unique ID of messages's author participant. Null in case of `system` sent message. + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :ivar url: An absolute API resource API URL for this message. + :ivar delivery: An object that contains the summary of delivery statuses for the message to non-chat participants. + :ivar links: Contains an absolute API resource URL to access the delivery & read receipts of this message. + :ivar content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + conversation_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.sid: Optional[str] = payload.get("sid") + self.index: Optional[int] = deserialize.integer(payload.get("index")) + self.author: Optional[str] = payload.get("author") + self.body: Optional[str] = payload.get("body") + self.media: Optional[List[Dict[str, object]]] = payload.get("media") + self.attributes: Optional[str] = payload.get("attributes") + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.delivery: Optional[Dict[str, object]] = payload.get("delivery") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.content_sid: Optional[str] = payload.get("content_sid") + + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid or self.sid, + } + self._context: Optional[MessageContext] = None + + @property + def _proxy(self) -> "MessageContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MessageContext for this MessageInstance + """ + if self._context is None: + self._context = MessageContext( + self._version, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "MessageInstance": + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MessageInstance": + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The updated MessageInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + subject=subject, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Asynchronous coroutine to update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The updated MessageInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + subject=subject, + ) + + @property + def delivery_receipts(self) -> DeliveryReceiptList: + """ + Access the delivery_receipts + """ + return self._proxy.delivery_receipts + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MessageContext(InstanceContext): + + def __init__(self, version: Version, conversation_sid: str, sid: str): + """ + Initialize the MessageContext + + :param version: Version that contains the resource + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid, + } + self._uri = "/Conversations/{conversation_sid}/Messages/{sid}".format( + **self._solution + ) + + self._delivery_receipts: Optional[DeliveryReceiptList] = None + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MessageInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MessageInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Author": author, + "Body": body, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "Subject": subject, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronous coroutine to update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Author": author, + "Body": body, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "Subject": subject, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + @property + def delivery_receipts(self) -> DeliveryReceiptList: + """ + Access the delivery_receipts + """ + if self._delivery_receipts is None: + self._delivery_receipts = DeliveryReceiptList( + self._version, + self._solution["conversation_sid"], + self._solution["sid"], + ) + return self._delivery_receipts + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MessagePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: + """ + Build an instance of MessageInstance + + :param payload: Payload response from the API + """ + return MessageInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MessageList(ListResource): + + def __init__(self, version: Version, conversation_sid: str): + """ + Initialize the MessageList + + :param version: Version that contains the resource + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for messages. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + } + self._uri = "/Conversations/{conversation_sid}/Messages".format( + **self._solution + ) + + def create( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + content_sid: Union[str, object] = values.unset, + content_variables: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param media_sid: The Media SID to be attached to the new Message. + :param content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template, required for template-generated messages. **Note** that if this field is set, `Body` and `MediaSid` parameters are ignored. + :param content_variables: A structurally valid JSON string that contains values to resolve Rich Content template variables. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The created MessageInstance + """ + + data = values.of( + { + "Author": author, + "Body": body, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MediaSid": media_sid, + "ContentSid": content_sid, + "ContentVariables": content_variables, + "Subject": subject, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + content_sid: Union[str, object] = values.unset, + content_variables: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param media_sid: The Media SID to be attached to the new Message. + :param content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template, required for template-generated messages. **Note** that if this field is set, `Body` and `MediaSid` parameters are ignored. + :param content_variables: A structurally valid JSON string that contains values to resolve Rich Content template variables. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The created MessageInstance + """ + + data = values.of( + { + "Author": author, + "Body": body, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MediaSid": media_sid, + "ContentSid": content_sid, + "ContentVariables": content_variables, + "Subject": subject, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + def stream( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: + """ + Streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(order=order, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessageInstance]: + """ + Asynchronously streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(order=order, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + order=order, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Asynchronously lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + order=order, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + async def page_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MessagePage: + """ + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MessagePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MessagePage: + """ + Asynchronously retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagePage(self._version, response, self._solution) + + def get(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return MessageContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) + + def __call__(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return MessageContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/message/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/message/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..5c81d92f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/message/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/message/__pycache__/delivery_receipt.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/message/__pycache__/delivery_receipt.cpython-312.pyc new file mode 100644 index 00000000..c2333695 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/message/__pycache__/delivery_receipt.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/message/delivery_receipt.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/message/delivery_receipt.py new file mode 100644 index 00000000..2ed297e0 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/message/delivery_receipt.py @@ -0,0 +1,482 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DeliveryReceiptInstance(InstanceResource): + + class DeliveryStatus(object): + READ = "read" + FAILED = "failed" + DELIVERED = "delivered" + UNDELIVERED = "undelivered" + SENT = "sent" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this participant. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar message_sid: The SID of the message within a [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) the delivery receipt belongs to + :ivar channel_message_sid: A messaging channel-specific identifier for the message delivered to participant e.g. `SMxx` for SMS, `WAxx` for Whatsapp etc. + :ivar participant_sid: The unique ID of the participant the delivery receipt belongs to. + :ivar status: + :ivar error_code: The message [delivery error code](https://www.twilio.com/docs/sms/api/message-resource#delivery-related-errors) for a `failed` status, + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. `null` if the delivery receipt has not been updated. + :ivar url: An absolute API resource URL for this delivery receipt. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + conversation_sid: str, + message_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.sid: Optional[str] = payload.get("sid") + self.message_sid: Optional[str] = payload.get("message_sid") + self.channel_message_sid: Optional[str] = payload.get("channel_message_sid") + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.status: Optional["DeliveryReceiptInstance.DeliveryStatus"] = payload.get( + "status" + ) + self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "conversation_sid": conversation_sid, + "message_sid": message_sid, + "sid": sid or self.sid, + } + self._context: Optional[DeliveryReceiptContext] = None + + @property + def _proxy(self) -> "DeliveryReceiptContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DeliveryReceiptContext for this DeliveryReceiptInstance + """ + if self._context is None: + self._context = DeliveryReceiptContext( + self._version, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "DeliveryReceiptInstance": + """ + Fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DeliveryReceiptInstance": + """ + Asynchronous coroutine to fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DeliveryReceiptContext(InstanceContext): + + def __init__( + self, version: Version, conversation_sid: str, message_sid: str, sid: str + ): + """ + Initialize the DeliveryReceiptContext + + :param version: Version that contains the resource + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :param message_sid: The SID of the message within a [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) the delivery receipt belongs to. + :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + "message_sid": message_sid, + "sid": sid, + } + self._uri = "/Conversations/{conversation_sid}/Messages/{message_sid}/Receipts/{sid}".format( + **self._solution + ) + + def fetch(self) -> DeliveryReceiptInstance: + """ + Fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DeliveryReceiptInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> DeliveryReceiptInstance: + """ + Asynchronous coroutine to fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DeliveryReceiptInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DeliveryReceiptPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DeliveryReceiptInstance: + """ + Build an instance of DeliveryReceiptInstance + + :param payload: Payload response from the API + """ + return DeliveryReceiptInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class DeliveryReceiptList(ListResource): + + def __init__(self, version: Version, conversation_sid: str, message_sid: str): + """ + Initialize the DeliveryReceiptList + + :param version: Version that contains the resource + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :param message_sid: The SID of the message within a [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) the delivery receipt belongs to. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + "message_sid": message_sid, + } + self._uri = ( + "/Conversations/{conversation_sid}/Messages/{message_sid}/Receipts".format( + **self._solution + ) + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DeliveryReceiptInstance]: + """ + Streams DeliveryReceiptInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DeliveryReceiptInstance]: + """ + Asynchronously streams DeliveryReceiptInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DeliveryReceiptInstance]: + """ + Lists DeliveryReceiptInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DeliveryReceiptInstance]: + """ + Asynchronously lists DeliveryReceiptInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DeliveryReceiptPage: + """ + Retrieve a single page of DeliveryReceiptInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DeliveryReceiptInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DeliveryReceiptPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DeliveryReceiptPage: + """ + Asynchronously retrieve a single page of DeliveryReceiptInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DeliveryReceiptInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DeliveryReceiptPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DeliveryReceiptPage: + """ + Retrieve a specific page of DeliveryReceiptInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DeliveryReceiptInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DeliveryReceiptPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DeliveryReceiptPage: + """ + Asynchronously retrieve a specific page of DeliveryReceiptInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DeliveryReceiptInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DeliveryReceiptPage(self._version, response, self._solution) + + def get(self, sid: str) -> DeliveryReceiptContext: + """ + Constructs a DeliveryReceiptContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return DeliveryReceiptContext( + self._version, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> DeliveryReceiptContext: + """ + Constructs a DeliveryReceiptContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return DeliveryReceiptContext( + self._version, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/participant.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/participant.py new file mode 100644 index 00000000..deb65264 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/participant.py @@ -0,0 +1,895 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ParticipantInstance(InstanceResource): + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this participant. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this participant. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :ivar attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + :ivar messaging_binding: Information about how this participant exchanges messages with the conversation. A JSON parameter consisting of type and address fields of the participant. + :ivar role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + :ivar url: An absolute API resource URL for this participant. + :ivar last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :ivar last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + conversation_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.sid: Optional[str] = payload.get("sid") + self.identity: Optional[str] = payload.get("identity") + self.attributes: Optional[str] = payload.get("attributes") + self.messaging_binding: Optional[Dict[str, object]] = payload.get( + "messaging_binding" + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.last_read_message_index: Optional[int] = deserialize.integer( + payload.get("last_read_message_index") + ) + self.last_read_timestamp: Optional[str] = payload.get("last_read_timestamp") + + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid or self.sid, + } + self._context: Optional[ParticipantContext] = None + + @property + def _proxy(self) -> "ParticipantContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ParticipantContext for this ParticipantInstance + """ + if self._context is None: + self._context = ParticipantContext( + self._version, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "ParticipantInstance": + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ParticipantInstance": + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> "ParticipantInstance": + """ + Update the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: The updated ParticipantInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + identity=identity, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> "ParticipantInstance": + """ + Asynchronous coroutine to update the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: The updated ParticipantInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + identity=identity, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ParticipantContext(InstanceContext): + + def __init__(self, version: Version, conversation_sid: str, sid: str): + """ + Initialize the ParticipantContext + + :param version: Version that contains the resource + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this participant. + :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid, + } + self._uri = "/Conversations/{conversation_sid}/Participants/{sid}".format( + **self._solution + ) + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ParticipantInstance: + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Update the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: The updated ParticipantInstance + """ + + data = values.of( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "RoleSid": role_sid, + "MessagingBinding.ProxyAddress": messaging_binding_proxy_address, + "MessagingBinding.ProjectedAddress": messaging_binding_projected_address, + "Identity": identity, + "LastReadMessageIndex": last_read_message_index, + "LastReadTimestamp": last_read_timestamp, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronous coroutine to update the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: The updated ParticipantInstance + """ + + data = values.of( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "RoleSid": role_sid, + "MessagingBinding.ProxyAddress": messaging_binding_proxy_address, + "MessagingBinding.ProjectedAddress": messaging_binding_projected_address, + "Identity": identity, + "LastReadMessageIndex": last_read_message_index, + "LastReadTimestamp": last_read_timestamp, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ParticipantPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: + """ + Build an instance of ParticipantInstance + + :param payload: Payload response from the API + """ + return ParticipantInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ParticipantList(ListResource): + + def __init__(self, version: Version, conversation_sid: str): + """ + Initialize the ParticipantList + + :param version: Version that contains the resource + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for participants. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + } + self._uri = "/Conversations/{conversation_sid}/Participants".format( + **self._solution + ) + + def create( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + identity: Union[str, object] = values.unset, + messaging_binding_address: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Create the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param messaging_binding_address: The address of the participant's device, e.g. a phone or WhatsApp number. Together with the Proxy address, this determines a participant uniquely. This field (with proxy_address) is only null when the participant is interacting from an SDK endpoint (see the 'identity' field). + :param messaging_binding_proxy_address: The address of the Twilio phone number (or WhatsApp number) that the participant is in contact with. This field, together with participant address, is only null when the participant is interacting from an SDK endpoint (see the 'identity' field). + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. Communication mask for the Conversation participant with Identity. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + + :returns: The created ParticipantInstance + """ + + data = values.of( + { + "Identity": identity, + "MessagingBinding.Address": messaging_binding_address, + "MessagingBinding.ProxyAddress": messaging_binding_proxy_address, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MessagingBinding.ProjectedAddress": messaging_binding_projected_address, + "RoleSid": role_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + identity: Union[str, object] = values.unset, + messaging_binding_address: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronously create the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param messaging_binding_address: The address of the participant's device, e.g. a phone or WhatsApp number. Together with the Proxy address, this determines a participant uniquely. This field (with proxy_address) is only null when the participant is interacting from an SDK endpoint (see the 'identity' field). + :param messaging_binding_proxy_address: The address of the Twilio phone number (or WhatsApp number) that the participant is in contact with. This field, together with participant address, is only null when the participant is interacting from an SDK endpoint (see the 'identity' field). + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. Communication mask for the Conversation participant with Identity. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + + :returns: The created ParticipantInstance + """ + + data = values.of( + { + "Identity": identity, + "MessagingBinding.Address": messaging_binding_address, + "MessagingBinding.ProxyAddress": messaging_binding_proxy_address, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MessagingBinding.ProjectedAddress": messaging_binding_projected_address, + "RoleSid": role_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ParticipantInstance]: + """ + Streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ParticipantInstance]: + """ + Asynchronously streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Asynchronously lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Asynchronously retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ParticipantPage: + """ + Retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ParticipantPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ParticipantPage: + """ + Asynchronously retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ParticipantPage(self._version, response, self._solution) + + def get(self, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return ParticipantContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return ParticipantContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/webhook.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/webhook.py new file mode 100644 index 00000000..837f88c2 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation/webhook.py @@ -0,0 +1,758 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class WebhookInstance(InstanceResource): + + class Method(object): + GET = "GET" + POST = "POST" + + class Target(object): + WEBHOOK = "webhook" + TRIGGER = "trigger" + STUDIO = "studio" + + """ + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this webhook. + :ivar target: The target of this webhook: `webhook`, `studio`, `trigger` + :ivar url: An absolute API resource URL for this webhook. + :ivar configuration: The configuration of this webhook. Is defined based on target. + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + conversation_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.target: Optional[str] = payload.get("target") + self.url: Optional[str] = payload.get("url") + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid or self.sid, + } + self._context: Optional[WebhookContext] = None + + @property + def _proxy(self) -> "WebhookContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WebhookContext for this WebhookInstance + """ + if self._context is None: + self._context = WebhookContext( + self._version, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "WebhookInstance": + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "WebhookInstance": + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> "WebhookInstance": + """ + Update the WebhookInstance + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: The updated WebhookInstance + """ + return self._proxy.update( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + + async def update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> "WebhookInstance": + """ + Asynchronous coroutine to update the WebhookInstance + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: The updated WebhookInstance + """ + return await self._proxy.update_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WebhookContext(InstanceContext): + + def __init__(self, version: Version, conversation_sid: str, sid: str): + """ + Initialize the WebhookContext + + :param version: Version that contains the resource + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this webhook. + :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid, + } + self._uri = "/Conversations/{conversation_sid}/Webhooks/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WebhookInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> WebhookInstance: + """ + Update the WebhookInstance + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronous coroutine to update the WebhookInstance + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WebhookPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: + """ + Build an instance of WebhookInstance + + :param payload: Payload response from the API + """ + return WebhookInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class WebhookList(ListResource): + + def __init__(self, version: Version, conversation_sid: str): + """ + Initialize the WebhookList + + :param version: Version that contains the resource + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this webhook. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + } + self._uri = "/Conversations/{conversation_sid}/Webhooks".format( + **self._solution + ) + + def create( + self, + target: "WebhookInstance.Target", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_replay_after: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Create the WebhookInstance + + :param target: + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + :param configuration_replay_after: The message index for which and it's successors the webhook will be replayed. Not set by default + + :returns: The created WebhookInstance + """ + + data = values.of( + { + "Target": target, + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + "Configuration.ReplayAfter": configuration_replay_after, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + async def create_async( + self, + target: "WebhookInstance.Target", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_replay_after: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronously create the WebhookInstance + + :param target: + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + :param configuration_replay_after: The message index for which and it's successors the webhook will be replayed. Not set by default + + :returns: The created WebhookInstance + """ + + data = values.of( + { + "Target": target, + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + "Configuration.ReplayAfter": configuration_replay_after, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WebhookInstance]: + """ + Streams WebhookInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WebhookInstance]: + """ + Asynchronously streams WebhookInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: + """ + Lists WebhookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: + """ + Asynchronously lists WebhookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebhookPage: + """ + Retrieve a single page of WebhookInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebhookInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebhookPage: + """ + Asynchronously retrieve a single page of WebhookInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebhookInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> WebhookPage: + """ + Retrieve a specific page of WebhookInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebhookInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return WebhookPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> WebhookPage: + """ + Asynchronously retrieve a specific page of WebhookInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebhookInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return WebhookPage(self._version, response, self._solution) + + def get(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return WebhookContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) + + def __call__(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return WebhookContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation_with_participants.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation_with_participants.py new file mode 100644 index 00000000..a818a29c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/conversation_with_participants.py @@ -0,0 +1,251 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ConversationWithParticipantsInstance(InstanceResource): + + class State(object): + INACTIVE = "inactive" + ACTIVE = "active" + CLOSED = "closed" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + :ivar messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :ivar attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + :ivar state: + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + :ivar timers: Timer date values representing state update for this conversation. + :ivar links: Contains absolute URLs to access the [participants](https://www.twilio.com/docs/conversations/api/conversation-participant-resource), [messages](https://www.twilio.com/docs/conversations/api/conversation-message-resource) and [webhooks](https://www.twilio.com/docs/conversations/api/conversation-scoped-webhook-resource) of this conversation. + :ivar bindings: + :ivar url: An absolute API resource URL for this conversation. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.attributes: Optional[str] = payload.get("attributes") + self.state: Optional["ConversationWithParticipantsInstance.State"] = ( + payload.get("state") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.timers: Optional[Dict[str, object]] = payload.get("timers") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.bindings: Optional[Dict[str, object]] = payload.get("bindings") + self.url: Optional[str] = payload.get("url") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class ConversationWithParticipantsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ConversationWithParticipantsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ConversationWithParticipants" + + def create( + self, + x_twilio_webhook_enabled: Union[ + "ConversationWithParticipantsInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union[ + "ConversationWithParticipantsInstance.State", object + ] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + participant: Union[List[str], object] = values.unset, + ) -> ConversationWithParticipantsInstance: + """ + Create the ConversationWithParticipantsInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + :param participant: The participant to be added to the conversation in JSON format. The JSON object attributes are as parameters in [Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). The maximum number of participants that can be added in a single request is 10. + + :returns: The created ConversationWithParticipantsInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "MessagingServiceSid": messaging_service_sid, + "Attributes": attributes, + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + "Participant": serialize.map(participant, lambda e: e), + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConversationWithParticipantsInstance(self._version, payload) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationWithParticipantsInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union[ + "ConversationWithParticipantsInstance.State", object + ] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + participant: Union[List[str], object] = values.unset, + ) -> ConversationWithParticipantsInstance: + """ + Asynchronously create the ConversationWithParticipantsInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + :param participant: The participant to be added to the conversation in JSON format. The JSON object attributes are as parameters in [Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). The maximum number of participants that can be added in a single request is 10. + + :returns: The created ConversationWithParticipantsInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "MessagingServiceSid": messaging_service_sid, + "Attributes": attributes, + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + "Participant": serialize.map(participant, lambda e: e), + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConversationWithParticipantsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/credential.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/credential.py new file mode 100644 index 00000000..f382458b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/credential.py @@ -0,0 +1,723 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CredentialInstance(InstanceResource): + + class PushType(object): + APN = "apn" + GCM = "gcm" + FCM = "fcm" + + """ + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this credential. + :ivar friendly_name: The human-readable name of this credential, limited to 64 characters. Optional. + :ivar type: + :ivar sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + :ivar url: An absolute API resource URL for this credential. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["CredentialInstance.PushType"] = payload.get("type") + self.sandbox: Optional[str] = payload.get("sandbox") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CredentialContext] = None + + @property + def _proxy(self) -> "CredentialContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CredentialInstance": + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CredentialInstance": + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + type: Union["CredentialInstance.PushType", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Update the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + return self._proxy.update( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_async( + self, + type: Union["CredentialInstance.PushType", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Asynchronous coroutine to update the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + return await self._proxy.update_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CredentialContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialInstance: + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + type: Union["CredentialInstance.PushType", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Update the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + type: Union["CredentialInstance.PushType", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronous coroutine to update the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: + """ + Build an instance of CredentialInstance + + :param payload: Payload response from the API + """ + return CredentialInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CredentialList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CredentialList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Credentials" + + def create( + self, + type: "CredentialInstance.PushType", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Create the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload) + + async def create_async( + self, + type: "CredentialInstance.PushType", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialInstance]: + """ + Streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialInstance]: + """ + Asynchronously streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Asynchronously lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Asynchronously retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response) + + def get_page(self, target_url: str) -> CredentialPage: + """ + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CredentialPage: + """ + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response) + + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return CredentialContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return CredentialContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/participant_conversation.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/participant_conversation.py new file mode 100644 index 00000000..0938bd54 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/participant_conversation.py @@ -0,0 +1,366 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ParticipantConversationInstance(InstanceResource): + + class State(object): + INACTIVE = "inactive" + ACTIVE = "active" + CLOSED = "closed" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + :ivar participant_sid: The unique ID of the [Participant](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). + :ivar participant_user_sid: The unique string that identifies the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). + :ivar participant_identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :ivar participant_messaging_binding: Information about how this participant exchanges messages with the conversation. A JSON parameter consisting of type and address fields of the participant. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) this Participant belongs to. + :ivar conversation_unique_name: An application-defined string that uniquely identifies the Conversation resource. + :ivar conversation_friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :ivar conversation_attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + :ivar conversation_date_created: The date that this conversation was created, given in ISO 8601 format. + :ivar conversation_date_updated: The date that this conversation was last updated, given in ISO 8601 format. + :ivar conversation_created_by: Identity of the creator of this Conversation. + :ivar conversation_state: + :ivar conversation_timers: Timer date values representing state update for this conversation. + :ivar links: Contains absolute URLs to access the [participant](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) and [conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) of this conversation. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.participant_user_sid: Optional[str] = payload.get("participant_user_sid") + self.participant_identity: Optional[str] = payload.get("participant_identity") + self.participant_messaging_binding: Optional[Dict[str, object]] = payload.get( + "participant_messaging_binding" + ) + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.conversation_unique_name: Optional[str] = payload.get( + "conversation_unique_name" + ) + self.conversation_friendly_name: Optional[str] = payload.get( + "conversation_friendly_name" + ) + self.conversation_attributes: Optional[str] = payload.get( + "conversation_attributes" + ) + self.conversation_date_created: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("conversation_date_created")) + ) + self.conversation_date_updated: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("conversation_date_updated")) + ) + self.conversation_created_by: Optional[str] = payload.get( + "conversation_created_by" + ) + self.conversation_state: Optional["ParticipantConversationInstance.State"] = ( + payload.get("conversation_state") + ) + self.conversation_timers: Optional[Dict[str, object]] = payload.get( + "conversation_timers" + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class ParticipantConversationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ParticipantConversationInstance: + """ + Build an instance of ParticipantConversationInstance + + :param payload: Payload response from the API + """ + return ParticipantConversationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ParticipantConversationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ParticipantConversationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ParticipantConversations" + + def stream( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ParticipantConversationInstance]: + """ + Streams ParticipantConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + identity=identity, address=address, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ParticipantConversationInstance]: + """ + Asynchronously streams ParticipantConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + identity=identity, address=address, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantConversationInstance]: + """ + Lists ParticipantConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + identity=identity, + address=address, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantConversationInstance]: + """ + Asynchronously lists ParticipantConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + identity=identity, + address=address, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantConversationPage: + """ + Retrieve a single page of ParticipantConversationInstance records from the API. + Request is executed immediately + + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantConversationInstance + """ + data = values.of( + { + "Identity": identity, + "Address": address, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantConversationPage(self._version, response) + + async def page_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantConversationPage: + """ + Asynchronously retrieve a single page of ParticipantConversationInstance records from the API. + Request is executed immediately + + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantConversationInstance + """ + data = values.of( + { + "Identity": identity, + "Address": address, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantConversationPage(self._version, response) + + def get_page(self, target_url: str) -> ParticipantConversationPage: + """ + Retrieve a specific page of ParticipantConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantConversationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ParticipantConversationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ParticipantConversationPage: + """ + Asynchronously retrieve a specific page of ParticipantConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantConversationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ParticipantConversationPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/role.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/role.py new file mode 100644 index 00000000..229e9b7d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/role.py @@ -0,0 +1,610 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RoleInstance(InstanceResource): + + class RoleType(object): + CONVERSATION = "conversation" + SERVICE = "service" + + """ + :ivar sid: The unique string that we created to identify the Role resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Role resource. + :ivar chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Role resource is associated with. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar permissions: An array of the permissions the role has been granted. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: An absolute API resource URL for this user role. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["RoleInstance.RoleType"] = payload.get("type") + self.permissions: Optional[List[str]] = payload.get("permissions") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[RoleContext] = None + + @property + def _proxy(self) -> "RoleContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RoleContext for this RoleInstance + """ + if self._context is None: + self._context = RoleContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RoleInstance": + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RoleInstance": + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + return await self._proxy.fetch_async() + + def update(self, permission: List[str]) -> "RoleInstance": + """ + Update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + return self._proxy.update( + permission=permission, + ) + + async def update_async(self, permission: List[str]) -> "RoleInstance": + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + return await self._proxy.update_async( + permission=permission, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RoleContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the RoleContext + + :param version: Version that contains the resource + :param sid: The SID of the Role resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Roles/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RoleInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RoleInstance: + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RoleInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update(self, permission: List[str]) -> RoleInstance: + """ + Update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async(self, permission: List[str]) -> RoleInstance: + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RolePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: + """ + Build an instance of RoleInstance + + :param payload: Payload response from the API + """ + return RoleInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RoleList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the RoleList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Roles" + + def create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: The created RoleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance(self._version, payload) + + async def create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Asynchronously create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: The created RoleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoleInstance]: + """ + Streams RoleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RoleInstance]: + """ + Asynchronously streams RoleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: + """ + Lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: + """ + Asynchronously lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePage: + """ + Retrieve a single page of RoleInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePage: + """ + Asynchronously retrieve a single page of RoleInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePage(self._version, response) + + def get_page(self, target_url: str) -> RolePage: + """ + Retrieve a specific page of RoleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RolePage(self._version, response) + + async def get_page_async(self, target_url: str) -> RolePage: + """ + Asynchronously retrieve a specific page of RoleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RolePage(self._version, response) + + def get(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: The SID of the Role resource to update. + """ + return RoleContext(self._version, sid=sid) + + def __call__(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: The SID of the Role resource to update. + """ + return RoleContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/__init__.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/__init__.py new file mode 100644 index 00000000..3b92c879 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/__init__.py @@ -0,0 +1,667 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.conversations.v1.service.binding import BindingList +from twilio.rest.conversations.v1.service.configuration import ConfigurationList +from twilio.rest.conversations.v1.service.conversation import ConversationList +from twilio.rest.conversations.v1.service.conversation_with_participants import ( + ConversationWithParticipantsList, +) +from twilio.rest.conversations.v1.service.participant_conversation import ( + ParticipantConversationList, +) +from twilio.rest.conversations.v1.service.role import RoleList +from twilio.rest.conversations.v1.service.user import UserList + + +class ServiceInstance(InstanceResource): + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this service. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar friendly_name: The human-readable name of this service, limited to 256 characters. Optional. + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + :ivar url: An absolute API resource URL for this service. + :ivar links: Contains absolute API resource URLs to access conversations, users, roles, bindings and configuration of this service. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + return self._proxy.bindings + + @property + def configuration(self) -> ConfigurationList: + """ + Access the configuration + """ + return self._proxy.configuration + + @property + def conversations(self) -> ConversationList: + """ + Access the conversations + """ + return self._proxy.conversations + + @property + def conversation_with_participants(self) -> ConversationWithParticipantsList: + """ + Access the conversation_with_participants + """ + return self._proxy.conversation_with_participants + + @property + def participant_conversations(self) -> ParticipantConversationList: + """ + Access the participant_conversations + """ + return self._proxy.participant_conversations + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + return self._proxy.roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + return self._proxy.users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._bindings: Optional[BindingList] = None + self._configuration: Optional[ConfigurationList] = None + self._conversations: Optional[ConversationList] = None + self._conversation_with_participants: Optional[ + ConversationWithParticipantsList + ] = None + self._participant_conversations: Optional[ParticipantConversationList] = None + self._roles: Optional[RoleList] = None + self._users: Optional[UserList] = None + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + if self._bindings is None: + self._bindings = BindingList( + self._version, + self._solution["sid"], + ) + return self._bindings + + @property + def configuration(self) -> ConfigurationList: + """ + Access the configuration + """ + if self._configuration is None: + self._configuration = ConfigurationList( + self._version, + self._solution["sid"], + ) + return self._configuration + + @property + def conversations(self) -> ConversationList: + """ + Access the conversations + """ + if self._conversations is None: + self._conversations = ConversationList( + self._version, + self._solution["sid"], + ) + return self._conversations + + @property + def conversation_with_participants(self) -> ConversationWithParticipantsList: + """ + Access the conversation_with_participants + """ + if self._conversation_with_participants is None: + self._conversation_with_participants = ConversationWithParticipantsList( + self._version, + self._solution["sid"], + ) + return self._conversation_with_participants + + @property + def participant_conversations(self) -> ParticipantConversationList: + """ + Access the participant_conversations + """ + if self._participant_conversations is None: + self._participant_conversations = ParticipantConversationList( + self._version, + self._solution["sid"], + ) + return self._participant_conversations + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + if self._roles is None: + self._roles = RoleList( + self._version, + self._solution["sid"], + ) + return self._roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + if self._users is None: + self._users = UserList( + self._version, + self._solution["sid"], + ) + return self._users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def create(self, friendly_name: str) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: The human-readable name of this service, limited to 256 characters. Optional. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async(self, friendly_name: str) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: The human-readable name of this service, limited to 256 characters. Optional. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..29ac49e3 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/__pycache__/binding.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/__pycache__/binding.cpython-312.pyc new file mode 100644 index 00000000..012bd946 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/__pycache__/binding.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/__pycache__/conversation_with_participants.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/__pycache__/conversation_with_participants.cpython-312.pyc new file mode 100644 index 00000000..7bc4753e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/__pycache__/conversation_with_participants.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/__pycache__/participant_conversation.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/__pycache__/participant_conversation.cpython-312.pyc new file mode 100644 index 00000000..fa0cd4cf Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/__pycache__/participant_conversation.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/__pycache__/role.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/__pycache__/role.cpython-312.pyc new file mode 100644 index 00000000..615c152e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/__pycache__/role.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/binding.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/binding.py new file mode 100644 index 00000000..363dab91 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/binding.py @@ -0,0 +1,536 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class BindingInstance(InstanceResource): + + class BindingType(object): + APN = "apn" + GCM = "gcm" + FCM = "fcm" + + """ + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this binding. + :ivar chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Binding resource is associated with. + :ivar credential_sid: The SID of the [Credential](https://www.twilio.com/docs/conversations/api/credential-resource) for the binding. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + :ivar endpoint: The unique endpoint identifier for the Binding. The format of this value depends on the `binding_type`. + :ivar identity: The application-defined string that uniquely identifies the [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more info. + :ivar binding_type: + :ivar message_types: The [Conversation message types](https://www.twilio.com/docs/chat/push-notification-configuration#push-types) the binding is subscribed to. + :ivar url: An absolute API resource URL for this binding. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + chat_service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.credential_sid: Optional[str] = payload.get("credential_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.endpoint: Optional[str] = payload.get("endpoint") + self.identity: Optional[str] = payload.get("identity") + self.binding_type: Optional["BindingInstance.BindingType"] = payload.get( + "binding_type" + ) + self.message_types: Optional[List[str]] = payload.get("message_types") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "chat_service_sid": chat_service_sid, + "sid": sid or self.sid, + } + self._context: Optional[BindingContext] = None + + @property + def _proxy(self) -> "BindingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BindingContext for this BindingInstance + """ + if self._context is None: + self._context = BindingContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "BindingInstance": + """ + Fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BindingInstance": + """ + Asynchronous coroutine to fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BindingContext(InstanceContext): + + def __init__(self, version: Version, chat_service_sid: str, sid: str): + """ + Initialize the BindingContext + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Binding resource is associated with. + :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "sid": sid, + } + self._uri = "/Services/{chat_service_sid}/Bindings/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> BindingInstance: + """ + Fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return BindingInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> BindingInstance: + """ + Asynchronous coroutine to fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return BindingInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BindingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> BindingInstance: + """ + Build an instance of BindingInstance + + :param payload: Payload response from the API + """ + return BindingInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class BindingList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the BindingList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Binding resource is associated with. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._uri = "/Services/{chat_service_sid}/Bindings".format(**self._solution) + + def stream( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BindingInstance]: + """ + Streams BindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BindingInstance]: + """ + Asynchronously streams BindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BindingInstance]: + """ + Lists BindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BindingInstance]: + """ + Asynchronously lists BindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BindingPage: + """ + Retrieve a single page of BindingInstance records from the API. + Request is executed immediately + + :param binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param identity: The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BindingInstance + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BindingPage(self._version, response, self._solution) + + async def page_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BindingPage: + """ + Asynchronously retrieve a single page of BindingInstance records from the API. + Request is executed immediately + + :param binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param identity: The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BindingInstance + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BindingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> BindingPage: + """ + Retrieve a specific page of BindingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BindingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return BindingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> BindingPage: + """ + Asynchronously retrieve a specific page of BindingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BindingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return BindingPage(self._version, response, self._solution) + + def get(self, sid: str) -> BindingContext: + """ + Constructs a BindingContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return BindingContext( + self._version, chat_service_sid=self._solution["chat_service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> BindingContext: + """ + Constructs a BindingContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return BindingContext( + self._version, chat_service_sid=self._solution["chat_service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/configuration/__init__.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/configuration/__init__.py new file mode 100644 index 00000000..e37c8888 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/configuration/__init__.py @@ -0,0 +1,375 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.conversations.v1.service.configuration.notification import ( + NotificationList, +) +from twilio.rest.conversations.v1.service.configuration.webhook import WebhookList + + +class ConfigurationInstance(InstanceResource): + """ + :ivar chat_service_sid: The unique string that we created to identify the Service configuration resource. + :ivar default_conversation_creator_role_sid: The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :ivar default_conversation_role_sid: The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :ivar default_chat_service_role_sid: The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :ivar url: An absolute API resource URL for this service configuration. + :ivar links: Contains an absolute API resource URL to access the push notifications configuration of this service. + :ivar reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], chat_service_sid: str + ): + super().__init__(version) + + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.default_conversation_creator_role_sid: Optional[str] = payload.get( + "default_conversation_creator_role_sid" + ) + self.default_conversation_role_sid: Optional[str] = payload.get( + "default_conversation_role_sid" + ) + self.default_chat_service_role_sid: Optional[str] = payload.get( + "default_chat_service_role_sid" + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.reachability_enabled: Optional[bool] = payload.get("reachability_enabled") + + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._context: Optional[ConfigurationContext] = None + + @property + def _proxy(self) -> "ConfigurationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConfigurationContext for this ConfigurationInstance + """ + if self._context is None: + self._context = ConfigurationContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + ) + return self._context + + def fetch(self) -> "ConfigurationInstance": + """ + Fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConfigurationInstance": + """ + Asynchronous coroutine to fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + default_conversation_creator_role_sid: Union[str, object] = values.unset, + default_conversation_role_sid: Union[str, object] = values.unset, + default_chat_service_role_sid: Union[str, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + ) -> "ConfigurationInstance": + """ + Update the ConfigurationInstance + + :param default_conversation_creator_role_sid: The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_conversation_role_sid: The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_chat_service_role_sid: The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. + + :returns: The updated ConfigurationInstance + """ + return self._proxy.update( + default_conversation_creator_role_sid=default_conversation_creator_role_sid, + default_conversation_role_sid=default_conversation_role_sid, + default_chat_service_role_sid=default_chat_service_role_sid, + reachability_enabled=reachability_enabled, + ) + + async def update_async( + self, + default_conversation_creator_role_sid: Union[str, object] = values.unset, + default_conversation_role_sid: Union[str, object] = values.unset, + default_chat_service_role_sid: Union[str, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + ) -> "ConfigurationInstance": + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param default_conversation_creator_role_sid: The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_conversation_role_sid: The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_chat_service_role_sid: The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. + + :returns: The updated ConfigurationInstance + """ + return await self._proxy.update_async( + default_conversation_creator_role_sid=default_conversation_creator_role_sid, + default_conversation_role_sid=default_conversation_role_sid, + default_chat_service_role_sid=default_chat_service_role_sid, + reachability_enabled=reachability_enabled, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConfigurationContext(InstanceContext): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the ConfigurationContext + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the Service configuration resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._uri = "/Services/{chat_service_sid}/Configuration".format( + **self._solution + ) + + def fetch(self) -> ConfigurationInstance: + """ + Fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ConfigurationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + + async def fetch_async(self) -> ConfigurationInstance: + """ + Asynchronous coroutine to fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ConfigurationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + + def update( + self, + default_conversation_creator_role_sid: Union[str, object] = values.unset, + default_conversation_role_sid: Union[str, object] = values.unset, + default_chat_service_role_sid: Union[str, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + ) -> ConfigurationInstance: + """ + Update the ConfigurationInstance + + :param default_conversation_creator_role_sid: The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_conversation_role_sid: The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_chat_service_role_sid: The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. + + :returns: The updated ConfigurationInstance + """ + + data = values.of( + { + "DefaultConversationCreatorRoleSid": default_conversation_creator_role_sid, + "DefaultConversationRoleSid": default_conversation_role_sid, + "DefaultChatServiceRoleSid": default_chat_service_role_sid, + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConfigurationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + async def update_async( + self, + default_conversation_creator_role_sid: Union[str, object] = values.unset, + default_conversation_role_sid: Union[str, object] = values.unset, + default_chat_service_role_sid: Union[str, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + ) -> ConfigurationInstance: + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param default_conversation_creator_role_sid: The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_conversation_role_sid: The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_chat_service_role_sid: The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. + + :returns: The updated ConfigurationInstance + """ + + data = values.of( + { + "DefaultConversationCreatorRoleSid": default_conversation_creator_role_sid, + "DefaultConversationRoleSid": default_conversation_role_sid, + "DefaultChatServiceRoleSid": default_chat_service_role_sid, + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConfigurationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConfigurationList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the ConfigurationList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the Service configuration resource to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + + self._notifications: Optional[NotificationList] = None + self._webhooks: Optional[WebhookList] = None + + @property + def notifications(self) -> NotificationList: + """ + Access the notifications + """ + if self._notifications is None: + self._notifications = NotificationList( + self._version, chat_service_sid=self._solution["chat_service_sid"] + ) + return self._notifications + + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + if self._webhooks is None: + self._webhooks = WebhookList( + self._version, chat_service_sid=self._solution["chat_service_sid"] + ) + return self._webhooks + + def get(self) -> ConfigurationContext: + """ + Constructs a ConfigurationContext + + """ + return ConfigurationContext( + self._version, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __call__(self) -> ConfigurationContext: + """ + Constructs a ConfigurationContext + + """ + return ConfigurationContext( + self._version, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/configuration/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/configuration/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..63431806 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/configuration/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/configuration/__pycache__/notification.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/configuration/__pycache__/notification.cpython-312.pyc new file mode 100644 index 00000000..d4b5d1e2 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/configuration/__pycache__/notification.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/configuration/__pycache__/webhook.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/configuration/__pycache__/webhook.cpython-312.pyc new file mode 100644 index 00000000..3ecf847c Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/configuration/__pycache__/webhook.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/configuration/notification.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/configuration/notification.py new file mode 100644 index 00000000..6aced281 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/configuration/notification.py @@ -0,0 +1,463 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NotificationInstance(InstanceResource): + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this configuration. + :ivar chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Configuration applies to. + :ivar new_message: The Push Notification configuration for New Messages. + :ivar added_to_conversation: The Push Notification configuration for being added to a Conversation. + :ivar removed_from_conversation: The Push Notification configuration for being removed from a Conversation. + :ivar log_enabled: Weather the notification logging is enabled. + :ivar url: An absolute API resource URL for this configuration. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], chat_service_sid: str + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.new_message: Optional[Dict[str, object]] = payload.get("new_message") + self.added_to_conversation: Optional[Dict[str, object]] = payload.get( + "added_to_conversation" + ) + self.removed_from_conversation: Optional[Dict[str, object]] = payload.get( + "removed_from_conversation" + ) + self.log_enabled: Optional[bool] = payload.get("log_enabled") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._context: Optional[NotificationContext] = None + + @property + def _proxy(self) -> "NotificationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: NotificationContext for this NotificationInstance + """ + if self._context is None: + self._context = NotificationContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + ) + return self._context + + def fetch(self) -> "NotificationInstance": + """ + Fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "NotificationInstance": + """ + Asynchronous coroutine to fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + log_enabled: Union[bool, object] = values.unset, + new_message_enabled: Union[bool, object] = values.unset, + new_message_template: Union[str, object] = values.unset, + new_message_sound: Union[str, object] = values.unset, + new_message_badge_count_enabled: Union[bool, object] = values.unset, + added_to_conversation_enabled: Union[bool, object] = values.unset, + added_to_conversation_template: Union[str, object] = values.unset, + added_to_conversation_sound: Union[str, object] = values.unset, + removed_from_conversation_enabled: Union[bool, object] = values.unset, + removed_from_conversation_template: Union[str, object] = values.unset, + removed_from_conversation_sound: Union[str, object] = values.unset, + new_message_with_media_enabled: Union[bool, object] = values.unset, + new_message_with_media_template: Union[str, object] = values.unset, + ) -> "NotificationInstance": + """ + Update the NotificationInstance + + :param log_enabled: Weather the notification logging is enabled. + :param new_message_enabled: Whether to send a notification when a new message is added to a conversation. The default is `false`. + :param new_message_template: The template to use to create the notification text displayed when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_sound: The name of the sound to play when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param added_to_conversation_enabled: Whether to send a notification when a participant is added to a conversation. The default is `false`. + :param added_to_conversation_template: The template to use to create the notification text displayed when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param added_to_conversation_sound: The name of the sound to play when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param removed_from_conversation_enabled: Whether to send a notification to a user when they are removed from a conversation. The default is `false`. + :param removed_from_conversation_template: The template to use to create the notification text displayed to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param removed_from_conversation_sound: The name of the sound to play to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param new_message_with_media_enabled: Whether to send a notification when a new message with media/file attachments is added to a conversation. The default is `false`. + :param new_message_with_media_template: The template to use to create the notification text displayed when a new message with media/file attachments is added to a conversation and `new_message.attachments.enabled` is `true`. + + :returns: The updated NotificationInstance + """ + return self._proxy.update( + log_enabled=log_enabled, + new_message_enabled=new_message_enabled, + new_message_template=new_message_template, + new_message_sound=new_message_sound, + new_message_badge_count_enabled=new_message_badge_count_enabled, + added_to_conversation_enabled=added_to_conversation_enabled, + added_to_conversation_template=added_to_conversation_template, + added_to_conversation_sound=added_to_conversation_sound, + removed_from_conversation_enabled=removed_from_conversation_enabled, + removed_from_conversation_template=removed_from_conversation_template, + removed_from_conversation_sound=removed_from_conversation_sound, + new_message_with_media_enabled=new_message_with_media_enabled, + new_message_with_media_template=new_message_with_media_template, + ) + + async def update_async( + self, + log_enabled: Union[bool, object] = values.unset, + new_message_enabled: Union[bool, object] = values.unset, + new_message_template: Union[str, object] = values.unset, + new_message_sound: Union[str, object] = values.unset, + new_message_badge_count_enabled: Union[bool, object] = values.unset, + added_to_conversation_enabled: Union[bool, object] = values.unset, + added_to_conversation_template: Union[str, object] = values.unset, + added_to_conversation_sound: Union[str, object] = values.unset, + removed_from_conversation_enabled: Union[bool, object] = values.unset, + removed_from_conversation_template: Union[str, object] = values.unset, + removed_from_conversation_sound: Union[str, object] = values.unset, + new_message_with_media_enabled: Union[bool, object] = values.unset, + new_message_with_media_template: Union[str, object] = values.unset, + ) -> "NotificationInstance": + """ + Asynchronous coroutine to update the NotificationInstance + + :param log_enabled: Weather the notification logging is enabled. + :param new_message_enabled: Whether to send a notification when a new message is added to a conversation. The default is `false`. + :param new_message_template: The template to use to create the notification text displayed when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_sound: The name of the sound to play when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param added_to_conversation_enabled: Whether to send a notification when a participant is added to a conversation. The default is `false`. + :param added_to_conversation_template: The template to use to create the notification text displayed when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param added_to_conversation_sound: The name of the sound to play when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param removed_from_conversation_enabled: Whether to send a notification to a user when they are removed from a conversation. The default is `false`. + :param removed_from_conversation_template: The template to use to create the notification text displayed to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param removed_from_conversation_sound: The name of the sound to play to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param new_message_with_media_enabled: Whether to send a notification when a new message with media/file attachments is added to a conversation. The default is `false`. + :param new_message_with_media_template: The template to use to create the notification text displayed when a new message with media/file attachments is added to a conversation and `new_message.attachments.enabled` is `true`. + + :returns: The updated NotificationInstance + """ + return await self._proxy.update_async( + log_enabled=log_enabled, + new_message_enabled=new_message_enabled, + new_message_template=new_message_template, + new_message_sound=new_message_sound, + new_message_badge_count_enabled=new_message_badge_count_enabled, + added_to_conversation_enabled=added_to_conversation_enabled, + added_to_conversation_template=added_to_conversation_template, + added_to_conversation_sound=added_to_conversation_sound, + removed_from_conversation_enabled=removed_from_conversation_enabled, + removed_from_conversation_template=removed_from_conversation_template, + removed_from_conversation_sound=removed_from_conversation_sound, + new_message_with_media_enabled=new_message_with_media_enabled, + new_message_with_media_template=new_message_with_media_template, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NotificationContext(InstanceContext): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the NotificationContext + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Configuration applies to. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._uri = "/Services/{chat_service_sid}/Configuration/Notifications".format( + **self._solution + ) + + def fetch(self) -> NotificationInstance: + """ + Fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return NotificationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + + async def fetch_async(self) -> NotificationInstance: + """ + Asynchronous coroutine to fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return NotificationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + + def update( + self, + log_enabled: Union[bool, object] = values.unset, + new_message_enabled: Union[bool, object] = values.unset, + new_message_template: Union[str, object] = values.unset, + new_message_sound: Union[str, object] = values.unset, + new_message_badge_count_enabled: Union[bool, object] = values.unset, + added_to_conversation_enabled: Union[bool, object] = values.unset, + added_to_conversation_template: Union[str, object] = values.unset, + added_to_conversation_sound: Union[str, object] = values.unset, + removed_from_conversation_enabled: Union[bool, object] = values.unset, + removed_from_conversation_template: Union[str, object] = values.unset, + removed_from_conversation_sound: Union[str, object] = values.unset, + new_message_with_media_enabled: Union[bool, object] = values.unset, + new_message_with_media_template: Union[str, object] = values.unset, + ) -> NotificationInstance: + """ + Update the NotificationInstance + + :param log_enabled: Weather the notification logging is enabled. + :param new_message_enabled: Whether to send a notification when a new message is added to a conversation. The default is `false`. + :param new_message_template: The template to use to create the notification text displayed when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_sound: The name of the sound to play when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param added_to_conversation_enabled: Whether to send a notification when a participant is added to a conversation. The default is `false`. + :param added_to_conversation_template: The template to use to create the notification text displayed when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param added_to_conversation_sound: The name of the sound to play when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param removed_from_conversation_enabled: Whether to send a notification to a user when they are removed from a conversation. The default is `false`. + :param removed_from_conversation_template: The template to use to create the notification text displayed to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param removed_from_conversation_sound: The name of the sound to play to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param new_message_with_media_enabled: Whether to send a notification when a new message with media/file attachments is added to a conversation. The default is `false`. + :param new_message_with_media_template: The template to use to create the notification text displayed when a new message with media/file attachments is added to a conversation and `new_message.attachments.enabled` is `true`. + + :returns: The updated NotificationInstance + """ + + data = values.of( + { + "LogEnabled": serialize.boolean_to_string(log_enabled), + "NewMessage.Enabled": serialize.boolean_to_string(new_message_enabled), + "NewMessage.Template": new_message_template, + "NewMessage.Sound": new_message_sound, + "NewMessage.BadgeCountEnabled": serialize.boolean_to_string( + new_message_badge_count_enabled + ), + "AddedToConversation.Enabled": serialize.boolean_to_string( + added_to_conversation_enabled + ), + "AddedToConversation.Template": added_to_conversation_template, + "AddedToConversation.Sound": added_to_conversation_sound, + "RemovedFromConversation.Enabled": serialize.boolean_to_string( + removed_from_conversation_enabled + ), + "RemovedFromConversation.Template": removed_from_conversation_template, + "RemovedFromConversation.Sound": removed_from_conversation_sound, + "NewMessage.WithMedia.Enabled": serialize.boolean_to_string( + new_message_with_media_enabled + ), + "NewMessage.WithMedia.Template": new_message_with_media_template, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NotificationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + async def update_async( + self, + log_enabled: Union[bool, object] = values.unset, + new_message_enabled: Union[bool, object] = values.unset, + new_message_template: Union[str, object] = values.unset, + new_message_sound: Union[str, object] = values.unset, + new_message_badge_count_enabled: Union[bool, object] = values.unset, + added_to_conversation_enabled: Union[bool, object] = values.unset, + added_to_conversation_template: Union[str, object] = values.unset, + added_to_conversation_sound: Union[str, object] = values.unset, + removed_from_conversation_enabled: Union[bool, object] = values.unset, + removed_from_conversation_template: Union[str, object] = values.unset, + removed_from_conversation_sound: Union[str, object] = values.unset, + new_message_with_media_enabled: Union[bool, object] = values.unset, + new_message_with_media_template: Union[str, object] = values.unset, + ) -> NotificationInstance: + """ + Asynchronous coroutine to update the NotificationInstance + + :param log_enabled: Weather the notification logging is enabled. + :param new_message_enabled: Whether to send a notification when a new message is added to a conversation. The default is `false`. + :param new_message_template: The template to use to create the notification text displayed when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_sound: The name of the sound to play when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param added_to_conversation_enabled: Whether to send a notification when a participant is added to a conversation. The default is `false`. + :param added_to_conversation_template: The template to use to create the notification text displayed when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param added_to_conversation_sound: The name of the sound to play when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param removed_from_conversation_enabled: Whether to send a notification to a user when they are removed from a conversation. The default is `false`. + :param removed_from_conversation_template: The template to use to create the notification text displayed to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param removed_from_conversation_sound: The name of the sound to play to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param new_message_with_media_enabled: Whether to send a notification when a new message with media/file attachments is added to a conversation. The default is `false`. + :param new_message_with_media_template: The template to use to create the notification text displayed when a new message with media/file attachments is added to a conversation and `new_message.attachments.enabled` is `true`. + + :returns: The updated NotificationInstance + """ + + data = values.of( + { + "LogEnabled": serialize.boolean_to_string(log_enabled), + "NewMessage.Enabled": serialize.boolean_to_string(new_message_enabled), + "NewMessage.Template": new_message_template, + "NewMessage.Sound": new_message_sound, + "NewMessage.BadgeCountEnabled": serialize.boolean_to_string( + new_message_badge_count_enabled + ), + "AddedToConversation.Enabled": serialize.boolean_to_string( + added_to_conversation_enabled + ), + "AddedToConversation.Template": added_to_conversation_template, + "AddedToConversation.Sound": added_to_conversation_sound, + "RemovedFromConversation.Enabled": serialize.boolean_to_string( + removed_from_conversation_enabled + ), + "RemovedFromConversation.Template": removed_from_conversation_template, + "RemovedFromConversation.Sound": removed_from_conversation_sound, + "NewMessage.WithMedia.Enabled": serialize.boolean_to_string( + new_message_with_media_enabled + ), + "NewMessage.WithMedia.Template": new_message_with_media_template, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NotificationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NotificationList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the NotificationList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Configuration applies to. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + + def get(self) -> NotificationContext: + """ + Constructs a NotificationContext + + """ + return NotificationContext( + self._version, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __call__(self) -> NotificationContext: + """ + Constructs a NotificationContext + + """ + return NotificationContext( + self._version, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/configuration/webhook.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/configuration/webhook.py new file mode 100644 index 00000000..706f4105 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/configuration/webhook.py @@ -0,0 +1,340 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WebhookInstance(InstanceResource): + + class Method(object): + GET = "GET" + POST = "POST" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this service. + :ivar chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + :ivar pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :ivar post_webhook_url: The absolute url the post-event webhook request should be sent to. + :ivar filters: The list of events that your configured webhook targets will receive. Events not configured here will not fire. Possible values are `onParticipantAdd`, `onParticipantAdded`, `onDeliveryUpdated`, `onConversationUpdated`, `onConversationRemove`, `onParticipantRemove`, `onConversationUpdate`, `onMessageAdd`, `onMessageRemoved`, `onParticipantUpdated`, `onConversationAdded`, `onMessageAdded`, `onConversationAdd`, `onConversationRemoved`, `onParticipantUpdate`, `onMessageRemove`, `onMessageUpdated`, `onParticipantRemoved`, `onMessageUpdate` or `onConversationStateUpdated`. + :ivar method: + :ivar url: An absolute API resource URL for this webhook. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], chat_service_sid: str + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.pre_webhook_url: Optional[str] = payload.get("pre_webhook_url") + self.post_webhook_url: Optional[str] = payload.get("post_webhook_url") + self.filters: Optional[List[str]] = payload.get("filters") + self.method: Optional["WebhookInstance.Method"] = payload.get("method") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._context: Optional[WebhookContext] = None + + @property + def _proxy(self) -> "WebhookContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WebhookContext for this WebhookInstance + """ + if self._context is None: + self._context = WebhookContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + ) + return self._context + + def fetch(self) -> "WebhookInstance": + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "WebhookInstance": + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + method: Union[str, object] = values.unset, + ) -> "WebhookInstance": + """ + Update the WebhookInstance + + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param filters: The list of events that your configured webhook targets will receive. Events not configured here will not fire. Possible values are `onParticipantAdd`, `onParticipantAdded`, `onDeliveryUpdated`, `onConversationUpdated`, `onConversationRemove`, `onParticipantRemove`, `onConversationUpdate`, `onMessageAdd`, `onMessageRemoved`, `onParticipantUpdated`, `onConversationAdded`, `onMessageAdded`, `onConversationAdd`, `onConversationRemoved`, `onParticipantUpdate`, `onMessageRemove`, `onMessageUpdated`, `onParticipantRemoved`, `onMessageUpdate` or `onConversationStateUpdated`. + :param method: The HTTP method to be used when sending a webhook request. One of `GET` or `POST`. + + :returns: The updated WebhookInstance + """ + return self._proxy.update( + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + filters=filters, + method=method, + ) + + async def update_async( + self, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + method: Union[str, object] = values.unset, + ) -> "WebhookInstance": + """ + Asynchronous coroutine to update the WebhookInstance + + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param filters: The list of events that your configured webhook targets will receive. Events not configured here will not fire. Possible values are `onParticipantAdd`, `onParticipantAdded`, `onDeliveryUpdated`, `onConversationUpdated`, `onConversationRemove`, `onParticipantRemove`, `onConversationUpdate`, `onMessageAdd`, `onMessageRemoved`, `onParticipantUpdated`, `onConversationAdded`, `onMessageAdded`, `onConversationAdd`, `onConversationRemoved`, `onParticipantUpdate`, `onMessageRemove`, `onMessageUpdated`, `onParticipantRemoved`, `onMessageUpdate` or `onConversationStateUpdated`. + :param method: The HTTP method to be used when sending a webhook request. One of `GET` or `POST`. + + :returns: The updated WebhookInstance + """ + return await self._proxy.update_async( + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + filters=filters, + method=method, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WebhookContext(InstanceContext): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the WebhookContext + + :param version: Version that contains the resource + :param chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._uri = "/Services/{chat_service_sid}/Configuration/Webhooks".format( + **self._solution + ) + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + + def update( + self, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + method: Union[str, object] = values.unset, + ) -> WebhookInstance: + """ + Update the WebhookInstance + + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param filters: The list of events that your configured webhook targets will receive. Events not configured here will not fire. Possible values are `onParticipantAdd`, `onParticipantAdded`, `onDeliveryUpdated`, `onConversationUpdated`, `onConversationRemove`, `onParticipantRemove`, `onConversationUpdate`, `onMessageAdd`, `onMessageRemoved`, `onParticipantUpdated`, `onConversationAdded`, `onMessageAdded`, `onConversationAdd`, `onConversationRemoved`, `onParticipantUpdate`, `onMessageRemove`, `onMessageUpdated`, `onParticipantRemoved`, `onMessageUpdate` or `onConversationStateUpdated`. + :param method: The HTTP method to be used when sending a webhook request. One of `GET` or `POST`. + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "Filters": serialize.map(filters, lambda e: e), + "Method": method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + async def update_async( + self, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + method: Union[str, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronous coroutine to update the WebhookInstance + + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param filters: The list of events that your configured webhook targets will receive. Events not configured here will not fire. Possible values are `onParticipantAdd`, `onParticipantAdded`, `onDeliveryUpdated`, `onConversationUpdated`, `onConversationRemove`, `onParticipantRemove`, `onConversationUpdate`, `onMessageAdd`, `onMessageRemoved`, `onParticipantUpdated`, `onConversationAdded`, `onMessageAdded`, `onConversationAdd`, `onConversationRemoved`, `onParticipantUpdate`, `onMessageRemove`, `onMessageUpdated`, `onParticipantRemoved`, `onMessageUpdate` or `onConversationStateUpdated`. + :param method: The HTTP method to be used when sending a webhook request. One of `GET` or `POST`. + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "Filters": serialize.map(filters, lambda e: e), + "Method": method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WebhookList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the WebhookList + + :param version: Version that contains the resource + :param chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + + def get(self) -> WebhookContext: + """ + Constructs a WebhookContext + + """ + return WebhookContext( + self._version, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __call__(self) -> WebhookContext: + """ + Constructs a WebhookContext + + """ + return WebhookContext( + self._version, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/__init__.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/__init__.py new file mode 100644 index 00000000..0f28c4df --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/__init__.py @@ -0,0 +1,1069 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.conversations.v1.service.conversation.message import MessageList +from twilio.rest.conversations.v1.service.conversation.participant import ( + ParticipantList, +) +from twilio.rest.conversations.v1.service.conversation.webhook import WebhookList + + +class ConversationInstance(InstanceResource): + + class State(object): + INACTIVE = "inactive" + ACTIVE = "active" + CLOSED = "closed" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + :ivar messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :ivar attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + :ivar state: + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + :ivar timers: Timer date values representing state update for this conversation. + :ivar url: An absolute API resource URL for this conversation. + :ivar links: Contains absolute URLs to access the [participants](https://www.twilio.com/docs/conversations/api/conversation-participant-resource), [messages](https://www.twilio.com/docs/conversations/api/conversation-message-resource) and [webhooks](https://www.twilio.com/docs/conversations/api/conversation-scoped-webhook-resource) of this conversation. + :ivar bindings: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + chat_service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.attributes: Optional[str] = payload.get("attributes") + self.state: Optional["ConversationInstance.State"] = payload.get("state") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.timers: Optional[Dict[str, object]] = payload.get("timers") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.bindings: Optional[Dict[str, object]] = payload.get("bindings") + + self._solution = { + "chat_service_sid": chat_service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ConversationContext] = None + + @property + def _proxy(self) -> "ConversationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConversationContext for this ConversationInstance + """ + if self._context is None: + self._context = ConversationContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "ConversationInstance": + """ + Fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConversationInstance": + """ + Asynchronous coroutine to fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> "ConversationInstance": + """ + Update the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The updated ConversationInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> "ConversationInstance": + """ + Asynchronous coroutine to update the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The updated ConversationInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages + + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + return self._proxy.participants + + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + return self._proxy.webhooks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConversationContext(InstanceContext): + + def __init__(self, version: Version, chat_service_sid: str, sid: str): + """ + Initialize the ConversationContext + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Conversation resource is associated with. + :param sid: A 34 character string that uniquely identifies this resource. Can also be the `unique_name` of the Conversation. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "sid": sid, + } + self._uri = "/Services/{chat_service_sid}/Conversations/{sid}".format( + **self._solution + ) + + self._messages: Optional[MessageList] = None + self._participants: Optional[ParticipantList] = None + self._webhooks: Optional[WebhookList] = None + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConversationInstance: + """ + Fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ConversationInstance: + """ + Asynchronous coroutine to fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ConversationInstance: + """ + Update the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The updated ConversationInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MessagingServiceSid": messaging_service_sid, + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "UniqueName": unique_name, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ConversationInstance: + """ + Asynchronous coroutine to update the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The updated ConversationInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MessagingServiceSid": messaging_service_sid, + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "UniqueName": unique_name, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + if self._messages is None: + self._messages = MessageList( + self._version, + self._solution["chat_service_sid"], + self._solution["sid"], + ) + return self._messages + + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + if self._participants is None: + self._participants = ParticipantList( + self._version, + self._solution["chat_service_sid"], + self._solution["sid"], + ) + return self._participants + + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + if self._webhooks is None: + self._webhooks = WebhookList( + self._version, + self._solution["chat_service_sid"], + self._solution["sid"], + ) + return self._webhooks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConversationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ConversationInstance: + """ + Build an instance of ConversationInstance + + :param payload: Payload response from the API + """ + return ConversationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ConversationList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the ConversationList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Conversation resource is associated with. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._uri = "/Services/{chat_service_sid}/Conversations".format( + **self._solution + ) + + def create( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ConversationInstance: + """ + Create the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The created ConversationInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "MessagingServiceSid": messaging_service_sid, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConversationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ConversationInstance: + """ + Asynchronously create the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The created ConversationInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "MessagingServiceSid": messaging_service_sid, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConversationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def stream( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConversationInstance]: + """ + Streams ConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param str end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param "ConversationInstance.State" state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + start_date=start_date, + end_date=end_date, + state=state, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConversationInstance]: + """ + Asynchronously streams ConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param str end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param "ConversationInstance.State" state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + start_date=start_date, + end_date=end_date, + state=state, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConversationInstance]: + """ + Lists ConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param str end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param "ConversationInstance.State" state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + start_date=start_date, + end_date=end_date, + state=state, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConversationInstance]: + """ + Asynchronously lists ConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param str end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param "ConversationInstance.State" state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + start_date=start_date, + end_date=end_date, + state=state, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConversationPage: + """ + Retrieve a single page of ConversationInstance records from the API. + Request is executed immediately + + :param start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConversationInstance + """ + data = values.of( + { + "StartDate": start_date, + "EndDate": end_date, + "State": state, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConversationPage(self._version, response, self._solution) + + async def page_async( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConversationPage: + """ + Asynchronously retrieve a single page of ConversationInstance records from the API. + Request is executed immediately + + :param start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConversationInstance + """ + data = values.of( + { + "StartDate": start_date, + "EndDate": end_date, + "State": state, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConversationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ConversationPage: + """ + Retrieve a specific page of ConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConversationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConversationPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ConversationPage: + """ + Asynchronously retrieve a specific page of ConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConversationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConversationPage(self._version, response, self._solution) + + def get(self, sid: str) -> ConversationContext: + """ + Constructs a ConversationContext + + :param sid: A 34 character string that uniquely identifies this resource. Can also be the `unique_name` of the Conversation. + """ + return ConversationContext( + self._version, chat_service_sid=self._solution["chat_service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ConversationContext: + """ + Constructs a ConversationContext + + :param sid: A 34 character string that uniquely identifies this resource. Can also be the `unique_name` of the Conversation. + """ + return ConversationContext( + self._version, chat_service_sid=self._solution["chat_service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..50627e70 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/__pycache__/participant.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/__pycache__/participant.cpython-312.pyc new file mode 100644 index 00000000..1159bb1a Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/__pycache__/participant.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/__pycache__/webhook.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/__pycache__/webhook.cpython-312.pyc new file mode 100644 index 00000000..bdce3e14 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/__pycache__/webhook.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/message/__init__.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/message/__init__.py new file mode 100644 index 00000000..c4123afd --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/message/__init__.py @@ -0,0 +1,943 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.conversations.v1.service.conversation.message.delivery_receipt import ( + DeliveryReceiptList, +) + + +class MessageInstance(InstanceResource): + + class OrderType(object): + ASC = "asc" + DESC = "desc" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this message. + :ivar chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Participant resource is associated with. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar index: The index of the message within the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource). + :ivar author: The channel specific identifier of the message's author. Defaults to `system`. + :ivar body: The content of the message, can be up to 1,600 characters long. + :ivar media: An array of objects that describe the Message's media, if the message contains media. Each object contains these fields: `content_type` with the MIME type of the media, `filename` with the name of the media, `sid` with the SID of the Media resource, and `size` with the media object's file size in bytes. If the Message has no media, this value is `null`. + :ivar attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + :ivar participant_sid: The unique ID of messages's author participant. Null in case of `system` sent message. + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :ivar delivery: An object that contains the summary of delivery statuses for the message to non-chat participants. + :ivar url: An absolute API resource URL for this message. + :ivar links: Contains an absolute API resource URL to access the delivery & read receipts of this message. + :ivar content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + chat_service_sid: str, + conversation_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.sid: Optional[str] = payload.get("sid") + self.index: Optional[int] = deserialize.integer(payload.get("index")) + self.author: Optional[str] = payload.get("author") + self.body: Optional[str] = payload.get("body") + self.media: Optional[List[Dict[str, object]]] = payload.get("media") + self.attributes: Optional[str] = payload.get("attributes") + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.delivery: Optional[Dict[str, object]] = payload.get("delivery") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.content_sid: Optional[str] = payload.get("content_sid") + + self._solution = { + "chat_service_sid": chat_service_sid, + "conversation_sid": conversation_sid, + "sid": sid or self.sid, + } + self._context: Optional[MessageContext] = None + + @property + def _proxy(self) -> "MessageContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MessageContext for this MessageInstance + """ + if self._context is None: + self._context = MessageContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "MessageInstance": + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MessageInstance": + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The updated MessageInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + subject=subject, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Asynchronous coroutine to update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The updated MessageInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + subject=subject, + ) + + @property + def delivery_receipts(self) -> DeliveryReceiptList: + """ + Access the delivery_receipts + """ + return self._proxy.delivery_receipts + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MessageContext(InstanceContext): + + def __init__( + self, version: Version, chat_service_sid: str, conversation_sid: str, sid: str + ): + """ + Initialize the MessageContext + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Participant resource is associated with. + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "conversation_sid": conversation_sid, + "sid": sid, + } + self._uri = "/Services/{chat_service_sid}/Conversations/{conversation_sid}/Messages/{sid}".format( + **self._solution + ) + + self._delivery_receipts: Optional[DeliveryReceiptList] = None + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Author": author, + "Body": body, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "Subject": subject, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronous coroutine to update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Author": author, + "Body": body, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "Subject": subject, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + @property + def delivery_receipts(self) -> DeliveryReceiptList: + """ + Access the delivery_receipts + """ + if self._delivery_receipts is None: + self._delivery_receipts = DeliveryReceiptList( + self._version, + self._solution["chat_service_sid"], + self._solution["conversation_sid"], + self._solution["sid"], + ) + return self._delivery_receipts + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MessagePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: + """ + Build an instance of MessageInstance + + :param payload: Payload response from the API + """ + return MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MessageList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str, conversation_sid: str): + """ + Initialize the MessageList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Participant resource is associated with. + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for messages. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "conversation_sid": conversation_sid, + } + self._uri = "/Services/{chat_service_sid}/Conversations/{conversation_sid}/Messages".format( + **self._solution + ) + + def create( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + content_sid: Union[str, object] = values.unset, + content_variables: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param media_sid: The Media SID to be attached to the new Message. + :param content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template, required for template-generated messages. **Note** that if this field is set, `Body` and `MediaSid` parameters are ignored. + :param content_variables: A structurally valid JSON string that contains values to resolve Rich Content template variables. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The created MessageInstance + """ + + data = values.of( + { + "Author": author, + "Body": body, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MediaSid": media_sid, + "ContentSid": content_sid, + "ContentVariables": content_variables, + "Subject": subject, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + content_sid: Union[str, object] = values.unset, + content_variables: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param media_sid: The Media SID to be attached to the new Message. + :param content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template, required for template-generated messages. **Note** that if this field is set, `Body` and `MediaSid` parameters are ignored. + :param content_variables: A structurally valid JSON string that contains values to resolve Rich Content template variables. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The created MessageInstance + """ + + data = values.of( + { + "Author": author, + "Body": body, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MediaSid": media_sid, + "ContentSid": content_sid, + "ContentVariables": content_variables, + "Subject": subject, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def stream( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: + """ + Streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(order=order, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessageInstance]: + """ + Asynchronously streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(order=order, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + order=order, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Asynchronously lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + order=order, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + async def page_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MessagePage: + """ + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MessagePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MessagePage: + """ + Asynchronously retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagePage(self._version, response, self._solution) + + def get(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return MessageContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return MessageContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/message/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/message/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..b7af6528 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/message/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/message/__pycache__/delivery_receipt.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/message/__pycache__/delivery_receipt.cpython-312.pyc new file mode 100644 index 00000000..2137e865 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/message/__pycache__/delivery_receipt.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/message/delivery_receipt.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/message/delivery_receipt.py new file mode 100644 index 00000000..939b6312 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/message/delivery_receipt.py @@ -0,0 +1,505 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DeliveryReceiptInstance(InstanceResource): + + class DeliveryStatus(object): + READ = "read" + FAILED = "failed" + DELIVERED = "delivered" + UNDELIVERED = "undelivered" + SENT = "sent" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this participant. + :ivar chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Message resource is associated with. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :ivar message_sid: The SID of the message within a [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) the delivery receipt belongs to + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar channel_message_sid: A messaging channel-specific identifier for the message delivered to participant e.g. `SMxx` for SMS, `WAxx` for Whatsapp etc. + :ivar participant_sid: The unique ID of the participant the delivery receipt belongs to. + :ivar status: + :ivar error_code: The message [delivery error code](https://www.twilio.com/docs/sms/api/message-resource#delivery-related-errors) for a `failed` status, + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. `null` if the delivery receipt has not been updated. + :ivar url: An absolute API resource URL for this delivery receipt. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + chat_service_sid: str, + conversation_sid: str, + message_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.message_sid: Optional[str] = payload.get("message_sid") + self.sid: Optional[str] = payload.get("sid") + self.channel_message_sid: Optional[str] = payload.get("channel_message_sid") + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.status: Optional["DeliveryReceiptInstance.DeliveryStatus"] = payload.get( + "status" + ) + self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "chat_service_sid": chat_service_sid, + "conversation_sid": conversation_sid, + "message_sid": message_sid, + "sid": sid or self.sid, + } + self._context: Optional[DeliveryReceiptContext] = None + + @property + def _proxy(self) -> "DeliveryReceiptContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DeliveryReceiptContext for this DeliveryReceiptInstance + """ + if self._context is None: + self._context = DeliveryReceiptContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "DeliveryReceiptInstance": + """ + Fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DeliveryReceiptInstance": + """ + Asynchronous coroutine to fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DeliveryReceiptContext(InstanceContext): + + def __init__( + self, + version: Version, + chat_service_sid: str, + conversation_sid: str, + message_sid: str, + sid: str, + ): + """ + Initialize the DeliveryReceiptContext + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Message resource is associated with. + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :param message_sid: The SID of the message within a [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) the delivery receipt belongs to. + :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "conversation_sid": conversation_sid, + "message_sid": message_sid, + "sid": sid, + } + self._uri = "/Services/{chat_service_sid}/Conversations/{conversation_sid}/Messages/{message_sid}/Receipts/{sid}".format( + **self._solution + ) + + def fetch(self) -> DeliveryReceiptInstance: + """ + Fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DeliveryReceiptInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> DeliveryReceiptInstance: + """ + Asynchronous coroutine to fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DeliveryReceiptInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DeliveryReceiptPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DeliveryReceiptInstance: + """ + Build an instance of DeliveryReceiptInstance + + :param payload: Payload response from the API + """ + return DeliveryReceiptInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class DeliveryReceiptList(ListResource): + + def __init__( + self, + version: Version, + chat_service_sid: str, + conversation_sid: str, + message_sid: str, + ): + """ + Initialize the DeliveryReceiptList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Message resource is associated with. + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :param message_sid: The SID of the message within a [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) the delivery receipt belongs to. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "conversation_sid": conversation_sid, + "message_sid": message_sid, + } + self._uri = "/Services/{chat_service_sid}/Conversations/{conversation_sid}/Messages/{message_sid}/Receipts".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DeliveryReceiptInstance]: + """ + Streams DeliveryReceiptInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DeliveryReceiptInstance]: + """ + Asynchronously streams DeliveryReceiptInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DeliveryReceiptInstance]: + """ + Lists DeliveryReceiptInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DeliveryReceiptInstance]: + """ + Asynchronously lists DeliveryReceiptInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DeliveryReceiptPage: + """ + Retrieve a single page of DeliveryReceiptInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DeliveryReceiptInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DeliveryReceiptPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DeliveryReceiptPage: + """ + Asynchronously retrieve a single page of DeliveryReceiptInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DeliveryReceiptInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DeliveryReceiptPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DeliveryReceiptPage: + """ + Retrieve a specific page of DeliveryReceiptInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DeliveryReceiptInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DeliveryReceiptPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DeliveryReceiptPage: + """ + Asynchronously retrieve a specific page of DeliveryReceiptInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DeliveryReceiptInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DeliveryReceiptPage(self._version, response, self._solution) + + def get(self, sid: str) -> DeliveryReceiptContext: + """ + Constructs a DeliveryReceiptContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return DeliveryReceiptContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> DeliveryReceiptContext: + """ + Constructs a DeliveryReceiptContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return DeliveryReceiptContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/participant.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/participant.py new file mode 100644 index 00000000..03a3cead --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/participant.py @@ -0,0 +1,925 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ParticipantInstance(InstanceResource): + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this participant. + :ivar chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Participant resource is associated with. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this participant. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + :ivar attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + :ivar messaging_binding: Information about how this participant exchanges messages with the conversation. A JSON parameter consisting of type and address fields of the participant. + :ivar role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :ivar date_created: The date on which this resource was created. + :ivar date_updated: The date on which this resource was last updated. + :ivar url: An absolute API resource URL for this participant. + :ivar last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :ivar last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + chat_service_sid: str, + conversation_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.sid: Optional[str] = payload.get("sid") + self.identity: Optional[str] = payload.get("identity") + self.attributes: Optional[str] = payload.get("attributes") + self.messaging_binding: Optional[Dict[str, object]] = payload.get( + "messaging_binding" + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.last_read_message_index: Optional[int] = deserialize.integer( + payload.get("last_read_message_index") + ) + self.last_read_timestamp: Optional[str] = payload.get("last_read_timestamp") + + self._solution = { + "chat_service_sid": chat_service_sid, + "conversation_sid": conversation_sid, + "sid": sid or self.sid, + } + self._context: Optional[ParticipantContext] = None + + @property + def _proxy(self) -> "ParticipantContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ParticipantContext for this ParticipantInstance + """ + if self._context is None: + self._context = ParticipantContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "ParticipantInstance": + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ParticipantInstance": + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + identity: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> "ParticipantInstance": + """ + Update the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date on which this resource was created. + :param date_updated: The date on which this resource was last updated. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: The updated ParticipantInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + identity=identity, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + identity: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> "ParticipantInstance": + """ + Asynchronous coroutine to update the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date on which this resource was created. + :param date_updated: The date on which this resource was last updated. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: The updated ParticipantInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + identity=identity, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ParticipantContext(InstanceContext): + + def __init__( + self, version: Version, chat_service_sid: str, conversation_sid: str, sid: str + ): + """ + Initialize the ParticipantContext + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Participant resource is associated with. + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this participant. + :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "conversation_sid": conversation_sid, + "sid": sid, + } + self._uri = "/Services/{chat_service_sid}/Conversations/{conversation_sid}/Participants/{sid}".format( + **self._solution + ) + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ParticipantInstance: + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + identity: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Update the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date on which this resource was created. + :param date_updated: The date on which this resource was last updated. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: The updated ParticipantInstance + """ + + data = values.of( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Identity": identity, + "Attributes": attributes, + "RoleSid": role_sid, + "MessagingBinding.ProxyAddress": messaging_binding_proxy_address, + "MessagingBinding.ProjectedAddress": messaging_binding_projected_address, + "LastReadMessageIndex": last_read_message_index, + "LastReadTimestamp": last_read_timestamp, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + identity: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronous coroutine to update the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date on which this resource was created. + :param date_updated: The date on which this resource was last updated. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: The updated ParticipantInstance + """ + + data = values.of( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Identity": identity, + "Attributes": attributes, + "RoleSid": role_sid, + "MessagingBinding.ProxyAddress": messaging_binding_proxy_address, + "MessagingBinding.ProjectedAddress": messaging_binding_projected_address, + "LastReadMessageIndex": last_read_message_index, + "LastReadTimestamp": last_read_timestamp, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ParticipantPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: + """ + Build an instance of ParticipantInstance + + :param payload: Payload response from the API + """ + return ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ParticipantList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str, conversation_sid: str): + """ + Initialize the ParticipantList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Participant resource is associated with. + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for participants. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "conversation_sid": conversation_sid, + } + self._uri = "/Services/{chat_service_sid}/Conversations/{conversation_sid}/Participants".format( + **self._solution + ) + + def create( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + identity: Union[str, object] = values.unset, + messaging_binding_address: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Create the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + :param messaging_binding_address: The address of the participant's device, e.g. a phone or WhatsApp number. Together with the Proxy address, this determines a participant uniquely. This field (with `proxy_address`) is only null when the participant is interacting from an SDK endpoint (see the `identity` field). + :param messaging_binding_proxy_address: The address of the Twilio phone number (or WhatsApp number) that the participant is in contact with. This field, together with participant address, is only null when the participant is interacting from an SDK endpoint (see the `identity` field). + :param date_created: The date on which this resource was created. + :param date_updated: The date on which this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + + :returns: The created ParticipantInstance + """ + + data = values.of( + { + "Identity": identity, + "MessagingBinding.Address": messaging_binding_address, + "MessagingBinding.ProxyAddress": messaging_binding_proxy_address, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MessagingBinding.ProjectedAddress": messaging_binding_projected_address, + "RoleSid": role_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + identity: Union[str, object] = values.unset, + messaging_binding_address: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronously create the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + :param messaging_binding_address: The address of the participant's device, e.g. a phone or WhatsApp number. Together with the Proxy address, this determines a participant uniquely. This field (with `proxy_address`) is only null when the participant is interacting from an SDK endpoint (see the `identity` field). + :param messaging_binding_proxy_address: The address of the Twilio phone number (or WhatsApp number) that the participant is in contact with. This field, together with participant address, is only null when the participant is interacting from an SDK endpoint (see the `identity` field). + :param date_created: The date on which this resource was created. + :param date_updated: The date on which this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + + :returns: The created ParticipantInstance + """ + + data = values.of( + { + "Identity": identity, + "MessagingBinding.Address": messaging_binding_address, + "MessagingBinding.ProxyAddress": messaging_binding_proxy_address, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MessagingBinding.ProjectedAddress": messaging_binding_projected_address, + "RoleSid": role_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ParticipantInstance]: + """ + Streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ParticipantInstance]: + """ + Asynchronously streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Asynchronously lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Asynchronously retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ParticipantPage: + """ + Retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ParticipantPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ParticipantPage: + """ + Asynchronously retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ParticipantPage(self._version, response, self._solution) + + def get(self, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return ParticipantContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return ParticipantContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/webhook.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/webhook.py new file mode 100644 index 00000000..08ec93ce --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation/webhook.py @@ -0,0 +1,788 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class WebhookInstance(InstanceResource): + + class Method(object): + GET = "GET" + POST = "POST" + + class Target(object): + WEBHOOK = "webhook" + TRIGGER = "trigger" + STUDIO = "studio" + + """ + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Participant resource is associated with. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this webhook. + :ivar target: The target of this webhook: `webhook`, `studio`, `trigger` + :ivar url: An absolute API resource URL for this webhook. + :ivar configuration: The configuration of this webhook. Is defined based on target. + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + chat_service_sid: str, + conversation_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.target: Optional[str] = payload.get("target") + self.url: Optional[str] = payload.get("url") + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "chat_service_sid": chat_service_sid, + "conversation_sid": conversation_sid, + "sid": sid or self.sid, + } + self._context: Optional[WebhookContext] = None + + @property + def _proxy(self) -> "WebhookContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WebhookContext for this WebhookInstance + """ + if self._context is None: + self._context = WebhookContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "WebhookInstance": + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "WebhookInstance": + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> "WebhookInstance": + """ + Update the WebhookInstance + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: The updated WebhookInstance + """ + return self._proxy.update( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + + async def update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> "WebhookInstance": + """ + Asynchronous coroutine to update the WebhookInstance + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: The updated WebhookInstance + """ + return await self._proxy.update_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WebhookContext(InstanceContext): + + def __init__( + self, version: Version, chat_service_sid: str, conversation_sid: str, sid: str + ): + """ + Initialize the WebhookContext + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Participant resource is associated with. + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this webhook. + :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "conversation_sid": conversation_sid, + "sid": sid, + } + self._uri = "/Services/{chat_service_sid}/Conversations/{conversation_sid}/Webhooks/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> WebhookInstance: + """ + Update the WebhookInstance + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronous coroutine to update the WebhookInstance + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WebhookPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: + """ + Build an instance of WebhookInstance + + :param payload: Payload response from the API + """ + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class WebhookList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str, conversation_sid: str): + """ + Initialize the WebhookList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Participant resource is associated with. + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this webhook. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "conversation_sid": conversation_sid, + } + self._uri = "/Services/{chat_service_sid}/Conversations/{conversation_sid}/Webhooks".format( + **self._solution + ) + + def create( + self, + target: "WebhookInstance.Target", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_replay_after: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Create the WebhookInstance + + :param target: + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + :param configuration_replay_after: The message index for which and it's successors the webhook will be replayed. Not set by default + + :returns: The created WebhookInstance + """ + + data = values.of( + { + "Target": target, + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + "Configuration.ReplayAfter": configuration_replay_after, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + async def create_async( + self, + target: "WebhookInstance.Target", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_replay_after: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronously create the WebhookInstance + + :param target: + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + :param configuration_replay_after: The message index for which and it's successors the webhook will be replayed. Not set by default + + :returns: The created WebhookInstance + """ + + data = values.of( + { + "Target": target, + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + "Configuration.ReplayAfter": configuration_replay_after, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WebhookInstance]: + """ + Streams WebhookInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WebhookInstance]: + """ + Asynchronously streams WebhookInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: + """ + Lists WebhookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: + """ + Asynchronously lists WebhookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebhookPage: + """ + Retrieve a single page of WebhookInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebhookInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebhookPage: + """ + Asynchronously retrieve a single page of WebhookInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebhookInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> WebhookPage: + """ + Retrieve a specific page of WebhookInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebhookInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return WebhookPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> WebhookPage: + """ + Asynchronously retrieve a specific page of WebhookInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebhookInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return WebhookPage(self._version, response, self._solution) + + def get(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return WebhookContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return WebhookContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation_with_participants.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation_with_participants.py new file mode 100644 index 00000000..ff82a8ce --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/conversation_with_participants.py @@ -0,0 +1,272 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ConversationWithParticipantsInstance(InstanceResource): + + class State(object): + INACTIVE = "inactive" + ACTIVE = "active" + CLOSED = "closed" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + :ivar messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :ivar attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + :ivar state: + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + :ivar timers: Timer date values representing state update for this conversation. + :ivar links: Contains absolute URLs to access the [participants](https://www.twilio.com/docs/conversations/api/conversation-participant-resource), [messages](https://www.twilio.com/docs/conversations/api/conversation-message-resource) and [webhooks](https://www.twilio.com/docs/conversations/api/conversation-scoped-webhook-resource) of this conversation. + :ivar bindings: + :ivar url: An absolute API resource URL for this conversation. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], chat_service_sid: str + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.attributes: Optional[str] = payload.get("attributes") + self.state: Optional["ConversationWithParticipantsInstance.State"] = ( + payload.get("state") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.timers: Optional[Dict[str, object]] = payload.get("timers") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.bindings: Optional[Dict[str, object]] = payload.get("bindings") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "chat_service_sid": chat_service_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return ( + "".format( + context + ) + ) + + +class ConversationWithParticipantsList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the ConversationWithParticipantsList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Conversation resource is associated with. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._uri = "/Services/{chat_service_sid}/ConversationWithParticipants".format( + **self._solution + ) + + def create( + self, + x_twilio_webhook_enabled: Union[ + "ConversationWithParticipantsInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union[ + "ConversationWithParticipantsInstance.State", object + ] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + participant: Union[List[str], object] = values.unset, + ) -> ConversationWithParticipantsInstance: + """ + Create the ConversationWithParticipantsInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + :param participant: The participant to be added to the conversation in JSON format. The JSON object attributes are as parameters in [Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). The maximum number of participants that can be added in a single request is 10. + + :returns: The created ConversationWithParticipantsInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "MessagingServiceSid": messaging_service_sid, + "Attributes": attributes, + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + "Participant": serialize.map(participant, lambda e: e), + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConversationWithParticipantsInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationWithParticipantsInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union[ + "ConversationWithParticipantsInstance.State", object + ] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + participant: Union[List[str], object] = values.unset, + ) -> ConversationWithParticipantsInstance: + """ + Asynchronously create the ConversationWithParticipantsInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + :param participant: The participant to be added to the conversation in JSON format. The JSON object attributes are as parameters in [Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). The maximum number of participants that can be added in a single request is 10. + + :returns: The created ConversationWithParticipantsInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "MessagingServiceSid": messaging_service_sid, + "Attributes": attributes, + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + "Participant": serialize.map(participant, lambda e: e), + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConversationWithParticipantsInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/participant_conversation.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/participant_conversation.py new file mode 100644 index 00000000..8ec561a7 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/participant_conversation.py @@ -0,0 +1,383 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ParticipantConversationInstance(InstanceResource): + + class State(object): + INACTIVE = "inactive" + ACTIVE = "active" + CLOSED = "closed" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + :ivar participant_sid: The unique ID of the [Participant](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). + :ivar participant_user_sid: The unique string that identifies the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). + :ivar participant_identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :ivar participant_messaging_binding: Information about how this participant exchanges messages with the conversation. A JSON parameter consisting of type and address fields of the participant. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) this Participant belongs to. + :ivar conversation_unique_name: An application-defined string that uniquely identifies the Conversation resource. + :ivar conversation_friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :ivar conversation_attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + :ivar conversation_date_created: The date that this conversation was created, given in ISO 8601 format. + :ivar conversation_date_updated: The date that this conversation was last updated, given in ISO 8601 format. + :ivar conversation_created_by: Identity of the creator of this Conversation. + :ivar conversation_state: + :ivar conversation_timers: Timer date values representing state update for this conversation. + :ivar links: Contains absolute URLs to access the [participant](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) and [conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) of this conversation. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], chat_service_sid: str + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.participant_user_sid: Optional[str] = payload.get("participant_user_sid") + self.participant_identity: Optional[str] = payload.get("participant_identity") + self.participant_messaging_binding: Optional[Dict[str, object]] = payload.get( + "participant_messaging_binding" + ) + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.conversation_unique_name: Optional[str] = payload.get( + "conversation_unique_name" + ) + self.conversation_friendly_name: Optional[str] = payload.get( + "conversation_friendly_name" + ) + self.conversation_attributes: Optional[str] = payload.get( + "conversation_attributes" + ) + self.conversation_date_created: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("conversation_date_created")) + ) + self.conversation_date_updated: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("conversation_date_updated")) + ) + self.conversation_created_by: Optional[str] = payload.get( + "conversation_created_by" + ) + self.conversation_state: Optional["ParticipantConversationInstance.State"] = ( + payload.get("conversation_state") + ) + self.conversation_timers: Optional[Dict[str, object]] = payload.get( + "conversation_timers" + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "chat_service_sid": chat_service_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class ParticipantConversationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ParticipantConversationInstance: + """ + Build an instance of ParticipantConversationInstance + + :param payload: Payload response from the API + """ + return ParticipantConversationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ParticipantConversationList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the ParticipantConversationList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Participant Conversations resource is associated with. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._uri = "/Services/{chat_service_sid}/ParticipantConversations".format( + **self._solution + ) + + def stream( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ParticipantConversationInstance]: + """ + Streams ParticipantConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + identity=identity, address=address, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ParticipantConversationInstance]: + """ + Asynchronously streams ParticipantConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + identity=identity, address=address, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantConversationInstance]: + """ + Lists ParticipantConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + identity=identity, + address=address, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantConversationInstance]: + """ + Asynchronously lists ParticipantConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + identity=identity, + address=address, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantConversationPage: + """ + Retrieve a single page of ParticipantConversationInstance records from the API. + Request is executed immediately + + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantConversationInstance + """ + data = values.of( + { + "Identity": identity, + "Address": address, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantConversationPage(self._version, response, self._solution) + + async def page_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantConversationPage: + """ + Asynchronously retrieve a single page of ParticipantConversationInstance records from the API. + Request is executed immediately + + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantConversationInstance + """ + data = values.of( + { + "Identity": identity, + "Address": address, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantConversationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ParticipantConversationPage: + """ + Retrieve a specific page of ParticipantConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantConversationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ParticipantConversationPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ParticipantConversationPage: + """ + Asynchronously retrieve a specific page of ParticipantConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantConversationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ParticipantConversationPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/role.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/role.py new file mode 100644 index 00000000..0884fb00 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/role.py @@ -0,0 +1,645 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RoleInstance(InstanceResource): + + class RoleType(object): + CONVERSATION = "conversation" + SERVICE = "service" + + """ + :ivar sid: The unique string that we created to identify the Role resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Role resource. + :ivar chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Role resource is associated with. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar permissions: An array of the permissions the role has been granted. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: An absolute API resource URL for this user role. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + chat_service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["RoleInstance.RoleType"] = payload.get("type") + self.permissions: Optional[List[str]] = payload.get("permissions") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "chat_service_sid": chat_service_sid, + "sid": sid or self.sid, + } + self._context: Optional[RoleContext] = None + + @property + def _proxy(self) -> "RoleContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RoleContext for this RoleInstance + """ + if self._context is None: + self._context = RoleContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RoleInstance": + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RoleInstance": + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + return await self._proxy.fetch_async() + + def update(self, permission: List[str]) -> "RoleInstance": + """ + Update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + return self._proxy.update( + permission=permission, + ) + + async def update_async(self, permission: List[str]) -> "RoleInstance": + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + return await self._proxy.update_async( + permission=permission, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RoleContext(InstanceContext): + + def __init__(self, version: Version, chat_service_sid: str, sid: str): + """ + Initialize the RoleContext + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) to update the Role resource in. + :param sid: The SID of the Role resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "sid": sid, + } + self._uri = "/Services/{chat_service_sid}/Roles/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RoleInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RoleInstance: + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RoleInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + def update(self, permission: List[str]) -> RoleInstance: + """ + Update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, permission: List[str]) -> RoleInstance: + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RolePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: + """ + Build an instance of RoleInstance + + :param payload: Payload response from the API + """ + return RoleInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RoleList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the RoleList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) to read the Role resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._uri = "/Services/{chat_service_sid}/Roles".format(**self._solution) + + def create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: The created RoleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + async def create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Asynchronously create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: The created RoleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoleInstance]: + """ + Streams RoleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RoleInstance]: + """ + Asynchronously streams RoleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: + """ + Lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: + """ + Asynchronously lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePage: + """ + Retrieve a single page of RoleInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePage: + """ + Asynchronously retrieve a single page of RoleInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RolePage: + """ + Retrieve a specific page of RoleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RolePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RolePage: + """ + Asynchronously retrieve a specific page of RoleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RolePage(self._version, response, self._solution) + + def get(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: The SID of the Role resource to update. + """ + return RoleContext( + self._version, chat_service_sid=self._solution["chat_service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: The SID of the Role resource to update. + """ + return RoleContext( + self._version, chat_service_sid=self._solution["chat_service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/user/__init__.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/user/__init__.py new file mode 100644 index 00000000..b8cda74c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/user/__init__.py @@ -0,0 +1,818 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.conversations.v1.service.user.user_conversation import ( + UserConversationList, +) + + +class UserInstance(InstanceResource): + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: The unique string that we created to identify the User resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the User resource. + :ivar chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the User resource is associated with. + :ivar role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) assigned to the user. + :ivar identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :ivar is_online: Whether the User is actively connected to this Conversations Service and online. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service's `reachability_enabled` is `false`, if the User has never been online for this Conversations Service, even if the Service's `reachability_enabled` is `true`. + :ivar is_notifiable: Whether the User has a potentially valid Push Notification registration (APN or GCM) for this Conversations Service. If at least one registration exists, `true`; otherwise `false`. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service's `reachability_enabled` is `false`, and if the User has never had a notification registration, even if the Service's `reachability_enabled` is `true`. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: An absolute API resource URL for this user. + :ivar links: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + chat_service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.role_sid: Optional[str] = payload.get("role_sid") + self.identity: Optional[str] = payload.get("identity") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.attributes: Optional[str] = payload.get("attributes") + self.is_online: Optional[bool] = payload.get("is_online") + self.is_notifiable: Optional[bool] = payload.get("is_notifiable") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "chat_service_sid": chat_service_sid, + "sid": sid or self.sid, + } + self._context: Optional[UserContext] = None + + @property + def _proxy(self) -> "UserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserContext for this UserInstance + """ + if self._context is None: + self._context = UserContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "UserInstance": + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserInstance": + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The updated UserInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Asynchronous coroutine to update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The updated UserInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + + @property + def user_conversations(self) -> UserConversationList: + """ + Access the user_conversations + """ + return self._proxy.user_conversations + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserContext(InstanceContext): + + def __init__(self, version: Version, chat_service_sid: str, sid: str): + """ + Initialize the UserContext + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the User resource is associated with. + :param sid: The SID of the User resource to update. This value can be either the `sid` or the `identity` of the User resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "sid": sid, + } + self._uri = "/Services/{chat_service_sid}/Users/{sid}".format(**self._solution) + + self._user_conversations: Optional[UserConversationList] = None + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The updated UserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": attributes, + "RoleSid": role_sid, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The updated UserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": attributes, + "RoleSid": role_sid, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + @property + def user_conversations(self) -> UserConversationList: + """ + Access the user_conversations + """ + if self._user_conversations is None: + self._user_conversations = UserConversationList( + self._version, + self._solution["chat_service_sid"], + self._solution["sid"], + ) + return self._user_conversations + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: + """ + Build an instance of UserInstance + + :param payload: Payload response from the API + """ + return UserInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class UserList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the UserList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) to read the User resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._uri = "/Services/{chat_service_sid}/Users".format(**self._solution) + + def create( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Create the UserInstance + + :param identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The created UserInstance + """ + + data = values.of( + { + "Identity": identity, + "FriendlyName": friendly_name, + "Attributes": attributes, + "RoleSid": role_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + async def create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The created UserInstance + """ + + data = values.of( + { + "Identity": identity, + "FriendlyName": friendly_name, + "Attributes": attributes, + "RoleSid": role_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserInstance]: + """ + Streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserInstance]: + """ + Asynchronously streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Asynchronously lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Asynchronously retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserPage: + """ + Retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserPage: + """ + Asynchronously retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserPage(self._version, response, self._solution) + + def get(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: The SID of the User resource to update. This value can be either the `sid` or the `identity` of the User resource to update. + """ + return UserContext( + self._version, chat_service_sid=self._solution["chat_service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: The SID of the User resource to update. This value can be either the `sid` or the `identity` of the User resource to update. + """ + return UserContext( + self._version, chat_service_sid=self._solution["chat_service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/user/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/user/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..faec7391 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/user/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/user/__pycache__/user_conversation.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/user/__pycache__/user_conversation.cpython-312.pyc new file mode 100644 index 00000000..b7e2f7d8 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/user/__pycache__/user_conversation.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/service/user/user_conversation.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/user/user_conversation.py new file mode 100644 index 00000000..4f1727f8 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/service/user/user_conversation.py @@ -0,0 +1,684 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UserConversationInstance(InstanceResource): + + class NotificationLevel(object): + DEFAULT = "default" + MUTED = "muted" + + class State(object): + INACTIVE = "inactive" + ACTIVE = "active" + CLOSED = "closed" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this User Conversation. + :ivar unread_messages_count: The number of unread Messages in the Conversation for the Participant. + :ivar last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + :ivar participant_sid: The unique ID of the [participant](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) the user conversation belongs to. + :ivar user_sid: The unique string that identifies the [User resource](https://www.twilio.com/docs/conversations/api/user-resource). + :ivar friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :ivar conversation_state: + :ivar timers: Timer date values representing state update for this conversation. + :ivar attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + :ivar date_created: The date that this conversation was created, given in ISO 8601 format. + :ivar date_updated: The date that this conversation was last updated, given in ISO 8601 format. + :ivar created_by: Identity of the creator of this Conversation. + :ivar notification_level: + :ivar unique_name: An application-defined string that uniquely identifies the Conversation resource. It can be used to address the resource in place of the resource's `conversation_sid` in the URL. + :ivar url: + :ivar links: Contains absolute URLs to access the [participant](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) and [conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) of this conversation. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + chat_service_sid: str, + user_sid: str, + conversation_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.unread_messages_count: Optional[int] = deserialize.integer( + payload.get("unread_messages_count") + ) + self.last_read_message_index: Optional[int] = deserialize.integer( + payload.get("last_read_message_index") + ) + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.user_sid: Optional[str] = payload.get("user_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.conversation_state: Optional["UserConversationInstance.State"] = ( + payload.get("conversation_state") + ) + self.timers: Optional[Dict[str, object]] = payload.get("timers") + self.attributes: Optional[str] = payload.get("attributes") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + self.notification_level: Optional[ + "UserConversationInstance.NotificationLevel" + ] = payload.get("notification_level") + self.unique_name: Optional[str] = payload.get("unique_name") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "chat_service_sid": chat_service_sid, + "user_sid": user_sid, + "conversation_sid": conversation_sid or self.conversation_sid, + } + self._context: Optional[UserConversationContext] = None + + @property + def _proxy(self) -> "UserConversationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserConversationContext for this UserConversationInstance + """ + if self._context is None: + self._context = UserConversationContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UserConversationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserConversationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "UserConversationInstance": + """ + Fetch the UserConversationInstance + + + :returns: The fetched UserConversationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserConversationInstance": + """ + Asynchronous coroutine to fetch the UserConversationInstance + + + :returns: The fetched UserConversationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> "UserConversationInstance": + """ + Update the UserConversationInstance + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: The updated UserConversationInstance + """ + return self._proxy.update( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + + async def update_async( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> "UserConversationInstance": + """ + Asynchronous coroutine to update the UserConversationInstance + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: The updated UserConversationInstance + """ + return await self._proxy.update_async( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserConversationContext(InstanceContext): + + def __init__( + self, + version: Version, + chat_service_sid: str, + user_sid: str, + conversation_sid: str, + ): + """ + Initialize the UserConversationContext + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Conversation resource is associated with. + :param user_sid: The unique SID identifier of the [User resource](https://www.twilio.com/docs/conversations/api/user-resource). This value can be either the `sid` or the `identity` of the User resource. + :param conversation_sid: The unique SID identifier of the Conversation. This value can be either the `sid` or the `unique_name` of the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource). + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "user_sid": user_sid, + "conversation_sid": conversation_sid, + } + self._uri = "/Services/{chat_service_sid}/Users/{user_sid}/Conversations/{conversation_sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the UserConversationInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserConversationInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserConversationInstance: + """ + Fetch the UserConversationInstance + + + :returns: The fetched UserConversationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + async def fetch_async(self) -> UserConversationInstance: + """ + Asynchronous coroutine to fetch the UserConversationInstance + + + :returns: The fetched UserConversationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def update( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> UserConversationInstance: + """ + Update the UserConversationInstance + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: The updated UserConversationInstance + """ + + data = values.of( + { + "NotificationLevel": notification_level, + "LastReadTimestamp": serialize.iso8601_datetime(last_read_timestamp), + "LastReadMessageIndex": last_read_message_index, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + async def update_async( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> UserConversationInstance: + """ + Asynchronous coroutine to update the UserConversationInstance + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: The updated UserConversationInstance + """ + + data = values.of( + { + "NotificationLevel": notification_level, + "LastReadTimestamp": serialize.iso8601_datetime(last_read_timestamp), + "LastReadMessageIndex": last_read_message_index, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserConversationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserConversationInstance: + """ + Build an instance of UserConversationInstance + + :param payload: Payload response from the API + """ + return UserConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + user_sid=self._solution["user_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class UserConversationList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str, user_sid: str): + """ + Initialize the UserConversationList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Conversation resource is associated with. + :param user_sid: The unique SID identifier of the [User resource](https://www.twilio.com/docs/conversations/api/user-resource). This value can be either the `sid` or the `identity` of the User resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "user_sid": user_sid, + } + self._uri = ( + "/Services/{chat_service_sid}/Users/{user_sid}/Conversations".format( + **self._solution + ) + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserConversationInstance]: + """ + Streams UserConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserConversationInstance]: + """ + Asynchronously streams UserConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserConversationInstance]: + """ + Lists UserConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserConversationInstance]: + """ + Asynchronously lists UserConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserConversationPage: + """ + Retrieve a single page of UserConversationInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserConversationInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserConversationPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserConversationPage: + """ + Asynchronously retrieve a single page of UserConversationInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserConversationInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserConversationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserConversationPage: + """ + Retrieve a specific page of UserConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserConversationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserConversationPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserConversationPage: + """ + Asynchronously retrieve a specific page of UserConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserConversationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserConversationPage(self._version, response, self._solution) + + def get(self, conversation_sid: str) -> UserConversationContext: + """ + Constructs a UserConversationContext + + :param conversation_sid: The unique SID identifier of the Conversation. This value can be either the `sid` or the `unique_name` of the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource). + """ + return UserConversationContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + user_sid=self._solution["user_sid"], + conversation_sid=conversation_sid, + ) + + def __call__(self, conversation_sid: str) -> UserConversationContext: + """ + Constructs a UserConversationContext + + :param conversation_sid: The unique SID identifier of the Conversation. This value can be either the `sid` or the `unique_name` of the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource). + """ + return UserConversationContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + user_sid=self._solution["user_sid"], + conversation_sid=conversation_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/user/__init__.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/user/__init__.py new file mode 100644 index 00000000..fe5d12f0 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/user/__init__.py @@ -0,0 +1,780 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.conversations.v1.user.user_conversation import UserConversationList + + +class UserInstance(InstanceResource): + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: The unique string that we created to identify the User resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the User resource. + :ivar chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the User resource is associated with. + :ivar role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) assigned to the user. + :ivar identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :ivar is_online: Whether the User is actively connected to this Conversations Service and online. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service's `reachability_enabled` is `false`, if the User has never been online for this Conversations Service, even if the Service's `reachability_enabled` is `true`. + :ivar is_notifiable: Whether the User has a potentially valid Push Notification registration (APN or GCM) for this Conversations Service. If at least one registration exists, `true`; otherwise `false`. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service's `reachability_enabled` is `false`, and if the User has never had a notification registration, even if the Service's `reachability_enabled` is `true`. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: An absolute API resource URL for this user. + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.role_sid: Optional[str] = payload.get("role_sid") + self.identity: Optional[str] = payload.get("identity") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.attributes: Optional[str] = payload.get("attributes") + self.is_online: Optional[bool] = payload.get("is_online") + self.is_notifiable: Optional[bool] = payload.get("is_notifiable") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[UserContext] = None + + @property + def _proxy(self) -> "UserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserContext for this UserInstance + """ + if self._context is None: + self._context = UserContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "UserInstance": + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserInstance": + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The updated UserInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Asynchronous coroutine to update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The updated UserInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + + @property + def user_conversations(self) -> UserConversationList: + """ + Access the user_conversations + """ + return self._proxy.user_conversations + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the UserContext + + :param version: Version that contains the resource + :param sid: The SID of the User resource to update. This value can be either the `sid` or the `identity` of the User resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Users/{sid}".format(**self._solution) + + self._user_conversations: Optional[UserConversationList] = None + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The updated UserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": attributes, + "RoleSid": role_sid, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The updated UserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": attributes, + "RoleSid": role_sid, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def user_conversations(self) -> UserConversationList: + """ + Access the user_conversations + """ + if self._user_conversations is None: + self._user_conversations = UserConversationList( + self._version, + self._solution["sid"], + ) + return self._user_conversations + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: + """ + Build an instance of UserInstance + + :param payload: Payload response from the API + """ + return UserInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class UserList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the UserList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Users" + + def create( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Create the UserInstance + + :param identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The created UserInstance + """ + + data = values.of( + { + "Identity": identity, + "FriendlyName": friendly_name, + "Attributes": attributes, + "RoleSid": role_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance(self._version, payload) + + async def create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The created UserInstance + """ + + data = values.of( + { + "Identity": identity, + "FriendlyName": friendly_name, + "Attributes": attributes, + "RoleSid": role_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserInstance]: + """ + Streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserInstance]: + """ + Asynchronously streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Asynchronously lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Asynchronously retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response) + + def get_page(self, target_url: str) -> UserPage: + """ + Retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserPage(self._version, response) + + async def get_page_async(self, target_url: str) -> UserPage: + """ + Asynchronously retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserPage(self._version, response) + + def get(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: The SID of the User resource to update. This value can be either the `sid` or the `identity` of the User resource to update. + """ + return UserContext(self._version, sid=sid) + + def __call__(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: The SID of the User resource to update. This value can be either the `sid` or the `identity` of the User resource to update. + """ + return UserContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/user/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/user/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..49809311 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/user/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/user/__pycache__/user_conversation.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/conversations/v1/user/__pycache__/user_conversation.cpython-312.pyc new file mode 100644 index 00000000..514ab8e8 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/conversations/v1/user/__pycache__/user_conversation.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/conversations/v1/user/user_conversation.py b/venv/Lib/site-packages/twilio/rest/conversations/v1/user/user_conversation.py new file mode 100644 index 00000000..16ce2c24 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/conversations/v1/user/user_conversation.py @@ -0,0 +1,658 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UserConversationInstance(InstanceResource): + + class NotificationLevel(object): + DEFAULT = "default" + MUTED = "muted" + + class State(object): + INACTIVE = "inactive" + ACTIVE = "active" + CLOSED = "closed" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this User Conversation. + :ivar unread_messages_count: The number of unread Messages in the Conversation for the Participant. + :ivar last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + :ivar participant_sid: The unique ID of the [participant](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) the user conversation belongs to. + :ivar user_sid: The unique string that identifies the [User resource](https://www.twilio.com/docs/conversations/api/user-resource). + :ivar friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :ivar conversation_state: + :ivar timers: Timer date values representing state update for this conversation. + :ivar attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + :ivar date_created: The date that this conversation was created, given in ISO 8601 format. + :ivar date_updated: The date that this conversation was last updated, given in ISO 8601 format. + :ivar created_by: Identity of the creator of this Conversation. + :ivar notification_level: + :ivar unique_name: An application-defined string that uniquely identifies the Conversation resource. It can be used to address the resource in place of the resource's `conversation_sid` in the URL. + :ivar url: + :ivar links: Contains absolute URLs to access the [participant](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) and [conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) of this conversation. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + user_sid: str, + conversation_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.unread_messages_count: Optional[int] = deserialize.integer( + payload.get("unread_messages_count") + ) + self.last_read_message_index: Optional[int] = deserialize.integer( + payload.get("last_read_message_index") + ) + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.user_sid: Optional[str] = payload.get("user_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.conversation_state: Optional["UserConversationInstance.State"] = ( + payload.get("conversation_state") + ) + self.timers: Optional[Dict[str, object]] = payload.get("timers") + self.attributes: Optional[str] = payload.get("attributes") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + self.notification_level: Optional[ + "UserConversationInstance.NotificationLevel" + ] = payload.get("notification_level") + self.unique_name: Optional[str] = payload.get("unique_name") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "user_sid": user_sid, + "conversation_sid": conversation_sid or self.conversation_sid, + } + self._context: Optional[UserConversationContext] = None + + @property + def _proxy(self) -> "UserConversationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserConversationContext for this UserConversationInstance + """ + if self._context is None: + self._context = UserConversationContext( + self._version, + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UserConversationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserConversationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "UserConversationInstance": + """ + Fetch the UserConversationInstance + + + :returns: The fetched UserConversationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserConversationInstance": + """ + Asynchronous coroutine to fetch the UserConversationInstance + + + :returns: The fetched UserConversationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> "UserConversationInstance": + """ + Update the UserConversationInstance + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: The updated UserConversationInstance + """ + return self._proxy.update( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + + async def update_async( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> "UserConversationInstance": + """ + Asynchronous coroutine to update the UserConversationInstance + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: The updated UserConversationInstance + """ + return await self._proxy.update_async( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserConversationContext(InstanceContext): + + def __init__(self, version: Version, user_sid: str, conversation_sid: str): + """ + Initialize the UserConversationContext + + :param version: Version that contains the resource + :param user_sid: The unique SID identifier of the [User resource](https://www.twilio.com/docs/conversations/api/user-resource). This value can be either the `sid` or the `identity` of the User resource. + :param conversation_sid: The unique SID identifier of the Conversation. This value can be either the `sid` or the `unique_name` of the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource). + """ + super().__init__(version) + + # Path Solution + self._solution = { + "user_sid": user_sid, + "conversation_sid": conversation_sid, + } + self._uri = "/Users/{user_sid}/Conversations/{conversation_sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the UserConversationInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserConversationInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserConversationInstance: + """ + Fetch the UserConversationInstance + + + :returns: The fetched UserConversationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserConversationInstance( + self._version, + payload, + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + async def fetch_async(self) -> UserConversationInstance: + """ + Asynchronous coroutine to fetch the UserConversationInstance + + + :returns: The fetched UserConversationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserConversationInstance( + self._version, + payload, + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def update( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> UserConversationInstance: + """ + Update the UserConversationInstance + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: The updated UserConversationInstance + """ + + data = values.of( + { + "NotificationLevel": notification_level, + "LastReadTimestamp": serialize.iso8601_datetime(last_read_timestamp), + "LastReadMessageIndex": last_read_message_index, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserConversationInstance( + self._version, + payload, + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + async def update_async( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> UserConversationInstance: + """ + Asynchronous coroutine to update the UserConversationInstance + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: The updated UserConversationInstance + """ + + data = values.of( + { + "NotificationLevel": notification_level, + "LastReadTimestamp": serialize.iso8601_datetime(last_read_timestamp), + "LastReadMessageIndex": last_read_message_index, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserConversationInstance( + self._version, + payload, + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserConversationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserConversationInstance: + """ + Build an instance of UserConversationInstance + + :param payload: Payload response from the API + """ + return UserConversationInstance( + self._version, payload, user_sid=self._solution["user_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class UserConversationList(ListResource): + + def __init__(self, version: Version, user_sid: str): + """ + Initialize the UserConversationList + + :param version: Version that contains the resource + :param user_sid: The unique SID identifier of the [User resource](https://www.twilio.com/docs/conversations/api/user-resource). This value can be either the `sid` or the `identity` of the User resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "user_sid": user_sid, + } + self._uri = "/Users/{user_sid}/Conversations".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserConversationInstance]: + """ + Streams UserConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserConversationInstance]: + """ + Asynchronously streams UserConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserConversationInstance]: + """ + Lists UserConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserConversationInstance]: + """ + Asynchronously lists UserConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserConversationPage: + """ + Retrieve a single page of UserConversationInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserConversationInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserConversationPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserConversationPage: + """ + Asynchronously retrieve a single page of UserConversationInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserConversationInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserConversationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserConversationPage: + """ + Retrieve a specific page of UserConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserConversationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserConversationPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserConversationPage: + """ + Asynchronously retrieve a specific page of UserConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserConversationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserConversationPage(self._version, response, self._solution) + + def get(self, conversation_sid: str) -> UserConversationContext: + """ + Constructs a UserConversationContext + + :param conversation_sid: The unique SID identifier of the Conversation. This value can be either the `sid` or the `unique_name` of the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource). + """ + return UserConversationContext( + self._version, + user_sid=self._solution["user_sid"], + conversation_sid=conversation_sid, + ) + + def __call__(self, conversation_sid: str) -> UserConversationContext: + """ + Constructs a UserConversationContext + + :param conversation_sid: The unique SID identifier of the Conversation. This value can be either the `sid` or the `unique_name` of the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource). + """ + return UserConversationContext( + self._version, + user_sid=self._solution["user_sid"], + conversation_sid=conversation_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/events/EventsBase.py b/venv/Lib/site-packages/twilio/rest/events/EventsBase.py new file mode 100644 index 00000000..eb2251ae --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/events/EventsBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.events.v1 import V1 + + +class EventsBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Events Domain + + :returns: Domain for Events + """ + super().__init__(twilio, "https://events.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Events + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/events/__init__.py b/venv/Lib/site-packages/twilio/rest/events/__init__.py new file mode 100644 index 00000000..c359cfe9 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/events/__init__.py @@ -0,0 +1,45 @@ +from warnings import warn + +from twilio.rest.events.EventsBase import EventsBase +from twilio.rest.events.v1.event_type import EventTypeList +from twilio.rest.events.v1.schema import SchemaList +from twilio.rest.events.v1.sink import SinkList +from twilio.rest.events.v1.subscription import SubscriptionList + + +class Events(EventsBase): + @property + def event_types(self) -> EventTypeList: + warn( + "event_types is deprecated. Use v1.event_types instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.event_types + + @property + def schemas(self) -> SchemaList: + warn( + "schemas is deprecated. Use v1.schemas instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.schemas + + @property + def sinks(self) -> SinkList: + warn( + "sinks is deprecated. Use v1.sinks instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.sinks + + @property + def subscriptions(self) -> SubscriptionList: + warn( + "subscriptions is deprecated. Use v1.subscriptions instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.subscriptions diff --git a/venv/Lib/site-packages/twilio/rest/events/__pycache__/EventsBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/events/__pycache__/EventsBase.cpython-312.pyc new file mode 100644 index 00000000..7bf1df0a Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/events/__pycache__/EventsBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/events/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/events/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..41d042e7 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/events/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/events/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/events/v1/__init__.py new file mode 100644 index 00000000..6b913554 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/events/v1/__init__.py @@ -0,0 +1,67 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Events + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.events.v1.event_type import EventTypeList +from twilio.rest.events.v1.schema import SchemaList +from twilio.rest.events.v1.sink import SinkList +from twilio.rest.events.v1.subscription import SubscriptionList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Events + + :param domain: The Twilio.events domain + """ + super().__init__(domain, "v1") + self._event_types: Optional[EventTypeList] = None + self._schemas: Optional[SchemaList] = None + self._sinks: Optional[SinkList] = None + self._subscriptions: Optional[SubscriptionList] = None + + @property + def event_types(self) -> EventTypeList: + if self._event_types is None: + self._event_types = EventTypeList(self) + return self._event_types + + @property + def schemas(self) -> SchemaList: + if self._schemas is None: + self._schemas = SchemaList(self) + return self._schemas + + @property + def sinks(self) -> SinkList: + if self._sinks is None: + self._sinks = SinkList(self) + return self._sinks + + @property + def subscriptions(self) -> SubscriptionList: + if self._subscriptions is None: + self._subscriptions = SubscriptionList(self) + return self._subscriptions + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/events/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/events/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..93d01866 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/events/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/events/v1/__pycache__/event_type.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/events/v1/__pycache__/event_type.cpython-312.pyc new file mode 100644 index 00000000..654d1c69 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/events/v1/__pycache__/event_type.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/events/v1/event_type.py b/venv/Lib/site-packages/twilio/rest/events/v1/event_type.py new file mode 100644 index 00000000..7eaaeb03 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/events/v1/event_type.py @@ -0,0 +1,437 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Events + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class EventTypeInstance(InstanceResource): + """ + :ivar type: A string that uniquely identifies this Event Type. + :ivar schema_id: A string that uniquely identifies the Schema this Event Type adheres to. + :ivar date_created: The date that this Event Type was created, given in ISO 8601 format. + :ivar date_updated: The date that this Event Type was updated, given in ISO 8601 format. + :ivar description: A human readable description for this Event Type. + :ivar status: A string that describes how this Event Type can be used. For example: `available`, `deprecated`, `restricted`, `discontinued`. When the status is `available`, the Event Type can be used normally. + :ivar documentation_url: The URL to the documentation or to the most relevant Twilio Changelog entry of this Event Type. + :ivar url: The URL of this resource. + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], type: Optional[str] = None + ): + super().__init__(version) + + self.type: Optional[str] = payload.get("type") + self.schema_id: Optional[str] = payload.get("schema_id") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.description: Optional[str] = payload.get("description") + self.status: Optional[str] = payload.get("status") + self.documentation_url: Optional[str] = payload.get("documentation_url") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "type": type or self.type, + } + self._context: Optional[EventTypeContext] = None + + @property + def _proxy(self) -> "EventTypeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EventTypeContext for this EventTypeInstance + """ + if self._context is None: + self._context = EventTypeContext( + self._version, + type=self._solution["type"], + ) + return self._context + + def fetch(self) -> "EventTypeInstance": + """ + Fetch the EventTypeInstance + + + :returns: The fetched EventTypeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EventTypeInstance": + """ + Asynchronous coroutine to fetch the EventTypeInstance + + + :returns: The fetched EventTypeInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EventTypeContext(InstanceContext): + + def __init__(self, version: Version, type: str): + """ + Initialize the EventTypeContext + + :param version: Version that contains the resource + :param type: A string that uniquely identifies this Event Type. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "type": type, + } + self._uri = "/Types/{type}".format(**self._solution) + + def fetch(self) -> EventTypeInstance: + """ + Fetch the EventTypeInstance + + + :returns: The fetched EventTypeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EventTypeInstance( + self._version, + payload, + type=self._solution["type"], + ) + + async def fetch_async(self) -> EventTypeInstance: + """ + Asynchronous coroutine to fetch the EventTypeInstance + + + :returns: The fetched EventTypeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EventTypeInstance( + self._version, + payload, + type=self._solution["type"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EventTypePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EventTypeInstance: + """ + Build an instance of EventTypeInstance + + :param payload: Payload response from the API + """ + return EventTypeInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class EventTypeList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the EventTypeList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Types" + + def stream( + self, + schema_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EventTypeInstance]: + """ + Streams EventTypeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str schema_id: A string parameter filtering the results to return only the Event Types using a given schema. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(schema_id=schema_id, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + schema_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EventTypeInstance]: + """ + Asynchronously streams EventTypeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str schema_id: A string parameter filtering the results to return only the Event Types using a given schema. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(schema_id=schema_id, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + schema_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventTypeInstance]: + """ + Lists EventTypeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str schema_id: A string parameter filtering the results to return only the Event Types using a given schema. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + schema_id=schema_id, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + schema_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventTypeInstance]: + """ + Asynchronously lists EventTypeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str schema_id: A string parameter filtering the results to return only the Event Types using a given schema. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + schema_id=schema_id, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + schema_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EventTypePage: + """ + Retrieve a single page of EventTypeInstance records from the API. + Request is executed immediately + + :param schema_id: A string parameter filtering the results to return only the Event Types using a given schema. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EventTypeInstance + """ + data = values.of( + { + "SchemaId": schema_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventTypePage(self._version, response) + + async def page_async( + self, + schema_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EventTypePage: + """ + Asynchronously retrieve a single page of EventTypeInstance records from the API. + Request is executed immediately + + :param schema_id: A string parameter filtering the results to return only the Event Types using a given schema. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EventTypeInstance + """ + data = values.of( + { + "SchemaId": schema_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventTypePage(self._version, response) + + def get_page(self, target_url: str) -> EventTypePage: + """ + Retrieve a specific page of EventTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EventTypeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EventTypePage(self._version, response) + + async def get_page_async(self, target_url: str) -> EventTypePage: + """ + Asynchronously retrieve a specific page of EventTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EventTypeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EventTypePage(self._version, response) + + def get(self, type: str) -> EventTypeContext: + """ + Constructs a EventTypeContext + + :param type: A string that uniquely identifies this Event Type. + """ + return EventTypeContext(self._version, type=type) + + def __call__(self, type: str) -> EventTypeContext: + """ + Constructs a EventTypeContext + + :param type: A string that uniquely identifies this Event Type. + """ + return EventTypeContext(self._version, type=type) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/events/v1/schema/__init__.py b/venv/Lib/site-packages/twilio/rest/events/v1/schema/__init__.py new file mode 100644 index 00000000..2c7ffa6b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/events/v1/schema/__init__.py @@ -0,0 +1,221 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Events + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.events.v1.schema.schema_version import SchemaVersionList + + +class SchemaInstance(InstanceResource): + """ + :ivar id: The unique identifier of the schema. Each schema can have multiple versions, that share the same id. + :ivar url: The URL of this resource. + :ivar links: Contains a dictionary of URL links to nested resources of this schema. + :ivar latest_version_date_created: The date that the latest schema version was created, given in ISO 8601 format. + :ivar latest_version: The latest version published of this schema. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], id: Optional[str] = None + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.latest_version_date_created: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("latest_version_date_created")) + ) + self.latest_version: Optional[int] = deserialize.integer( + payload.get("latest_version") + ) + + self._solution = { + "id": id or self.id, + } + self._context: Optional[SchemaContext] = None + + @property + def _proxy(self) -> "SchemaContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SchemaContext for this SchemaInstance + """ + if self._context is None: + self._context = SchemaContext( + self._version, + id=self._solution["id"], + ) + return self._context + + def fetch(self) -> "SchemaInstance": + """ + Fetch the SchemaInstance + + + :returns: The fetched SchemaInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SchemaInstance": + """ + Asynchronous coroutine to fetch the SchemaInstance + + + :returns: The fetched SchemaInstance + """ + return await self._proxy.fetch_async() + + @property + def versions(self) -> SchemaVersionList: + """ + Access the versions + """ + return self._proxy.versions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SchemaContext(InstanceContext): + + def __init__(self, version: Version, id: str): + """ + Initialize the SchemaContext + + :param version: Version that contains the resource + :param id: The unique identifier of the schema. Each schema can have multiple versions, that share the same id. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Schemas/{id}".format(**self._solution) + + self._versions: Optional[SchemaVersionList] = None + + def fetch(self) -> SchemaInstance: + """ + Fetch the SchemaInstance + + + :returns: The fetched SchemaInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SchemaInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_async(self) -> SchemaInstance: + """ + Asynchronous coroutine to fetch the SchemaInstance + + + :returns: The fetched SchemaInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SchemaInstance( + self._version, + payload, + id=self._solution["id"], + ) + + @property + def versions(self) -> SchemaVersionList: + """ + Access the versions + """ + if self._versions is None: + self._versions = SchemaVersionList( + self._version, + self._solution["id"], + ) + return self._versions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SchemaList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SchemaList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, id: str) -> SchemaContext: + """ + Constructs a SchemaContext + + :param id: The unique identifier of the schema. Each schema can have multiple versions, that share the same id. + """ + return SchemaContext(self._version, id=id) + + def __call__(self, id: str) -> SchemaContext: + """ + Constructs a SchemaContext + + :param id: The unique identifier of the schema. Each schema can have multiple versions, that share the same id. + """ + return SchemaContext(self._version, id=id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/events/v1/schema/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/events/v1/schema/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..88fbc3b2 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/events/v1/schema/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/events/v1/schema/__pycache__/schema_version.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/events/v1/schema/__pycache__/schema_version.cpython-312.pyc new file mode 100644 index 00000000..5390750e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/events/v1/schema/__pycache__/schema_version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/events/v1/schema/schema_version.py b/venv/Lib/site-packages/twilio/rest/events/v1/schema/schema_version.py new file mode 100644 index 00000000..be000b9c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/events/v1/schema/schema_version.py @@ -0,0 +1,432 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Events + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SchemaVersionInstance(InstanceResource): + """ + :ivar id: The unique identifier of the schema. Each schema can have multiple versions, that share the same id. + :ivar schema_version: The version of this schema. + :ivar date_created: The date the schema version was created, given in ISO 8601 format. + :ivar url: The URL of this resource. + :ivar raw: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + id: str, + schema_version: Optional[int] = None, + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.schema_version: Optional[int] = deserialize.integer( + payload.get("schema_version") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + self.raw: Optional[str] = payload.get("raw") + + self._solution = { + "id": id, + "schema_version": schema_version or self.schema_version, + } + self._context: Optional[SchemaVersionContext] = None + + @property + def _proxy(self) -> "SchemaVersionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SchemaVersionContext for this SchemaVersionInstance + """ + if self._context is None: + self._context = SchemaVersionContext( + self._version, + id=self._solution["id"], + schema_version=self._solution["schema_version"], + ) + return self._context + + def fetch(self) -> "SchemaVersionInstance": + """ + Fetch the SchemaVersionInstance + + + :returns: The fetched SchemaVersionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SchemaVersionInstance": + """ + Asynchronous coroutine to fetch the SchemaVersionInstance + + + :returns: The fetched SchemaVersionInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SchemaVersionContext(InstanceContext): + + def __init__(self, version: Version, id: str, schema_version: int): + """ + Initialize the SchemaVersionContext + + :param version: Version that contains the resource + :param id: The unique identifier of the schema. Each schema can have multiple versions, that share the same id. + :param schema_version: The version of the schema + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + "schema_version": schema_version, + } + self._uri = "/Schemas/{id}/Versions/{schema_version}".format(**self._solution) + + def fetch(self) -> SchemaVersionInstance: + """ + Fetch the SchemaVersionInstance + + + :returns: The fetched SchemaVersionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SchemaVersionInstance( + self._version, + payload, + id=self._solution["id"], + schema_version=self._solution["schema_version"], + ) + + async def fetch_async(self) -> SchemaVersionInstance: + """ + Asynchronous coroutine to fetch the SchemaVersionInstance + + + :returns: The fetched SchemaVersionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SchemaVersionInstance( + self._version, + payload, + id=self._solution["id"], + schema_version=self._solution["schema_version"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SchemaVersionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SchemaVersionInstance: + """ + Build an instance of SchemaVersionInstance + + :param payload: Payload response from the API + """ + return SchemaVersionInstance(self._version, payload, id=self._solution["id"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SchemaVersionList(ListResource): + + def __init__(self, version: Version, id: str): + """ + Initialize the SchemaVersionList + + :param version: Version that contains the resource + :param id: The unique identifier of the schema. Each schema can have multiple versions, that share the same id. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Schemas/{id}/Versions".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SchemaVersionInstance]: + """ + Streams SchemaVersionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SchemaVersionInstance]: + """ + Asynchronously streams SchemaVersionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SchemaVersionInstance]: + """ + Lists SchemaVersionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SchemaVersionInstance]: + """ + Asynchronously lists SchemaVersionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SchemaVersionPage: + """ + Retrieve a single page of SchemaVersionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SchemaVersionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SchemaVersionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SchemaVersionPage: + """ + Asynchronously retrieve a single page of SchemaVersionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SchemaVersionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SchemaVersionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SchemaVersionPage: + """ + Retrieve a specific page of SchemaVersionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SchemaVersionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SchemaVersionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SchemaVersionPage: + """ + Asynchronously retrieve a specific page of SchemaVersionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SchemaVersionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SchemaVersionPage(self._version, response, self._solution) + + def get(self, schema_version: int) -> SchemaVersionContext: + """ + Constructs a SchemaVersionContext + + :param schema_version: The version of the schema + """ + return SchemaVersionContext( + self._version, id=self._solution["id"], schema_version=schema_version + ) + + def __call__(self, schema_version: int) -> SchemaVersionContext: + """ + Constructs a SchemaVersionContext + + :param schema_version: The version of the schema + """ + return SchemaVersionContext( + self._version, id=self._solution["id"], schema_version=schema_version + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/events/v1/sink/__init__.py b/venv/Lib/site-packages/twilio/rest/events/v1/sink/__init__.py new file mode 100644 index 00000000..3771f83b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/events/v1/sink/__init__.py @@ -0,0 +1,703 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Events + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.events.v1.sink.sink_test import SinkTestList +from twilio.rest.events.v1.sink.sink_validate import SinkValidateList + + +class SinkInstance(InstanceResource): + + class SinkType(object): + KINESIS = "kinesis" + WEBHOOK = "webhook" + SEGMENT = "segment" + EMAIL = "email" + + class Status(object): + INITIALIZED = "initialized" + VALIDATING = "validating" + ACTIVE = "active" + FAILED = "failed" + + """ + :ivar date_created: The date that this Sink was created, given in ISO 8601 format. + :ivar date_updated: The date that this Sink was updated, given in ISO 8601 format. + :ivar description: A human readable description for the Sink + :ivar sid: A 34 character string that uniquely identifies this Sink. + :ivar sink_configuration: The information required for Twilio to connect to the provided Sink encoded as JSON. + :ivar sink_type: + :ivar status: + :ivar url: The URL of this resource. + :ivar links: Contains a dictionary of URL links to nested resources of this Sink. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.description: Optional[str] = payload.get("description") + self.sid: Optional[str] = payload.get("sid") + self.sink_configuration: Optional[Dict[str, object]] = payload.get( + "sink_configuration" + ) + self.sink_type: Optional["SinkInstance.SinkType"] = payload.get("sink_type") + self.status: Optional["SinkInstance.Status"] = payload.get("status") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SinkContext] = None + + @property + def _proxy(self) -> "SinkContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SinkContext for this SinkInstance + """ + if self._context is None: + self._context = SinkContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SinkInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SinkInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SinkInstance": + """ + Fetch the SinkInstance + + + :returns: The fetched SinkInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SinkInstance": + """ + Asynchronous coroutine to fetch the SinkInstance + + + :returns: The fetched SinkInstance + """ + return await self._proxy.fetch_async() + + def update(self, description: str) -> "SinkInstance": + """ + Update the SinkInstance + + :param description: A human readable description for the Sink **This value should not contain PII.** + + :returns: The updated SinkInstance + """ + return self._proxy.update( + description=description, + ) + + async def update_async(self, description: str) -> "SinkInstance": + """ + Asynchronous coroutine to update the SinkInstance + + :param description: A human readable description for the Sink **This value should not contain PII.** + + :returns: The updated SinkInstance + """ + return await self._proxy.update_async( + description=description, + ) + + @property + def sink_test(self) -> SinkTestList: + """ + Access the sink_test + """ + return self._proxy.sink_test + + @property + def sink_validate(self) -> SinkValidateList: + """ + Access the sink_validate + """ + return self._proxy.sink_validate + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SinkContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SinkContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this Sink. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Sinks/{sid}".format(**self._solution) + + self._sink_test: Optional[SinkTestList] = None + self._sink_validate: Optional[SinkValidateList] = None + + def delete(self) -> bool: + """ + Deletes the SinkInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SinkInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SinkInstance: + """ + Fetch the SinkInstance + + + :returns: The fetched SinkInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SinkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SinkInstance: + """ + Asynchronous coroutine to fetch the SinkInstance + + + :returns: The fetched SinkInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SinkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update(self, description: str) -> SinkInstance: + """ + Update the SinkInstance + + :param description: A human readable description for the Sink **This value should not contain PII.** + + :returns: The updated SinkInstance + """ + + data = values.of( + { + "Description": description, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SinkInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async(self, description: str) -> SinkInstance: + """ + Asynchronous coroutine to update the SinkInstance + + :param description: A human readable description for the Sink **This value should not contain PII.** + + :returns: The updated SinkInstance + """ + + data = values.of( + { + "Description": description, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SinkInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def sink_test(self) -> SinkTestList: + """ + Access the sink_test + """ + if self._sink_test is None: + self._sink_test = SinkTestList( + self._version, + self._solution["sid"], + ) + return self._sink_test + + @property + def sink_validate(self) -> SinkValidateList: + """ + Access the sink_validate + """ + if self._sink_validate is None: + self._sink_validate = SinkValidateList( + self._version, + self._solution["sid"], + ) + return self._sink_validate + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SinkPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SinkInstance: + """ + Build an instance of SinkInstance + + :param payload: Payload response from the API + """ + return SinkInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SinkList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SinkList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Sinks" + + def create( + self, + description: str, + sink_configuration: object, + sink_type: "SinkInstance.SinkType", + ) -> SinkInstance: + """ + Create the SinkInstance + + :param description: A human readable description for the Sink **This value should not contain PII.** + :param sink_configuration: The information required for Twilio to connect to the provided Sink encoded as JSON. + :param sink_type: + + :returns: The created SinkInstance + """ + + data = values.of( + { + "Description": description, + "SinkConfiguration": serialize.object(sink_configuration), + "SinkType": sink_type, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SinkInstance(self._version, payload) + + async def create_async( + self, + description: str, + sink_configuration: object, + sink_type: "SinkInstance.SinkType", + ) -> SinkInstance: + """ + Asynchronously create the SinkInstance + + :param description: A human readable description for the Sink **This value should not contain PII.** + :param sink_configuration: The information required for Twilio to connect to the provided Sink encoded as JSON. + :param sink_type: + + :returns: The created SinkInstance + """ + + data = values.of( + { + "Description": description, + "SinkConfiguration": serialize.object(sink_configuration), + "SinkType": sink_type, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SinkInstance(self._version, payload) + + def stream( + self, + in_use: Union[bool, object] = values.unset, + status: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SinkInstance]: + """ + Streams SinkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool in_use: A boolean query parameter filtering the results to return sinks used/not used by a subscription. + :param str status: A String query parameter filtering the results by status `initialized`, `validating`, `active` or `failed`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(in_use=in_use, status=status, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + in_use: Union[bool, object] = values.unset, + status: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SinkInstance]: + """ + Asynchronously streams SinkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool in_use: A boolean query parameter filtering the results to return sinks used/not used by a subscription. + :param str status: A String query parameter filtering the results by status `initialized`, `validating`, `active` or `failed`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + in_use=in_use, status=status, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + in_use: Union[bool, object] = values.unset, + status: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SinkInstance]: + """ + Lists SinkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool in_use: A boolean query parameter filtering the results to return sinks used/not used by a subscription. + :param str status: A String query parameter filtering the results by status `initialized`, `validating`, `active` or `failed`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + in_use=in_use, + status=status, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + in_use: Union[bool, object] = values.unset, + status: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SinkInstance]: + """ + Asynchronously lists SinkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool in_use: A boolean query parameter filtering the results to return sinks used/not used by a subscription. + :param str status: A String query parameter filtering the results by status `initialized`, `validating`, `active` or `failed`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + in_use=in_use, + status=status, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + in_use: Union[bool, object] = values.unset, + status: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SinkPage: + """ + Retrieve a single page of SinkInstance records from the API. + Request is executed immediately + + :param in_use: A boolean query parameter filtering the results to return sinks used/not used by a subscription. + :param status: A String query parameter filtering the results by status `initialized`, `validating`, `active` or `failed`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SinkInstance + """ + data = values.of( + { + "InUse": serialize.boolean_to_string(in_use), + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SinkPage(self._version, response) + + async def page_async( + self, + in_use: Union[bool, object] = values.unset, + status: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SinkPage: + """ + Asynchronously retrieve a single page of SinkInstance records from the API. + Request is executed immediately + + :param in_use: A boolean query parameter filtering the results to return sinks used/not used by a subscription. + :param status: A String query parameter filtering the results by status `initialized`, `validating`, `active` or `failed`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SinkInstance + """ + data = values.of( + { + "InUse": serialize.boolean_to_string(in_use), + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SinkPage(self._version, response) + + def get_page(self, target_url: str) -> SinkPage: + """ + Retrieve a specific page of SinkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SinkInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SinkPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SinkPage: + """ + Asynchronously retrieve a specific page of SinkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SinkInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SinkPage(self._version, response) + + def get(self, sid: str) -> SinkContext: + """ + Constructs a SinkContext + + :param sid: A 34 character string that uniquely identifies this Sink. + """ + return SinkContext(self._version, sid=sid) + + def __call__(self, sid: str) -> SinkContext: + """ + Constructs a SinkContext + + :param sid: A 34 character string that uniquely identifies this Sink. + """ + return SinkContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/events/v1/sink/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/events/v1/sink/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..95bf7341 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/events/v1/sink/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/events/v1/sink/__pycache__/sink_test.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/events/v1/sink/__pycache__/sink_test.cpython-312.pyc new file mode 100644 index 00000000..f6b8131d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/events/v1/sink/__pycache__/sink_test.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/events/v1/sink/__pycache__/sink_validate.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/events/v1/sink/__pycache__/sink_validate.cpython-312.pyc new file mode 100644 index 00000000..2888b2b7 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/events/v1/sink/__pycache__/sink_validate.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/events/v1/sink/sink_test.py b/venv/Lib/site-packages/twilio/rest/events/v1/sink/sink_test.py new file mode 100644 index 00000000..566106ef --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/events/v1/sink/sink_test.py @@ -0,0 +1,105 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Events + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class SinkTestInstance(InstanceResource): + """ + :ivar result: Feedback indicating whether the test event was generated. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], sid: str): + super().__init__(version) + + self.result: Optional[str] = payload.get("result") + + self._solution = { + "sid": sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SinkTestList(ListResource): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SinkTestList + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies the Sink to be Tested. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Sinks/{sid}/Test".format(**self._solution) + + def create(self) -> SinkTestInstance: + """ + Create the SinkTestInstance + + + :returns: The created SinkTestInstance + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = self._version.create(method="POST", uri=self._uri, headers=headers) + + return SinkTestInstance(self._version, payload, sid=self._solution["sid"]) + + async def create_async(self) -> SinkTestInstance: + """ + Asynchronously create the SinkTestInstance + + + :returns: The created SinkTestInstance + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, headers=headers + ) + + return SinkTestInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/events/v1/sink/sink_validate.py b/venv/Lib/site-packages/twilio/rest/events/v1/sink/sink_validate.py new file mode 100644 index 00000000..53eef814 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/events/v1/sink/sink_validate.py @@ -0,0 +1,123 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Events + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class SinkValidateInstance(InstanceResource): + """ + :ivar result: Feedback indicating whether the given Sink was validated. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], sid: str): + super().__init__(version) + + self.result: Optional[str] = payload.get("result") + + self._solution = { + "sid": sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SinkValidateList(ListResource): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SinkValidateList + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies the Sink being validated. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Sinks/{sid}/Validate".format(**self._solution) + + def create(self, test_id: str) -> SinkValidateInstance: + """ + Create the SinkValidateInstance + + :param test_id: A 34 character string that uniquely identifies the test event for a Sink being validated. + + :returns: The created SinkValidateInstance + """ + + data = values.of( + { + "TestId": test_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SinkValidateInstance(self._version, payload, sid=self._solution["sid"]) + + async def create_async(self, test_id: str) -> SinkValidateInstance: + """ + Asynchronously create the SinkValidateInstance + + :param test_id: A 34 character string that uniquely identifies the test event for a Sink being validated. + + :returns: The created SinkValidateInstance + """ + + data = values.of( + { + "TestId": test_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SinkValidateInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/events/v1/subscription/__init__.py b/venv/Lib/site-packages/twilio/rest/events/v1/subscription/__init__.py new file mode 100644 index 00000000..872c9ed7 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/events/v1/subscription/__init__.py @@ -0,0 +1,665 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Events + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.events.v1.subscription.subscribed_event import SubscribedEventList + + +class SubscriptionInstance(InstanceResource): + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar sid: A 34 character string that uniquely identifies this Subscription. + :ivar date_created: The date that this Subscription was created, given in ISO 8601 format. + :ivar date_updated: The date that this Subscription was updated, given in ISO 8601 format. + :ivar description: A human readable description for the Subscription + :ivar sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. + :ivar url: The URL of this resource. + :ivar links: Contains a dictionary of URL links to nested resources of this Subscription. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.description: Optional[str] = payload.get("description") + self.sink_sid: Optional[str] = payload.get("sink_sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SubscriptionContext] = None + + @property + def _proxy(self) -> "SubscriptionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SubscriptionContext for this SubscriptionInstance + """ + if self._context is None: + self._context = SubscriptionContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SubscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SubscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SubscriptionInstance": + """ + Fetch the SubscriptionInstance + + + :returns: The fetched SubscriptionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SubscriptionInstance": + """ + Asynchronous coroutine to fetch the SubscriptionInstance + + + :returns: The fetched SubscriptionInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + description: Union[str, object] = values.unset, + sink_sid: Union[str, object] = values.unset, + ) -> "SubscriptionInstance": + """ + Update the SubscriptionInstance + + :param description: A human readable description for the Subscription. + :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. + + :returns: The updated SubscriptionInstance + """ + return self._proxy.update( + description=description, + sink_sid=sink_sid, + ) + + async def update_async( + self, + description: Union[str, object] = values.unset, + sink_sid: Union[str, object] = values.unset, + ) -> "SubscriptionInstance": + """ + Asynchronous coroutine to update the SubscriptionInstance + + :param description: A human readable description for the Subscription. + :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. + + :returns: The updated SubscriptionInstance + """ + return await self._proxy.update_async( + description=description, + sink_sid=sink_sid, + ) + + @property + def subscribed_events(self) -> SubscribedEventList: + """ + Access the subscribed_events + """ + return self._proxy.subscribed_events + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SubscriptionContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SubscriptionContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this Subscription. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Subscriptions/{sid}".format(**self._solution) + + self._subscribed_events: Optional[SubscribedEventList] = None + + def delete(self) -> bool: + """ + Deletes the SubscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SubscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SubscriptionInstance: + """ + Fetch the SubscriptionInstance + + + :returns: The fetched SubscriptionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SubscriptionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SubscriptionInstance: + """ + Asynchronous coroutine to fetch the SubscriptionInstance + + + :returns: The fetched SubscriptionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SubscriptionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + description: Union[str, object] = values.unset, + sink_sid: Union[str, object] = values.unset, + ) -> SubscriptionInstance: + """ + Update the SubscriptionInstance + + :param description: A human readable description for the Subscription. + :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. + + :returns: The updated SubscriptionInstance + """ + + data = values.of( + { + "Description": description, + "SinkSid": sink_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SubscriptionInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + description: Union[str, object] = values.unset, + sink_sid: Union[str, object] = values.unset, + ) -> SubscriptionInstance: + """ + Asynchronous coroutine to update the SubscriptionInstance + + :param description: A human readable description for the Subscription. + :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. + + :returns: The updated SubscriptionInstance + """ + + data = values.of( + { + "Description": description, + "SinkSid": sink_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SubscriptionInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def subscribed_events(self) -> SubscribedEventList: + """ + Access the subscribed_events + """ + if self._subscribed_events is None: + self._subscribed_events = SubscribedEventList( + self._version, + self._solution["sid"], + ) + return self._subscribed_events + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SubscriptionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SubscriptionInstance: + """ + Build an instance of SubscriptionInstance + + :param payload: Payload response from the API + """ + return SubscriptionInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SubscriptionList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SubscriptionList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Subscriptions" + + def create( + self, description: str, sink_sid: str, types: List[object] + ) -> SubscriptionInstance: + """ + Create the SubscriptionInstance + + :param description: A human readable description for the Subscription **This value should not contain PII.** + :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. + :param types: An array of objects containing the subscribed Event Types + + :returns: The created SubscriptionInstance + """ + + data = values.of( + { + "Description": description, + "SinkSid": sink_sid, + "Types": serialize.map(types, lambda e: serialize.object(e)), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SubscriptionInstance(self._version, payload) + + async def create_async( + self, description: str, sink_sid: str, types: List[object] + ) -> SubscriptionInstance: + """ + Asynchronously create the SubscriptionInstance + + :param description: A human readable description for the Subscription **This value should not contain PII.** + :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. + :param types: An array of objects containing the subscribed Event Types + + :returns: The created SubscriptionInstance + """ + + data = values.of( + { + "Description": description, + "SinkSid": sink_sid, + "Types": serialize.map(types, lambda e: serialize.object(e)), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SubscriptionInstance(self._version, payload) + + def stream( + self, + sink_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SubscriptionInstance]: + """ + Streams SubscriptionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sink_sid: The SID of the sink that the list of Subscriptions should be filtered by. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(sink_sid=sink_sid, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + sink_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SubscriptionInstance]: + """ + Asynchronously streams SubscriptionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sink_sid: The SID of the sink that the list of Subscriptions should be filtered by. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(sink_sid=sink_sid, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + sink_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SubscriptionInstance]: + """ + Lists SubscriptionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sink_sid: The SID of the sink that the list of Subscriptions should be filtered by. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + sink_sid=sink_sid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + sink_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SubscriptionInstance]: + """ + Asynchronously lists SubscriptionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sink_sid: The SID of the sink that the list of Subscriptions should be filtered by. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + sink_sid=sink_sid, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + sink_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SubscriptionPage: + """ + Retrieve a single page of SubscriptionInstance records from the API. + Request is executed immediately + + :param sink_sid: The SID of the sink that the list of Subscriptions should be filtered by. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SubscriptionInstance + """ + data = values.of( + { + "SinkSid": sink_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SubscriptionPage(self._version, response) + + async def page_async( + self, + sink_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SubscriptionPage: + """ + Asynchronously retrieve a single page of SubscriptionInstance records from the API. + Request is executed immediately + + :param sink_sid: The SID of the sink that the list of Subscriptions should be filtered by. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SubscriptionInstance + """ + data = values.of( + { + "SinkSid": sink_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SubscriptionPage(self._version, response) + + def get_page(self, target_url: str) -> SubscriptionPage: + """ + Retrieve a specific page of SubscriptionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SubscriptionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SubscriptionPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SubscriptionPage: + """ + Asynchronously retrieve a specific page of SubscriptionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SubscriptionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SubscriptionPage(self._version, response) + + def get(self, sid: str) -> SubscriptionContext: + """ + Constructs a SubscriptionContext + + :param sid: A 34 character string that uniquely identifies this Subscription. + """ + return SubscriptionContext(self._version, sid=sid) + + def __call__(self, sid: str) -> SubscriptionContext: + """ + Constructs a SubscriptionContext + + :param sid: A 34 character string that uniquely identifies this Subscription. + """ + return SubscriptionContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/events/v1/subscription/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/events/v1/subscription/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..e554d6d6 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/events/v1/subscription/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/events/v1/subscription/__pycache__/subscribed_event.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/events/v1/subscription/__pycache__/subscribed_event.cpython-312.pyc new file mode 100644 index 00000000..d88e9aa9 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/events/v1/subscription/__pycache__/subscribed_event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/events/v1/subscription/subscribed_event.py b/venv/Lib/site-packages/twilio/rest/events/v1/subscription/subscribed_event.py new file mode 100644 index 00000000..dae60ac2 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/events/v1/subscription/subscribed_event.py @@ -0,0 +1,641 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Events + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SubscribedEventInstance(InstanceResource): + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar type: Type of event being subscribed to. + :ivar schema_version: The schema version that the Subscription should use. + :ivar subscription_sid: The unique SID identifier of the Subscription. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + subscription_sid: str, + type: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.type: Optional[str] = payload.get("type") + self.schema_version: Optional[int] = deserialize.integer( + payload.get("schema_version") + ) + self.subscription_sid: Optional[str] = payload.get("subscription_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "subscription_sid": subscription_sid, + "type": type or self.type, + } + self._context: Optional[SubscribedEventContext] = None + + @property + def _proxy(self) -> "SubscribedEventContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SubscribedEventContext for this SubscribedEventInstance + """ + if self._context is None: + self._context = SubscribedEventContext( + self._version, + subscription_sid=self._solution["subscription_sid"], + type=self._solution["type"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SubscribedEventInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SubscribedEventInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SubscribedEventInstance": + """ + Fetch the SubscribedEventInstance + + + :returns: The fetched SubscribedEventInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SubscribedEventInstance": + """ + Asynchronous coroutine to fetch the SubscribedEventInstance + + + :returns: The fetched SubscribedEventInstance + """ + return await self._proxy.fetch_async() + + def update( + self, schema_version: Union[int, object] = values.unset + ) -> "SubscribedEventInstance": + """ + Update the SubscribedEventInstance + + :param schema_version: The schema version that the Subscription should use. + + :returns: The updated SubscribedEventInstance + """ + return self._proxy.update( + schema_version=schema_version, + ) + + async def update_async( + self, schema_version: Union[int, object] = values.unset + ) -> "SubscribedEventInstance": + """ + Asynchronous coroutine to update the SubscribedEventInstance + + :param schema_version: The schema version that the Subscription should use. + + :returns: The updated SubscribedEventInstance + """ + return await self._proxy.update_async( + schema_version=schema_version, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SubscribedEventContext(InstanceContext): + + def __init__(self, version: Version, subscription_sid: str, type: str): + """ + Initialize the SubscribedEventContext + + :param version: Version that contains the resource + :param subscription_sid: The unique SID identifier of the Subscription. + :param type: Type of event being subscribed to. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "subscription_sid": subscription_sid, + "type": type, + } + self._uri = "/Subscriptions/{subscription_sid}/SubscribedEvents/{type}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the SubscribedEventInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SubscribedEventInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SubscribedEventInstance: + """ + Fetch the SubscribedEventInstance + + + :returns: The fetched SubscribedEventInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SubscribedEventInstance( + self._version, + payload, + subscription_sid=self._solution["subscription_sid"], + type=self._solution["type"], + ) + + async def fetch_async(self) -> SubscribedEventInstance: + """ + Asynchronous coroutine to fetch the SubscribedEventInstance + + + :returns: The fetched SubscribedEventInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SubscribedEventInstance( + self._version, + payload, + subscription_sid=self._solution["subscription_sid"], + type=self._solution["type"], + ) + + def update( + self, schema_version: Union[int, object] = values.unset + ) -> SubscribedEventInstance: + """ + Update the SubscribedEventInstance + + :param schema_version: The schema version that the Subscription should use. + + :returns: The updated SubscribedEventInstance + """ + + data = values.of( + { + "SchemaVersion": schema_version, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SubscribedEventInstance( + self._version, + payload, + subscription_sid=self._solution["subscription_sid"], + type=self._solution["type"], + ) + + async def update_async( + self, schema_version: Union[int, object] = values.unset + ) -> SubscribedEventInstance: + """ + Asynchronous coroutine to update the SubscribedEventInstance + + :param schema_version: The schema version that the Subscription should use. + + :returns: The updated SubscribedEventInstance + """ + + data = values.of( + { + "SchemaVersion": schema_version, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SubscribedEventInstance( + self._version, + payload, + subscription_sid=self._solution["subscription_sid"], + type=self._solution["type"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SubscribedEventPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SubscribedEventInstance: + """ + Build an instance of SubscribedEventInstance + + :param payload: Payload response from the API + """ + return SubscribedEventInstance( + self._version, payload, subscription_sid=self._solution["subscription_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SubscribedEventList(ListResource): + + def __init__(self, version: Version, subscription_sid: str): + """ + Initialize the SubscribedEventList + + :param version: Version that contains the resource + :param subscription_sid: The unique SID identifier of the Subscription. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "subscription_sid": subscription_sid, + } + self._uri = "/Subscriptions/{subscription_sid}/SubscribedEvents".format( + **self._solution + ) + + def create( + self, type: str, schema_version: Union[int, object] = values.unset + ) -> SubscribedEventInstance: + """ + Create the SubscribedEventInstance + + :param type: Type of event being subscribed to. + :param schema_version: The schema version that the Subscription should use. + + :returns: The created SubscribedEventInstance + """ + + data = values.of( + { + "Type": type, + "SchemaVersion": schema_version, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SubscribedEventInstance( + self._version, payload, subscription_sid=self._solution["subscription_sid"] + ) + + async def create_async( + self, type: str, schema_version: Union[int, object] = values.unset + ) -> SubscribedEventInstance: + """ + Asynchronously create the SubscribedEventInstance + + :param type: Type of event being subscribed to. + :param schema_version: The schema version that the Subscription should use. + + :returns: The created SubscribedEventInstance + """ + + data = values.of( + { + "Type": type, + "SchemaVersion": schema_version, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SubscribedEventInstance( + self._version, payload, subscription_sid=self._solution["subscription_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SubscribedEventInstance]: + """ + Streams SubscribedEventInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SubscribedEventInstance]: + """ + Asynchronously streams SubscribedEventInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SubscribedEventInstance]: + """ + Lists SubscribedEventInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SubscribedEventInstance]: + """ + Asynchronously lists SubscribedEventInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SubscribedEventPage: + """ + Retrieve a single page of SubscribedEventInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SubscribedEventInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SubscribedEventPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SubscribedEventPage: + """ + Asynchronously retrieve a single page of SubscribedEventInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SubscribedEventInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SubscribedEventPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SubscribedEventPage: + """ + Retrieve a specific page of SubscribedEventInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SubscribedEventInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SubscribedEventPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SubscribedEventPage: + """ + Asynchronously retrieve a specific page of SubscribedEventInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SubscribedEventInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SubscribedEventPage(self._version, response, self._solution) + + def get(self, type: str) -> SubscribedEventContext: + """ + Constructs a SubscribedEventContext + + :param type: Type of event being subscribed to. + """ + return SubscribedEventContext( + self._version, + subscription_sid=self._solution["subscription_sid"], + type=type, + ) + + def __call__(self, type: str) -> SubscribedEventContext: + """ + Constructs a SubscribedEventContext + + :param type: Type of event being subscribed to. + """ + return SubscribedEventContext( + self._version, + subscription_sid=self._solution["subscription_sid"], + type=type, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/FlexApiBase.py b/venv/Lib/site-packages/twilio/rest/flex_api/FlexApiBase.py new file mode 100644 index 00000000..3bda5b6b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/FlexApiBase.py @@ -0,0 +1,55 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.flex_api.v1 import V1 +from twilio.rest.flex_api.v2 import V2 + + +class FlexApiBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the FlexApi Domain + + :returns: Domain for FlexApi + """ + super().__init__(twilio, "https://flex-api.twilio.com") + self._v1: Optional[V1] = None + self._v2: Optional[V2] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of FlexApi + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of FlexApi + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/__init__.py b/venv/Lib/site-packages/twilio/rest/flex_api/__init__.py new file mode 100644 index 00000000..8f679516 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/__init__.py @@ -0,0 +1,185 @@ +from warnings import warn + +from twilio.rest.flex_api.FlexApiBase import FlexApiBase +from twilio.rest.flex_api.v1.assessments import AssessmentsList +from twilio.rest.flex_api.v1.channel import ChannelList +from twilio.rest.flex_api.v1.configuration import ConfigurationList +from twilio.rest.flex_api.v1.flex_flow import FlexFlowList +from twilio.rest.flex_api.v1.insights_assessments_comment import ( + InsightsAssessmentsCommentList, +) +from twilio.rest.flex_api.v1.insights_conversations import InsightsConversationsList +from twilio.rest.flex_api.v1.insights_questionnaires import InsightsQuestionnairesList +from twilio.rest.flex_api.v1.insights_questionnaires_category import ( + InsightsQuestionnairesCategoryList, +) +from twilio.rest.flex_api.v1.insights_questionnaires_question import ( + InsightsQuestionnairesQuestionList, +) +from twilio.rest.flex_api.v1.insights_segments import InsightsSegmentsList +from twilio.rest.flex_api.v1.insights_session import InsightsSessionList +from twilio.rest.flex_api.v1.insights_settings_answer_sets import ( + InsightsSettingsAnswerSetsList, +) +from twilio.rest.flex_api.v1.insights_settings_comment import ( + InsightsSettingsCommentList, +) +from twilio.rest.flex_api.v1.insights_user_roles import InsightsUserRolesList +from twilio.rest.flex_api.v1.interaction import InteractionList +from twilio.rest.flex_api.v1.web_channel import WebChannelList +from twilio.rest.flex_api.v2.web_channels import WebChannelsList + + +class FlexApi(FlexApiBase): + @property + def assessments(self) -> AssessmentsList: + warn( + "assessments is deprecated. Use v1.assessments instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.assessments + + @property + def channel(self) -> ChannelList: + warn( + "channel is deprecated. Use v1.channel instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.channel + + @property + def configuration(self) -> ConfigurationList: + warn( + "configuration is deprecated. Use v1.configuration instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.configuration + + @property + def flex_flow(self) -> FlexFlowList: + warn( + "flex_flow is deprecated. Use v1.flex_flow instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.flex_flow + + @property + def insights_assessments_comment(self) -> InsightsAssessmentsCommentList: + warn( + "insights_assessments_comment is deprecated. Use v1.insights_assessments_comment instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.insights_assessments_comment + + @property + def insights_conversations(self) -> InsightsConversationsList: + warn( + "insights_conversations is deprecated. Use v1.insights_conversations instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.insights_conversations + + @property + def insights_questionnaires(self) -> InsightsQuestionnairesList: + warn( + "insights_questionnaires is deprecated. Use v1.insights_questionnaires instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.insights_questionnaires + + @property + def insights_questionnaires_category(self) -> InsightsQuestionnairesCategoryList: + warn( + "insights_questionnaires_category is deprecated. Use v1.insights_questionnaires_category instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.insights_questionnaires_category + + @property + def insights_questionnaires_question(self) -> InsightsQuestionnairesQuestionList: + warn( + "insights_questionnaires_question is deprecated. Use v1.insights_questionnaires_question instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.insights_questionnaires_question + + @property + def insights_segments(self) -> InsightsSegmentsList: + warn( + "insights_segments is deprecated. Use v1.insights_segments instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.insights_segments + + @property + def insights_session(self) -> InsightsSessionList: + warn( + "insights_session is deprecated. Use v1.insights_session instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.insights_session + + @property + def insights_settings_answer_sets(self) -> InsightsSettingsAnswerSetsList: + warn( + "insights_settings_answer_sets is deprecated. Use v1.insights_settings_answer_sets instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.insights_settings_answer_sets + + @property + def insights_settings_comment(self) -> InsightsSettingsCommentList: + warn( + "insights_settings_comment is deprecated. Use v1.insights_settings_comment instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.insights_settings_comment + + @property + def insights_user_roles(self) -> InsightsUserRolesList: + warn( + "insights_user_roles is deprecated. Use v1.insights_user_roles instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.insights_user_roles + + @property + def interaction(self) -> InteractionList: + warn( + "interaction is deprecated. Use v1.interaction instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.interaction + + @property + def web_channel(self) -> WebChannelList: + warn( + "web_channel is deprecated. Use v1.web_channel instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.web_channel + + @property + def web_channels(self) -> WebChannelsList: + warn( + "web_channels is deprecated. Use v2.web_channels instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.web_channels diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/__pycache__/FlexApiBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/__pycache__/FlexApiBase.cpython-312.pyc new file mode 100644 index 00000000..a2276ae7 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/__pycache__/FlexApiBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..d37a718f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__init__.py new file mode 100644 index 00000000..eeb00227 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__init__.py @@ -0,0 +1,245 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.flex_api.v1.assessments import AssessmentsList +from twilio.rest.flex_api.v1.channel import ChannelList +from twilio.rest.flex_api.v1.configuration import ConfigurationList +from twilio.rest.flex_api.v1.flex_flow import FlexFlowList +from twilio.rest.flex_api.v1.insights_assessments_comment import ( + InsightsAssessmentsCommentList, +) +from twilio.rest.flex_api.v1.insights_conversations import InsightsConversationsList +from twilio.rest.flex_api.v1.insights_questionnaires import InsightsQuestionnairesList +from twilio.rest.flex_api.v1.insights_questionnaires_category import ( + InsightsQuestionnairesCategoryList, +) +from twilio.rest.flex_api.v1.insights_questionnaires_question import ( + InsightsQuestionnairesQuestionList, +) +from twilio.rest.flex_api.v1.insights_segments import InsightsSegmentsList +from twilio.rest.flex_api.v1.insights_session import InsightsSessionList +from twilio.rest.flex_api.v1.insights_settings_answer_sets import ( + InsightsSettingsAnswerSetsList, +) +from twilio.rest.flex_api.v1.insights_settings_comment import ( + InsightsSettingsCommentList, +) +from twilio.rest.flex_api.v1.insights_user_roles import InsightsUserRolesList +from twilio.rest.flex_api.v1.interaction import InteractionList +from twilio.rest.flex_api.v1.plugin import PluginList +from twilio.rest.flex_api.v1.plugin_archive import PluginArchiveList +from twilio.rest.flex_api.v1.plugin_configuration import PluginConfigurationList +from twilio.rest.flex_api.v1.plugin_configuration_archive import ( + PluginConfigurationArchiveList, +) +from twilio.rest.flex_api.v1.plugin_release import PluginReleaseList +from twilio.rest.flex_api.v1.plugin_version_archive import PluginVersionArchiveList +from twilio.rest.flex_api.v1.provisioning_status import ProvisioningStatusList +from twilio.rest.flex_api.v1.web_channel import WebChannelList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of FlexApi + + :param domain: The Twilio.flex_api domain + """ + super().__init__(domain, "v1") + self._assessments: Optional[AssessmentsList] = None + self._channel: Optional[ChannelList] = None + self._configuration: Optional[ConfigurationList] = None + self._flex_flow: Optional[FlexFlowList] = None + self._insights_assessments_comment: Optional[InsightsAssessmentsCommentList] = ( + None + ) + self._insights_conversations: Optional[InsightsConversationsList] = None + self._insights_questionnaires: Optional[InsightsQuestionnairesList] = None + self._insights_questionnaires_category: Optional[ + InsightsQuestionnairesCategoryList + ] = None + self._insights_questionnaires_question: Optional[ + InsightsQuestionnairesQuestionList + ] = None + self._insights_segments: Optional[InsightsSegmentsList] = None + self._insights_session: Optional[InsightsSessionList] = None + self._insights_settings_answer_sets: Optional[ + InsightsSettingsAnswerSetsList + ] = None + self._insights_settings_comment: Optional[InsightsSettingsCommentList] = None + self._insights_user_roles: Optional[InsightsUserRolesList] = None + self._interaction: Optional[InteractionList] = None + self._plugins: Optional[PluginList] = None + self._plugin_archive: Optional[PluginArchiveList] = None + self._plugin_configurations: Optional[PluginConfigurationList] = None + self._plugin_configuration_archive: Optional[PluginConfigurationArchiveList] = ( + None + ) + self._plugin_releases: Optional[PluginReleaseList] = None + self._plugin_version_archive: Optional[PluginVersionArchiveList] = None + self._provisioning_status: Optional[ProvisioningStatusList] = None + self._web_channel: Optional[WebChannelList] = None + + @property + def assessments(self) -> AssessmentsList: + if self._assessments is None: + self._assessments = AssessmentsList(self) + return self._assessments + + @property + def channel(self) -> ChannelList: + if self._channel is None: + self._channel = ChannelList(self) + return self._channel + + @property + def configuration(self) -> ConfigurationList: + if self._configuration is None: + self._configuration = ConfigurationList(self) + return self._configuration + + @property + def flex_flow(self) -> FlexFlowList: + if self._flex_flow is None: + self._flex_flow = FlexFlowList(self) + return self._flex_flow + + @property + def insights_assessments_comment(self) -> InsightsAssessmentsCommentList: + if self._insights_assessments_comment is None: + self._insights_assessments_comment = InsightsAssessmentsCommentList(self) + return self._insights_assessments_comment + + @property + def insights_conversations(self) -> InsightsConversationsList: + if self._insights_conversations is None: + self._insights_conversations = InsightsConversationsList(self) + return self._insights_conversations + + @property + def insights_questionnaires(self) -> InsightsQuestionnairesList: + if self._insights_questionnaires is None: + self._insights_questionnaires = InsightsQuestionnairesList(self) + return self._insights_questionnaires + + @property + def insights_questionnaires_category(self) -> InsightsQuestionnairesCategoryList: + if self._insights_questionnaires_category is None: + self._insights_questionnaires_category = InsightsQuestionnairesCategoryList( + self + ) + return self._insights_questionnaires_category + + @property + def insights_questionnaires_question(self) -> InsightsQuestionnairesQuestionList: + if self._insights_questionnaires_question is None: + self._insights_questionnaires_question = InsightsQuestionnairesQuestionList( + self + ) + return self._insights_questionnaires_question + + @property + def insights_segments(self) -> InsightsSegmentsList: + if self._insights_segments is None: + self._insights_segments = InsightsSegmentsList(self) + return self._insights_segments + + @property + def insights_session(self) -> InsightsSessionList: + if self._insights_session is None: + self._insights_session = InsightsSessionList(self) + return self._insights_session + + @property + def insights_settings_answer_sets(self) -> InsightsSettingsAnswerSetsList: + if self._insights_settings_answer_sets is None: + self._insights_settings_answer_sets = InsightsSettingsAnswerSetsList(self) + return self._insights_settings_answer_sets + + @property + def insights_settings_comment(self) -> InsightsSettingsCommentList: + if self._insights_settings_comment is None: + self._insights_settings_comment = InsightsSettingsCommentList(self) + return self._insights_settings_comment + + @property + def insights_user_roles(self) -> InsightsUserRolesList: + if self._insights_user_roles is None: + self._insights_user_roles = InsightsUserRolesList(self) + return self._insights_user_roles + + @property + def interaction(self) -> InteractionList: + if self._interaction is None: + self._interaction = InteractionList(self) + return self._interaction + + @property + def plugins(self) -> PluginList: + if self._plugins is None: + self._plugins = PluginList(self) + return self._plugins + + @property + def plugin_archive(self) -> PluginArchiveList: + if self._plugin_archive is None: + self._plugin_archive = PluginArchiveList(self) + return self._plugin_archive + + @property + def plugin_configurations(self) -> PluginConfigurationList: + if self._plugin_configurations is None: + self._plugin_configurations = PluginConfigurationList(self) + return self._plugin_configurations + + @property + def plugin_configuration_archive(self) -> PluginConfigurationArchiveList: + if self._plugin_configuration_archive is None: + self._plugin_configuration_archive = PluginConfigurationArchiveList(self) + return self._plugin_configuration_archive + + @property + def plugin_releases(self) -> PluginReleaseList: + if self._plugin_releases is None: + self._plugin_releases = PluginReleaseList(self) + return self._plugin_releases + + @property + def plugin_version_archive(self) -> PluginVersionArchiveList: + if self._plugin_version_archive is None: + self._plugin_version_archive = PluginVersionArchiveList(self) + return self._plugin_version_archive + + @property + def provisioning_status(self) -> ProvisioningStatusList: + if self._provisioning_status is None: + self._provisioning_status = ProvisioningStatusList(self) + return self._provisioning_status + + @property + def web_channel(self) -> WebChannelList: + if self._web_channel is None: + self._web_channel = WebChannelList(self) + return self._web_channel + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..b2ef7cac Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/assessments.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/assessments.cpython-312.pyc new file mode 100644 index 00000000..a959ca9f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/assessments.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/channel.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/channel.cpython-312.pyc new file mode 100644 index 00000000..af1714c8 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/channel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/configuration.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/configuration.cpython-312.pyc new file mode 100644 index 00000000..bef98cd2 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/configuration.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/flex_flow.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/flex_flow.cpython-312.pyc new file mode 100644 index 00000000..74e74bfe Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/flex_flow.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_assessments_comment.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_assessments_comment.cpython-312.pyc new file mode 100644 index 00000000..e8a4f358 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_assessments_comment.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_conversations.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_conversations.cpython-312.pyc new file mode 100644 index 00000000..e7b992b8 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_conversations.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_questionnaires.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_questionnaires.cpython-312.pyc new file mode 100644 index 00000000..09cb1c61 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_questionnaires.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_questionnaires_category.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_questionnaires_category.cpython-312.pyc new file mode 100644 index 00000000..778c00fe Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_questionnaires_category.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_questionnaires_question.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_questionnaires_question.cpython-312.pyc new file mode 100644 index 00000000..c828082f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_questionnaires_question.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_segments.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_segments.cpython-312.pyc new file mode 100644 index 00000000..0ab6ed7d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_segments.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_session.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_session.cpython-312.pyc new file mode 100644 index 00000000..4a27b7d4 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_session.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_settings_answer_sets.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_settings_answer_sets.cpython-312.pyc new file mode 100644 index 00000000..18275751 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_settings_answer_sets.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_settings_comment.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_settings_comment.cpython-312.pyc new file mode 100644 index 00000000..373a090a Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_settings_comment.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_user_roles.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_user_roles.cpython-312.pyc new file mode 100644 index 00000000..8b68aac4 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/insights_user_roles.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/plugin_archive.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/plugin_archive.cpython-312.pyc new file mode 100644 index 00000000..fbf6571f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/plugin_archive.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/plugin_configuration_archive.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/plugin_configuration_archive.cpython-312.pyc new file mode 100644 index 00000000..33ba504b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/plugin_configuration_archive.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/plugin_release.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/plugin_release.cpython-312.pyc new file mode 100644 index 00000000..6d48af40 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/plugin_release.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/plugin_version_archive.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/plugin_version_archive.cpython-312.pyc new file mode 100644 index 00000000..96521fdc Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/plugin_version_archive.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/provisioning_status.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/provisioning_status.cpython-312.pyc new file mode 100644 index 00000000..0c3ad0d5 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/provisioning_status.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/web_channel.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/web_channel.cpython-312.pyc new file mode 100644 index 00000000..d65b7473 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/__pycache__/web_channel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/assessments.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/assessments.py new file mode 100644 index 00000000..130514b2 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/assessments.py @@ -0,0 +1,685 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AssessmentsInstance(InstanceResource): + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar assessment_sid: The SID of the assessment + :ivar offset: Offset of the conversation + :ivar report: The flag indicating if this assessment is part of report + :ivar weight: The weightage given to this comment + :ivar agent_id: The id of the Agent + :ivar segment_id: Segment Id of conversation + :ivar user_name: The name of the user. + :ivar user_email: The email id of the user. + :ivar answer_text: The answer text selected by user + :ivar answer_id: The id of the answer selected by user + :ivar assessment: Assessment Details associated with an assessment + :ivar timestamp: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + assessment_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.assessment_sid: Optional[str] = payload.get("assessment_sid") + self.offset: Optional[float] = deserialize.decimal(payload.get("offset")) + self.report: Optional[bool] = payload.get("report") + self.weight: Optional[float] = deserialize.decimal(payload.get("weight")) + self.agent_id: Optional[str] = payload.get("agent_id") + self.segment_id: Optional[str] = payload.get("segment_id") + self.user_name: Optional[str] = payload.get("user_name") + self.user_email: Optional[str] = payload.get("user_email") + self.answer_text: Optional[str] = payload.get("answer_text") + self.answer_id: Optional[str] = payload.get("answer_id") + self.assessment: Optional[Dict[str, object]] = payload.get("assessment") + self.timestamp: Optional[float] = deserialize.decimal(payload.get("timestamp")) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "assessment_sid": assessment_sid or self.assessment_sid, + } + self._context: Optional[AssessmentsContext] = None + + @property + def _proxy(self) -> "AssessmentsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AssessmentsContext for this AssessmentsInstance + """ + if self._context is None: + self._context = AssessmentsContext( + self._version, + assessment_sid=self._solution["assessment_sid"], + ) + return self._context + + def update( + self, + offset: float, + answer_text: str, + answer_id: str, + authorization: Union[str, object] = values.unset, + ) -> "AssessmentsInstance": + """ + Update the AssessmentsInstance + + :param offset: The offset of the conversation + :param answer_text: The answer text selected by user + :param answer_id: The id of the answer selected by user + :param authorization: The Authorization HTTP request header + + :returns: The updated AssessmentsInstance + """ + return self._proxy.update( + offset=offset, + answer_text=answer_text, + answer_id=answer_id, + authorization=authorization, + ) + + async def update_async( + self, + offset: float, + answer_text: str, + answer_id: str, + authorization: Union[str, object] = values.unset, + ) -> "AssessmentsInstance": + """ + Asynchronous coroutine to update the AssessmentsInstance + + :param offset: The offset of the conversation + :param answer_text: The answer text selected by user + :param answer_id: The id of the answer selected by user + :param authorization: The Authorization HTTP request header + + :returns: The updated AssessmentsInstance + """ + return await self._proxy.update_async( + offset=offset, + answer_text=answer_text, + answer_id=answer_id, + authorization=authorization, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AssessmentsContext(InstanceContext): + + def __init__(self, version: Version, assessment_sid: str): + """ + Initialize the AssessmentsContext + + :param version: Version that contains the resource + :param assessment_sid: The SID of the assessment to be modified + """ + super().__init__(version) + + # Path Solution + self._solution = { + "assessment_sid": assessment_sid, + } + self._uri = "/Insights/QualityManagement/Assessments/{assessment_sid}".format( + **self._solution + ) + + def update( + self, + offset: float, + answer_text: str, + answer_id: str, + authorization: Union[str, object] = values.unset, + ) -> AssessmentsInstance: + """ + Update the AssessmentsInstance + + :param offset: The offset of the conversation + :param answer_text: The answer text selected by user + :param answer_id: The id of the answer selected by user + :param authorization: The Authorization HTTP request header + + :returns: The updated AssessmentsInstance + """ + + data = values.of( + { + "Offset": offset, + "AnswerText": answer_text, + "AnswerId": answer_id, + } + ) + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AssessmentsInstance( + self._version, payload, assessment_sid=self._solution["assessment_sid"] + ) + + async def update_async( + self, + offset: float, + answer_text: str, + answer_id: str, + authorization: Union[str, object] = values.unset, + ) -> AssessmentsInstance: + """ + Asynchronous coroutine to update the AssessmentsInstance + + :param offset: The offset of the conversation + :param answer_text: The answer text selected by user + :param answer_id: The id of the answer selected by user + :param authorization: The Authorization HTTP request header + + :returns: The updated AssessmentsInstance + """ + + data = values.of( + { + "Offset": offset, + "AnswerText": answer_text, + "AnswerId": answer_id, + } + ) + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AssessmentsInstance( + self._version, payload, assessment_sid=self._solution["assessment_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AssessmentsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AssessmentsInstance: + """ + Build an instance of AssessmentsInstance + + :param payload: Payload response from the API + """ + return AssessmentsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AssessmentsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AssessmentsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Insights/QualityManagement/Assessments" + + def create( + self, + category_sid: str, + category_name: str, + segment_id: str, + agent_id: str, + offset: float, + metric_id: str, + metric_name: str, + answer_text: str, + answer_id: str, + questionnaire_sid: str, + authorization: Union[str, object] = values.unset, + ) -> AssessmentsInstance: + """ + Create the AssessmentsInstance + + :param category_sid: The SID of the category + :param category_name: The name of the category + :param segment_id: Segment Id of the conversation + :param agent_id: The id of the Agent + :param offset: The offset of the conversation. + :param metric_id: The question SID selected for assessment + :param metric_name: The question name of the assessment + :param answer_text: The answer text selected by user + :param answer_id: The id of the answer selected by user + :param questionnaire_sid: Questionnaire SID of the associated question + :param authorization: The Authorization HTTP request header + + :returns: The created AssessmentsInstance + """ + + data = values.of( + { + "CategorySid": category_sid, + "CategoryName": category_name, + "SegmentId": segment_id, + "AgentId": agent_id, + "Offset": offset, + "MetricId": metric_id, + "MetricName": metric_name, + "AnswerText": answer_text, + "AnswerId": answer_id, + "QuestionnaireSid": questionnaire_sid, + } + ) + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AssessmentsInstance(self._version, payload) + + async def create_async( + self, + category_sid: str, + category_name: str, + segment_id: str, + agent_id: str, + offset: float, + metric_id: str, + metric_name: str, + answer_text: str, + answer_id: str, + questionnaire_sid: str, + authorization: Union[str, object] = values.unset, + ) -> AssessmentsInstance: + """ + Asynchronously create the AssessmentsInstance + + :param category_sid: The SID of the category + :param category_name: The name of the category + :param segment_id: Segment Id of the conversation + :param agent_id: The id of the Agent + :param offset: The offset of the conversation. + :param metric_id: The question SID selected for assessment + :param metric_name: The question name of the assessment + :param answer_text: The answer text selected by user + :param answer_id: The id of the answer selected by user + :param questionnaire_sid: Questionnaire SID of the associated question + :param authorization: The Authorization HTTP request header + + :returns: The created AssessmentsInstance + """ + + data = values.of( + { + "CategorySid": category_sid, + "CategoryName": category_name, + "SegmentId": segment_id, + "AgentId": agent_id, + "Offset": offset, + "MetricId": metric_id, + "MetricName": metric_name, + "AnswerText": answer_text, + "AnswerId": answer_id, + "QuestionnaireSid": questionnaire_sid, + } + ) + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AssessmentsInstance(self._version, payload) + + def stream( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AssessmentsInstance]: + """ + Streams AssessmentsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + authorization=authorization, + segment_id=segment_id, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AssessmentsInstance]: + """ + Asynchronously streams AssessmentsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + authorization=authorization, + segment_id=segment_id, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssessmentsInstance]: + """ + Lists AssessmentsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + authorization=authorization, + segment_id=segment_id, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssessmentsInstance]: + """ + Asynchronously lists AssessmentsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + authorization=authorization, + segment_id=segment_id, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssessmentsPage: + """ + Retrieve a single page of AssessmentsInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param segment_id: The id of the segment. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssessmentsInstance + """ + data = values.of( + { + "Authorization": authorization, + "SegmentId": segment_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssessmentsPage(self._version, response) + + async def page_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssessmentsPage: + """ + Asynchronously retrieve a single page of AssessmentsInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param segment_id: The id of the segment. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssessmentsInstance + """ + data = values.of( + { + "Authorization": authorization, + "SegmentId": segment_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssessmentsPage(self._version, response) + + def get_page(self, target_url: str) -> AssessmentsPage: + """ + Retrieve a specific page of AssessmentsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssessmentsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AssessmentsPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AssessmentsPage: + """ + Asynchronously retrieve a specific page of AssessmentsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssessmentsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AssessmentsPage(self._version, response) + + def get(self, assessment_sid: str) -> AssessmentsContext: + """ + Constructs a AssessmentsContext + + :param assessment_sid: The SID of the assessment to be modified + """ + return AssessmentsContext(self._version, assessment_sid=assessment_sid) + + def __call__(self, assessment_sid: str) -> AssessmentsContext: + """ + Constructs a AssessmentsContext + + :param assessment_sid: The SID of the assessment to be modified + """ + return AssessmentsContext(self._version, assessment_sid=assessment_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/channel.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/channel.py new file mode 100644 index 00000000..aa98ff8d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/channel.py @@ -0,0 +1,575 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ChannelInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Channel resource and owns this Workflow. + :ivar flex_flow_sid: The SID of the Flex Flow. + :ivar sid: The unique string that we created to identify the Channel resource. + :ivar user_sid: The SID of the chat user. + :ivar task_sid: The SID of the TaskRouter Task. Only valid when integration type is `task`. `null` for integration types `studio` & `external` + :ivar url: The absolute URL of the Flex chat channel resource. + :ivar date_created: The date and time in GMT when the Flex chat channel was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Flex chat channel was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.flex_flow_sid: Optional[str] = payload.get("flex_flow_sid") + self.sid: Optional[str] = payload.get("sid") + self.user_sid: Optional[str] = payload.get("user_sid") + self.task_sid: Optional[str] = payload.get("task_sid") + self.url: Optional[str] = payload.get("url") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ChannelContext] = None + + @property + def _proxy(self) -> "ChannelContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ChannelContext for this ChannelInstance + """ + if self._context is None: + self._context = ChannelContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ChannelInstance": + """ + Fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ChannelInstance": + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ChannelContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ChannelContext + + :param version: Version that contains the resource + :param sid: The SID of the Flex chat channel resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Channels/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChannelInstance: + """ + Fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ChannelInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ChannelInstance: + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: + """ + Build an instance of ChannelInstance + + :param payload: Payload response from the API + """ + return ChannelInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ChannelList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ChannelList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Channels" + + def create( + self, + flex_flow_sid: str, + identity: str, + chat_user_friendly_name: str, + chat_friendly_name: str, + target: Union[str, object] = values.unset, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + task_attributes: Union[str, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + ) -> ChannelInstance: + """ + Create the ChannelInstance + + :param flex_flow_sid: The SID of the Flex Flow. + :param identity: The `identity` value that uniquely identifies the new resource's chat User. + :param chat_user_friendly_name: The chat participant's friendly name. + :param chat_friendly_name: The chat channel's friendly name. + :param target: The Target Contact Identity, for example the phone number of an SMS. + :param chat_unique_name: The chat channel's unique name. + :param pre_engagement_data: The pre-engagement data. + :param task_sid: The SID of the TaskRouter Task. Only valid when integration type is `task`. `null` for integration types `studio` & `external` + :param task_attributes: The Task attributes to be added for the TaskRouter Task. + :param long_lived: Whether to create the channel as long-lived. + + :returns: The created ChannelInstance + """ + + data = values.of( + { + "FlexFlowSid": flex_flow_sid, + "Identity": identity, + "ChatUserFriendlyName": chat_user_friendly_name, + "ChatFriendlyName": chat_friendly_name, + "Target": target, + "ChatUniqueName": chat_unique_name, + "PreEngagementData": pre_engagement_data, + "TaskSid": task_sid, + "TaskAttributes": task_attributes, + "LongLived": serialize.boolean_to_string(long_lived), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance(self._version, payload) + + async def create_async( + self, + flex_flow_sid: str, + identity: str, + chat_user_friendly_name: str, + chat_friendly_name: str, + target: Union[str, object] = values.unset, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + task_attributes: Union[str, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronously create the ChannelInstance + + :param flex_flow_sid: The SID of the Flex Flow. + :param identity: The `identity` value that uniquely identifies the new resource's chat User. + :param chat_user_friendly_name: The chat participant's friendly name. + :param chat_friendly_name: The chat channel's friendly name. + :param target: The Target Contact Identity, for example the phone number of an SMS. + :param chat_unique_name: The chat channel's unique name. + :param pre_engagement_data: The pre-engagement data. + :param task_sid: The SID of the TaskRouter Task. Only valid when integration type is `task`. `null` for integration types `studio` & `external` + :param task_attributes: The Task attributes to be added for the TaskRouter Task. + :param long_lived: Whether to create the channel as long-lived. + + :returns: The created ChannelInstance + """ + + data = values.of( + { + "FlexFlowSid": flex_flow_sid, + "Identity": identity, + "ChatUserFriendlyName": chat_user_friendly_name, + "ChatFriendlyName": chat_friendly_name, + "Target": target, + "ChatUniqueName": chat_unique_name, + "PreEngagementData": pre_engagement_data, + "TaskSid": task_sid, + "TaskAttributes": task_attributes, + "LongLived": serialize.boolean_to_string(long_lived), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChannelInstance]: + """ + Streams ChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ChannelInstance]: + """ + Asynchronously streams ChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: + """ + Lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: + """ + Asynchronously lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: + """ + Retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: + """ + Asynchronously retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response) + + def get_page(self, target_url: str) -> ChannelPage: + """ + Retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ChannelPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ChannelPage: + """ + Asynchronously retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelPage(self._version, response) + + def get(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: The SID of the Flex chat channel resource to fetch. + """ + return ChannelContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: The SID of the Flex chat channel resource to fetch. + """ + return ChannelContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/configuration.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/configuration.py new file mode 100644 index 00000000..28a66be0 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/configuration.py @@ -0,0 +1,439 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ConfigurationInstance(InstanceResource): + + class Status(object): + OK = "ok" + INPROGRESS = "inprogress" + NOTSTARTED = "notstarted" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Configuration resource. + :ivar date_created: The date and time in GMT when the Configuration resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Configuration resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar attributes: An object that contains application-specific data. + :ivar status: + :ivar taskrouter_workspace_sid: The SID of the TaskRouter Workspace. + :ivar taskrouter_target_workflow_sid: The SID of the TaskRouter target Workflow. + :ivar taskrouter_target_taskqueue_sid: The SID of the TaskRouter Target TaskQueue. + :ivar taskrouter_taskqueues: The list of TaskRouter TaskQueues. + :ivar taskrouter_skills: The Skill description for TaskRouter workers. + :ivar taskrouter_worker_channels: The TaskRouter default channel capacities and availability for workers. + :ivar taskrouter_worker_attributes: The TaskRouter Worker attributes. + :ivar taskrouter_offline_activity_sid: The TaskRouter SID of the offline activity. + :ivar runtime_domain: The URL where the Flex instance is hosted. + :ivar messaging_service_instance_sid: The SID of the Messaging service instance. + :ivar chat_service_instance_sid: The SID of the chat service this user belongs to. + :ivar flex_service_instance_sid: The SID of the Flex service instance. + :ivar flex_instance_sid: The SID of the Flex instance. + :ivar ui_language: The primary language of the Flex UI. + :ivar ui_attributes: The object that describes Flex UI characteristics and settings. + :ivar ui_dependencies: The object that defines the NPM packages and versions to be used in Hosted Flex. + :ivar ui_version: The Pinned UI version. + :ivar service_version: The Flex Service version. + :ivar call_recording_enabled: Whether call recording is enabled. + :ivar call_recording_webhook_url: The call recording webhook URL. + :ivar crm_enabled: Whether CRM is present for Flex. + :ivar crm_type: The CRM type. + :ivar crm_callback_url: The CRM Callback URL. + :ivar crm_fallback_url: The CRM Fallback URL. + :ivar crm_attributes: An object that contains the CRM attributes. + :ivar public_attributes: The list of public attributes, which are visible to unauthenticated clients. + :ivar plugin_service_enabled: Whether the plugin service enabled. + :ivar plugin_service_attributes: The plugin service attributes. + :ivar integrations: A list of objects that contain the configurations for the Integrations supported in this configuration. + :ivar outbound_call_flows: The list of outbound call flows. + :ivar serverless_service_sids: The list of serverless service SIDs. + :ivar queue_stats_configuration: Configurable parameters for Queues Statistics. + :ivar notifications: Configurable parameters for Notifications. + :ivar markdown: Configurable parameters for Markdown. + :ivar url: The absolute URL of the Configuration resource. + :ivar flex_insights_hr: Object with enabled/disabled flag with list of workspaces. + :ivar flex_insights_drilldown: Setting this to true will redirect Flex UI to the URL set in flex_url + :ivar flex_url: URL to redirect to in case drilldown is enabled. + :ivar channel_configs: Settings for different limits for Flex Conversations channels attachments. + :ivar debugger_integration: Configurable parameters for Debugger Integration. + :ivar flex_ui_status_report: Configurable parameters for Flex UI Status report. + :ivar agent_conv_end_methods: Agent conversation end methods. + :ivar citrix_voice_vdi: Citrix voice vdi configuration and settings. + :ivar offline_config: Presence and presence ttl configuration + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.attributes: Optional[Dict[str, object]] = payload.get("attributes") + self.status: Optional["ConfigurationInstance.Status"] = payload.get("status") + self.taskrouter_workspace_sid: Optional[str] = payload.get( + "taskrouter_workspace_sid" + ) + self.taskrouter_target_workflow_sid: Optional[str] = payload.get( + "taskrouter_target_workflow_sid" + ) + self.taskrouter_target_taskqueue_sid: Optional[str] = payload.get( + "taskrouter_target_taskqueue_sid" + ) + self.taskrouter_taskqueues: Optional[List[Dict[str, object]]] = payload.get( + "taskrouter_taskqueues" + ) + self.taskrouter_skills: Optional[List[Dict[str, object]]] = payload.get( + "taskrouter_skills" + ) + self.taskrouter_worker_channels: Optional[Dict[str, object]] = payload.get( + "taskrouter_worker_channels" + ) + self.taskrouter_worker_attributes: Optional[Dict[str, object]] = payload.get( + "taskrouter_worker_attributes" + ) + self.taskrouter_offline_activity_sid: Optional[str] = payload.get( + "taskrouter_offline_activity_sid" + ) + self.runtime_domain: Optional[str] = payload.get("runtime_domain") + self.messaging_service_instance_sid: Optional[str] = payload.get( + "messaging_service_instance_sid" + ) + self.chat_service_instance_sid: Optional[str] = payload.get( + "chat_service_instance_sid" + ) + self.flex_service_instance_sid: Optional[str] = payload.get( + "flex_service_instance_sid" + ) + self.flex_instance_sid: Optional[str] = payload.get("flex_instance_sid") + self.ui_language: Optional[str] = payload.get("ui_language") + self.ui_attributes: Optional[Dict[str, object]] = payload.get("ui_attributes") + self.ui_dependencies: Optional[Dict[str, object]] = payload.get( + "ui_dependencies" + ) + self.ui_version: Optional[str] = payload.get("ui_version") + self.service_version: Optional[str] = payload.get("service_version") + self.call_recording_enabled: Optional[bool] = payload.get( + "call_recording_enabled" + ) + self.call_recording_webhook_url: Optional[str] = payload.get( + "call_recording_webhook_url" + ) + self.crm_enabled: Optional[bool] = payload.get("crm_enabled") + self.crm_type: Optional[str] = payload.get("crm_type") + self.crm_callback_url: Optional[str] = payload.get("crm_callback_url") + self.crm_fallback_url: Optional[str] = payload.get("crm_fallback_url") + self.crm_attributes: Optional[Dict[str, object]] = payload.get("crm_attributes") + self.public_attributes: Optional[Dict[str, object]] = payload.get( + "public_attributes" + ) + self.plugin_service_enabled: Optional[bool] = payload.get( + "plugin_service_enabled" + ) + self.plugin_service_attributes: Optional[Dict[str, object]] = payload.get( + "plugin_service_attributes" + ) + self.integrations: Optional[List[Dict[str, object]]] = payload.get( + "integrations" + ) + self.outbound_call_flows: Optional[Dict[str, object]] = payload.get( + "outbound_call_flows" + ) + self.serverless_service_sids: Optional[List[str]] = payload.get( + "serverless_service_sids" + ) + self.queue_stats_configuration: Optional[Dict[str, object]] = payload.get( + "queue_stats_configuration" + ) + self.notifications: Optional[Dict[str, object]] = payload.get("notifications") + self.markdown: Optional[Dict[str, object]] = payload.get("markdown") + self.url: Optional[str] = payload.get("url") + self.flex_insights_hr: Optional[Dict[str, object]] = payload.get( + "flex_insights_hr" + ) + self.flex_insights_drilldown: Optional[bool] = payload.get( + "flex_insights_drilldown" + ) + self.flex_url: Optional[str] = payload.get("flex_url") + self.channel_configs: Optional[List[Dict[str, object]]] = payload.get( + "channel_configs" + ) + self.debugger_integration: Optional[Dict[str, object]] = payload.get( + "debugger_integration" + ) + self.flex_ui_status_report: Optional[Dict[str, object]] = payload.get( + "flex_ui_status_report" + ) + self.agent_conv_end_methods: Optional[Dict[str, object]] = payload.get( + "agent_conv_end_methods" + ) + self.citrix_voice_vdi: Optional[Dict[str, object]] = payload.get( + "citrix_voice_vdi" + ) + self.offline_config: Optional[Dict[str, object]] = payload.get("offline_config") + + self._context: Optional[ConfigurationContext] = None + + @property + def _proxy(self) -> "ConfigurationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConfigurationContext for this ConfigurationInstance + """ + if self._context is None: + self._context = ConfigurationContext( + self._version, + ) + return self._context + + def fetch( + self, ui_version: Union[str, object] = values.unset + ) -> "ConfigurationInstance": + """ + Fetch the ConfigurationInstance + + :param ui_version: The Pinned UI version of the Configuration resource to fetch. + + :returns: The fetched ConfigurationInstance + """ + return self._proxy.fetch( + ui_version=ui_version, + ) + + async def fetch_async( + self, ui_version: Union[str, object] = values.unset + ) -> "ConfigurationInstance": + """ + Asynchronous coroutine to fetch the ConfigurationInstance + + :param ui_version: The Pinned UI version of the Configuration resource to fetch. + + :returns: The fetched ConfigurationInstance + """ + return await self._proxy.fetch_async( + ui_version=ui_version, + ) + + def update( + self, body: Union[object, object] = values.unset + ) -> "ConfigurationInstance": + """ + Update the ConfigurationInstance + + :param body: + + :returns: The updated ConfigurationInstance + """ + return self._proxy.update( + body=body, + ) + + async def update_async( + self, body: Union[object, object] = values.unset + ) -> "ConfigurationInstance": + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param body: + + :returns: The updated ConfigurationInstance + """ + return await self._proxy.update_async( + body=body, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class ConfigurationContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the ConfigurationContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/Configuration" + + def fetch( + self, ui_version: Union[str, object] = values.unset + ) -> ConfigurationInstance: + """ + Fetch the ConfigurationInstance + + :param ui_version: The Pinned UI version of the Configuration resource to fetch. + + :returns: The fetched ConfigurationInstance + """ + + data = values.of( + { + "UiVersion": ui_version, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return ConfigurationInstance( + self._version, + payload, + ) + + async def fetch_async( + self, ui_version: Union[str, object] = values.unset + ) -> ConfigurationInstance: + """ + Asynchronous coroutine to fetch the ConfigurationInstance + + :param ui_version: The Pinned UI version of the Configuration resource to fetch. + + :returns: The fetched ConfigurationInstance + """ + + data = values.of( + { + "UiVersion": ui_version, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return ConfigurationInstance( + self._version, + payload, + ) + + def update( + self, body: Union[object, object] = values.unset + ) -> ConfigurationInstance: + """ + Update the ConfigurationInstance + + :param body: + + :returns: The updated ConfigurationInstance + """ + data = body.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConfigurationInstance(self._version, payload) + + async def update_async( + self, body: Union[object, object] = values.unset + ) -> ConfigurationInstance: + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param body: + + :returns: The updated ConfigurationInstance + """ + data = body.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConfigurationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class ConfigurationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ConfigurationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> ConfigurationContext: + """ + Constructs a ConfigurationContext + + """ + return ConfigurationContext(self._version) + + def __call__(self) -> ConfigurationContext: + """ + Constructs a ConfigurationContext + + """ + return ConfigurationContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/flex_flow.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/flex_flow.py new file mode 100644 index 00000000..0ae26346 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/flex_flow.py @@ -0,0 +1,965 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class FlexFlowInstance(InstanceResource): + + class ChannelType(object): + WEB = "web" + SMS = "sms" + FACEBOOK = "facebook" + WHATSAPP = "whatsapp" + LINE = "line" + CUSTOM = "custom" + + class IntegrationType(object): + STUDIO = "studio" + EXTERNAL = "external" + TASK = "task" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Flow resource and owns this Workflow. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar sid: The unique string that we created to identify the Flex Flow resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar chat_service_sid: The SID of the chat service. + :ivar channel_type: + :ivar contact_identity: The channel contact's Identity. + :ivar enabled: Whether the Flex Flow is enabled. + :ivar integration_type: + :ivar integration: An object that contains specific parameters for the integration. + :ivar long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :ivar janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :ivar url: The absolute URL of the Flex Flow resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.channel_type: Optional["FlexFlowInstance.ChannelType"] = payload.get( + "channel_type" + ) + self.contact_identity: Optional[str] = payload.get("contact_identity") + self.enabled: Optional[bool] = payload.get("enabled") + self.integration_type: Optional["FlexFlowInstance.IntegrationType"] = ( + payload.get("integration_type") + ) + self.integration: Optional[Dict[str, object]] = payload.get("integration") + self.long_lived: Optional[bool] = payload.get("long_lived") + self.janitor_enabled: Optional[bool] = payload.get("janitor_enabled") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[FlexFlowContext] = None + + @property + def _proxy(self) -> "FlexFlowContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FlexFlowContext for this FlexFlowInstance + """ + if self._context is None: + self._context = FlexFlowContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the FlexFlowInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FlexFlowInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "FlexFlowInstance": + """ + Fetch the FlexFlowInstance + + + :returns: The fetched FlexFlowInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FlexFlowInstance": + """ + Asynchronous coroutine to fetch the FlexFlowInstance + + + :returns: The fetched FlexFlowInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + chat_service_sid: Union[str, object] = values.unset, + channel_type: Union["FlexFlowInstance.ChannelType", object] = values.unset, + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> "FlexFlowInstance": + """ + Update the FlexFlowInstance + + :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. + :param chat_service_sid: The SID of the chat service. + :param channel_type: + :param contact_identity: The channel contact's Identity. + :param enabled: Whether the new Flex Flow is enabled. + :param integration_type: + :param integration_flow_sid: The SID of the Studio Flow. Required when `integrationType` is `studio`. + :param integration_url: The URL of the external webhook. Required when `integrationType` is `external`. + :param integration_workspace_sid: The Workspace SID for a new Task. Required when `integrationType` is `task`. + :param integration_workflow_sid: The Workflow SID for a new Task. Required when `integrationType` is `task`. + :param integration_channel: The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. + :param integration_timeout: The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_priority: The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_creation_on_message: In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. + :param long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. + + :returns: The updated FlexFlowInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + chat_service_sid=chat_service_sid, + channel_type=channel_type, + contact_identity=contact_identity, + enabled=enabled, + integration_type=integration_type, + integration_flow_sid=integration_flow_sid, + integration_url=integration_url, + integration_workspace_sid=integration_workspace_sid, + integration_workflow_sid=integration_workflow_sid, + integration_channel=integration_channel, + integration_timeout=integration_timeout, + integration_priority=integration_priority, + integration_creation_on_message=integration_creation_on_message, + long_lived=long_lived, + janitor_enabled=janitor_enabled, + integration_retry_count=integration_retry_count, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + chat_service_sid: Union[str, object] = values.unset, + channel_type: Union["FlexFlowInstance.ChannelType", object] = values.unset, + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> "FlexFlowInstance": + """ + Asynchronous coroutine to update the FlexFlowInstance + + :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. + :param chat_service_sid: The SID of the chat service. + :param channel_type: + :param contact_identity: The channel contact's Identity. + :param enabled: Whether the new Flex Flow is enabled. + :param integration_type: + :param integration_flow_sid: The SID of the Studio Flow. Required when `integrationType` is `studio`. + :param integration_url: The URL of the external webhook. Required when `integrationType` is `external`. + :param integration_workspace_sid: The Workspace SID for a new Task. Required when `integrationType` is `task`. + :param integration_workflow_sid: The Workflow SID for a new Task. Required when `integrationType` is `task`. + :param integration_channel: The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. + :param integration_timeout: The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_priority: The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_creation_on_message: In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. + :param long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. + + :returns: The updated FlexFlowInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + chat_service_sid=chat_service_sid, + channel_type=channel_type, + contact_identity=contact_identity, + enabled=enabled, + integration_type=integration_type, + integration_flow_sid=integration_flow_sid, + integration_url=integration_url, + integration_workspace_sid=integration_workspace_sid, + integration_workflow_sid=integration_workflow_sid, + integration_channel=integration_channel, + integration_timeout=integration_timeout, + integration_priority=integration_priority, + integration_creation_on_message=integration_creation_on_message, + long_lived=long_lived, + janitor_enabled=janitor_enabled, + integration_retry_count=integration_retry_count, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FlexFlowContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the FlexFlowContext + + :param version: Version that contains the resource + :param sid: The SID of the Flex Flow resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/FlexFlows/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the FlexFlowInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FlexFlowInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> FlexFlowInstance: + """ + Fetch the FlexFlowInstance + + + :returns: The fetched FlexFlowInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FlexFlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> FlexFlowInstance: + """ + Asynchronous coroutine to fetch the FlexFlowInstance + + + :returns: The fetched FlexFlowInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FlexFlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + chat_service_sid: Union[str, object] = values.unset, + channel_type: Union["FlexFlowInstance.ChannelType", object] = values.unset, + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> FlexFlowInstance: + """ + Update the FlexFlowInstance + + :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. + :param chat_service_sid: The SID of the chat service. + :param channel_type: + :param contact_identity: The channel contact's Identity. + :param enabled: Whether the new Flex Flow is enabled. + :param integration_type: + :param integration_flow_sid: The SID of the Studio Flow. Required when `integrationType` is `studio`. + :param integration_url: The URL of the external webhook. Required when `integrationType` is `external`. + :param integration_workspace_sid: The Workspace SID for a new Task. Required when `integrationType` is `task`. + :param integration_workflow_sid: The Workflow SID for a new Task. Required when `integrationType` is `task`. + :param integration_channel: The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. + :param integration_timeout: The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_priority: The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_creation_on_message: In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. + :param long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. + + :returns: The updated FlexFlowInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ChatServiceSid": chat_service_sid, + "ChannelType": channel_type, + "ContactIdentity": contact_identity, + "Enabled": serialize.boolean_to_string(enabled), + "IntegrationType": integration_type, + "Integration.FlowSid": integration_flow_sid, + "Integration.Url": integration_url, + "Integration.WorkspaceSid": integration_workspace_sid, + "Integration.WorkflowSid": integration_workflow_sid, + "Integration.Channel": integration_channel, + "Integration.Timeout": integration_timeout, + "Integration.Priority": integration_priority, + "Integration.CreationOnMessage": serialize.boolean_to_string( + integration_creation_on_message + ), + "LongLived": serialize.boolean_to_string(long_lived), + "JanitorEnabled": serialize.boolean_to_string(janitor_enabled), + "Integration.RetryCount": integration_retry_count, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlexFlowInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + chat_service_sid: Union[str, object] = values.unset, + channel_type: Union["FlexFlowInstance.ChannelType", object] = values.unset, + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> FlexFlowInstance: + """ + Asynchronous coroutine to update the FlexFlowInstance + + :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. + :param chat_service_sid: The SID of the chat service. + :param channel_type: + :param contact_identity: The channel contact's Identity. + :param enabled: Whether the new Flex Flow is enabled. + :param integration_type: + :param integration_flow_sid: The SID of the Studio Flow. Required when `integrationType` is `studio`. + :param integration_url: The URL of the external webhook. Required when `integrationType` is `external`. + :param integration_workspace_sid: The Workspace SID for a new Task. Required when `integrationType` is `task`. + :param integration_workflow_sid: The Workflow SID for a new Task. Required when `integrationType` is `task`. + :param integration_channel: The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. + :param integration_timeout: The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_priority: The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_creation_on_message: In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. + :param long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. + + :returns: The updated FlexFlowInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ChatServiceSid": chat_service_sid, + "ChannelType": channel_type, + "ContactIdentity": contact_identity, + "Enabled": serialize.boolean_to_string(enabled), + "IntegrationType": integration_type, + "Integration.FlowSid": integration_flow_sid, + "Integration.Url": integration_url, + "Integration.WorkspaceSid": integration_workspace_sid, + "Integration.WorkflowSid": integration_workflow_sid, + "Integration.Channel": integration_channel, + "Integration.Timeout": integration_timeout, + "Integration.Priority": integration_priority, + "Integration.CreationOnMessage": serialize.boolean_to_string( + integration_creation_on_message + ), + "LongLived": serialize.boolean_to_string(long_lived), + "JanitorEnabled": serialize.boolean_to_string(janitor_enabled), + "Integration.RetryCount": integration_retry_count, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlexFlowInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FlexFlowPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> FlexFlowInstance: + """ + Build an instance of FlexFlowInstance + + :param payload: Payload response from the API + """ + return FlexFlowInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class FlexFlowList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the FlexFlowList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/FlexFlows" + + def create( + self, + friendly_name: str, + chat_service_sid: str, + channel_type: "FlexFlowInstance.ChannelType", + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> FlexFlowInstance: + """ + Create the FlexFlowInstance + + :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. + :param chat_service_sid: The SID of the chat service. + :param channel_type: + :param contact_identity: The channel contact's Identity. + :param enabled: Whether the new Flex Flow is enabled. + :param integration_type: + :param integration_flow_sid: The SID of the Studio Flow. Required when `integrationType` is `studio`. + :param integration_url: The URL of the external webhook. Required when `integrationType` is `external`. + :param integration_workspace_sid: The Workspace SID for a new Task. Required when `integrationType` is `task`. + :param integration_workflow_sid: The Workflow SID for a new Task. Required when `integrationType` is `task`. + :param integration_channel: The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. + :param integration_timeout: The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_priority: The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_creation_on_message: In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. + :param long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. + + :returns: The created FlexFlowInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ChatServiceSid": chat_service_sid, + "ChannelType": channel_type, + "ContactIdentity": contact_identity, + "Enabled": serialize.boolean_to_string(enabled), + "IntegrationType": integration_type, + "Integration.FlowSid": integration_flow_sid, + "Integration.Url": integration_url, + "Integration.WorkspaceSid": integration_workspace_sid, + "Integration.WorkflowSid": integration_workflow_sid, + "Integration.Channel": integration_channel, + "Integration.Timeout": integration_timeout, + "Integration.Priority": integration_priority, + "Integration.CreationOnMessage": serialize.boolean_to_string( + integration_creation_on_message + ), + "LongLived": serialize.boolean_to_string(long_lived), + "JanitorEnabled": serialize.boolean_to_string(janitor_enabled), + "Integration.RetryCount": integration_retry_count, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlexFlowInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + chat_service_sid: str, + channel_type: "FlexFlowInstance.ChannelType", + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> FlexFlowInstance: + """ + Asynchronously create the FlexFlowInstance + + :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. + :param chat_service_sid: The SID of the chat service. + :param channel_type: + :param contact_identity: The channel contact's Identity. + :param enabled: Whether the new Flex Flow is enabled. + :param integration_type: + :param integration_flow_sid: The SID of the Studio Flow. Required when `integrationType` is `studio`. + :param integration_url: The URL of the external webhook. Required when `integrationType` is `external`. + :param integration_workspace_sid: The Workspace SID for a new Task. Required when `integrationType` is `task`. + :param integration_workflow_sid: The Workflow SID for a new Task. Required when `integrationType` is `task`. + :param integration_channel: The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. + :param integration_timeout: The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_priority: The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_creation_on_message: In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. + :param long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. + + :returns: The created FlexFlowInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ChatServiceSid": chat_service_sid, + "ChannelType": channel_type, + "ContactIdentity": contact_identity, + "Enabled": serialize.boolean_to_string(enabled), + "IntegrationType": integration_type, + "Integration.FlowSid": integration_flow_sid, + "Integration.Url": integration_url, + "Integration.WorkspaceSid": integration_workspace_sid, + "Integration.WorkflowSid": integration_workflow_sid, + "Integration.Channel": integration_channel, + "Integration.Timeout": integration_timeout, + "Integration.Priority": integration_priority, + "Integration.CreationOnMessage": serialize.boolean_to_string( + integration_creation_on_message + ), + "LongLived": serialize.boolean_to_string(long_lived), + "JanitorEnabled": serialize.boolean_to_string(janitor_enabled), + "Integration.RetryCount": integration_retry_count, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlexFlowInstance(self._version, payload) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FlexFlowInstance]: + """ + Streams FlexFlowInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the Flex Flow resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(friendly_name=friendly_name, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FlexFlowInstance]: + """ + Asynchronously streams FlexFlowInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the Flex Flow resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FlexFlowInstance]: + """ + Lists FlexFlowInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the Flex Flow resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FlexFlowInstance]: + """ + Asynchronously lists FlexFlowInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the Flex Flow resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FlexFlowPage: + """ + Retrieve a single page of FlexFlowInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the Flex Flow resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FlexFlowInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FlexFlowPage(self._version, response) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FlexFlowPage: + """ + Asynchronously retrieve a single page of FlexFlowInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the Flex Flow resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FlexFlowInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FlexFlowPage(self._version, response) + + def get_page(self, target_url: str) -> FlexFlowPage: + """ + Retrieve a specific page of FlexFlowInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FlexFlowInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return FlexFlowPage(self._version, response) + + async def get_page_async(self, target_url: str) -> FlexFlowPage: + """ + Asynchronously retrieve a specific page of FlexFlowInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FlexFlowInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return FlexFlowPage(self._version, response) + + def get(self, sid: str) -> FlexFlowContext: + """ + Constructs a FlexFlowContext + + :param sid: The SID of the Flex Flow resource to update. + """ + return FlexFlowContext(self._version, sid=sid) + + def __call__(self, sid: str) -> FlexFlowContext: + """ + Constructs a FlexFlowContext + + :param sid: The SID of the Flex Flow resource to update. + """ + return FlexFlowContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_assessments_comment.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_assessments_comment.py new file mode 100644 index 00000000..2b6c7934 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_assessments_comment.py @@ -0,0 +1,469 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InsightsAssessmentsCommentInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Insights resource and owns this resource. + :ivar assessment_sid: The SID of the assessment. + :ivar comment: The comment added for assessment. + :ivar offset: The offset + :ivar report: The flag indicating if this assessment is part of report + :ivar weight: The weightage given to this comment + :ivar agent_id: The id of the agent. + :ivar segment_id: The id of the segment. + :ivar user_name: The name of the user. + :ivar user_email: The email id of the user. + :ivar timestamp: The timestamp when the record is inserted + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.assessment_sid: Optional[str] = payload.get("assessment_sid") + self.comment: Optional[Dict[str, object]] = payload.get("comment") + self.offset: Optional[float] = deserialize.decimal(payload.get("offset")) + self.report: Optional[bool] = payload.get("report") + self.weight: Optional[float] = deserialize.decimal(payload.get("weight")) + self.agent_id: Optional[str] = payload.get("agent_id") + self.segment_id: Optional[str] = payload.get("segment_id") + self.user_name: Optional[str] = payload.get("user_name") + self.user_email: Optional[str] = payload.get("user_email") + self.timestamp: Optional[float] = deserialize.decimal(payload.get("timestamp")) + self.url: Optional[str] = payload.get("url") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class InsightsAssessmentsCommentPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> InsightsAssessmentsCommentInstance: + """ + Build an instance of InsightsAssessmentsCommentInstance + + :param payload: Payload response from the API + """ + return InsightsAssessmentsCommentInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class InsightsAssessmentsCommentList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InsightsAssessmentsCommentList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Insights/QualityManagement/Assessments/Comments" + + def create( + self, + category_id: str, + category_name: str, + comment: str, + segment_id: str, + agent_id: str, + offset: float, + authorization: Union[str, object] = values.unset, + ) -> InsightsAssessmentsCommentInstance: + """ + Create the InsightsAssessmentsCommentInstance + + :param category_id: The ID of the category + :param category_name: The name of the category + :param comment: The Assessment comment. + :param segment_id: The id of the segment. + :param agent_id: The id of the agent. + :param offset: The offset + :param authorization: The Authorization HTTP request header + + :returns: The created InsightsAssessmentsCommentInstance + """ + + data = values.of( + { + "CategoryId": category_id, + "CategoryName": category_name, + "Comment": comment, + "SegmentId": segment_id, + "AgentId": agent_id, + "Offset": offset, + } + ) + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsAssessmentsCommentInstance(self._version, payload) + + async def create_async( + self, + category_id: str, + category_name: str, + comment: str, + segment_id: str, + agent_id: str, + offset: float, + authorization: Union[str, object] = values.unset, + ) -> InsightsAssessmentsCommentInstance: + """ + Asynchronously create the InsightsAssessmentsCommentInstance + + :param category_id: The ID of the category + :param category_name: The name of the category + :param comment: The Assessment comment. + :param segment_id: The id of the segment. + :param agent_id: The id of the agent. + :param offset: The offset + :param authorization: The Authorization HTTP request header + + :returns: The created InsightsAssessmentsCommentInstance + """ + + data = values.of( + { + "CategoryId": category_id, + "CategoryName": category_name, + "Comment": comment, + "SegmentId": segment_id, + "AgentId": agent_id, + "Offset": offset, + } + ) + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsAssessmentsCommentInstance(self._version, payload) + + def stream( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + agent_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InsightsAssessmentsCommentInstance]: + """ + Streams InsightsAssessmentsCommentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param str agent_id: The id of the agent. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + authorization=authorization, + segment_id=segment_id, + agent_id=agent_id, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + agent_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InsightsAssessmentsCommentInstance]: + """ + Asynchronously streams InsightsAssessmentsCommentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param str agent_id: The id of the agent. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + authorization=authorization, + segment_id=segment_id, + agent_id=agent_id, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + agent_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InsightsAssessmentsCommentInstance]: + """ + Lists InsightsAssessmentsCommentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param str agent_id: The id of the agent. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + authorization=authorization, + segment_id=segment_id, + agent_id=agent_id, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + agent_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InsightsAssessmentsCommentInstance]: + """ + Asynchronously lists InsightsAssessmentsCommentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param str agent_id: The id of the agent. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + authorization=authorization, + segment_id=segment_id, + agent_id=agent_id, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + agent_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InsightsAssessmentsCommentPage: + """ + Retrieve a single page of InsightsAssessmentsCommentInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param segment_id: The id of the segment. + :param agent_id: The id of the agent. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InsightsAssessmentsCommentInstance + """ + data = values.of( + { + "Authorization": authorization, + "SegmentId": segment_id, + "AgentId": agent_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InsightsAssessmentsCommentPage(self._version, response) + + async def page_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + agent_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InsightsAssessmentsCommentPage: + """ + Asynchronously retrieve a single page of InsightsAssessmentsCommentInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param segment_id: The id of the segment. + :param agent_id: The id of the agent. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InsightsAssessmentsCommentInstance + """ + data = values.of( + { + "Authorization": authorization, + "SegmentId": segment_id, + "AgentId": agent_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InsightsAssessmentsCommentPage(self._version, response) + + def get_page(self, target_url: str) -> InsightsAssessmentsCommentPage: + """ + Retrieve a specific page of InsightsAssessmentsCommentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InsightsAssessmentsCommentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InsightsAssessmentsCommentPage(self._version, response) + + async def get_page_async(self, target_url: str) -> InsightsAssessmentsCommentPage: + """ + Asynchronously retrieve a specific page of InsightsAssessmentsCommentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InsightsAssessmentsCommentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InsightsAssessmentsCommentPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_conversations.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_conversations.py new file mode 100644 index 00000000..efdcea20 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_conversations.py @@ -0,0 +1,333 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InsightsConversationsInstance(InstanceResource): + """ + :ivar account_id: The id of the account. + :ivar conversation_id: The unique id of the conversation + :ivar segment_count: The count of segments for a conversation + :ivar segments: The Segments of a conversation + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_id: Optional[str] = payload.get("account_id") + self.conversation_id: Optional[str] = payload.get("conversation_id") + self.segment_count: Optional[int] = deserialize.integer( + payload.get("segment_count") + ) + self.segments: Optional[List[Dict[str, object]]] = payload.get("segments") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class InsightsConversationsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InsightsConversationsInstance: + """ + Build an instance of InsightsConversationsInstance + + :param payload: Payload response from the API + """ + return InsightsConversationsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class InsightsConversationsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InsightsConversationsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Insights/Conversations" + + def stream( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InsightsConversationsInstance]: + """ + Streams InsightsConversationsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: Unique Id of the segment for which conversation details needs to be fetched + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + authorization=authorization, + segment_id=segment_id, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InsightsConversationsInstance]: + """ + Asynchronously streams InsightsConversationsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: Unique Id of the segment for which conversation details needs to be fetched + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + authorization=authorization, + segment_id=segment_id, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InsightsConversationsInstance]: + """ + Lists InsightsConversationsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: Unique Id of the segment for which conversation details needs to be fetched + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + authorization=authorization, + segment_id=segment_id, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InsightsConversationsInstance]: + """ + Asynchronously lists InsightsConversationsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: Unique Id of the segment for which conversation details needs to be fetched + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + authorization=authorization, + segment_id=segment_id, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InsightsConversationsPage: + """ + Retrieve a single page of InsightsConversationsInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param segment_id: Unique Id of the segment for which conversation details needs to be fetched + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InsightsConversationsInstance + """ + data = values.of( + { + "Authorization": authorization, + "SegmentId": segment_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InsightsConversationsPage(self._version, response) + + async def page_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InsightsConversationsPage: + """ + Asynchronously retrieve a single page of InsightsConversationsInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param segment_id: Unique Id of the segment for which conversation details needs to be fetched + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InsightsConversationsInstance + """ + data = values.of( + { + "Authorization": authorization, + "SegmentId": segment_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InsightsConversationsPage(self._version, response) + + def get_page(self, target_url: str) -> InsightsConversationsPage: + """ + Retrieve a specific page of InsightsConversationsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InsightsConversationsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InsightsConversationsPage(self._version, response) + + async def get_page_async(self, target_url: str) -> InsightsConversationsPage: + """ + Asynchronously retrieve a specific page of InsightsConversationsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InsightsConversationsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InsightsConversationsPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_questionnaires.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_questionnaires.py new file mode 100644 index 00000000..d21aff82 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_questionnaires.py @@ -0,0 +1,813 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InsightsQuestionnairesInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Insights resource and owns this resource. + :ivar questionnaire_sid: The sid of this questionnaire + :ivar name: The name of this category. + :ivar description: The description of this questionnaire + :ivar active: The flag to enable or disable questionnaire + :ivar questions: The list of questions with category for a questionnaire + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + questionnaire_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.questionnaire_sid: Optional[str] = payload.get("questionnaire_sid") + self.name: Optional[str] = payload.get("name") + self.description: Optional[str] = payload.get("description") + self.active: Optional[bool] = payload.get("active") + self.questions: Optional[List[Dict[str, object]]] = payload.get("questions") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "questionnaire_sid": questionnaire_sid or self.questionnaire_sid, + } + self._context: Optional[InsightsQuestionnairesContext] = None + + @property + def _proxy(self) -> "InsightsQuestionnairesContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InsightsQuestionnairesContext for this InsightsQuestionnairesInstance + """ + if self._context is None: + self._context = InsightsQuestionnairesContext( + self._version, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + return self._context + + def delete(self, authorization: Union[str, object] = values.unset) -> bool: + """ + Deletes the InsightsQuestionnairesInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + authorization=authorization, + ) + + async def delete_async( + self, authorization: Union[str, object] = values.unset + ) -> bool: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + authorization=authorization, + ) + + def fetch( + self, authorization: Union[str, object] = values.unset + ) -> "InsightsQuestionnairesInstance": + """ + Fetch the InsightsQuestionnairesInstance + + :param authorization: The Authorization HTTP request header + + :returns: The fetched InsightsQuestionnairesInstance + """ + return self._proxy.fetch( + authorization=authorization, + ) + + async def fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> "InsightsQuestionnairesInstance": + """ + Asynchronous coroutine to fetch the InsightsQuestionnairesInstance + + :param authorization: The Authorization HTTP request header + + :returns: The fetched InsightsQuestionnairesInstance + """ + return await self._proxy.fetch_async( + authorization=authorization, + ) + + def update( + self, + active: bool, + authorization: Union[str, object] = values.unset, + name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> "InsightsQuestionnairesInstance": + """ + Update the InsightsQuestionnairesInstance + + :param active: The flag to enable or disable questionnaire + :param authorization: The Authorization HTTP request header + :param name: The name of this questionnaire + :param description: The description of this questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: The updated InsightsQuestionnairesInstance + """ + return self._proxy.update( + active=active, + authorization=authorization, + name=name, + description=description, + question_sids=question_sids, + ) + + async def update_async( + self, + active: bool, + authorization: Union[str, object] = values.unset, + name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> "InsightsQuestionnairesInstance": + """ + Asynchronous coroutine to update the InsightsQuestionnairesInstance + + :param active: The flag to enable or disable questionnaire + :param authorization: The Authorization HTTP request header + :param name: The name of this questionnaire + :param description: The description of this questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: The updated InsightsQuestionnairesInstance + """ + return await self._proxy.update_async( + active=active, + authorization=authorization, + name=name, + description=description, + question_sids=question_sids, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InsightsQuestionnairesContext(InstanceContext): + + def __init__(self, version: Version, questionnaire_sid: str): + """ + Initialize the InsightsQuestionnairesContext + + :param version: Version that contains the resource + :param questionnaire_sid: The SID of the questionnaire + """ + super().__init__(version) + + # Path Solution + self._solution = { + "questionnaire_sid": questionnaire_sid, + } + self._uri = ( + "/Insights/QualityManagement/Questionnaires/{questionnaire_sid}".format( + **self._solution + ) + ) + + def delete(self, authorization: Union[str, object] = values.unset) -> bool: + """ + Deletes the InsightsQuestionnairesInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, authorization: Union[str, object] = values.unset + ) -> bool: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch( + self, authorization: Union[str, object] = values.unset + ) -> InsightsQuestionnairesInstance: + """ + Fetch the InsightsQuestionnairesInstance + + :param authorization: The Authorization HTTP request header + + :returns: The fetched InsightsQuestionnairesInstance + """ + + data = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + + async def fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> InsightsQuestionnairesInstance: + """ + Asynchronous coroutine to fetch the InsightsQuestionnairesInstance + + :param authorization: The Authorization HTTP request header + + :returns: The fetched InsightsQuestionnairesInstance + """ + + data = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + + def update( + self, + active: bool, + authorization: Union[str, object] = values.unset, + name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> InsightsQuestionnairesInstance: + """ + Update the InsightsQuestionnairesInstance + + :param active: The flag to enable or disable questionnaire + :param authorization: The Authorization HTTP request header + :param name: The name of this questionnaire + :param description: The description of this questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: The updated InsightsQuestionnairesInstance + """ + + data = values.of( + { + "Active": serialize.boolean_to_string(active), + "Name": name, + "Description": description, + "QuestionSids": serialize.map(question_sids, lambda e: e), + } + ) + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + + async def update_async( + self, + active: bool, + authorization: Union[str, object] = values.unset, + name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> InsightsQuestionnairesInstance: + """ + Asynchronous coroutine to update the InsightsQuestionnairesInstance + + :param active: The flag to enable or disable questionnaire + :param authorization: The Authorization HTTP request header + :param name: The name of this questionnaire + :param description: The description of this questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: The updated InsightsQuestionnairesInstance + """ + + data = values.of( + { + "Active": serialize.boolean_to_string(active), + "Name": name, + "Description": description, + "QuestionSids": serialize.map(question_sids, lambda e: e), + } + ) + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InsightsQuestionnairesPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InsightsQuestionnairesInstance: + """ + Build an instance of InsightsQuestionnairesInstance + + :param payload: Payload response from the API + """ + return InsightsQuestionnairesInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class InsightsQuestionnairesList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InsightsQuestionnairesList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Insights/QualityManagement/Questionnaires" + + def create( + self, + name: str, + authorization: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + active: Union[bool, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> InsightsQuestionnairesInstance: + """ + Create the InsightsQuestionnairesInstance + + :param name: The name of this questionnaire + :param authorization: The Authorization HTTP request header + :param description: The description of this questionnaire + :param active: The flag to enable or disable questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: The created InsightsQuestionnairesInstance + """ + + data = values.of( + { + "Name": name, + "Description": description, + "Active": serialize.boolean_to_string(active), + "QuestionSids": serialize.map(question_sids, lambda e: e), + } + ) + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsQuestionnairesInstance(self._version, payload) + + async def create_async( + self, + name: str, + authorization: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + active: Union[bool, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> InsightsQuestionnairesInstance: + """ + Asynchronously create the InsightsQuestionnairesInstance + + :param name: The name of this questionnaire + :param authorization: The Authorization HTTP request header + :param description: The description of this questionnaire + :param active: The flag to enable or disable questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: The created InsightsQuestionnairesInstance + """ + + data = values.of( + { + "Name": name, + "Description": description, + "Active": serialize.boolean_to_string(active), + "QuestionSids": serialize.map(question_sids, lambda e: e), + } + ) + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsQuestionnairesInstance(self._version, payload) + + def stream( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InsightsQuestionnairesInstance]: + """ + Streams InsightsQuestionnairesInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param bool include_inactive: Flag indicating whether to include inactive questionnaires or not + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + authorization=authorization, + include_inactive=include_inactive, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InsightsQuestionnairesInstance]: + """ + Asynchronously streams InsightsQuestionnairesInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param bool include_inactive: Flag indicating whether to include inactive questionnaires or not + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + authorization=authorization, + include_inactive=include_inactive, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InsightsQuestionnairesInstance]: + """ + Lists InsightsQuestionnairesInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param bool include_inactive: Flag indicating whether to include inactive questionnaires or not + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + authorization=authorization, + include_inactive=include_inactive, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InsightsQuestionnairesInstance]: + """ + Asynchronously lists InsightsQuestionnairesInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param bool include_inactive: Flag indicating whether to include inactive questionnaires or not + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + authorization=authorization, + include_inactive=include_inactive, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InsightsQuestionnairesPage: + """ + Retrieve a single page of InsightsQuestionnairesInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param include_inactive: Flag indicating whether to include inactive questionnaires or not + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InsightsQuestionnairesInstance + """ + data = values.of( + { + "Authorization": authorization, + "IncludeInactive": serialize.boolean_to_string(include_inactive), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InsightsQuestionnairesPage(self._version, response) + + async def page_async( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InsightsQuestionnairesPage: + """ + Asynchronously retrieve a single page of InsightsQuestionnairesInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param include_inactive: Flag indicating whether to include inactive questionnaires or not + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InsightsQuestionnairesInstance + """ + data = values.of( + { + "Authorization": authorization, + "IncludeInactive": serialize.boolean_to_string(include_inactive), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InsightsQuestionnairesPage(self._version, response) + + def get_page(self, target_url: str) -> InsightsQuestionnairesPage: + """ + Retrieve a specific page of InsightsQuestionnairesInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InsightsQuestionnairesInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InsightsQuestionnairesPage(self._version, response) + + async def get_page_async(self, target_url: str) -> InsightsQuestionnairesPage: + """ + Asynchronously retrieve a specific page of InsightsQuestionnairesInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InsightsQuestionnairesInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InsightsQuestionnairesPage(self._version, response) + + def get(self, questionnaire_sid: str) -> InsightsQuestionnairesContext: + """ + Constructs a InsightsQuestionnairesContext + + :param questionnaire_sid: The SID of the questionnaire + """ + return InsightsQuestionnairesContext( + self._version, questionnaire_sid=questionnaire_sid + ) + + def __call__(self, questionnaire_sid: str) -> InsightsQuestionnairesContext: + """ + Constructs a InsightsQuestionnairesContext + + :param questionnaire_sid: The SID of the questionnaire + """ + return InsightsQuestionnairesContext( + self._version, questionnaire_sid=questionnaire_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_questionnaires_category.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_questionnaires_category.py new file mode 100644 index 00000000..817a4753 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_questionnaires_category.py @@ -0,0 +1,631 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InsightsQuestionnairesCategoryInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Insights resource and owns this resource. + :ivar category_sid: The SID of the category + :ivar name: The name of this category. + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + category_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.category_sid: Optional[str] = payload.get("category_sid") + self.name: Optional[str] = payload.get("name") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "category_sid": category_sid or self.category_sid, + } + self._context: Optional[InsightsQuestionnairesCategoryContext] = None + + @property + def _proxy(self) -> "InsightsQuestionnairesCategoryContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InsightsQuestionnairesCategoryContext for this InsightsQuestionnairesCategoryInstance + """ + if self._context is None: + self._context = InsightsQuestionnairesCategoryContext( + self._version, + category_sid=self._solution["category_sid"], + ) + return self._context + + def delete(self, authorization: Union[str, object] = values.unset) -> bool: + """ + Deletes the InsightsQuestionnairesCategoryInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + authorization=authorization, + ) + + async def delete_async( + self, authorization: Union[str, object] = values.unset + ) -> bool: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesCategoryInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + authorization=authorization, + ) + + def update( + self, name: str, authorization: Union[str, object] = values.unset + ) -> "InsightsQuestionnairesCategoryInstance": + """ + Update the InsightsQuestionnairesCategoryInstance + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: The updated InsightsQuestionnairesCategoryInstance + """ + return self._proxy.update( + name=name, + authorization=authorization, + ) + + async def update_async( + self, name: str, authorization: Union[str, object] = values.unset + ) -> "InsightsQuestionnairesCategoryInstance": + """ + Asynchronous coroutine to update the InsightsQuestionnairesCategoryInstance + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: The updated InsightsQuestionnairesCategoryInstance + """ + return await self._proxy.update_async( + name=name, + authorization=authorization, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class InsightsQuestionnairesCategoryContext(InstanceContext): + + def __init__(self, version: Version, category_sid: str): + """ + Initialize the InsightsQuestionnairesCategoryContext + + :param version: Version that contains the resource + :param category_sid: The SID of the category to be updated + """ + super().__init__(version) + + # Path Solution + self._solution = { + "category_sid": category_sid, + } + self._uri = "/Insights/QualityManagement/Categories/{category_sid}".format( + **self._solution + ) + + def delete(self, authorization: Union[str, object] = values.unset) -> bool: + """ + Deletes the InsightsQuestionnairesCategoryInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, authorization: Union[str, object] = values.unset + ) -> bool: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesCategoryInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def update( + self, name: str, authorization: Union[str, object] = values.unset + ) -> InsightsQuestionnairesCategoryInstance: + """ + Update the InsightsQuestionnairesCategoryInstance + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: The updated InsightsQuestionnairesCategoryInstance + """ + + data = values.of( + { + "Name": name, + } + ) + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsQuestionnairesCategoryInstance( + self._version, payload, category_sid=self._solution["category_sid"] + ) + + async def update_async( + self, name: str, authorization: Union[str, object] = values.unset + ) -> InsightsQuestionnairesCategoryInstance: + """ + Asynchronous coroutine to update the InsightsQuestionnairesCategoryInstance + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: The updated InsightsQuestionnairesCategoryInstance + """ + + data = values.of( + { + "Name": name, + } + ) + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsQuestionnairesCategoryInstance( + self._version, payload, category_sid=self._solution["category_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class InsightsQuestionnairesCategoryPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> InsightsQuestionnairesCategoryInstance: + """ + Build an instance of InsightsQuestionnairesCategoryInstance + + :param payload: Payload response from the API + """ + return InsightsQuestionnairesCategoryInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class InsightsQuestionnairesCategoryList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InsightsQuestionnairesCategoryList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Insights/QualityManagement/Categories" + + def create( + self, name: str, authorization: Union[str, object] = values.unset + ) -> InsightsQuestionnairesCategoryInstance: + """ + Create the InsightsQuestionnairesCategoryInstance + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: The created InsightsQuestionnairesCategoryInstance + """ + + data = values.of( + { + "Name": name, + } + ) + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsQuestionnairesCategoryInstance(self._version, payload) + + async def create_async( + self, name: str, authorization: Union[str, object] = values.unset + ) -> InsightsQuestionnairesCategoryInstance: + """ + Asynchronously create the InsightsQuestionnairesCategoryInstance + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: The created InsightsQuestionnairesCategoryInstance + """ + + data = values.of( + { + "Name": name, + } + ) + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsQuestionnairesCategoryInstance(self._version, payload) + + def stream( + self, + authorization: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InsightsQuestionnairesCategoryInstance]: + """ + Streams InsightsQuestionnairesCategoryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(authorization=authorization, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + authorization: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InsightsQuestionnairesCategoryInstance]: + """ + Asynchronously streams InsightsQuestionnairesCategoryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + authorization=authorization, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + authorization: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InsightsQuestionnairesCategoryInstance]: + """ + Lists InsightsQuestionnairesCategoryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + authorization=authorization, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + authorization: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InsightsQuestionnairesCategoryInstance]: + """ + Asynchronously lists InsightsQuestionnairesCategoryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + authorization=authorization, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + authorization: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InsightsQuestionnairesCategoryPage: + """ + Retrieve a single page of InsightsQuestionnairesCategoryInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InsightsQuestionnairesCategoryInstance + """ + data = values.of( + { + "Authorization": authorization, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InsightsQuestionnairesCategoryPage(self._version, response) + + async def page_async( + self, + authorization: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InsightsQuestionnairesCategoryPage: + """ + Asynchronously retrieve a single page of InsightsQuestionnairesCategoryInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InsightsQuestionnairesCategoryInstance + """ + data = values.of( + { + "Authorization": authorization, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InsightsQuestionnairesCategoryPage(self._version, response) + + def get_page(self, target_url: str) -> InsightsQuestionnairesCategoryPage: + """ + Retrieve a specific page of InsightsQuestionnairesCategoryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InsightsQuestionnairesCategoryInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InsightsQuestionnairesCategoryPage(self._version, response) + + async def get_page_async( + self, target_url: str + ) -> InsightsQuestionnairesCategoryPage: + """ + Asynchronously retrieve a specific page of InsightsQuestionnairesCategoryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InsightsQuestionnairesCategoryInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InsightsQuestionnairesCategoryPage(self._version, response) + + def get(self, category_sid: str) -> InsightsQuestionnairesCategoryContext: + """ + Constructs a InsightsQuestionnairesCategoryContext + + :param category_sid: The SID of the category to be updated + """ + return InsightsQuestionnairesCategoryContext( + self._version, category_sid=category_sid + ) + + def __call__(self, category_sid: str) -> InsightsQuestionnairesCategoryContext: + """ + Constructs a InsightsQuestionnairesCategoryContext + + :param category_sid: The SID of the category to be updated + """ + return InsightsQuestionnairesCategoryContext( + self._version, category_sid=category_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_questionnaires_question.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_questionnaires_question.py new file mode 100644 index 00000000..33e23045 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_questionnaires_question.py @@ -0,0 +1,749 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InsightsQuestionnairesQuestionInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Insights resource and owns this resource. + :ivar question_sid: The SID of the question + :ivar question: The question. + :ivar description: The description for the question. + :ivar category: The Category for the question. + :ivar answer_set_id: The answer_set for the question. + :ivar allow_na: The flag to enable for disable NA for answer. + :ivar usage: Integer value that tells a particular question is used by how many questionnaires + :ivar answer_set: Set of answers for the question + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + question_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.question_sid: Optional[str] = payload.get("question_sid") + self.question: Optional[str] = payload.get("question") + self.description: Optional[str] = payload.get("description") + self.category: Optional[Dict[str, object]] = payload.get("category") + self.answer_set_id: Optional[str] = payload.get("answer_set_id") + self.allow_na: Optional[bool] = payload.get("allow_na") + self.usage: Optional[int] = deserialize.integer(payload.get("usage")) + self.answer_set: Optional[Dict[str, object]] = payload.get("answer_set") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "question_sid": question_sid or self.question_sid, + } + self._context: Optional[InsightsQuestionnairesQuestionContext] = None + + @property + def _proxy(self) -> "InsightsQuestionnairesQuestionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InsightsQuestionnairesQuestionContext for this InsightsQuestionnairesQuestionInstance + """ + if self._context is None: + self._context = InsightsQuestionnairesQuestionContext( + self._version, + question_sid=self._solution["question_sid"], + ) + return self._context + + def delete(self, authorization: Union[str, object] = values.unset) -> bool: + """ + Deletes the InsightsQuestionnairesQuestionInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + authorization=authorization, + ) + + async def delete_async( + self, authorization: Union[str, object] = values.unset + ) -> bool: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesQuestionInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + authorization=authorization, + ) + + def update( + self, + allow_na: bool, + authorization: Union[str, object] = values.unset, + category_sid: Union[str, object] = values.unset, + question: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + answer_set_id: Union[str, object] = values.unset, + ) -> "InsightsQuestionnairesQuestionInstance": + """ + Update the InsightsQuestionnairesQuestionInstance + + :param allow_na: The flag to enable for disable NA for answer. + :param authorization: The Authorization HTTP request header + :param category_sid: The SID of the category + :param question: The question. + :param description: The description for the question. + :param answer_set_id: The answer_set for the question. + + :returns: The updated InsightsQuestionnairesQuestionInstance + """ + return self._proxy.update( + allow_na=allow_na, + authorization=authorization, + category_sid=category_sid, + question=question, + description=description, + answer_set_id=answer_set_id, + ) + + async def update_async( + self, + allow_na: bool, + authorization: Union[str, object] = values.unset, + category_sid: Union[str, object] = values.unset, + question: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + answer_set_id: Union[str, object] = values.unset, + ) -> "InsightsQuestionnairesQuestionInstance": + """ + Asynchronous coroutine to update the InsightsQuestionnairesQuestionInstance + + :param allow_na: The flag to enable for disable NA for answer. + :param authorization: The Authorization HTTP request header + :param category_sid: The SID of the category + :param question: The question. + :param description: The description for the question. + :param answer_set_id: The answer_set for the question. + + :returns: The updated InsightsQuestionnairesQuestionInstance + """ + return await self._proxy.update_async( + allow_na=allow_na, + authorization=authorization, + category_sid=category_sid, + question=question, + description=description, + answer_set_id=answer_set_id, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class InsightsQuestionnairesQuestionContext(InstanceContext): + + def __init__(self, version: Version, question_sid: str): + """ + Initialize the InsightsQuestionnairesQuestionContext + + :param version: Version that contains the resource + :param question_sid: The SID of the question + """ + super().__init__(version) + + # Path Solution + self._solution = { + "question_sid": question_sid, + } + self._uri = "/Insights/QualityManagement/Questions/{question_sid}".format( + **self._solution + ) + + def delete(self, authorization: Union[str, object] = values.unset) -> bool: + """ + Deletes the InsightsQuestionnairesQuestionInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, authorization: Union[str, object] = values.unset + ) -> bool: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesQuestionInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def update( + self, + allow_na: bool, + authorization: Union[str, object] = values.unset, + category_sid: Union[str, object] = values.unset, + question: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + answer_set_id: Union[str, object] = values.unset, + ) -> InsightsQuestionnairesQuestionInstance: + """ + Update the InsightsQuestionnairesQuestionInstance + + :param allow_na: The flag to enable for disable NA for answer. + :param authorization: The Authorization HTTP request header + :param category_sid: The SID of the category + :param question: The question. + :param description: The description for the question. + :param answer_set_id: The answer_set for the question. + + :returns: The updated InsightsQuestionnairesQuestionInstance + """ + + data = values.of( + { + "AllowNa": serialize.boolean_to_string(allow_na), + "CategorySid": category_sid, + "Question": question, + "Description": description, + "AnswerSetId": answer_set_id, + } + ) + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsQuestionnairesQuestionInstance( + self._version, payload, question_sid=self._solution["question_sid"] + ) + + async def update_async( + self, + allow_na: bool, + authorization: Union[str, object] = values.unset, + category_sid: Union[str, object] = values.unset, + question: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + answer_set_id: Union[str, object] = values.unset, + ) -> InsightsQuestionnairesQuestionInstance: + """ + Asynchronous coroutine to update the InsightsQuestionnairesQuestionInstance + + :param allow_na: The flag to enable for disable NA for answer. + :param authorization: The Authorization HTTP request header + :param category_sid: The SID of the category + :param question: The question. + :param description: The description for the question. + :param answer_set_id: The answer_set for the question. + + :returns: The updated InsightsQuestionnairesQuestionInstance + """ + + data = values.of( + { + "AllowNa": serialize.boolean_to_string(allow_na), + "CategorySid": category_sid, + "Question": question, + "Description": description, + "AnswerSetId": answer_set_id, + } + ) + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsQuestionnairesQuestionInstance( + self._version, payload, question_sid=self._solution["question_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class InsightsQuestionnairesQuestionPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> InsightsQuestionnairesQuestionInstance: + """ + Build an instance of InsightsQuestionnairesQuestionInstance + + :param payload: Payload response from the API + """ + return InsightsQuestionnairesQuestionInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class InsightsQuestionnairesQuestionList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InsightsQuestionnairesQuestionList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Insights/QualityManagement/Questions" + + def create( + self, + category_sid: str, + question: str, + answer_set_id: str, + allow_na: bool, + authorization: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> InsightsQuestionnairesQuestionInstance: + """ + Create the InsightsQuestionnairesQuestionInstance + + :param category_sid: The SID of the category + :param question: The question. + :param answer_set_id: The answer_set for the question. + :param allow_na: The flag to enable for disable NA for answer. + :param authorization: The Authorization HTTP request header + :param description: The description for the question. + + :returns: The created InsightsQuestionnairesQuestionInstance + """ + + data = values.of( + { + "CategorySid": category_sid, + "Question": question, + "AnswerSetId": answer_set_id, + "AllowNa": serialize.boolean_to_string(allow_na), + "Description": description, + } + ) + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsQuestionnairesQuestionInstance(self._version, payload) + + async def create_async( + self, + category_sid: str, + question: str, + answer_set_id: str, + allow_na: bool, + authorization: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> InsightsQuestionnairesQuestionInstance: + """ + Asynchronously create the InsightsQuestionnairesQuestionInstance + + :param category_sid: The SID of the category + :param question: The question. + :param answer_set_id: The answer_set for the question. + :param allow_na: The flag to enable for disable NA for answer. + :param authorization: The Authorization HTTP request header + :param description: The description for the question. + + :returns: The created InsightsQuestionnairesQuestionInstance + """ + + data = values.of( + { + "CategorySid": category_sid, + "Question": question, + "AnswerSetId": answer_set_id, + "AllowNa": serialize.boolean_to_string(allow_na), + "Description": description, + } + ) + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsQuestionnairesQuestionInstance(self._version, payload) + + def stream( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InsightsQuestionnairesQuestionInstance]: + """ + Streams InsightsQuestionnairesQuestionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param List[str] category_sid: The list of category SIDs + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + authorization=authorization, + category_sid=category_sid, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InsightsQuestionnairesQuestionInstance]: + """ + Asynchronously streams InsightsQuestionnairesQuestionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param List[str] category_sid: The list of category SIDs + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + authorization=authorization, + category_sid=category_sid, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InsightsQuestionnairesQuestionInstance]: + """ + Lists InsightsQuestionnairesQuestionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param List[str] category_sid: The list of category SIDs + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + authorization=authorization, + category_sid=category_sid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InsightsQuestionnairesQuestionInstance]: + """ + Asynchronously lists InsightsQuestionnairesQuestionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param List[str] category_sid: The list of category SIDs + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + authorization=authorization, + category_sid=category_sid, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InsightsQuestionnairesQuestionPage: + """ + Retrieve a single page of InsightsQuestionnairesQuestionInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param category_sid: The list of category SIDs + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InsightsQuestionnairesQuestionInstance + """ + data = values.of( + { + "Authorization": authorization, + "CategorySid": serialize.map(category_sid, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InsightsQuestionnairesQuestionPage(self._version, response) + + async def page_async( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InsightsQuestionnairesQuestionPage: + """ + Asynchronously retrieve a single page of InsightsQuestionnairesQuestionInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param category_sid: The list of category SIDs + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InsightsQuestionnairesQuestionInstance + """ + data = values.of( + { + "Authorization": authorization, + "CategorySid": serialize.map(category_sid, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InsightsQuestionnairesQuestionPage(self._version, response) + + def get_page(self, target_url: str) -> InsightsQuestionnairesQuestionPage: + """ + Retrieve a specific page of InsightsQuestionnairesQuestionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InsightsQuestionnairesQuestionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InsightsQuestionnairesQuestionPage(self._version, response) + + async def get_page_async( + self, target_url: str + ) -> InsightsQuestionnairesQuestionPage: + """ + Asynchronously retrieve a specific page of InsightsQuestionnairesQuestionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InsightsQuestionnairesQuestionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InsightsQuestionnairesQuestionPage(self._version, response) + + def get(self, question_sid: str) -> InsightsQuestionnairesQuestionContext: + """ + Constructs a InsightsQuestionnairesQuestionContext + + :param question_sid: The SID of the question + """ + return InsightsQuestionnairesQuestionContext( + self._version, question_sid=question_sid + ) + + def __call__(self, question_sid: str) -> InsightsQuestionnairesQuestionContext: + """ + Constructs a InsightsQuestionnairesQuestionContext + + :param question_sid: The SID of the question + """ + return InsightsQuestionnairesQuestionContext( + self._version, question_sid=question_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_segments.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_segments.py new file mode 100644 index 00000000..7c98e81c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_segments.py @@ -0,0 +1,395 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InsightsSegmentsInstance(InstanceResource): + """ + :ivar segment_id: To unique id of the segment + :ivar external_id: The unique id for the conversation. + :ivar queue: + :ivar external_contact: + :ivar external_segment_link_id: The uuid for the external_segment_link. + :ivar date: The date of the conversation. + :ivar account_id: The unique id for the account. + :ivar external_segment_link: The hyperlink to recording of the task event. + :ivar agent_id: The unique id for the agent. + :ivar agent_phone: The phone number of the agent. + :ivar agent_name: The name of the agent. + :ivar agent_team_name: The team name to which agent belongs. + :ivar agent_team_name_in_hierarchy: he team name to which agent belongs. + :ivar agent_link: The link to the agent conversation. + :ivar customer_phone: The phone number of the customer. + :ivar customer_name: The name of the customer. + :ivar customer_link: The link to the customer conversation. + :ivar segment_recording_offset: The offset value for the recording. + :ivar media: The media identifiers of the conversation. + :ivar assessment_type: The type of the assessment. + :ivar assessment_percentage: The percentage scored on the Assessments. + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.segment_id: Optional[str] = payload.get("segment_id") + self.external_id: Optional[str] = payload.get("external_id") + self.queue: Optional[str] = payload.get("queue") + self.external_contact: Optional[str] = payload.get("external_contact") + self.external_segment_link_id: Optional[str] = payload.get( + "external_segment_link_id" + ) + self.date: Optional[str] = payload.get("date") + self.account_id: Optional[str] = payload.get("account_id") + self.external_segment_link: Optional[str] = payload.get("external_segment_link") + self.agent_id: Optional[str] = payload.get("agent_id") + self.agent_phone: Optional[str] = payload.get("agent_phone") + self.agent_name: Optional[str] = payload.get("agent_name") + self.agent_team_name: Optional[str] = payload.get("agent_team_name") + self.agent_team_name_in_hierarchy: Optional[str] = payload.get( + "agent_team_name_in_hierarchy" + ) + self.agent_link: Optional[str] = payload.get("agent_link") + self.customer_phone: Optional[str] = payload.get("customer_phone") + self.customer_name: Optional[str] = payload.get("customer_name") + self.customer_link: Optional[str] = payload.get("customer_link") + self.segment_recording_offset: Optional[str] = payload.get( + "segment_recording_offset" + ) + self.media: Optional[Dict[str, object]] = payload.get("media") + self.assessment_type: Optional[Dict[str, object]] = payload.get( + "assessment_type" + ) + self.assessment_percentage: Optional[Dict[str, object]] = payload.get( + "assessment_percentage" + ) + self.url: Optional[str] = payload.get("url") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class InsightsSegmentsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InsightsSegmentsInstance: + """ + Build an instance of InsightsSegmentsInstance + + :param payload: Payload response from the API + """ + return InsightsSegmentsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class InsightsSegmentsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InsightsSegmentsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Insights/Segments" + + def stream( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + reservation_id: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InsightsSegmentsInstance]: + """ + Streams InsightsSegmentsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: To unique id of the segment + :param List[str] reservation_id: The list of reservation Ids + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + authorization=authorization, + segment_id=segment_id, + reservation_id=reservation_id, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + reservation_id: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InsightsSegmentsInstance]: + """ + Asynchronously streams InsightsSegmentsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: To unique id of the segment + :param List[str] reservation_id: The list of reservation Ids + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + authorization=authorization, + segment_id=segment_id, + reservation_id=reservation_id, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + reservation_id: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InsightsSegmentsInstance]: + """ + Lists InsightsSegmentsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: To unique id of the segment + :param List[str] reservation_id: The list of reservation Ids + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + authorization=authorization, + segment_id=segment_id, + reservation_id=reservation_id, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + reservation_id: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InsightsSegmentsInstance]: + """ + Asynchronously lists InsightsSegmentsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: To unique id of the segment + :param List[str] reservation_id: The list of reservation Ids + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + authorization=authorization, + segment_id=segment_id, + reservation_id=reservation_id, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + reservation_id: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InsightsSegmentsPage: + """ + Retrieve a single page of InsightsSegmentsInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param segment_id: To unique id of the segment + :param reservation_id: The list of reservation Ids + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InsightsSegmentsInstance + """ + data = values.of( + { + "Authorization": authorization, + "SegmentId": segment_id, + "ReservationId": serialize.map(reservation_id, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InsightsSegmentsPage(self._version, response) + + async def page_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + reservation_id: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InsightsSegmentsPage: + """ + Asynchronously retrieve a single page of InsightsSegmentsInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param segment_id: To unique id of the segment + :param reservation_id: The list of reservation Ids + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InsightsSegmentsInstance + """ + data = values.of( + { + "Authorization": authorization, + "SegmentId": segment_id, + "ReservationId": serialize.map(reservation_id, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InsightsSegmentsPage(self._version, response) + + def get_page(self, target_url: str) -> InsightsSegmentsPage: + """ + Retrieve a specific page of InsightsSegmentsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InsightsSegmentsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InsightsSegmentsPage(self._version, response) + + async def get_page_async(self, target_url: str) -> InsightsSegmentsPage: + """ + Asynchronously retrieve a specific page of InsightsSegmentsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InsightsSegmentsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InsightsSegmentsPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_session.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_session.py new file mode 100644 index 00000000..b4174aa9 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_session.py @@ -0,0 +1,190 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class InsightsSessionInstance(InstanceResource): + """ + :ivar workspace_id: Unique ID to identify the user's workspace + :ivar session_expiry: The session expiry date and time, given in ISO 8601 format. + :ivar session_id: The unique ID for the session + :ivar base_url: The base URL to fetch reports and dashboards + :ivar url: The URL of this resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.workspace_id: Optional[str] = payload.get("workspace_id") + self.session_expiry: Optional[str] = payload.get("session_expiry") + self.session_id: Optional[str] = payload.get("session_id") + self.base_url: Optional[str] = payload.get("base_url") + self.url: Optional[str] = payload.get("url") + + self._context: Optional[InsightsSessionContext] = None + + @property + def _proxy(self) -> "InsightsSessionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InsightsSessionContext for this InsightsSessionInstance + """ + if self._context is None: + self._context = InsightsSessionContext( + self._version, + ) + return self._context + + def create( + self, authorization: Union[str, object] = values.unset + ) -> "InsightsSessionInstance": + """ + Create the InsightsSessionInstance + + :param authorization: The Authorization HTTP request header + + :returns: The created InsightsSessionInstance + """ + return self._proxy.create( + authorization=authorization, + ) + + async def create_async( + self, authorization: Union[str, object] = values.unset + ) -> "InsightsSessionInstance": + """ + Asynchronous coroutine to create the InsightsSessionInstance + + :param authorization: The Authorization HTTP request header + + :returns: The created InsightsSessionInstance + """ + return await self._proxy.create_async( + authorization=authorization, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class InsightsSessionContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the InsightsSessionContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/Insights/Session" + + def create( + self, authorization: Union[str, object] = values.unset + ) -> InsightsSessionInstance: + """ + Create the InsightsSessionInstance + + :param authorization: The Authorization HTTP request header + + :returns: The created InsightsSessionInstance + """ + data = values.of( + { + "Authorization": authorization, + } + ) + + payload = self._version.create(method="POST", uri=self._uri, data=data) + + return InsightsSessionInstance(self._version, payload) + + async def create_async( + self, authorization: Union[str, object] = values.unset + ) -> InsightsSessionInstance: + """ + Asynchronous coroutine to create the InsightsSessionInstance + + :param authorization: The Authorization HTTP request header + + :returns: The created InsightsSessionInstance + """ + data = values.of( + { + "Authorization": authorization, + } + ) + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data + ) + + return InsightsSessionInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class InsightsSessionList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InsightsSessionList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> InsightsSessionContext: + """ + Constructs a InsightsSessionContext + + """ + return InsightsSessionContext(self._version) + + def __call__(self) -> InsightsSessionContext: + """ + Constructs a InsightsSessionContext + + """ + return InsightsSessionContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_settings_answer_sets.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_settings_answer_sets.py new file mode 100644 index 00000000..9b0e89e9 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_settings_answer_sets.py @@ -0,0 +1,118 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class InsightsSettingsAnswerSetsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Insights resource and owns this resource. + :ivar answer_sets: The lis of answer sets + :ivar answer_set_categories: The list of answer set categories + :ivar not_applicable: The details for not applicable answer set + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.answer_sets: Optional[Dict[str, object]] = payload.get("answer_sets") + self.answer_set_categories: Optional[Dict[str, object]] = payload.get( + "answer_set_categories" + ) + self.not_applicable: Optional[Dict[str, object]] = payload.get("not_applicable") + self.url: Optional[str] = payload.get("url") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class InsightsSettingsAnswerSetsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InsightsSettingsAnswerSetsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Insights/QualityManagement/Settings/AnswerSets" + + def fetch( + self, authorization: Union[str, object] = values.unset + ) -> InsightsSettingsAnswerSetsInstance: + """ + Asynchronously fetch the InsightsSettingsAnswerSetsInstance + + :param authorization: The Authorization HTTP request header + :returns: The fetched InsightsSettingsAnswerSetsInstance + """ + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InsightsSettingsAnswerSetsInstance(self._version, payload) + + async def fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> InsightsSettingsAnswerSetsInstance: + """ + Asynchronously fetch the InsightsSettingsAnswerSetsInstance + + :param authorization: The Authorization HTTP request header + :returns: The fetched InsightsSettingsAnswerSetsInstance + """ + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InsightsSettingsAnswerSetsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_settings_comment.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_settings_comment.py new file mode 100644 index 00000000..18733a49 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_settings_comment.py @@ -0,0 +1,112 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class InsightsSettingsCommentInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Insights resource and owns this resource. + :ivar comments: + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.comments: Optional[Dict[str, object]] = payload.get("comments") + self.url: Optional[str] = payload.get("url") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class InsightsSettingsCommentList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InsightsSettingsCommentList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Insights/QualityManagement/Settings/CommentTags" + + def fetch( + self, authorization: Union[str, object] = values.unset + ) -> InsightsSettingsCommentInstance: + """ + Asynchronously fetch the InsightsSettingsCommentInstance + + :param authorization: The Authorization HTTP request header + :returns: The fetched InsightsSettingsCommentInstance + """ + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InsightsSettingsCommentInstance(self._version, payload) + + async def fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> InsightsSettingsCommentInstance: + """ + Asynchronously fetch the InsightsSettingsCommentInstance + + :param authorization: The Authorization HTTP request header + :returns: The fetched InsightsSettingsCommentInstance + """ + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InsightsSettingsCommentInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_user_roles.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_user_roles.py new file mode 100644 index 00000000..19cb10b8 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/insights_user_roles.py @@ -0,0 +1,202 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class InsightsUserRolesInstance(InstanceResource): + """ + :ivar roles: Flex Insights roles for the user + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.roles: Optional[List[str]] = payload.get("roles") + self.url: Optional[str] = payload.get("url") + + self._context: Optional[InsightsUserRolesContext] = None + + @property + def _proxy(self) -> "InsightsUserRolesContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InsightsUserRolesContext for this InsightsUserRolesInstance + """ + if self._context is None: + self._context = InsightsUserRolesContext( + self._version, + ) + return self._context + + def fetch( + self, authorization: Union[str, object] = values.unset + ) -> "InsightsUserRolesInstance": + """ + Fetch the InsightsUserRolesInstance + + :param authorization: The Authorization HTTP request header + + :returns: The fetched InsightsUserRolesInstance + """ + return self._proxy.fetch( + authorization=authorization, + ) + + async def fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> "InsightsUserRolesInstance": + """ + Asynchronous coroutine to fetch the InsightsUserRolesInstance + + :param authorization: The Authorization HTTP request header + + :returns: The fetched InsightsUserRolesInstance + """ + return await self._proxy.fetch_async( + authorization=authorization, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class InsightsUserRolesContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the InsightsUserRolesContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/Insights/UserRoles" + + def fetch( + self, authorization: Union[str, object] = values.unset + ) -> InsightsUserRolesInstance: + """ + Fetch the InsightsUserRolesInstance + + :param authorization: The Authorization HTTP request header + + :returns: The fetched InsightsUserRolesInstance + """ + + data = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return InsightsUserRolesInstance( + self._version, + payload, + ) + + async def fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> InsightsUserRolesInstance: + """ + Asynchronous coroutine to fetch the InsightsUserRolesInstance + + :param authorization: The Authorization HTTP request header + + :returns: The fetched InsightsUserRolesInstance + """ + + data = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return InsightsUserRolesInstance( + self._version, + payload, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class InsightsUserRolesList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InsightsUserRolesList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> InsightsUserRolesContext: + """ + Constructs a InsightsUserRolesContext + + """ + return InsightsUserRolesContext(self._version) + + def __call__(self) -> InsightsUserRolesContext: + """ + Constructs a InsightsUserRolesContext + + """ + return InsightsUserRolesContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/__init__.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/__init__.py new file mode 100644 index 00000000..653938f2 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/__init__.py @@ -0,0 +1,386 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.flex_api.v1.interaction.interaction_channel import ( + InteractionChannelList, +) + + +class InteractionInstance(InstanceResource): + """ + :ivar sid: The unique string created by Twilio to identify an Interaction resource, prefixed with KD. + :ivar channel: A JSON object that defines the Interaction’s communication channel and includes details about the channel. See the [Outbound SMS](https://www.twilio.com/docs/flex/developer/conversations/interactions-api/interactions#agent-initiated-outbound-interactions) and [inbound (API-initiated)](https://www.twilio.com/docs/flex/developer/conversations/interactions-api/interactions#api-initiated-contact) Channel object examples. + :ivar routing: A JSON Object representing the routing rules for the Interaction Channel. See [Outbound SMS Example](https://www.twilio.com/docs/flex/developer/conversations/interactions-api/interactions#agent-initiated-outbound-interactions) for an example Routing object. The Interactions resource uses TaskRouter for all routing functionality. All attributes in the Routing object on your Interaction request body are added “as is” to the task. For a list of known attributes consumed by the Flex UI and/or Flex Insights, see [Known Task Attributes](https://www.twilio.com/docs/flex/developer/conversations/interactions-api#task-attributes). + :ivar url: + :ivar links: + :ivar interaction_context_sid: + :ivar webhook_ttid: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.channel: Optional[Dict[str, object]] = payload.get("channel") + self.routing: Optional[Dict[str, object]] = payload.get("routing") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.interaction_context_sid: Optional[str] = payload.get( + "interaction_context_sid" + ) + self.webhook_ttid: Optional[str] = payload.get("webhook_ttid") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[InteractionContext] = None + + @property + def _proxy(self) -> "InteractionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InteractionContext for this InteractionInstance + """ + if self._context is None: + self._context = InteractionContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "InteractionInstance": + """ + Fetch the InteractionInstance + + + :returns: The fetched InteractionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InteractionInstance": + """ + Asynchronous coroutine to fetch the InteractionInstance + + + :returns: The fetched InteractionInstance + """ + return await self._proxy.fetch_async() + + def update( + self, webhook_ttid: Union[str, object] = values.unset + ) -> "InteractionInstance": + """ + Update the InteractionInstance + + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: The updated InteractionInstance + """ + return self._proxy.update( + webhook_ttid=webhook_ttid, + ) + + async def update_async( + self, webhook_ttid: Union[str, object] = values.unset + ) -> "InteractionInstance": + """ + Asynchronous coroutine to update the InteractionInstance + + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: The updated InteractionInstance + """ + return await self._proxy.update_async( + webhook_ttid=webhook_ttid, + ) + + @property + def channels(self) -> InteractionChannelList: + """ + Access the channels + """ + return self._proxy.channels + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InteractionContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the InteractionContext + + :param version: Version that contains the resource + :param sid: The SID of the Interaction resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Interactions/{sid}".format(**self._solution) + + self._channels: Optional[InteractionChannelList] = None + + def fetch(self) -> InteractionInstance: + """ + Fetch the InteractionInstance + + + :returns: The fetched InteractionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InteractionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> InteractionInstance: + """ + Asynchronous coroutine to fetch the InteractionInstance + + + :returns: The fetched InteractionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InteractionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, webhook_ttid: Union[str, object] = values.unset + ) -> InteractionInstance: + """ + Update the InteractionInstance + + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: The updated InteractionInstance + """ + + data = values.of( + { + "WebhookTtid": webhook_ttid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, webhook_ttid: Union[str, object] = values.unset + ) -> InteractionInstance: + """ + Asynchronous coroutine to update the InteractionInstance + + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: The updated InteractionInstance + """ + + data = values.of( + { + "WebhookTtid": webhook_ttid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def channels(self) -> InteractionChannelList: + """ + Access the channels + """ + if self._channels is None: + self._channels = InteractionChannelList( + self._version, + self._solution["sid"], + ) + return self._channels + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InteractionList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InteractionList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Interactions" + + def create( + self, + channel: object, + routing: Union[object, object] = values.unset, + interaction_context_sid: Union[str, object] = values.unset, + webhook_ttid: Union[str, object] = values.unset, + ) -> InteractionInstance: + """ + Create the InteractionInstance + + :param channel: The Interaction's channel. + :param routing: The Interaction's routing logic. + :param interaction_context_sid: The Interaction context sid is used for adding a context lookup sid + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: The created InteractionInstance + """ + + data = values.of( + { + "Channel": serialize.object(channel), + "Routing": serialize.object(routing), + "InteractionContextSid": interaction_context_sid, + "WebhookTtid": webhook_ttid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionInstance(self._version, payload) + + async def create_async( + self, + channel: object, + routing: Union[object, object] = values.unset, + interaction_context_sid: Union[str, object] = values.unset, + webhook_ttid: Union[str, object] = values.unset, + ) -> InteractionInstance: + """ + Asynchronously create the InteractionInstance + + :param channel: The Interaction's channel. + :param routing: The Interaction's routing logic. + :param interaction_context_sid: The Interaction context sid is used for adding a context lookup sid + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: The created InteractionInstance + """ + + data = values.of( + { + "Channel": serialize.object(channel), + "Routing": serialize.object(routing), + "InteractionContextSid": interaction_context_sid, + "WebhookTtid": webhook_ttid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionInstance(self._version, payload) + + def get(self, sid: str) -> InteractionContext: + """ + Constructs a InteractionContext + + :param sid: The SID of the Interaction resource to fetch. + """ + return InteractionContext(self._version, sid=sid) + + def __call__(self, sid: str) -> InteractionContext: + """ + Constructs a InteractionContext + + :param sid: The SID of the Interaction resource to fetch. + """ + return InteractionContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..3c1e9f02 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/interaction_channel/__init__.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/interaction_channel/__init__.py new file mode 100644 index 00000000..b029104c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/interaction_channel/__init__.py @@ -0,0 +1,644 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.flex_api.v1.interaction.interaction_channel.interaction_channel_invite import ( + InteractionChannelInviteList, +) +from twilio.rest.flex_api.v1.interaction.interaction_channel.interaction_channel_participant import ( + InteractionChannelParticipantList, +) +from twilio.rest.flex_api.v1.interaction.interaction_channel.interaction_transfer import ( + InteractionTransferList, +) + + +class InteractionChannelInstance(InstanceResource): + + class ChannelStatus(object): + SETUP = "setup" + ACTIVE = "active" + FAILED = "failed" + CLOSED = "closed" + INACTIVE = "inactive" + + class Type(object): + VOICE = "voice" + SMS = "sms" + EMAIL = "email" + WEB = "web" + WHATSAPP = "whatsapp" + CHAT = "chat" + MESSENGER = "messenger" + GBM = "gbm" + + class UpdateChannelStatus(object): + CLOSED = "closed" + INACTIVE = "inactive" + + """ + :ivar sid: The unique string created by Twilio to identify an Interaction Channel resource, prefixed with UO. + :ivar interaction_sid: The unique string created by Twilio to identify an Interaction resource, prefixed with KD. + :ivar type: + :ivar status: + :ivar error_code: The Twilio error code for a failed channel. + :ivar error_message: The error message for a failed channel. + :ivar url: + :ivar links: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + interaction_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.interaction_sid: Optional[str] = payload.get("interaction_sid") + self.type: Optional["InteractionChannelInstance.Type"] = payload.get("type") + self.status: Optional["InteractionChannelInstance.ChannelStatus"] = payload.get( + "status" + ) + self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) + self.error_message: Optional[str] = payload.get("error_message") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "interaction_sid": interaction_sid, + "sid": sid or self.sid, + } + self._context: Optional[InteractionChannelContext] = None + + @property + def _proxy(self) -> "InteractionChannelContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InteractionChannelContext for this InteractionChannelInstance + """ + if self._context is None: + self._context = InteractionChannelContext( + self._version, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "InteractionChannelInstance": + """ + Fetch the InteractionChannelInstance + + + :returns: The fetched InteractionChannelInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InteractionChannelInstance": + """ + Asynchronous coroutine to fetch the InteractionChannelInstance + + + :returns: The fetched InteractionChannelInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + status: "InteractionChannelInstance.UpdateChannelStatus", + routing: Union[object, object] = values.unset, + ) -> "InteractionChannelInstance": + """ + Update the InteractionChannelInstance + + :param status: + :param routing: It changes the state of associated tasks. Routing status is required, When the channel status is set to `inactive`. Allowed Value for routing status is `closed`. Otherwise Optional, if not specified, all tasks will be set to `wrapping`. + + :returns: The updated InteractionChannelInstance + """ + return self._proxy.update( + status=status, + routing=routing, + ) + + async def update_async( + self, + status: "InteractionChannelInstance.UpdateChannelStatus", + routing: Union[object, object] = values.unset, + ) -> "InteractionChannelInstance": + """ + Asynchronous coroutine to update the InteractionChannelInstance + + :param status: + :param routing: It changes the state of associated tasks. Routing status is required, When the channel status is set to `inactive`. Allowed Value for routing status is `closed`. Otherwise Optional, if not specified, all tasks will be set to `wrapping`. + + :returns: The updated InteractionChannelInstance + """ + return await self._proxy.update_async( + status=status, + routing=routing, + ) + + @property + def invites(self) -> InteractionChannelInviteList: + """ + Access the invites + """ + return self._proxy.invites + + @property + def participants(self) -> InteractionChannelParticipantList: + """ + Access the participants + """ + return self._proxy.participants + + @property + def transfers(self) -> InteractionTransferList: + """ + Access the transfers + """ + return self._proxy.transfers + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InteractionChannelContext(InstanceContext): + + def __init__(self, version: Version, interaction_sid: str, sid: str): + """ + Initialize the InteractionChannelContext + + :param version: Version that contains the resource + :param interaction_sid: The unique string created by Twilio to identify an Interaction resource, prefixed with KD. + :param sid: The unique string created by Twilio to identify an Interaction Channel resource, prefixed with UO. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "interaction_sid": interaction_sid, + "sid": sid, + } + self._uri = "/Interactions/{interaction_sid}/Channels/{sid}".format( + **self._solution + ) + + self._invites: Optional[InteractionChannelInviteList] = None + self._participants: Optional[InteractionChannelParticipantList] = None + self._transfers: Optional[InteractionTransferList] = None + + def fetch(self) -> InteractionChannelInstance: + """ + Fetch the InteractionChannelInstance + + + :returns: The fetched InteractionChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InteractionChannelInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> InteractionChannelInstance: + """ + Asynchronous coroutine to fetch the InteractionChannelInstance + + + :returns: The fetched InteractionChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InteractionChannelInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + status: "InteractionChannelInstance.UpdateChannelStatus", + routing: Union[object, object] = values.unset, + ) -> InteractionChannelInstance: + """ + Update the InteractionChannelInstance + + :param status: + :param routing: It changes the state of associated tasks. Routing status is required, When the channel status is set to `inactive`. Allowed Value for routing status is `closed`. Otherwise Optional, if not specified, all tasks will be set to `wrapping`. + + :returns: The updated InteractionChannelInstance + """ + + data = values.of( + { + "Status": status, + "Routing": serialize.object(routing), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionChannelInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + status: "InteractionChannelInstance.UpdateChannelStatus", + routing: Union[object, object] = values.unset, + ) -> InteractionChannelInstance: + """ + Asynchronous coroutine to update the InteractionChannelInstance + + :param status: + :param routing: It changes the state of associated tasks. Routing status is required, When the channel status is set to `inactive`. Allowed Value for routing status is `closed`. Otherwise Optional, if not specified, all tasks will be set to `wrapping`. + + :returns: The updated InteractionChannelInstance + """ + + data = values.of( + { + "Status": status, + "Routing": serialize.object(routing), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionChannelInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], + ) + + @property + def invites(self) -> InteractionChannelInviteList: + """ + Access the invites + """ + if self._invites is None: + self._invites = InteractionChannelInviteList( + self._version, + self._solution["interaction_sid"], + self._solution["sid"], + ) + return self._invites + + @property + def participants(self) -> InteractionChannelParticipantList: + """ + Access the participants + """ + if self._participants is None: + self._participants = InteractionChannelParticipantList( + self._version, + self._solution["interaction_sid"], + self._solution["sid"], + ) + return self._participants + + @property + def transfers(self) -> InteractionTransferList: + """ + Access the transfers + """ + if self._transfers is None: + self._transfers = InteractionTransferList( + self._version, + self._solution["interaction_sid"], + self._solution["sid"], + ) + return self._transfers + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InteractionChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InteractionChannelInstance: + """ + Build an instance of InteractionChannelInstance + + :param payload: Payload response from the API + """ + return InteractionChannelInstance( + self._version, payload, interaction_sid=self._solution["interaction_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class InteractionChannelList(ListResource): + + def __init__(self, version: Version, interaction_sid: str): + """ + Initialize the InteractionChannelList + + :param version: Version that contains the resource + :param interaction_sid: The unique string created by Twilio to identify an Interaction resource, prefixed with KD. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "interaction_sid": interaction_sid, + } + self._uri = "/Interactions/{interaction_sid}/Channels".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InteractionChannelInstance]: + """ + Streams InteractionChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InteractionChannelInstance]: + """ + Asynchronously streams InteractionChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InteractionChannelInstance]: + """ + Lists InteractionChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InteractionChannelInstance]: + """ + Asynchronously lists InteractionChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InteractionChannelPage: + """ + Retrieve a single page of InteractionChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InteractionChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InteractionChannelPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InteractionChannelPage: + """ + Asynchronously retrieve a single page of InteractionChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InteractionChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InteractionChannelPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> InteractionChannelPage: + """ + Retrieve a specific page of InteractionChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InteractionChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InteractionChannelPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> InteractionChannelPage: + """ + Asynchronously retrieve a specific page of InteractionChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InteractionChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InteractionChannelPage(self._version, response, self._solution) + + def get(self, sid: str) -> InteractionChannelContext: + """ + Constructs a InteractionChannelContext + + :param sid: The unique string created by Twilio to identify an Interaction Channel resource, prefixed with UO. + """ + return InteractionChannelContext( + self._version, interaction_sid=self._solution["interaction_sid"], sid=sid + ) + + def __call__(self, sid: str) -> InteractionChannelContext: + """ + Constructs a InteractionChannelContext + + :param sid: The unique string created by Twilio to identify an Interaction Channel resource, prefixed with UO. + """ + return InteractionChannelContext( + self._version, interaction_sid=self._solution["interaction_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/interaction_channel/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/interaction_channel/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..08871700 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/interaction_channel/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/interaction_channel/__pycache__/interaction_channel_invite.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/interaction_channel/__pycache__/interaction_channel_invite.cpython-312.pyc new file mode 100644 index 00000000..c83bd7f0 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/interaction_channel/__pycache__/interaction_channel_invite.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/interaction_channel/__pycache__/interaction_channel_participant.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/interaction_channel/__pycache__/interaction_channel_participant.cpython-312.pyc new file mode 100644 index 00000000..cf2c2298 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/interaction_channel/__pycache__/interaction_channel_participant.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/interaction_channel/__pycache__/interaction_transfer.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/interaction_channel/__pycache__/interaction_transfer.cpython-312.pyc new file mode 100644 index 00000000..45b6187e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/interaction_channel/__pycache__/interaction_transfer.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_invite.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_invite.py new file mode 100644 index 00000000..a81acd4f --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_invite.py @@ -0,0 +1,372 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InteractionChannelInviteInstance(InstanceResource): + """ + :ivar sid: The unique string created by Twilio to identify an Interaction Channel Invite resource. + :ivar interaction_sid: The Interaction SID for this Channel. + :ivar channel_sid: The Channel SID for this Invite. + :ivar routing: A JSON object representing the routing rules for the Interaction Channel. See [Outbound SMS Example](https://www.twilio.com/docs/flex/developer/conversations/interactions-api/interactions#agent-initiated-outbound-interactions) for an example Routing object. The Interactions resource uses TaskRouter for all routing functionality. All attributes in the Routing object on your Interaction request body are added “as is” to the task. For a list of known attributes consumed by the Flex UI and/or Flex Insights, see [Known Task Attributes](https://www.twilio.com/docs/flex/developer/conversations/interactions-api#task-attributes). + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + interaction_sid: str, + channel_sid: str, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.interaction_sid: Optional[str] = payload.get("interaction_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.routing: Optional[Dict[str, object]] = payload.get("routing") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "interaction_sid": interaction_sid, + "channel_sid": channel_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InteractionChannelInvitePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InteractionChannelInviteInstance: + """ + Build an instance of InteractionChannelInviteInstance + + :param payload: Payload response from the API + """ + return InteractionChannelInviteInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class InteractionChannelInviteList(ListResource): + + def __init__(self, version: Version, interaction_sid: str, channel_sid: str): + """ + Initialize the InteractionChannelInviteList + + :param version: Version that contains the resource + :param interaction_sid: The Interaction SID for this Channel. + :param channel_sid: The Channel SID for this Participant. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "interaction_sid": interaction_sid, + "channel_sid": channel_sid, + } + self._uri = ( + "/Interactions/{interaction_sid}/Channels/{channel_sid}/Invites".format( + **self._solution + ) + ) + + def create(self, routing: object) -> InteractionChannelInviteInstance: + """ + Create the InteractionChannelInviteInstance + + :param routing: The Interaction's routing logic. + + :returns: The created InteractionChannelInviteInstance + """ + + data = values.of( + { + "Routing": serialize.object(routing), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionChannelInviteInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async(self, routing: object) -> InteractionChannelInviteInstance: + """ + Asynchronously create the InteractionChannelInviteInstance + + :param routing: The Interaction's routing logic. + + :returns: The created InteractionChannelInviteInstance + """ + + data = values.of( + { + "Routing": serialize.object(routing), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionChannelInviteInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InteractionChannelInviteInstance]: + """ + Streams InteractionChannelInviteInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InteractionChannelInviteInstance]: + """ + Asynchronously streams InteractionChannelInviteInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InteractionChannelInviteInstance]: + """ + Lists InteractionChannelInviteInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InteractionChannelInviteInstance]: + """ + Asynchronously lists InteractionChannelInviteInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InteractionChannelInvitePage: + """ + Retrieve a single page of InteractionChannelInviteInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InteractionChannelInviteInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InteractionChannelInvitePage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InteractionChannelInvitePage: + """ + Asynchronously retrieve a single page of InteractionChannelInviteInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InteractionChannelInviteInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InteractionChannelInvitePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> InteractionChannelInvitePage: + """ + Retrieve a specific page of InteractionChannelInviteInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InteractionChannelInviteInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InteractionChannelInvitePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> InteractionChannelInvitePage: + """ + Asynchronously retrieve a specific page of InteractionChannelInviteInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InteractionChannelInviteInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InteractionChannelInvitePage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_participant.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_participant.py new file mode 100644 index 00000000..53d2d40d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_participant.py @@ -0,0 +1,599 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InteractionChannelParticipantInstance(InstanceResource): + + class Status(object): + CLOSED = "closed" + WRAPUP = "wrapup" + + class Type(object): + SUPERVISOR = "supervisor" + CUSTOMER = "customer" + EXTERNAL = "external" + AGENT = "agent" + UNKNOWN = "unknown" + + """ + :ivar sid: The unique string created by Twilio to identify an Interaction Channel Participant resource. + :ivar type: + :ivar interaction_sid: The Interaction Sid for this channel. + :ivar channel_sid: The Channel Sid for this Participant. + :ivar url: + :ivar routing_properties: The Participant's routing properties. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + interaction_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.type: Optional["InteractionChannelParticipantInstance.Type"] = payload.get( + "type" + ) + self.interaction_sid: Optional[str] = payload.get("interaction_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.url: Optional[str] = payload.get("url") + self.routing_properties: Optional[Dict[str, object]] = payload.get( + "routing_properties" + ) + + self._solution = { + "interaction_sid": interaction_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[InteractionChannelParticipantContext] = None + + @property + def _proxy(self) -> "InteractionChannelParticipantContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InteractionChannelParticipantContext for this InteractionChannelParticipantInstance + """ + if self._context is None: + self._context = InteractionChannelParticipantContext( + self._version, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def update( + self, status: "InteractionChannelParticipantInstance.Status" + ) -> "InteractionChannelParticipantInstance": + """ + Update the InteractionChannelParticipantInstance + + :param status: + + :returns: The updated InteractionChannelParticipantInstance + """ + return self._proxy.update( + status=status, + ) + + async def update_async( + self, status: "InteractionChannelParticipantInstance.Status" + ) -> "InteractionChannelParticipantInstance": + """ + Asynchronous coroutine to update the InteractionChannelParticipantInstance + + :param status: + + :returns: The updated InteractionChannelParticipantInstance + """ + return await self._proxy.update_async( + status=status, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class InteractionChannelParticipantContext(InstanceContext): + + def __init__( + self, version: Version, interaction_sid: str, channel_sid: str, sid: str + ): + """ + Initialize the InteractionChannelParticipantContext + + :param version: Version that contains the resource + :param interaction_sid: The Interaction Sid for this channel. + :param channel_sid: The Channel Sid for this Participant. + :param sid: The unique string created by Twilio to identify an Interaction Channel resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "interaction_sid": interaction_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = "/Interactions/{interaction_sid}/Channels/{channel_sid}/Participants/{sid}".format( + **self._solution + ) + + def update( + self, status: "InteractionChannelParticipantInstance.Status" + ) -> InteractionChannelParticipantInstance: + """ + Update the InteractionChannelParticipantInstance + + :param status: + + :returns: The updated InteractionChannelParticipantInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionChannelParticipantInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, status: "InteractionChannelParticipantInstance.Status" + ) -> InteractionChannelParticipantInstance: + """ + Asynchronous coroutine to update the InteractionChannelParticipantInstance + + :param status: + + :returns: The updated InteractionChannelParticipantInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionChannelParticipantInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class InteractionChannelParticipantPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> InteractionChannelParticipantInstance: + """ + Build an instance of InteractionChannelParticipantInstance + + :param payload: Payload response from the API + """ + return InteractionChannelParticipantInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class InteractionChannelParticipantList(ListResource): + + def __init__(self, version: Version, interaction_sid: str, channel_sid: str): + """ + Initialize the InteractionChannelParticipantList + + :param version: Version that contains the resource + :param interaction_sid: The Interaction Sid for this channel. + :param channel_sid: The Channel Sid for this Participant. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "interaction_sid": interaction_sid, + "channel_sid": channel_sid, + } + self._uri = "/Interactions/{interaction_sid}/Channels/{channel_sid}/Participants".format( + **self._solution + ) + + def create( + self, + type: "InteractionChannelParticipantInstance.Type", + media_properties: object, + routing_properties: Union[object, object] = values.unset, + ) -> InteractionChannelParticipantInstance: + """ + Create the InteractionChannelParticipantInstance + + :param type: + :param media_properties: JSON representing the Media Properties for the new Participant. + :param routing_properties: Object representing the Routing Properties for the new Participant. + + :returns: The created InteractionChannelParticipantInstance + """ + + data = values.of( + { + "Type": type, + "MediaProperties": serialize.object(media_properties), + "RoutingProperties": serialize.object(routing_properties), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionChannelParticipantInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, + type: "InteractionChannelParticipantInstance.Type", + media_properties: object, + routing_properties: Union[object, object] = values.unset, + ) -> InteractionChannelParticipantInstance: + """ + Asynchronously create the InteractionChannelParticipantInstance + + :param type: + :param media_properties: JSON representing the Media Properties for the new Participant. + :param routing_properties: Object representing the Routing Properties for the new Participant. + + :returns: The created InteractionChannelParticipantInstance + """ + + data = values.of( + { + "Type": type, + "MediaProperties": serialize.object(media_properties), + "RoutingProperties": serialize.object(routing_properties), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionChannelParticipantInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InteractionChannelParticipantInstance]: + """ + Streams InteractionChannelParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InteractionChannelParticipantInstance]: + """ + Asynchronously streams InteractionChannelParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InteractionChannelParticipantInstance]: + """ + Lists InteractionChannelParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InteractionChannelParticipantInstance]: + """ + Asynchronously lists InteractionChannelParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InteractionChannelParticipantPage: + """ + Retrieve a single page of InteractionChannelParticipantInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InteractionChannelParticipantInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InteractionChannelParticipantPage( + self._version, response, self._solution + ) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InteractionChannelParticipantPage: + """ + Asynchronously retrieve a single page of InteractionChannelParticipantInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InteractionChannelParticipantInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InteractionChannelParticipantPage( + self._version, response, self._solution + ) + + def get_page(self, target_url: str) -> InteractionChannelParticipantPage: + """ + Retrieve a specific page of InteractionChannelParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InteractionChannelParticipantInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InteractionChannelParticipantPage( + self._version, response, self._solution + ) + + async def get_page_async( + self, target_url: str + ) -> InteractionChannelParticipantPage: + """ + Asynchronously retrieve a specific page of InteractionChannelParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InteractionChannelParticipantInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InteractionChannelParticipantPage( + self._version, response, self._solution + ) + + def get(self, sid: str) -> InteractionChannelParticipantContext: + """ + Constructs a InteractionChannelParticipantContext + + :param sid: The unique string created by Twilio to identify an Interaction Channel resource. + """ + return InteractionChannelParticipantContext( + self._version, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InteractionChannelParticipantContext: + """ + Constructs a InteractionChannelParticipantContext + + :param sid: The unique string created by Twilio to identify an Interaction Channel resource. + """ + return InteractionChannelParticipantContext( + self._version, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_transfer.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_transfer.py new file mode 100644 index 00000000..04a5afac --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_transfer.py @@ -0,0 +1,423 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class InteractionTransferInstance(InstanceResource): + + class TransferStatus(object): + ACTIVE = "active" + FAILED = "failed" + COMPLETED = "completed" + + class TransferType(object): + WARM = "warm" + COLD = "cold" + EXTERNAL = "external" + + """ + :ivar sid: The unique string created by Twilio to identify an Interaction Transfer resource. + :ivar instance_sid: The SID of the Instance associated with the Transfer. + :ivar account_sid: The SID of the Account that created the Transfer. + :ivar interaction_sid: The Interaction Sid for this channel. + :ivar channel_sid: The Channel Sid for this Transfer. + :ivar execution_sid: The Execution SID associated with the Transfer. + :ivar type: + :ivar status: + :ivar _from: The SID of the Participant initiating the Transfer. + :ivar to: The SID of the Participant receiving the Transfer. + :ivar note_sid: The SID of the Note associated with the Transfer. + :ivar summary_sid: The SID of the Summary associated with the Transfer. + :ivar date_created: The date and time when the Transfer was created. + :ivar date_updated: The date and time when the Transfer was last updated. + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + interaction_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.instance_sid: Optional[str] = payload.get("instance_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.interaction_sid: Optional[str] = payload.get("interaction_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.execution_sid: Optional[str] = payload.get("execution_sid") + self.type: Optional["InteractionTransferInstance.TransferType"] = payload.get( + "type" + ) + self.status: Optional["InteractionTransferInstance.TransferStatus"] = ( + payload.get("status") + ) + self._from: Optional[str] = payload.get("from") + self.to: Optional[str] = payload.get("to") + self.note_sid: Optional[str] = payload.get("note_sid") + self.summary_sid: Optional[str] = payload.get("summary_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "interaction_sid": interaction_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[InteractionTransferContext] = None + + @property + def _proxy(self) -> "InteractionTransferContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InteractionTransferContext for this InteractionTransferInstance + """ + if self._context is None: + self._context = InteractionTransferContext( + self._version, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "InteractionTransferInstance": + """ + Fetch the InteractionTransferInstance + + + :returns: The fetched InteractionTransferInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InteractionTransferInstance": + """ + Asynchronous coroutine to fetch the InteractionTransferInstance + + + :returns: The fetched InteractionTransferInstance + """ + return await self._proxy.fetch_async() + + def update( + self, body: Union[object, object] = values.unset + ) -> "InteractionTransferInstance": + """ + Update the InteractionTransferInstance + + :param body: + + :returns: The updated InteractionTransferInstance + """ + return self._proxy.update( + body=body, + ) + + async def update_async( + self, body: Union[object, object] = values.unset + ) -> "InteractionTransferInstance": + """ + Asynchronous coroutine to update the InteractionTransferInstance + + :param body: + + :returns: The updated InteractionTransferInstance + """ + return await self._proxy.update_async( + body=body, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InteractionTransferContext(InstanceContext): + + def __init__( + self, version: Version, interaction_sid: str, channel_sid: str, sid: str + ): + """ + Initialize the InteractionTransferContext + + :param version: Version that contains the resource + :param interaction_sid: The Interaction Sid for this channel. + :param channel_sid: The Channel Sid for this Transfer. + :param sid: The unique string created by Twilio to identify a Transfer resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "interaction_sid": interaction_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = "/Interactions/{interaction_sid}/Channels/{channel_sid}/Transfers/{sid}".format( + **self._solution + ) + + def fetch(self) -> InteractionTransferInstance: + """ + Fetch the InteractionTransferInstance + + + :returns: The fetched InteractionTransferInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> InteractionTransferInstance: + """ + Asynchronous coroutine to fetch the InteractionTransferInstance + + + :returns: The fetched InteractionTransferInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update( + self, body: Union[object, object] = values.unset + ) -> InteractionTransferInstance: + """ + Update the InteractionTransferInstance + + :param body: + + :returns: The updated InteractionTransferInstance + """ + data = body.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, body: Union[object, object] = values.unset + ) -> InteractionTransferInstance: + """ + Asynchronous coroutine to update the InteractionTransferInstance + + :param body: + + :returns: The updated InteractionTransferInstance + """ + data = body.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InteractionTransferList(ListResource): + + def __init__(self, version: Version, interaction_sid: str, channel_sid: str): + """ + Initialize the InteractionTransferList + + :param version: Version that contains the resource + :param interaction_sid: The Interaction Sid for the Interaction + :param channel_sid: The Channel Sid for the Channel. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "interaction_sid": interaction_sid, + "channel_sid": channel_sid, + } + self._uri = ( + "/Interactions/{interaction_sid}/Channels/{channel_sid}/Transfers".format( + **self._solution + ) + ) + + def create( + self, body: Union[object, object] = values.unset + ) -> InteractionTransferInstance: + """ + Create the InteractionTransferInstance + + :param body: + + :returns: The created InteractionTransferInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> InteractionTransferInstance: + """ + Asynchronously create the InteractionTransferInstance + + :param body: + + :returns: The created InteractionTransferInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def get(self, sid: str) -> InteractionTransferContext: + """ + Constructs a InteractionTransferContext + + :param sid: The unique string created by Twilio to identify a Transfer resource. + """ + return InteractionTransferContext( + self._version, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InteractionTransferContext: + """ + Constructs a InteractionTransferContext + + :param sid: The unique string created by Twilio to identify a Transfer resource. + """ + return InteractionTransferContext( + self._version, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin/__init__.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin/__init__.py new file mode 100644 index 00000000..2415c427 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin/__init__.py @@ -0,0 +1,707 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.flex_api.v1.plugin.plugin_versions import PluginVersionsList + + +class PluginInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Flex Plugin resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Plugin resource and owns this resource. + :ivar unique_name: The name that uniquely identifies this Flex Plugin resource. + :ivar friendly_name: The friendly name this Flex Plugin resource. + :ivar description: A descriptive string that you create to describe the plugin resource. It can be up to 500 characters long + :ivar archived: Whether the Flex Plugin is archived. The default value is false. + :ivar date_created: The date and time in GMT-7 when the Flex Plugin was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT-7 when the Flex Plugin was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Flex Plugin resource. + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.archived: Optional[bool] = payload.get("archived") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[PluginContext] = None + + @property + def _proxy(self) -> "PluginContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PluginContext for this PluginInstance + """ + if self._context is None: + self._context = PluginContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginInstance": + """ + Fetch the PluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginInstance + """ + return self._proxy.fetch( + flex_metadata=flex_metadata, + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginInstance": + """ + Asynchronous coroutine to fetch the PluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginInstance + """ + return await self._proxy.fetch_async( + flex_metadata=flex_metadata, + ) + + def update( + self, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> "PluginInstance": + """ + Update the PluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + :param friendly_name: The Flex Plugin's friendly name. + :param description: A descriptive string that you update to describe the plugin resource. It can be up to 500 characters long + + :returns: The updated PluginInstance + """ + return self._proxy.update( + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + + async def update_async( + self, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> "PluginInstance": + """ + Asynchronous coroutine to update the PluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + :param friendly_name: The Flex Plugin's friendly name. + :param description: A descriptive string that you update to describe the plugin resource. It can be up to 500 characters long + + :returns: The updated PluginInstance + """ + return await self._proxy.update_async( + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + + @property + def plugin_versions(self) -> PluginVersionsList: + """ + Access the plugin_versions + """ + return self._proxy.plugin_versions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PluginContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the PluginContext + + :param version: Version that contains the resource + :param sid: The SID of the Flex Plugin resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/PluginService/Plugins/{sid}".format(**self._solution) + + self._plugin_versions: Optional[PluginVersionsList] = None + + def fetch(self, flex_metadata: Union[str, object] = values.unset) -> PluginInstance: + """ + Fetch the PluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginInstance + """ + + data = values.of( + { + "Flex-Metadata": flex_metadata, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PluginInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginInstance: + """ + Asynchronous coroutine to fetch the PluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginInstance + """ + + data = values.of( + { + "Flex-Metadata": flex_metadata, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PluginInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> PluginInstance: + """ + Update the PluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + :param friendly_name: The Flex Plugin's friendly name. + :param description: A descriptive string that you update to describe the plugin resource. It can be up to 500 characters long + + :returns: The updated PluginInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Description": description, + } + ) + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> PluginInstance: + """ + Asynchronous coroutine to update the PluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + :param friendly_name: The Flex Plugin's friendly name. + :param description: A descriptive string that you update to describe the plugin resource. It can be up to 500 characters long + + :returns: The updated PluginInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Description": description, + } + ) + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def plugin_versions(self) -> PluginVersionsList: + """ + Access the plugin_versions + """ + if self._plugin_versions is None: + self._plugin_versions = PluginVersionsList( + self._version, + self._solution["sid"], + ) + return self._plugin_versions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PluginPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PluginInstance: + """ + Build an instance of PluginInstance + + :param payload: Payload response from the API + """ + return PluginInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class PluginList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PluginList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/PluginService/Plugins" + + def create( + self, + unique_name: str, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> PluginInstance: + """ + Create the PluginInstance + + :param unique_name: The Flex Plugin's unique name. + :param flex_metadata: The Flex-Metadata HTTP request header + :param friendly_name: The Flex Plugin's friendly name. + :param description: A descriptive string that you create to describe the plugin resource. It can be up to 500 characters long + + :returns: The created PluginInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + "Description": description, + } + ) + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginInstance(self._version, payload) + + async def create_async( + self, + unique_name: str, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> PluginInstance: + """ + Asynchronously create the PluginInstance + + :param unique_name: The Flex Plugin's unique name. + :param flex_metadata: The Flex-Metadata HTTP request header + :param friendly_name: The Flex Plugin's friendly name. + :param description: A descriptive string that you create to describe the plugin resource. It can be up to 500 characters long + + :returns: The created PluginInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + "Description": description, + } + ) + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginInstance(self._version, payload) + + def stream( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PluginInstance]: + """ + Streams PluginInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(flex_metadata=flex_metadata, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PluginInstance]: + """ + Asynchronously streams PluginInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PluginInstance]: + """ + Lists PluginInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PluginInstance]: + """ + Asynchronously lists PluginInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PluginPage: + """ + Retrieve a single page of PluginInstance records from the API. + Request is executed immediately + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PluginInstance + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PluginPage(self._version, response) + + async def page_async( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PluginPage: + """ + Asynchronously retrieve a single page of PluginInstance records from the API. + Request is executed immediately + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PluginInstance + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PluginPage(self._version, response) + + def get_page(self, target_url: str) -> PluginPage: + """ + Retrieve a specific page of PluginInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PluginInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PluginPage(self._version, response) + + async def get_page_async(self, target_url: str) -> PluginPage: + """ + Asynchronously retrieve a specific page of PluginInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PluginInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PluginPage(self._version, response) + + def get(self, sid: str) -> PluginContext: + """ + Constructs a PluginContext + + :param sid: The SID of the Flex Plugin resource to update. + """ + return PluginContext(self._version, sid=sid) + + def __call__(self, sid: str) -> PluginContext: + """ + Constructs a PluginContext + + :param sid: The SID of the Flex Plugin resource to update. + """ + return PluginContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..5f54ec24 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin/__pycache__/plugin_versions.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin/__pycache__/plugin_versions.cpython-312.pyc new file mode 100644 index 00000000..65ceaf0b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin/__pycache__/plugin_versions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin/plugin_versions.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin/plugin_versions.py new file mode 100644 index 00000000..4d66ef57 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin/plugin_versions.py @@ -0,0 +1,612 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class PluginVersionsInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Flex Plugin Version resource. + :ivar plugin_sid: The SID of the Flex Plugin resource this Flex Plugin Version belongs to. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Plugin Version resource and owns this resource. + :ivar version: The unique version of this Flex Plugin Version. + :ivar plugin_url: The URL of where the Flex Plugin Version JavaScript bundle is hosted on. + :ivar changelog: A changelog that describes the changes this Flex Plugin Version brings. + :ivar private: Whether the Flex Plugin Version is validated. The default value is false. + :ivar archived: Whether the Flex Plugin Version is archived. The default value is false. + :ivar validated: + :ivar date_created: The date and time in GMT when the Flex Plugin Version was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Flex Plugin Version resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + plugin_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.plugin_sid: Optional[str] = payload.get("plugin_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.version: Optional[str] = payload.get("version") + self.plugin_url: Optional[str] = payload.get("plugin_url") + self.changelog: Optional[str] = payload.get("changelog") + self.private: Optional[bool] = payload.get("private") + self.archived: Optional[bool] = payload.get("archived") + self.validated: Optional[bool] = payload.get("validated") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "plugin_sid": plugin_sid, + "sid": sid or self.sid, + } + self._context: Optional[PluginVersionsContext] = None + + @property + def _proxy(self) -> "PluginVersionsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PluginVersionsContext for this PluginVersionsInstance + """ + if self._context is None: + self._context = PluginVersionsContext( + self._version, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginVersionsInstance": + """ + Fetch the PluginVersionsInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginVersionsInstance + """ + return self._proxy.fetch( + flex_metadata=flex_metadata, + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginVersionsInstance": + """ + Asynchronous coroutine to fetch the PluginVersionsInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginVersionsInstance + """ + return await self._proxy.fetch_async( + flex_metadata=flex_metadata, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PluginVersionsContext(InstanceContext): + + def __init__(self, version: Version, plugin_sid: str, sid: str): + """ + Initialize the PluginVersionsContext + + :param version: Version that contains the resource + :param plugin_sid: The SID of the Flex Plugin the resource to belongs to. + :param sid: The SID of the Flex Plugin Version resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "plugin_sid": plugin_sid, + "sid": sid, + } + self._uri = "/PluginService/Plugins/{plugin_sid}/Versions/{sid}".format( + **self._solution + ) + + def fetch( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginVersionsInstance: + """ + Fetch the PluginVersionsInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginVersionsInstance + """ + + data = values.of( + { + "Flex-Metadata": flex_metadata, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PluginVersionsInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginVersionsInstance: + """ + Asynchronous coroutine to fetch the PluginVersionsInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginVersionsInstance + """ + + data = values.of( + { + "Flex-Metadata": flex_metadata, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PluginVersionsInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PluginVersionsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PluginVersionsInstance: + """ + Build an instance of PluginVersionsInstance + + :param payload: Payload response from the API + """ + return PluginVersionsInstance( + self._version, payload, plugin_sid=self._solution["plugin_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class PluginVersionsList(ListResource): + + def __init__(self, version: Version, plugin_sid: str): + """ + Initialize the PluginVersionsList + + :param version: Version that contains the resource + :param plugin_sid: The SID of the Flex Plugin the resource to belongs to. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "plugin_sid": plugin_sid, + } + self._uri = "/PluginService/Plugins/{plugin_sid}/Versions".format( + **self._solution + ) + + def create( + self, + version: str, + plugin_url: str, + flex_metadata: Union[str, object] = values.unset, + changelog: Union[str, object] = values.unset, + private: Union[bool, object] = values.unset, + cli_version: Union[str, object] = values.unset, + validate_status: Union[str, object] = values.unset, + ) -> PluginVersionsInstance: + """ + Create the PluginVersionsInstance + + :param version: The Flex Plugin Version's version. + :param plugin_url: The URL of the Flex Plugin Version bundle + :param flex_metadata: The Flex-Metadata HTTP request header + :param changelog: The changelog of the Flex Plugin Version. + :param private: Whether this Flex Plugin Version requires authorization. + :param cli_version: The version of Flex Plugins CLI used to create this plugin + :param validate_status: The validation status of the plugin, indicating whether it has been validated + + :returns: The created PluginVersionsInstance + """ + + data = values.of( + { + "Version": version, + "PluginUrl": plugin_url, + "Changelog": changelog, + "Private": serialize.boolean_to_string(private), + "CliVersion": cli_version, + "ValidateStatus": validate_status, + } + ) + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginVersionsInstance( + self._version, payload, plugin_sid=self._solution["plugin_sid"] + ) + + async def create_async( + self, + version: str, + plugin_url: str, + flex_metadata: Union[str, object] = values.unset, + changelog: Union[str, object] = values.unset, + private: Union[bool, object] = values.unset, + cli_version: Union[str, object] = values.unset, + validate_status: Union[str, object] = values.unset, + ) -> PluginVersionsInstance: + """ + Asynchronously create the PluginVersionsInstance + + :param version: The Flex Plugin Version's version. + :param plugin_url: The URL of the Flex Plugin Version bundle + :param flex_metadata: The Flex-Metadata HTTP request header + :param changelog: The changelog of the Flex Plugin Version. + :param private: Whether this Flex Plugin Version requires authorization. + :param cli_version: The version of Flex Plugins CLI used to create this plugin + :param validate_status: The validation status of the plugin, indicating whether it has been validated + + :returns: The created PluginVersionsInstance + """ + + data = values.of( + { + "Version": version, + "PluginUrl": plugin_url, + "Changelog": changelog, + "Private": serialize.boolean_to_string(private), + "CliVersion": cli_version, + "ValidateStatus": validate_status, + } + ) + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginVersionsInstance( + self._version, payload, plugin_sid=self._solution["plugin_sid"] + ) + + def stream( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PluginVersionsInstance]: + """ + Streams PluginVersionsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(flex_metadata=flex_metadata, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PluginVersionsInstance]: + """ + Asynchronously streams PluginVersionsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PluginVersionsInstance]: + """ + Lists PluginVersionsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PluginVersionsInstance]: + """ + Asynchronously lists PluginVersionsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PluginVersionsPage: + """ + Retrieve a single page of PluginVersionsInstance records from the API. + Request is executed immediately + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PluginVersionsInstance + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PluginVersionsPage(self._version, response, self._solution) + + async def page_async( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PluginVersionsPage: + """ + Asynchronously retrieve a single page of PluginVersionsInstance records from the API. + Request is executed immediately + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PluginVersionsInstance + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PluginVersionsPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> PluginVersionsPage: + """ + Retrieve a specific page of PluginVersionsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PluginVersionsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PluginVersionsPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> PluginVersionsPage: + """ + Asynchronously retrieve a specific page of PluginVersionsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PluginVersionsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PluginVersionsPage(self._version, response, self._solution) + + def get(self, sid: str) -> PluginVersionsContext: + """ + Constructs a PluginVersionsContext + + :param sid: The SID of the Flex Plugin Version resource to fetch. + """ + return PluginVersionsContext( + self._version, plugin_sid=self._solution["plugin_sid"], sid=sid + ) + + def __call__(self, sid: str) -> PluginVersionsContext: + """ + Constructs a PluginVersionsContext + + :param sid: The SID of the Flex Plugin Version resource to fetch. + """ + return PluginVersionsContext( + self._version, plugin_sid=self._solution["plugin_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin_archive.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin_archive.py new file mode 100644 index 00000000..e7f526a9 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin_archive.py @@ -0,0 +1,230 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PluginArchiveInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Flex Plugin resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Plugin resource and owns this resource. + :ivar unique_name: The name that uniquely identifies this Flex Plugin resource. + :ivar friendly_name: The friendly name this Flex Plugin resource. + :ivar description: A descriptive string that you create to describe the plugin resource. It can be up to 500 characters long + :ivar archived: Whether the Flex Plugin is archived. The default value is false. + :ivar date_created: The date and time in GMT when the Flex Plugin was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Flex Plugin was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Flex Plugin resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.archived: Optional[bool] = payload.get("archived") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[PluginArchiveContext] = None + + @property + def _proxy(self) -> "PluginArchiveContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PluginArchiveContext for this PluginArchiveInstance + """ + if self._context is None: + self._context = PluginArchiveContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def update( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginArchiveInstance": + """ + Update the PluginArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginArchiveInstance + """ + return self._proxy.update( + flex_metadata=flex_metadata, + ) + + async def update_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginArchiveInstance": + """ + Asynchronous coroutine to update the PluginArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginArchiveInstance + """ + return await self._proxy.update_async( + flex_metadata=flex_metadata, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PluginArchiveContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the PluginArchiveContext + + :param version: Version that contains the resource + :param sid: The SID of the Flex Plugin resource to archive. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/PluginService/Plugins/{sid}/Archive".format(**self._solution) + + def update( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginArchiveInstance: + """ + Update the PluginArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginArchiveInstance + """ + + data = values.of({}) + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginArchiveInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginArchiveInstance: + """ + Asynchronous coroutine to update the PluginArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginArchiveInstance + """ + + data = values.of({}) + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginArchiveInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PluginArchiveList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PluginArchiveList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, sid: str) -> PluginArchiveContext: + """ + Constructs a PluginArchiveContext + + :param sid: The SID of the Flex Plugin resource to archive. + """ + return PluginArchiveContext(self._version, sid=sid) + + def __call__(self, sid: str) -> PluginArchiveContext: + """ + Constructs a PluginArchiveContext + + :param sid: The SID of the Flex Plugin resource to archive. + """ + return PluginArchiveContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin_configuration/__init__.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin_configuration/__init__.py new file mode 100644 index 00000000..b17d697e --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin_configuration/__init__.py @@ -0,0 +1,583 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.flex_api.v1.plugin_configuration.configured_plugin import ( + ConfiguredPluginList, +) + + +class PluginConfigurationInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Flex Plugin Configuration resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Plugin Configuration resource and owns this resource. + :ivar name: The name of this Flex Plugin Configuration. + :ivar description: The description of the Flex Plugin Configuration resource. + :ivar archived: Whether the Flex Plugin Configuration is archived. The default value is false. + :ivar date_created: The date and time in GMT when the Flex Plugin Configuration was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Flex Plugin Configuration resource. + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.name: Optional[str] = payload.get("name") + self.description: Optional[str] = payload.get("description") + self.archived: Optional[bool] = payload.get("archived") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[PluginConfigurationContext] = None + + @property + def _proxy(self) -> "PluginConfigurationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PluginConfigurationContext for this PluginConfigurationInstance + """ + if self._context is None: + self._context = PluginConfigurationContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginConfigurationInstance": + """ + Fetch the PluginConfigurationInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginConfigurationInstance + """ + return self._proxy.fetch( + flex_metadata=flex_metadata, + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginConfigurationInstance": + """ + Asynchronous coroutine to fetch the PluginConfigurationInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginConfigurationInstance + """ + return await self._proxy.fetch_async( + flex_metadata=flex_metadata, + ) + + @property + def plugins(self) -> ConfiguredPluginList: + """ + Access the plugins + """ + return self._proxy.plugins + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PluginConfigurationContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the PluginConfigurationContext + + :param version: Version that contains the resource + :param sid: The SID of the Flex Plugin Configuration resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/PluginService/Configurations/{sid}".format(**self._solution) + + self._plugins: Optional[ConfiguredPluginList] = None + + def fetch( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginConfigurationInstance: + """ + Fetch the PluginConfigurationInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginConfigurationInstance + """ + + data = values.of( + { + "Flex-Metadata": flex_metadata, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PluginConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginConfigurationInstance: + """ + Asynchronous coroutine to fetch the PluginConfigurationInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginConfigurationInstance + """ + + data = values.of( + { + "Flex-Metadata": flex_metadata, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PluginConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + @property + def plugins(self) -> ConfiguredPluginList: + """ + Access the plugins + """ + if self._plugins is None: + self._plugins = ConfiguredPluginList( + self._version, + self._solution["sid"], + ) + return self._plugins + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PluginConfigurationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PluginConfigurationInstance: + """ + Build an instance of PluginConfigurationInstance + + :param payload: Payload response from the API + """ + return PluginConfigurationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class PluginConfigurationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PluginConfigurationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/PluginService/Configurations" + + def create( + self, + name: str, + flex_metadata: Union[str, object] = values.unset, + plugins: Union[List[object], object] = values.unset, + description: Union[str, object] = values.unset, + ) -> PluginConfigurationInstance: + """ + Create the PluginConfigurationInstance + + :param name: The Flex Plugin Configuration's name. + :param flex_metadata: The Flex-Metadata HTTP request header + :param plugins: A list of objects that describe the plugin versions included in the configuration. Each object contains the sid of the plugin version. + :param description: The Flex Plugin Configuration's description. + + :returns: The created PluginConfigurationInstance + """ + + data = values.of( + { + "Name": name, + "Plugins": serialize.map(plugins, lambda e: serialize.object(e)), + "Description": description, + } + ) + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginConfigurationInstance(self._version, payload) + + async def create_async( + self, + name: str, + flex_metadata: Union[str, object] = values.unset, + plugins: Union[List[object], object] = values.unset, + description: Union[str, object] = values.unset, + ) -> PluginConfigurationInstance: + """ + Asynchronously create the PluginConfigurationInstance + + :param name: The Flex Plugin Configuration's name. + :param flex_metadata: The Flex-Metadata HTTP request header + :param plugins: A list of objects that describe the plugin versions included in the configuration. Each object contains the sid of the plugin version. + :param description: The Flex Plugin Configuration's description. + + :returns: The created PluginConfigurationInstance + """ + + data = values.of( + { + "Name": name, + "Plugins": serialize.map(plugins, lambda e: serialize.object(e)), + "Description": description, + } + ) + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginConfigurationInstance(self._version, payload) + + def stream( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PluginConfigurationInstance]: + """ + Streams PluginConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(flex_metadata=flex_metadata, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PluginConfigurationInstance]: + """ + Asynchronously streams PluginConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PluginConfigurationInstance]: + """ + Lists PluginConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PluginConfigurationInstance]: + """ + Asynchronously lists PluginConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PluginConfigurationPage: + """ + Retrieve a single page of PluginConfigurationInstance records from the API. + Request is executed immediately + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PluginConfigurationInstance + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PluginConfigurationPage(self._version, response) + + async def page_async( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PluginConfigurationPage: + """ + Asynchronously retrieve a single page of PluginConfigurationInstance records from the API. + Request is executed immediately + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PluginConfigurationInstance + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PluginConfigurationPage(self._version, response) + + def get_page(self, target_url: str) -> PluginConfigurationPage: + """ + Retrieve a specific page of PluginConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PluginConfigurationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PluginConfigurationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> PluginConfigurationPage: + """ + Asynchronously retrieve a specific page of PluginConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PluginConfigurationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PluginConfigurationPage(self._version, response) + + def get(self, sid: str) -> PluginConfigurationContext: + """ + Constructs a PluginConfigurationContext + + :param sid: The SID of the Flex Plugin Configuration resource to fetch. + """ + return PluginConfigurationContext(self._version, sid=sid) + + def __call__(self, sid: str) -> PluginConfigurationContext: + """ + Constructs a PluginConfigurationContext + + :param sid: The SID of the Flex Plugin Configuration resource to fetch. + """ + return PluginConfigurationContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin_configuration/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin_configuration/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..e8f3748d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin_configuration/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin_configuration/__pycache__/configured_plugin.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin_configuration/__pycache__/configured_plugin.cpython-312.pyc new file mode 100644 index 00000000..ea4bbf32 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin_configuration/__pycache__/configured_plugin.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin_configuration/configured_plugin.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin_configuration/configured_plugin.py new file mode 100644 index 00000000..062a7db7 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin_configuration/configured_plugin.py @@ -0,0 +1,524 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ConfiguredPluginInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the Flex Plugin resource is installed for. + :ivar configuration_sid: The SID of the Flex Plugin Configuration that this Flex Plugin belongs to. + :ivar plugin_sid: The SID of the Flex Plugin. + :ivar plugin_version_sid: The SID of the Flex Plugin Version. + :ivar phase: The phase this Flex Plugin would initialize at runtime. + :ivar plugin_url: The URL of where the Flex Plugin Version JavaScript bundle is hosted on. + :ivar unique_name: The name that uniquely identifies this Flex Plugin resource. + :ivar friendly_name: The friendly name of this Flex Plugin resource. + :ivar description: A descriptive string that you create to describe the plugin resource. It can be up to 500 characters long + :ivar plugin_archived: Whether the Flex Plugin is archived. The default value is false. + :ivar version: The latest version of this Flex Plugin Version. + :ivar changelog: A changelog that describes the changes this Flex Plugin Version brings. + :ivar plugin_version_archived: Whether the Flex Plugin Version is archived. The default value is false. + :ivar private: Whether to validate the request is authorized to access the Flex Plugin Version. + :ivar date_created: The date and time in GMT when the Flex Plugin was installed specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Flex Plugin resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + configuration_sid: str, + plugin_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.configuration_sid: Optional[str] = payload.get("configuration_sid") + self.plugin_sid: Optional[str] = payload.get("plugin_sid") + self.plugin_version_sid: Optional[str] = payload.get("plugin_version_sid") + self.phase: Optional[int] = deserialize.integer(payload.get("phase")) + self.plugin_url: Optional[str] = payload.get("plugin_url") + self.unique_name: Optional[str] = payload.get("unique_name") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.plugin_archived: Optional[bool] = payload.get("plugin_archived") + self.version: Optional[str] = payload.get("version") + self.changelog: Optional[str] = payload.get("changelog") + self.plugin_version_archived: Optional[bool] = payload.get( + "plugin_version_archived" + ) + self.private: Optional[bool] = payload.get("private") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "configuration_sid": configuration_sid, + "plugin_sid": plugin_sid or self.plugin_sid, + } + self._context: Optional[ConfiguredPluginContext] = None + + @property + def _proxy(self) -> "ConfiguredPluginContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConfiguredPluginContext for this ConfiguredPluginInstance + """ + if self._context is None: + self._context = ConfiguredPluginContext( + self._version, + configuration_sid=self._solution["configuration_sid"], + plugin_sid=self._solution["plugin_sid"], + ) + return self._context + + def fetch( + self, flex_metadata: Union[str, object] = values.unset + ) -> "ConfiguredPluginInstance": + """ + Fetch the ConfiguredPluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched ConfiguredPluginInstance + """ + return self._proxy.fetch( + flex_metadata=flex_metadata, + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> "ConfiguredPluginInstance": + """ + Asynchronous coroutine to fetch the ConfiguredPluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched ConfiguredPluginInstance + """ + return await self._proxy.fetch_async( + flex_metadata=flex_metadata, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConfiguredPluginContext(InstanceContext): + + def __init__(self, version: Version, configuration_sid: str, plugin_sid: str): + """ + Initialize the ConfiguredPluginContext + + :param version: Version that contains the resource + :param configuration_sid: The SID of the Flex Plugin Configuration the resource to belongs to. + :param plugin_sid: The unique string that we created to identify the Flex Plugin resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "configuration_sid": configuration_sid, + "plugin_sid": plugin_sid, + } + self._uri = "/PluginService/Configurations/{configuration_sid}/Plugins/{plugin_sid}".format( + **self._solution + ) + + def fetch( + self, flex_metadata: Union[str, object] = values.unset + ) -> ConfiguredPluginInstance: + """ + Fetch the ConfiguredPluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched ConfiguredPluginInstance + """ + + data = values.of( + { + "Flex-Metadata": flex_metadata, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return ConfiguredPluginInstance( + self._version, + payload, + configuration_sid=self._solution["configuration_sid"], + plugin_sid=self._solution["plugin_sid"], + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ConfiguredPluginInstance: + """ + Asynchronous coroutine to fetch the ConfiguredPluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched ConfiguredPluginInstance + """ + + data = values.of( + { + "Flex-Metadata": flex_metadata, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return ConfiguredPluginInstance( + self._version, + payload, + configuration_sid=self._solution["configuration_sid"], + plugin_sid=self._solution["plugin_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConfiguredPluginPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ConfiguredPluginInstance: + """ + Build an instance of ConfiguredPluginInstance + + :param payload: Payload response from the API + """ + return ConfiguredPluginInstance( + self._version, + payload, + configuration_sid=self._solution["configuration_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ConfiguredPluginList(ListResource): + + def __init__(self, version: Version, configuration_sid: str): + """ + Initialize the ConfiguredPluginList + + :param version: Version that contains the resource + :param configuration_sid: The SID of the Flex Plugin Configuration the resource to belongs to. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "configuration_sid": configuration_sid, + } + self._uri = "/PluginService/Configurations/{configuration_sid}/Plugins".format( + **self._solution + ) + + def stream( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConfiguredPluginInstance]: + """ + Streams ConfiguredPluginInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(flex_metadata=flex_metadata, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConfiguredPluginInstance]: + """ + Asynchronously streams ConfiguredPluginInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConfiguredPluginInstance]: + """ + Lists ConfiguredPluginInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConfiguredPluginInstance]: + """ + Asynchronously lists ConfiguredPluginInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConfiguredPluginPage: + """ + Retrieve a single page of ConfiguredPluginInstance records from the API. + Request is executed immediately + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConfiguredPluginInstance + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConfiguredPluginPage(self._version, response, self._solution) + + async def page_async( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConfiguredPluginPage: + """ + Asynchronously retrieve a single page of ConfiguredPluginInstance records from the API. + Request is executed immediately + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConfiguredPluginInstance + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConfiguredPluginPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ConfiguredPluginPage: + """ + Retrieve a specific page of ConfiguredPluginInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConfiguredPluginInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConfiguredPluginPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ConfiguredPluginPage: + """ + Asynchronously retrieve a specific page of ConfiguredPluginInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConfiguredPluginInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConfiguredPluginPage(self._version, response, self._solution) + + def get(self, plugin_sid: str) -> ConfiguredPluginContext: + """ + Constructs a ConfiguredPluginContext + + :param plugin_sid: The unique string that we created to identify the Flex Plugin resource. + """ + return ConfiguredPluginContext( + self._version, + configuration_sid=self._solution["configuration_sid"], + plugin_sid=plugin_sid, + ) + + def __call__(self, plugin_sid: str) -> ConfiguredPluginContext: + """ + Constructs a ConfiguredPluginContext + + :param plugin_sid: The unique string that we created to identify the Flex Plugin resource. + """ + return ConfiguredPluginContext( + self._version, + configuration_sid=self._solution["configuration_sid"], + plugin_sid=plugin_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin_configuration_archive.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin_configuration_archive.py new file mode 100644 index 00000000..3fec0733 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin_configuration_archive.py @@ -0,0 +1,234 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PluginConfigurationArchiveInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Flex Plugin Configuration resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Plugin Configuration resource and owns this resource. + :ivar name: The name of this Flex Plugin Configuration. + :ivar description: The description of the Flex Plugin Configuration resource. + :ivar archived: Whether the Flex Plugin Configuration is archived. The default value is false. + :ivar date_created: The date and time in GMT when the Flex Plugin Configuration was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Flex Plugin Configuration resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.name: Optional[str] = payload.get("name") + self.description: Optional[str] = payload.get("description") + self.archived: Optional[bool] = payload.get("archived") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[PluginConfigurationArchiveContext] = None + + @property + def _proxy(self) -> "PluginConfigurationArchiveContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PluginConfigurationArchiveContext for this PluginConfigurationArchiveInstance + """ + if self._context is None: + self._context = PluginConfigurationArchiveContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def update( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginConfigurationArchiveInstance": + """ + Update the PluginConfigurationArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginConfigurationArchiveInstance + """ + return self._proxy.update( + flex_metadata=flex_metadata, + ) + + async def update_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginConfigurationArchiveInstance": + """ + Asynchronous coroutine to update the PluginConfigurationArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginConfigurationArchiveInstance + """ + return await self._proxy.update_async( + flex_metadata=flex_metadata, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class PluginConfigurationArchiveContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the PluginConfigurationArchiveContext + + :param version: Version that contains the resource + :param sid: The SID of the Flex Plugin Configuration resource to archive. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/PluginService/Configurations/{sid}/Archive".format( + **self._solution + ) + + def update( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginConfigurationArchiveInstance: + """ + Update the PluginConfigurationArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginConfigurationArchiveInstance + """ + + data = values.of({}) + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginConfigurationArchiveInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginConfigurationArchiveInstance: + """ + Asynchronous coroutine to update the PluginConfigurationArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginConfigurationArchiveInstance + """ + + data = values.of({}) + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginConfigurationArchiveInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class PluginConfigurationArchiveList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PluginConfigurationArchiveList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, sid: str) -> PluginConfigurationArchiveContext: + """ + Constructs a PluginConfigurationArchiveContext + + :param sid: The SID of the Flex Plugin Configuration resource to archive. + """ + return PluginConfigurationArchiveContext(self._version, sid=sid) + + def __call__(self, sid: str) -> PluginConfigurationArchiveContext: + """ + Constructs a PluginConfigurationArchiveContext + + :param sid: The SID of the Flex Plugin Configuration resource to archive. + """ + return PluginConfigurationArchiveContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin_release.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin_release.py new file mode 100644 index 00000000..0694b05f --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin_release.py @@ -0,0 +1,537 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class PluginReleaseInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Plugin Release resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Plugin Release resource and owns this resource. + :ivar configuration_sid: The SID of the Plugin Configuration resource to release. + :ivar date_created: The date and time in GMT when the Flex Plugin Release was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Plugin Release resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.configuration_sid: Optional[str] = payload.get("configuration_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[PluginReleaseContext] = None + + @property + def _proxy(self) -> "PluginReleaseContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PluginReleaseContext for this PluginReleaseInstance + """ + if self._context is None: + self._context = PluginReleaseContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginReleaseInstance": + """ + Fetch the PluginReleaseInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginReleaseInstance + """ + return self._proxy.fetch( + flex_metadata=flex_metadata, + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginReleaseInstance": + """ + Asynchronous coroutine to fetch the PluginReleaseInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginReleaseInstance + """ + return await self._proxy.fetch_async( + flex_metadata=flex_metadata, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PluginReleaseContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the PluginReleaseContext + + :param version: Version that contains the resource + :param sid: The SID of the Flex Plugin Release resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/PluginService/Releases/{sid}".format(**self._solution) + + def fetch( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginReleaseInstance: + """ + Fetch the PluginReleaseInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginReleaseInstance + """ + + data = values.of( + { + "Flex-Metadata": flex_metadata, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PluginReleaseInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginReleaseInstance: + """ + Asynchronous coroutine to fetch the PluginReleaseInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginReleaseInstance + """ + + data = values.of( + { + "Flex-Metadata": flex_metadata, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PluginReleaseInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PluginReleasePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PluginReleaseInstance: + """ + Build an instance of PluginReleaseInstance + + :param payload: Payload response from the API + """ + return PluginReleaseInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class PluginReleaseList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PluginReleaseList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/PluginService/Releases" + + def create( + self, configuration_id: str, flex_metadata: Union[str, object] = values.unset + ) -> PluginReleaseInstance: + """ + Create the PluginReleaseInstance + + :param configuration_id: The SID or the Version of the Flex Plugin Configuration to release. + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The created PluginReleaseInstance + """ + + data = values.of( + { + "ConfigurationId": configuration_id, + } + ) + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginReleaseInstance(self._version, payload) + + async def create_async( + self, configuration_id: str, flex_metadata: Union[str, object] = values.unset + ) -> PluginReleaseInstance: + """ + Asynchronously create the PluginReleaseInstance + + :param configuration_id: The SID or the Version of the Flex Plugin Configuration to release. + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The created PluginReleaseInstance + """ + + data = values.of( + { + "ConfigurationId": configuration_id, + } + ) + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginReleaseInstance(self._version, payload) + + def stream( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PluginReleaseInstance]: + """ + Streams PluginReleaseInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(flex_metadata=flex_metadata, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PluginReleaseInstance]: + """ + Asynchronously streams PluginReleaseInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PluginReleaseInstance]: + """ + Lists PluginReleaseInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PluginReleaseInstance]: + """ + Asynchronously lists PluginReleaseInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PluginReleasePage: + """ + Retrieve a single page of PluginReleaseInstance records from the API. + Request is executed immediately + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PluginReleaseInstance + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PluginReleasePage(self._version, response) + + async def page_async( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PluginReleasePage: + """ + Asynchronously retrieve a single page of PluginReleaseInstance records from the API. + Request is executed immediately + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PluginReleaseInstance + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PluginReleasePage(self._version, response) + + def get_page(self, target_url: str) -> PluginReleasePage: + """ + Retrieve a specific page of PluginReleaseInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PluginReleaseInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PluginReleasePage(self._version, response) + + async def get_page_async(self, target_url: str) -> PluginReleasePage: + """ + Asynchronously retrieve a specific page of PluginReleaseInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PluginReleaseInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PluginReleasePage(self._version, response) + + def get(self, sid: str) -> PluginReleaseContext: + """ + Constructs a PluginReleaseContext + + :param sid: The SID of the Flex Plugin Release resource to fetch. + """ + return PluginReleaseContext(self._version, sid=sid) + + def __call__(self, sid: str) -> PluginReleaseContext: + """ + Constructs a PluginReleaseContext + + :param sid: The SID of the Flex Plugin Release resource to fetch. + """ + return PluginReleaseContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin_version_archive.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin_version_archive.py new file mode 100644 index 00000000..be169d4d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/plugin_version_archive.py @@ -0,0 +1,256 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PluginVersionArchiveInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Flex Plugin Version resource. + :ivar plugin_sid: The SID of the Flex Plugin resource this Flex Plugin Version belongs to. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Plugin Version resource and owns this resource. + :ivar version: The unique version of this Flex Plugin Version. + :ivar plugin_url: The URL of where the Flex Plugin Version JavaScript bundle is hosted on. + :ivar changelog: A changelog that describes the changes this Flex Plugin Version brings. + :ivar private: Whether to inject credentials while accessing this Plugin Version. The default value is false. + :ivar archived: Whether the Flex Plugin Version is archived. The default value is false. + :ivar date_created: The date and time in GMT when the Flex Plugin Version was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Flex Plugin Version resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + plugin_sid: Optional[str] = None, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.plugin_sid: Optional[str] = payload.get("plugin_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.version: Optional[str] = payload.get("version") + self.plugin_url: Optional[str] = payload.get("plugin_url") + self.changelog: Optional[str] = payload.get("changelog") + self.private: Optional[bool] = payload.get("private") + self.archived: Optional[bool] = payload.get("archived") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "plugin_sid": plugin_sid or self.plugin_sid, + "sid": sid or self.sid, + } + self._context: Optional[PluginVersionArchiveContext] = None + + @property + def _proxy(self) -> "PluginVersionArchiveContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PluginVersionArchiveContext for this PluginVersionArchiveInstance + """ + if self._context is None: + self._context = PluginVersionArchiveContext( + self._version, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + return self._context + + def update( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginVersionArchiveInstance": + """ + Update the PluginVersionArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginVersionArchiveInstance + """ + return self._proxy.update( + flex_metadata=flex_metadata, + ) + + async def update_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginVersionArchiveInstance": + """ + Asynchronous coroutine to update the PluginVersionArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginVersionArchiveInstance + """ + return await self._proxy.update_async( + flex_metadata=flex_metadata, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PluginVersionArchiveContext(InstanceContext): + + def __init__(self, version: Version, plugin_sid: str, sid: str): + """ + Initialize the PluginVersionArchiveContext + + :param version: Version that contains the resource + :param plugin_sid: The SID of the Flex Plugin the resource to belongs to. + :param sid: The SID of the Flex Plugin Version resource to archive. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "plugin_sid": plugin_sid, + "sid": sid, + } + self._uri = "/PluginService/Plugins/{plugin_sid}/Versions/{sid}/Archive".format( + **self._solution + ) + + def update( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginVersionArchiveInstance: + """ + Update the PluginVersionArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginVersionArchiveInstance + """ + + data = values.of({}) + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginVersionArchiveInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginVersionArchiveInstance: + """ + Asynchronous coroutine to update the PluginVersionArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginVersionArchiveInstance + """ + + data = values.of({}) + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginVersionArchiveInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PluginVersionArchiveList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PluginVersionArchiveList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, plugin_sid: str, sid: str) -> PluginVersionArchiveContext: + """ + Constructs a PluginVersionArchiveContext + + :param plugin_sid: The SID of the Flex Plugin the resource to belongs to. + :param sid: The SID of the Flex Plugin Version resource to archive. + """ + return PluginVersionArchiveContext( + self._version, plugin_sid=plugin_sid, sid=sid + ) + + def __call__(self, plugin_sid: str, sid: str) -> PluginVersionArchiveContext: + """ + Constructs a PluginVersionArchiveContext + + :param plugin_sid: The SID of the Flex Plugin the resource to belongs to. + :param sid: The SID of the Flex Plugin Version resource to archive. + """ + return PluginVersionArchiveContext( + self._version, plugin_sid=plugin_sid, sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/provisioning_status.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/provisioning_status.py new file mode 100644 index 00000000..2a7bc5b4 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/provisioning_status.py @@ -0,0 +1,181 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ProvisioningStatusInstance(InstanceResource): + + class Status(object): + ACTIVE = "active" + IN_PROGRESS = "in-progress" + NOT_CONFIGURED = "not-configured" + FAILED = "failed" + + """ + :ivar status: + :ivar url: The absolute URL of the resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.status: Optional["ProvisioningStatusInstance.Status"] = payload.get( + "status" + ) + self.url: Optional[str] = payload.get("url") + + self._context: Optional[ProvisioningStatusContext] = None + + @property + def _proxy(self) -> "ProvisioningStatusContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ProvisioningStatusContext for this ProvisioningStatusInstance + """ + if self._context is None: + self._context = ProvisioningStatusContext( + self._version, + ) + return self._context + + def fetch(self) -> "ProvisioningStatusInstance": + """ + Fetch the ProvisioningStatusInstance + + + :returns: The fetched ProvisioningStatusInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ProvisioningStatusInstance": + """ + Asynchronous coroutine to fetch the ProvisioningStatusInstance + + + :returns: The fetched ProvisioningStatusInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class ProvisioningStatusContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the ProvisioningStatusContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/account/provision/status" + + def fetch(self) -> ProvisioningStatusInstance: + """ + Fetch the ProvisioningStatusInstance + + + :returns: The fetched ProvisioningStatusInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ProvisioningStatusInstance( + self._version, + payload, + ) + + async def fetch_async(self) -> ProvisioningStatusInstance: + """ + Asynchronous coroutine to fetch the ProvisioningStatusInstance + + + :returns: The fetched ProvisioningStatusInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ProvisioningStatusInstance( + self._version, + payload, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class ProvisioningStatusList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ProvisioningStatusList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> ProvisioningStatusContext: + """ + Constructs a ProvisioningStatusContext + + """ + return ProvisioningStatusContext(self._version) + + def __call__(self) -> ProvisioningStatusContext: + """ + Constructs a ProvisioningStatusContext + + """ + return ProvisioningStatusContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v1/web_channel.py b/venv/Lib/site-packages/twilio/rest/flex_api/v1/web_channel.py new file mode 100644 index 00000000..46e44fce --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v1/web_channel.py @@ -0,0 +1,651 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class WebChannelInstance(InstanceResource): + + class ChatStatus(object): + INACTIVE = "inactive" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the WebChannel resource and owns this Workflow. + :ivar flex_flow_sid: The SID of the Flex Flow. + :ivar sid: The unique string that we created to identify the WebChannel resource. + :ivar url: The absolute URL of the WebChannel resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.flex_flow_sid: Optional[str] = payload.get("flex_flow_sid") + self.sid: Optional[str] = payload.get("sid") + self.url: Optional[str] = payload.get("url") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[WebChannelContext] = None + + @property + def _proxy(self) -> "WebChannelContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WebChannelContext for this WebChannelInstance + """ + if self._context is None: + self._context = WebChannelContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the WebChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "WebChannelInstance": + """ + Fetch the WebChannelInstance + + + :returns: The fetched WebChannelInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "WebChannelInstance": + """ + Asynchronous coroutine to fetch the WebChannelInstance + + + :returns: The fetched WebChannelInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> "WebChannelInstance": + """ + Update the WebChannelInstance + + :param chat_status: + :param post_engagement_data: The post-engagement data. + + :returns: The updated WebChannelInstance + """ + return self._proxy.update( + chat_status=chat_status, + post_engagement_data=post_engagement_data, + ) + + async def update_async( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> "WebChannelInstance": + """ + Asynchronous coroutine to update the WebChannelInstance + + :param chat_status: + :param post_engagement_data: The post-engagement data. + + :returns: The updated WebChannelInstance + """ + return await self._proxy.update_async( + chat_status=chat_status, + post_engagement_data=post_engagement_data, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WebChannelContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the WebChannelContext + + :param version: Version that contains the resource + :param sid: The SID of the WebChannel resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/WebChannels/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the WebChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebChannelInstance: + """ + Fetch the WebChannelInstance + + + :returns: The fetched WebChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WebChannelInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> WebChannelInstance: + """ + Asynchronous coroutine to fetch the WebChannelInstance + + + :returns: The fetched WebChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WebChannelInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> WebChannelInstance: + """ + Update the WebChannelInstance + + :param chat_status: + :param post_engagement_data: The post-engagement data. + + :returns: The updated WebChannelInstance + """ + + data = values.of( + { + "ChatStatus": chat_status, + "PostEngagementData": post_engagement_data, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebChannelInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> WebChannelInstance: + """ + Asynchronous coroutine to update the WebChannelInstance + + :param chat_status: + :param post_engagement_data: The post-engagement data. + + :returns: The updated WebChannelInstance + """ + + data = values.of( + { + "ChatStatus": chat_status, + "PostEngagementData": post_engagement_data, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebChannelInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WebChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WebChannelInstance: + """ + Build an instance of WebChannelInstance + + :param payload: Payload response from the API + """ + return WebChannelInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class WebChannelList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the WebChannelList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/WebChannels" + + def create( + self, + flex_flow_sid: str, + identity: str, + customer_friendly_name: str, + chat_friendly_name: str, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + ) -> WebChannelInstance: + """ + Create the WebChannelInstance + + :param flex_flow_sid: The SID of the Flex Flow. + :param identity: The chat identity. + :param customer_friendly_name: The chat participant's friendly name. + :param chat_friendly_name: The chat channel's friendly name. + :param chat_unique_name: The chat channel's unique name. + :param pre_engagement_data: The pre-engagement data. + + :returns: The created WebChannelInstance + """ + + data = values.of( + { + "FlexFlowSid": flex_flow_sid, + "Identity": identity, + "CustomerFriendlyName": customer_friendly_name, + "ChatFriendlyName": chat_friendly_name, + "ChatUniqueName": chat_unique_name, + "PreEngagementData": pre_engagement_data, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebChannelInstance(self._version, payload) + + async def create_async( + self, + flex_flow_sid: str, + identity: str, + customer_friendly_name: str, + chat_friendly_name: str, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + ) -> WebChannelInstance: + """ + Asynchronously create the WebChannelInstance + + :param flex_flow_sid: The SID of the Flex Flow. + :param identity: The chat identity. + :param customer_friendly_name: The chat participant's friendly name. + :param chat_friendly_name: The chat channel's friendly name. + :param chat_unique_name: The chat channel's unique name. + :param pre_engagement_data: The pre-engagement data. + + :returns: The created WebChannelInstance + """ + + data = values.of( + { + "FlexFlowSid": flex_flow_sid, + "Identity": identity, + "CustomerFriendlyName": customer_friendly_name, + "ChatFriendlyName": chat_friendly_name, + "ChatUniqueName": chat_unique_name, + "PreEngagementData": pre_engagement_data, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebChannelInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WebChannelInstance]: + """ + Streams WebChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WebChannelInstance]: + """ + Asynchronously streams WebChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebChannelInstance]: + """ + Lists WebChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebChannelInstance]: + """ + Asynchronously lists WebChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebChannelPage: + """ + Retrieve a single page of WebChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebChannelPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebChannelPage: + """ + Asynchronously retrieve a single page of WebChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebChannelPage(self._version, response) + + def get_page(self, target_url: str) -> WebChannelPage: + """ + Retrieve a specific page of WebChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return WebChannelPage(self._version, response) + + async def get_page_async(self, target_url: str) -> WebChannelPage: + """ + Asynchronously retrieve a specific page of WebChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return WebChannelPage(self._version, response) + + def get(self, sid: str) -> WebChannelContext: + """ + Constructs a WebChannelContext + + :param sid: The SID of the WebChannel resource to update. + """ + return WebChannelContext(self._version, sid=sid) + + def __call__(self, sid: str) -> WebChannelContext: + """ + Constructs a WebChannelContext + + :param sid: The SID of the WebChannel resource to update. + """ + return WebChannelContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v2/__init__.py b/venv/Lib/site-packages/twilio/rest/flex_api/v2/__init__.py new file mode 100644 index 00000000..e05ffcdf --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v2/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.flex_api.v2.flex_user import FlexUserList +from twilio.rest.flex_api.v2.web_channels import WebChannelsList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of FlexApi + + :param domain: The Twilio.flex_api domain + """ + super().__init__(domain, "v2") + self._flex_user: Optional[FlexUserList] = None + self._web_channels: Optional[WebChannelsList] = None + + @property + def flex_user(self) -> FlexUserList: + if self._flex_user is None: + self._flex_user = FlexUserList(self) + return self._flex_user + + @property + def web_channels(self) -> WebChannelsList: + if self._web_channels is None: + self._web_channels = WebChannelsList(self) + return self._web_channels + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v2/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v2/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..7783895d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v2/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v2/__pycache__/flex_user.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v2/__pycache__/flex_user.cpython-312.pyc new file mode 100644 index 00000000..42e37bcb Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v2/__pycache__/flex_user.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v2/__pycache__/web_channels.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/flex_api/v2/__pycache__/web_channels.cpython-312.pyc new file mode 100644 index 00000000..66e4a616 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/flex_api/v2/__pycache__/web_channels.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v2/flex_user.py b/venv/Lib/site-packages/twilio/rest/flex_api/v2/flex_user.py new file mode 100644 index 00000000..eb2228d0 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v2/flex_user.py @@ -0,0 +1,358 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class FlexUserInstance(InstanceResource): + """ + :ivar account_sid: The unique SID of the account that created the resource. + :ivar instance_sid: The unique ID created by Twilio to identify a Flex instance. + :ivar user_sid: The unique SID identifier of the Twilio Unified User. + :ivar flex_user_sid: The unique SID identifier of the Flex User. + :ivar worker_sid: The unique SID identifier of the worker. + :ivar workspace_sid: The unique SID identifier of the workspace. + :ivar flex_team_sid: The unique SID identifier of the Flex Team. + :ivar username: Username of the User. + :ivar email: Email of the User. + :ivar locale: The locale preference of the user. + :ivar roles: The roles of the user. + :ivar created_date: The date that this user was created, given in ISO 8601 format. + :ivar updated_date: The date that this user was updated, given in ISO 8601 format. + :ivar version: The current version of the user. + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + instance_sid: Optional[str] = None, + flex_user_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.instance_sid: Optional[str] = payload.get("instance_sid") + self.user_sid: Optional[str] = payload.get("user_sid") + self.flex_user_sid: Optional[str] = payload.get("flex_user_sid") + self.worker_sid: Optional[str] = payload.get("worker_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.flex_team_sid: Optional[str] = payload.get("flex_team_sid") + self.username: Optional[str] = payload.get("username") + self.email: Optional[str] = payload.get("email") + self.locale: Optional[str] = payload.get("locale") + self.roles: Optional[List[str]] = payload.get("roles") + self.created_date: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("created_date") + ) + self.updated_date: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updated_date") + ) + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "instance_sid": instance_sid or self.instance_sid, + "flex_user_sid": flex_user_sid or self.flex_user_sid, + } + self._context: Optional[FlexUserContext] = None + + @property + def _proxy(self) -> "FlexUserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FlexUserContext for this FlexUserInstance + """ + if self._context is None: + self._context = FlexUserContext( + self._version, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + return self._context + + def fetch(self) -> "FlexUserInstance": + """ + Fetch the FlexUserInstance + + + :returns: The fetched FlexUserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FlexUserInstance": + """ + Asynchronous coroutine to fetch the FlexUserInstance + + + :returns: The fetched FlexUserInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + email: Union[str, object] = values.unset, + user_sid: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + ) -> "FlexUserInstance": + """ + Update the FlexUserInstance + + :param email: Email of the User. + :param user_sid: The unique SID identifier of the Twilio Unified User. + :param locale: The locale preference of the user. + + :returns: The updated FlexUserInstance + """ + return self._proxy.update( + email=email, + user_sid=user_sid, + locale=locale, + ) + + async def update_async( + self, + email: Union[str, object] = values.unset, + user_sid: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + ) -> "FlexUserInstance": + """ + Asynchronous coroutine to update the FlexUserInstance + + :param email: Email of the User. + :param user_sid: The unique SID identifier of the Twilio Unified User. + :param locale: The locale preference of the user. + + :returns: The updated FlexUserInstance + """ + return await self._proxy.update_async( + email=email, + user_sid=user_sid, + locale=locale, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FlexUserContext(InstanceContext): + + def __init__(self, version: Version, instance_sid: str, flex_user_sid: str): + """ + Initialize the FlexUserContext + + :param version: Version that contains the resource + :param instance_sid: The unique ID created by Twilio to identify a Flex instance. + :param flex_user_sid: The unique id for the flex user. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "instance_sid": instance_sid, + "flex_user_sid": flex_user_sid, + } + self._uri = "/Instances/{instance_sid}/Users/{flex_user_sid}".format( + **self._solution + ) + + def fetch(self) -> FlexUserInstance: + """ + Fetch the FlexUserInstance + + + :returns: The fetched FlexUserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FlexUserInstance( + self._version, + payload, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + + async def fetch_async(self) -> FlexUserInstance: + """ + Asynchronous coroutine to fetch the FlexUserInstance + + + :returns: The fetched FlexUserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FlexUserInstance( + self._version, + payload, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + + def update( + self, + email: Union[str, object] = values.unset, + user_sid: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + ) -> FlexUserInstance: + """ + Update the FlexUserInstance + + :param email: Email of the User. + :param user_sid: The unique SID identifier of the Twilio Unified User. + :param locale: The locale preference of the user. + + :returns: The updated FlexUserInstance + """ + + data = values.of( + { + "Email": email, + "UserSid": user_sid, + "Locale": locale, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlexUserInstance( + self._version, + payload, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + + async def update_async( + self, + email: Union[str, object] = values.unset, + user_sid: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + ) -> FlexUserInstance: + """ + Asynchronous coroutine to update the FlexUserInstance + + :param email: Email of the User. + :param user_sid: The unique SID identifier of the Twilio Unified User. + :param locale: The locale preference of the user. + + :returns: The updated FlexUserInstance + """ + + data = values.of( + { + "Email": email, + "UserSid": user_sid, + "Locale": locale, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlexUserInstance( + self._version, + payload, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FlexUserList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the FlexUserList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, instance_sid: str, flex_user_sid: str) -> FlexUserContext: + """ + Constructs a FlexUserContext + + :param instance_sid: The unique ID created by Twilio to identify a Flex instance. + :param flex_user_sid: The unique id for the flex user. + """ + return FlexUserContext( + self._version, instance_sid=instance_sid, flex_user_sid=flex_user_sid + ) + + def __call__(self, instance_sid: str, flex_user_sid: str) -> FlexUserContext: + """ + Constructs a FlexUserContext + + :param instance_sid: The unique ID created by Twilio to identify a Flex instance. + :param flex_user_sid: The unique id for the flex user. + """ + return FlexUserContext( + self._version, instance_sid=instance_sid, flex_user_sid=flex_user_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/flex_api/v2/web_channels.py b/venv/Lib/site-packages/twilio/rest/flex_api/v2/web_channels.py new file mode 100644 index 00000000..8e5aff82 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/flex_api/v2/web_channels.py @@ -0,0 +1,154 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WebChannelsInstance(InstanceResource): + """ + :ivar conversation_sid: The unique string representing the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource) created. + :ivar identity: The unique string representing the User created and should be authorized to participate in the Conversation. For more details, see [User Identity & Access Tokens](https://www.twilio.com/docs/conversations/identity). + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.identity: Optional[str] = payload.get("identity") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class WebChannelsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the WebChannelsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/WebChats" + + def create( + self, + address_sid: str, + ui_version: Union[str, object] = values.unset, + chat_friendly_name: Union[str, object] = values.unset, + customer_friendly_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + ) -> WebChannelsInstance: + """ + Create the WebChannelsInstance + + :param address_sid: The SID of the Conversations Address. See [Address Configuration Resource](https://www.twilio.com/docs/conversations/api/address-configuration-resource) for configuration details. When a conversation is created on the Flex backend, the callback URL will be set to the corresponding Studio Flow SID or webhook URL in your address configuration. + :param ui_version: The Ui-Version HTTP request header + :param chat_friendly_name: The Conversation's friendly name. See the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource) for an example. + :param customer_friendly_name: The Conversation participant's friendly name. See the [Conversation Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) for an example. + :param pre_engagement_data: The pre-engagement data. + + :returns: The created WebChannelsInstance + """ + + data = values.of( + { + "AddressSid": address_sid, + "ChatFriendlyName": chat_friendly_name, + "CustomerFriendlyName": customer_friendly_name, + "PreEngagementData": pre_engagement_data, + } + ) + headers = values.of( + { + "Ui-Version": ui_version, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebChannelsInstance(self._version, payload) + + async def create_async( + self, + address_sid: str, + ui_version: Union[str, object] = values.unset, + chat_friendly_name: Union[str, object] = values.unset, + customer_friendly_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + ) -> WebChannelsInstance: + """ + Asynchronously create the WebChannelsInstance + + :param address_sid: The SID of the Conversations Address. See [Address Configuration Resource](https://www.twilio.com/docs/conversations/api/address-configuration-resource) for configuration details. When a conversation is created on the Flex backend, the callback URL will be set to the corresponding Studio Flow SID or webhook URL in your address configuration. + :param ui_version: The Ui-Version HTTP request header + :param chat_friendly_name: The Conversation's friendly name. See the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource) for an example. + :param customer_friendly_name: The Conversation participant's friendly name. See the [Conversation Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) for an example. + :param pre_engagement_data: The pre-engagement data. + + :returns: The created WebChannelsInstance + """ + + data = values.of( + { + "AddressSid": address_sid, + "ChatFriendlyName": chat_friendly_name, + "CustomerFriendlyName": customer_friendly_name, + "PreEngagementData": pre_engagement_data, + } + ) + headers = values.of( + { + "Ui-Version": ui_version, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebChannelsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/frontline_api/FrontlineApiBase.py b/venv/Lib/site-packages/twilio/rest/frontline_api/FrontlineApiBase.py new file mode 100644 index 00000000..d9dadc16 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/frontline_api/FrontlineApiBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.frontline_api.v1 import V1 + + +class FrontlineApiBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the FrontlineApi Domain + + :returns: Domain for FrontlineApi + """ + super().__init__(twilio, "https://frontline-api.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of FrontlineApi + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/frontline_api/__init__.py b/venv/Lib/site-packages/twilio/rest/frontline_api/__init__.py new file mode 100644 index 00000000..300fafa3 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/frontline_api/__init__.py @@ -0,0 +1,15 @@ +from warnings import warn + +from twilio.rest.frontline_api.FrontlineApiBase import FrontlineApiBase +from twilio.rest.frontline_api.v1.user import UserList + + +class FrontlineApi(FrontlineApiBase): + @property + def users(self) -> UserList: + warn( + "users is deprecated. Use v1.users instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.users diff --git a/venv/Lib/site-packages/twilio/rest/frontline_api/__pycache__/FrontlineApiBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/frontline_api/__pycache__/FrontlineApiBase.cpython-312.pyc new file mode 100644 index 00000000..7c873cbf Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/frontline_api/__pycache__/FrontlineApiBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/frontline_api/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/frontline_api/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..03495895 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/frontline_api/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/frontline_api/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/frontline_api/v1/__init__.py new file mode 100644 index 00000000..610ed371 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/frontline_api/v1/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Frontline + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.frontline_api.v1.user import UserList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of FrontlineApi + + :param domain: The Twilio.frontline_api domain + """ + super().__init__(domain, "v1") + self._users: Optional[UserList] = None + + @property + def users(self) -> UserList: + if self._users is None: + self._users = UserList(self) + return self._users + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/frontline_api/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/frontline_api/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..5cdf6641 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/frontline_api/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/frontline_api/v1/__pycache__/user.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/frontline_api/v1/__pycache__/user.cpython-312.pyc new file mode 100644 index 00000000..66abf7c7 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/frontline_api/v1/__pycache__/user.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/frontline_api/v1/user.py b/venv/Lib/site-packages/twilio/rest/frontline_api/v1/user.py new file mode 100644 index 00000000..a45ed2ff --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/frontline_api/v1/user.py @@ -0,0 +1,326 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Frontline + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class UserInstance(InstanceResource): + + class StateType(object): + ACTIVE = "active" + DEACTIVATED = "deactivated" + + """ + :ivar sid: The unique string that we created to identify the User resource. + :ivar identity: The application-defined string that uniquely identifies the resource's User. This value is often a username or an email address, and is case-sensitive. + :ivar friendly_name: The string that you assigned to describe the User. + :ivar avatar: The avatar URL which will be shown in Frontline application. + :ivar state: + :ivar is_available: Whether the User is available for new conversations. Defaults to `false` for new users. + :ivar url: An absolute API resource URL for this user. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.identity: Optional[str] = payload.get("identity") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.avatar: Optional[str] = payload.get("avatar") + self.state: Optional["UserInstance.StateType"] = payload.get("state") + self.is_available: Optional[bool] = payload.get("is_available") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[UserContext] = None + + @property + def _proxy(self) -> "UserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserContext for this UserInstance + """ + if self._context is None: + self._context = UserContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "UserInstance": + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserInstance": + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + avatar: Union[str, object] = values.unset, + state: Union["UserInstance.StateType", object] = values.unset, + is_available: Union[bool, object] = values.unset, + ) -> "UserInstance": + """ + Update the UserInstance + + :param friendly_name: The string that you assigned to describe the User. + :param avatar: The avatar URL which will be shown in Frontline application. + :param state: + :param is_available: Whether the User is available for new conversations. Set to `false` to prevent User from receiving new inbound conversations if you are using [Pool Routing](https://www.twilio.com/docs/frontline/handle-incoming-conversations#3-pool-routing). + + :returns: The updated UserInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + avatar=avatar, + state=state, + is_available=is_available, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + avatar: Union[str, object] = values.unset, + state: Union["UserInstance.StateType", object] = values.unset, + is_available: Union[bool, object] = values.unset, + ) -> "UserInstance": + """ + Asynchronous coroutine to update the UserInstance + + :param friendly_name: The string that you assigned to describe the User. + :param avatar: The avatar URL which will be shown in Frontline application. + :param state: + :param is_available: Whether the User is available for new conversations. Set to `false` to prevent User from receiving new inbound conversations if you are using [Pool Routing](https://www.twilio.com/docs/frontline/handle-incoming-conversations#3-pool-routing). + + :returns: The updated UserInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + avatar=avatar, + state=state, + is_available=is_available, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the UserContext + + :param version: Version that contains the resource + :param sid: The SID of the User resource to update. This value can be either the `sid` or the `identity` of the User resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Users/{sid}".format(**self._solution) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + avatar: Union[str, object] = values.unset, + state: Union["UserInstance.StateType", object] = values.unset, + is_available: Union[bool, object] = values.unset, + ) -> UserInstance: + """ + Update the UserInstance + + :param friendly_name: The string that you assigned to describe the User. + :param avatar: The avatar URL which will be shown in Frontline application. + :param state: + :param is_available: Whether the User is available for new conversations. Set to `false` to prevent User from receiving new inbound conversations if you are using [Pool Routing](https://www.twilio.com/docs/frontline/handle-incoming-conversations#3-pool-routing). + + :returns: The updated UserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Avatar": avatar, + "State": state, + "IsAvailable": serialize.boolean_to_string(is_available), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + avatar: Union[str, object] = values.unset, + state: Union["UserInstance.StateType", object] = values.unset, + is_available: Union[bool, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param friendly_name: The string that you assigned to describe the User. + :param avatar: The avatar URL which will be shown in Frontline application. + :param state: + :param is_available: Whether the User is available for new conversations. Set to `false` to prevent User from receiving new inbound conversations if you are using [Pool Routing](https://www.twilio.com/docs/frontline/handle-incoming-conversations#3-pool-routing). + + :returns: The updated UserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Avatar": avatar, + "State": state, + "IsAvailable": serialize.boolean_to_string(is_available), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the UserList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: The SID of the User resource to update. This value can be either the `sid` or the `identity` of the User resource to update. + """ + return UserContext(self._version, sid=sid) + + def __call__(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: The SID of the User resource to update. This value can be either the `sid` or the `identity` of the User resource to update. + """ + return UserContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/iam/IamBase.py b/venv/Lib/site-packages/twilio/rest/iam/IamBase.py new file mode 100644 index 00000000..2882ec14 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/iam/IamBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.iam.v1 import V1 + + +class IamBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Iam Domain + + :returns: Domain for Iam + """ + super().__init__(twilio, "https://iam.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Iam + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/iam/__init__.py b/venv/Lib/site-packages/twilio/rest/iam/__init__.py new file mode 100644 index 00000000..994ecee6 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/iam/__init__.py @@ -0,0 +1,25 @@ +from warnings import warn + +from twilio.rest.iam.IamBase import IamBase +from twilio.rest.iam.v1.api_key import ApiKeyList +from twilio.rest.iam.v1.get_api_keys import GetApiKeysList + + +class Iam(IamBase): + @property + def api_key(self) -> ApiKeyList: + warn( + "api_key is deprecated. Use v1.api_key instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.api_key + + @property + def get_api_keys(self) -> GetApiKeysList: + warn( + "get_api_keys is deprecated. Use v1.get_api_keys instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.get_api_keys diff --git a/venv/Lib/site-packages/twilio/rest/iam/__pycache__/IamBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/iam/__pycache__/IamBase.cpython-312.pyc new file mode 100644 index 00000000..bca5507f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/iam/__pycache__/IamBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/iam/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/iam/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..36c0940b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/iam/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/iam/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/iam/v1/__init__.py new file mode 100644 index 00000000..08c45435 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/iam/v1/__init__.py @@ -0,0 +1,67 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Iam + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.iam.v1.api_key import ApiKeyList +from twilio.rest.iam.v1.get_api_keys import GetApiKeysList +from twilio.rest.iam.v1.new_api_key import NewApiKeyList +from twilio.rest.iam.v1.token import TokenList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Iam + + :param domain: The Twilio.iam domain + """ + super().__init__(domain, "v1") + self._api_key: Optional[ApiKeyList] = None + self._get_api_keys: Optional[GetApiKeysList] = None + self._new_api_key: Optional[NewApiKeyList] = None + self._token: Optional[TokenList] = None + + @property + def api_key(self) -> ApiKeyList: + if self._api_key is None: + self._api_key = ApiKeyList(self) + return self._api_key + + @property + def get_api_keys(self) -> GetApiKeysList: + if self._get_api_keys is None: + self._get_api_keys = GetApiKeysList(self) + return self._get_api_keys + + @property + def new_api_key(self) -> NewApiKeyList: + if self._new_api_key is None: + self._new_api_key = NewApiKeyList(self) + return self._new_api_key + + @property + def token(self) -> TokenList: + if self._token is None: + self._token = TokenList(self) + return self._token + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/iam/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/iam/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..67c7de22 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/iam/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/iam/v1/__pycache__/api_key.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/iam/v1/__pycache__/api_key.cpython-312.pyc new file mode 100644 index 00000000..8026913d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/iam/v1/__pycache__/api_key.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/iam/v1/__pycache__/get_api_keys.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/iam/v1/__pycache__/get_api_keys.cpython-312.pyc new file mode 100644 index 00000000..3a70dd63 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/iam/v1/__pycache__/get_api_keys.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/iam/v1/__pycache__/new_api_key.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/iam/v1/__pycache__/new_api_key.cpython-312.pyc new file mode 100644 index 00000000..11c56f25 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/iam/v1/__pycache__/new_api_key.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/iam/v1/__pycache__/token.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/iam/v1/__pycache__/token.cpython-312.pyc new file mode 100644 index 00000000..170cc389 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/iam/v1/__pycache__/token.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/iam/v1/api_key.py b/venv/Lib/site-packages/twilio/rest/iam/v1/api_key.py new file mode 100644 index 00000000..f07512c0 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/iam/v1/api_key.py @@ -0,0 +1,342 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Iam + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ApiKeyInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Key resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar policy: The \\`Policy\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.policy: Optional[Dict[str, object]] = payload.get("policy") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ApiKeyContext] = None + + @property + def _proxy(self) -> "ApiKeyContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ApiKeyContext for this ApiKeyInstance + """ + if self._context is None: + self._context = ApiKeyContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ApiKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ApiKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ApiKeyInstance": + """ + Fetch the ApiKeyInstance + + + :returns: The fetched ApiKeyInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ApiKeyInstance": + """ + Asynchronous coroutine to fetch the ApiKeyInstance + + + :returns: The fetched ApiKeyInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> "ApiKeyInstance": + """ + Update the ApiKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). + + :returns: The updated ApiKeyInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + policy=policy, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> "ApiKeyInstance": + """ + Asynchronous coroutine to update the ApiKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). + + :returns: The updated ApiKeyInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + policy=policy, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ApiKeyContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ApiKeyContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Key resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Keys/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the ApiKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ApiKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ApiKeyInstance: + """ + Fetch the ApiKeyInstance + + + :returns: The fetched ApiKeyInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ApiKeyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ApiKeyInstance: + """ + Asynchronous coroutine to fetch the ApiKeyInstance + + + :returns: The fetched ApiKeyInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ApiKeyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> ApiKeyInstance: + """ + Update the ApiKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). + + :returns: The updated ApiKeyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Policy": serialize.object(policy), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ApiKeyInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> ApiKeyInstance: + """ + Asynchronous coroutine to update the ApiKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). + + :returns: The updated ApiKeyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Policy": serialize.object(policy), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ApiKeyInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ApiKeyList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ApiKeyList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, sid: str) -> ApiKeyContext: + """ + Constructs a ApiKeyContext + + :param sid: The Twilio-provided string that uniquely identifies the Key resource to update. + """ + return ApiKeyContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ApiKeyContext: + """ + Constructs a ApiKeyContext + + :param sid: The Twilio-provided string that uniquely identifies the Key resource to update. + """ + return ApiKeyContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/iam/v1/get_api_keys.py b/venv/Lib/site-packages/twilio/rest/iam/v1/get_api_keys.py new file mode 100644 index 00000000..03b29cdb --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/iam/v1/get_api_keys.py @@ -0,0 +1,304 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Iam + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class GetApiKeysInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Key resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class GetApiKeysPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> GetApiKeysInstance: + """ + Build an instance of GetApiKeysInstance + + :param payload: Payload response from the API + """ + return GetApiKeysInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class GetApiKeysList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the GetApiKeysList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Keys" + + def stream( + self, + account_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[GetApiKeysInstance]: + """ + Streams GetApiKeysInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(account_sid=account_sid, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + account_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[GetApiKeysInstance]: + """ + Asynchronously streams GetApiKeysInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + account_sid=account_sid, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + account_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[GetApiKeysInstance]: + """ + Lists GetApiKeysInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + account_sid=account_sid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + account_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[GetApiKeysInstance]: + """ + Asynchronously lists GetApiKeysInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + account_sid=account_sid, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + account_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> GetApiKeysPage: + """ + Retrieve a single page of GetApiKeysInstance records from the API. + Request is executed immediately + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of GetApiKeysInstance + """ + data = values.of( + { + "AccountSid": account_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return GetApiKeysPage(self._version, response) + + async def page_async( + self, + account_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> GetApiKeysPage: + """ + Asynchronously retrieve a single page of GetApiKeysInstance records from the API. + Request is executed immediately + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of GetApiKeysInstance + """ + data = values.of( + { + "AccountSid": account_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return GetApiKeysPage(self._version, response) + + def get_page(self, target_url: str) -> GetApiKeysPage: + """ + Retrieve a specific page of GetApiKeysInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of GetApiKeysInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return GetApiKeysPage(self._version, response) + + async def get_page_async(self, target_url: str) -> GetApiKeysPage: + """ + Asynchronously retrieve a specific page of GetApiKeysInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of GetApiKeysInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return GetApiKeysPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/iam/v1/new_api_key.py b/venv/Lib/site-packages/twilio/rest/iam/v1/new_api_key.py new file mode 100644 index 00000000..760ce79c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/iam/v1/new_api_key.py @@ -0,0 +1,157 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Iam + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NewApiKeyInstance(InstanceResource): + + class Keytype(object): + RESTRICTED = "restricted" + + """ + :ivar sid: The unique string that that we created to identify the NewKey resource. You will use this as the basic-auth `user` when authenticating to the API. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT that the API Key was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the new API Key was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar secret: The secret your application uses to sign Access Tokens and to authenticate to the REST API (you will use this as the basic-auth `password`). **Note that for security reasons, this field is ONLY returned when the API Key is first created.** + :ivar policy: Collection of allow assertions. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.secret: Optional[str] = payload.get("secret") + self.policy: Optional[Dict[str, object]] = payload.get("policy") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class NewApiKeyList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the NewApiKeyList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Keys" + + def create( + self, + account_sid: str, + friendly_name: Union[str, object] = values.unset, + key_type: Union["NewApiKeyInstance.Keytype", object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> NewApiKeyInstance: + """ + Create the NewApiKeyInstance + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param key_type: + :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). + + :returns: The created NewApiKeyInstance + """ + + data = values.of( + { + "AccountSid": account_sid, + "FriendlyName": friendly_name, + "KeyType": key_type, + "Policy": serialize.object(policy), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NewApiKeyInstance(self._version, payload) + + async def create_async( + self, + account_sid: str, + friendly_name: Union[str, object] = values.unset, + key_type: Union["NewApiKeyInstance.Keytype", object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> NewApiKeyInstance: + """ + Asynchronously create the NewApiKeyInstance + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param key_type: + :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). + + :returns: The created NewApiKeyInstance + """ + + data = values.of( + { + "AccountSid": account_sid, + "FriendlyName": friendly_name, + "KeyType": key_type, + "Policy": serialize.object(policy), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NewApiKeyInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/iam/v1/token.py b/venv/Lib/site-packages/twilio/rest/iam/v1/token.py new file mode 100644 index 00000000..50d3d119 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/iam/v1/token.py @@ -0,0 +1,170 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Iam + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TokenInstance(InstanceResource): + """ + :ivar access_token: Token which carries the necessary information to access a Twilio resource directly. + :ivar refresh_token: Token which carries the information necessary to get a new access token. + :ivar id_token: Token which carries the information necessary of user profile. + :ivar token_type: Token type + :ivar expires_in: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.access_token: Optional[str] = payload.get("access_token") + self.refresh_token: Optional[str] = payload.get("refresh_token") + self.id_token: Optional[str] = payload.get("id_token") + self.token_type: Optional[str] = payload.get("token_type") + self.expires_in: Optional[int] = payload.get("expires_in") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class TokenList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TokenList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/token" + + def create( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> TokenInstance: + """ + Create the TokenInstance + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: The created TokenInstance + """ + + data = values.of( + { + "grant_type": grant_type, + "client_id": client_id, + "client_secret": client_secret, + "code": code, + "redirect_uri": redirect_uri, + "audience": audience, + "refresh_token": refresh_token, + "scope": scope, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TokenInstance(self._version, payload) + + async def create_async( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> TokenInstance: + """ + Asynchronously create the TokenInstance + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: The created TokenInstance + """ + + data = values.of( + { + "grant_type": grant_type, + "client_id": client_id, + "client_secret": client_secret, + "code": code, + "redirect_uri": redirect_uri, + "audience": audience, + "refresh_token": refresh_token, + "scope": scope, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TokenInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/insights/InsightsBase.py b/venv/Lib/site-packages/twilio/rest/insights/InsightsBase.py new file mode 100644 index 00000000..458122ce --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/insights/InsightsBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.insights.v1 import V1 + + +class InsightsBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Insights Domain + + :returns: Domain for Insights + """ + super().__init__(twilio, "https://insights.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Insights + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/insights/__init__.py b/venv/Lib/site-packages/twilio/rest/insights/__init__.py new file mode 100644 index 00000000..0f145779 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/insights/__init__.py @@ -0,0 +1,55 @@ +from warnings import warn + +from twilio.rest.insights.InsightsBase import InsightsBase +from twilio.rest.insights.v1.call import CallList +from twilio.rest.insights.v1.call_summaries import CallSummariesList +from twilio.rest.insights.v1.conference import ConferenceList +from twilio.rest.insights.v1.room import RoomList +from twilio.rest.insights.v1.setting import SettingList + + +class Insights(InsightsBase): + @property + def settings(self) -> SettingList: + warn( + "settings is deprecated. Use v1.settings instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.settings + + @property + def calls(self) -> CallList: + warn( + "calls is deprecated. Use v1.calls instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.calls + + @property + def call_summaries(self) -> CallSummariesList: + warn( + "call_summaries is deprecated. Use v1.call_summaries instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.call_summaries + + @property + def conferences(self) -> ConferenceList: + warn( + "conferences is deprecated. Use v1.conferences instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.conferences + + @property + def rooms(self) -> RoomList: + warn( + "rooms is deprecated. Use v1.rooms instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.rooms diff --git a/venv/Lib/site-packages/twilio/rest/insights/__pycache__/InsightsBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/insights/__pycache__/InsightsBase.cpython-312.pyc new file mode 100644 index 00000000..ad107378 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/insights/__pycache__/InsightsBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/insights/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/insights/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..34ad31f1 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/insights/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/insights/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/insights/v1/__init__.py new file mode 100644 index 00000000..8f7d1946 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/insights/v1/__init__.py @@ -0,0 +1,75 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.insights.v1.call import CallList +from twilio.rest.insights.v1.call_summaries import CallSummariesList +from twilio.rest.insights.v1.conference import ConferenceList +from twilio.rest.insights.v1.room import RoomList +from twilio.rest.insights.v1.setting import SettingList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Insights + + :param domain: The Twilio.insights domain + """ + super().__init__(domain, "v1") + self._calls: Optional[CallList] = None + self._call_summaries: Optional[CallSummariesList] = None + self._conferences: Optional[ConferenceList] = None + self._rooms: Optional[RoomList] = None + self._settings: Optional[SettingList] = None + + @property + def calls(self) -> CallList: + if self._calls is None: + self._calls = CallList(self) + return self._calls + + @property + def call_summaries(self) -> CallSummariesList: + if self._call_summaries is None: + self._call_summaries = CallSummariesList(self) + return self._call_summaries + + @property + def conferences(self) -> ConferenceList: + if self._conferences is None: + self._conferences = ConferenceList(self) + return self._conferences + + @property + def rooms(self) -> RoomList: + if self._rooms is None: + self._rooms = RoomList(self) + return self._rooms + + @property + def settings(self) -> SettingList: + if self._settings is None: + self._settings = SettingList(self) + return self._settings + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/insights/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/insights/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..94f60f8b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/insights/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/insights/v1/__pycache__/call_summaries.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/insights/v1/__pycache__/call_summaries.cpython-312.pyc new file mode 100644 index 00000000..d19901aa Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/insights/v1/__pycache__/call_summaries.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/insights/v1/__pycache__/setting.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/insights/v1/__pycache__/setting.cpython-312.pyc new file mode 100644 index 00000000..9988323c Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/insights/v1/__pycache__/setting.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/insights/v1/call/__init__.py b/venv/Lib/site-packages/twilio/rest/insights/v1/call/__init__.py new file mode 100644 index 00000000..cb08aa58 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/insights/v1/call/__init__.py @@ -0,0 +1,275 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.insights.v1.call.annotation import AnnotationList +from twilio.rest.insights.v1.call.call_summary import CallSummaryList +from twilio.rest.insights.v1.call.event import EventList +from twilio.rest.insights.v1.call.metric import MetricList + + +class CallInstance(InstanceResource): + """ + :ivar sid: + :ivar url: + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CallContext] = None + + @property + def _proxy(self) -> "CallContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CallContext for this CallInstance + """ + if self._context is None: + self._context = CallContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "CallInstance": + """ + Fetch the CallInstance + + + :returns: The fetched CallInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CallInstance": + """ + Asynchronous coroutine to fetch the CallInstance + + + :returns: The fetched CallInstance + """ + return await self._proxy.fetch_async() + + @property + def annotation(self) -> AnnotationList: + """ + Access the annotation + """ + return self._proxy.annotation + + @property + def summary(self) -> CallSummaryList: + """ + Access the summary + """ + return self._proxy.summary + + @property + def events(self) -> EventList: + """ + Access the events + """ + return self._proxy.events + + @property + def metrics(self) -> MetricList: + """ + Access the metrics + """ + return self._proxy.metrics + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CallContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CallContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Voice/{sid}".format(**self._solution) + + self._annotation: Optional[AnnotationList] = None + self._summary: Optional[CallSummaryList] = None + self._events: Optional[EventList] = None + self._metrics: Optional[MetricList] = None + + def fetch(self) -> CallInstance: + """ + Fetch the CallInstance + + + :returns: The fetched CallInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CallInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CallInstance: + """ + Asynchronous coroutine to fetch the CallInstance + + + :returns: The fetched CallInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CallInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + @property + def annotation(self) -> AnnotationList: + """ + Access the annotation + """ + if self._annotation is None: + self._annotation = AnnotationList( + self._version, + self._solution["sid"], + ) + return self._annotation + + @property + def summary(self) -> CallSummaryList: + """ + Access the summary + """ + if self._summary is None: + self._summary = CallSummaryList( + self._version, + self._solution["sid"], + ) + return self._summary + + @property + def events(self) -> EventList: + """ + Access the events + """ + if self._events is None: + self._events = EventList( + self._version, + self._solution["sid"], + ) + return self._events + + @property + def metrics(self) -> MetricList: + """ + Access the metrics + """ + if self._metrics is None: + self._metrics = MetricList( + self._version, + self._solution["sid"], + ) + return self._metrics + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CallList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CallList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, sid: str) -> CallContext: + """ + Constructs a CallContext + + :param sid: + """ + return CallContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CallContext: + """ + Constructs a CallContext + + :param sid: + """ + return CallContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/insights/v1/call/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/insights/v1/call/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..5b60641e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/insights/v1/call/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/insights/v1/call/__pycache__/annotation.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/insights/v1/call/__pycache__/annotation.cpython-312.pyc new file mode 100644 index 00000000..43144622 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/insights/v1/call/__pycache__/annotation.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/insights/v1/call/__pycache__/call_summary.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/insights/v1/call/__pycache__/call_summary.cpython-312.pyc new file mode 100644 index 00000000..74e96c6c Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/insights/v1/call/__pycache__/call_summary.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/insights/v1/call/__pycache__/event.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/insights/v1/call/__pycache__/event.cpython-312.pyc new file mode 100644 index 00000000..2fb8d34b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/insights/v1/call/__pycache__/event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/insights/v1/call/__pycache__/metric.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/insights/v1/call/__pycache__/metric.cpython-312.pyc new file mode 100644 index 00000000..cc41fc60 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/insights/v1/call/__pycache__/metric.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/insights/v1/call/annotation.py b/venv/Lib/site-packages/twilio/rest/insights/v1/call/annotation.py new file mode 100644 index 00000000..6e705d39 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/insights/v1/call/annotation.py @@ -0,0 +1,395 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class AnnotationInstance(InstanceResource): + + class AnsweredBy(object): + UNKNOWN_ANSWERED_BY = "unknown_answered_by" + HUMAN = "human" + MACHINE = "machine" + + class ConnectivityIssue(object): + UNKNOWN_CONNECTIVITY_ISSUE = "unknown_connectivity_issue" + NO_CONNECTIVITY_ISSUE = "no_connectivity_issue" + INVALID_NUMBER = "invalid_number" + CALLER_ID = "caller_id" + DROPPED_CALL = "dropped_call" + NUMBER_REACHABILITY = "number_reachability" + + """ + :ivar call_sid: The unique SID identifier of the Call. + :ivar account_sid: The unique SID identifier of the Account. + :ivar answered_by: + :ivar connectivity_issue: + :ivar quality_issues: Specifies if the call had any subjective quality issues. Possible values are one or more of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, or `static_noise`. + :ivar spam: Specifies if the call was a spam call. Use this to provide feedback on whether calls placed from your account were marked as spam, or if inbound calls received by your account were unwanted spam. Is of type Boolean: true, false. Use true if the call was a spam call. + :ivar call_score: Specifies the Call Score, if available. This is of type integer. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for rating the call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :ivar comment: Specifies any comments pertaining to the call. Twilio does not treat this field as PII, so no PII should be included in comments. + :ivar incident: Incident or support ticket associated with this call. The `incident` property is of type string with a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in `incident`. + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): + super().__init__(version) + + self.call_sid: Optional[str] = payload.get("call_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.answered_by: Optional["AnnotationInstance.AnsweredBy"] = payload.get( + "answered_by" + ) + self.connectivity_issue: Optional["AnnotationInstance.ConnectivityIssue"] = ( + payload.get("connectivity_issue") + ) + self.quality_issues: Optional[List[str]] = payload.get("quality_issues") + self.spam: Optional[bool] = payload.get("spam") + self.call_score: Optional[int] = deserialize.integer(payload.get("call_score")) + self.comment: Optional[str] = payload.get("comment") + self.incident: Optional[str] = payload.get("incident") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "call_sid": call_sid, + } + self._context: Optional[AnnotationContext] = None + + @property + def _proxy(self) -> "AnnotationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AnnotationContext for this AnnotationInstance + """ + if self._context is None: + self._context = AnnotationContext( + self._version, + call_sid=self._solution["call_sid"], + ) + return self._context + + def fetch(self) -> "AnnotationInstance": + """ + Fetch the AnnotationInstance + + + :returns: The fetched AnnotationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AnnotationInstance": + """ + Asynchronous coroutine to fetch the AnnotationInstance + + + :returns: The fetched AnnotationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + answered_by: Union["AnnotationInstance.AnsweredBy", object] = values.unset, + connectivity_issue: Union[ + "AnnotationInstance.ConnectivityIssue", object + ] = values.unset, + quality_issues: Union[str, object] = values.unset, + spam: Union[bool, object] = values.unset, + call_score: Union[int, object] = values.unset, + comment: Union[str, object] = values.unset, + incident: Union[str, object] = values.unset, + ) -> "AnnotationInstance": + """ + Update the AnnotationInstance + + :param answered_by: + :param connectivity_issue: + :param quality_issues: Specify if the call had any subjective quality issues. Possible values, one or more of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. Use comma separated values to indicate multiple quality issues for the same call. + :param spam: A boolean flag to indicate if the call was a spam call. Use this to provide feedback on whether calls placed from your account were marked as spam, or if inbound calls received by your account were unwanted spam. Use `true` if the call was a spam call. + :param call_score: Specify the call score. This is of type integer. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for rating the call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param comment: Specify any comments pertaining to the call. `comment` has a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in the `comment`. + :param incident: Associate this call with an incident or support ticket. The `incident` parameter is of type string with a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in `incident`. + + :returns: The updated AnnotationInstance + """ + return self._proxy.update( + answered_by=answered_by, + connectivity_issue=connectivity_issue, + quality_issues=quality_issues, + spam=spam, + call_score=call_score, + comment=comment, + incident=incident, + ) + + async def update_async( + self, + answered_by: Union["AnnotationInstance.AnsweredBy", object] = values.unset, + connectivity_issue: Union[ + "AnnotationInstance.ConnectivityIssue", object + ] = values.unset, + quality_issues: Union[str, object] = values.unset, + spam: Union[bool, object] = values.unset, + call_score: Union[int, object] = values.unset, + comment: Union[str, object] = values.unset, + incident: Union[str, object] = values.unset, + ) -> "AnnotationInstance": + """ + Asynchronous coroutine to update the AnnotationInstance + + :param answered_by: + :param connectivity_issue: + :param quality_issues: Specify if the call had any subjective quality issues. Possible values, one or more of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. Use comma separated values to indicate multiple quality issues for the same call. + :param spam: A boolean flag to indicate if the call was a spam call. Use this to provide feedback on whether calls placed from your account were marked as spam, or if inbound calls received by your account were unwanted spam. Use `true` if the call was a spam call. + :param call_score: Specify the call score. This is of type integer. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for rating the call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param comment: Specify any comments pertaining to the call. `comment` has a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in the `comment`. + :param incident: Associate this call with an incident or support ticket. The `incident` parameter is of type string with a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in `incident`. + + :returns: The updated AnnotationInstance + """ + return await self._proxy.update_async( + answered_by=answered_by, + connectivity_issue=connectivity_issue, + quality_issues=quality_issues, + spam=spam, + call_score=call_score, + comment=comment, + incident=incident, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AnnotationContext(InstanceContext): + + def __init__(self, version: Version, call_sid: str): + """ + Initialize the AnnotationContext + + :param version: Version that contains the resource + :param call_sid: The unique string that Twilio created to identify this Call resource. It always starts with a CA. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "call_sid": call_sid, + } + self._uri = "/Voice/{call_sid}/Annotation".format(**self._solution) + + def fetch(self) -> AnnotationInstance: + """ + Fetch the AnnotationInstance + + + :returns: The fetched AnnotationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AnnotationInstance( + self._version, + payload, + call_sid=self._solution["call_sid"], + ) + + async def fetch_async(self) -> AnnotationInstance: + """ + Asynchronous coroutine to fetch the AnnotationInstance + + + :returns: The fetched AnnotationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AnnotationInstance( + self._version, + payload, + call_sid=self._solution["call_sid"], + ) + + def update( + self, + answered_by: Union["AnnotationInstance.AnsweredBy", object] = values.unset, + connectivity_issue: Union[ + "AnnotationInstance.ConnectivityIssue", object + ] = values.unset, + quality_issues: Union[str, object] = values.unset, + spam: Union[bool, object] = values.unset, + call_score: Union[int, object] = values.unset, + comment: Union[str, object] = values.unset, + incident: Union[str, object] = values.unset, + ) -> AnnotationInstance: + """ + Update the AnnotationInstance + + :param answered_by: + :param connectivity_issue: + :param quality_issues: Specify if the call had any subjective quality issues. Possible values, one or more of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. Use comma separated values to indicate multiple quality issues for the same call. + :param spam: A boolean flag to indicate if the call was a spam call. Use this to provide feedback on whether calls placed from your account were marked as spam, or if inbound calls received by your account were unwanted spam. Use `true` if the call was a spam call. + :param call_score: Specify the call score. This is of type integer. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for rating the call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param comment: Specify any comments pertaining to the call. `comment` has a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in the `comment`. + :param incident: Associate this call with an incident or support ticket. The `incident` parameter is of type string with a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in `incident`. + + :returns: The updated AnnotationInstance + """ + + data = values.of( + { + "AnsweredBy": answered_by, + "ConnectivityIssue": connectivity_issue, + "QualityIssues": quality_issues, + "Spam": serialize.boolean_to_string(spam), + "CallScore": call_score, + "Comment": comment, + "Incident": incident, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AnnotationInstance( + self._version, payload, call_sid=self._solution["call_sid"] + ) + + async def update_async( + self, + answered_by: Union["AnnotationInstance.AnsweredBy", object] = values.unset, + connectivity_issue: Union[ + "AnnotationInstance.ConnectivityIssue", object + ] = values.unset, + quality_issues: Union[str, object] = values.unset, + spam: Union[bool, object] = values.unset, + call_score: Union[int, object] = values.unset, + comment: Union[str, object] = values.unset, + incident: Union[str, object] = values.unset, + ) -> AnnotationInstance: + """ + Asynchronous coroutine to update the AnnotationInstance + + :param answered_by: + :param connectivity_issue: + :param quality_issues: Specify if the call had any subjective quality issues. Possible values, one or more of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. Use comma separated values to indicate multiple quality issues for the same call. + :param spam: A boolean flag to indicate if the call was a spam call. Use this to provide feedback on whether calls placed from your account were marked as spam, or if inbound calls received by your account were unwanted spam. Use `true` if the call was a spam call. + :param call_score: Specify the call score. This is of type integer. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for rating the call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param comment: Specify any comments pertaining to the call. `comment` has a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in the `comment`. + :param incident: Associate this call with an incident or support ticket. The `incident` parameter is of type string with a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in `incident`. + + :returns: The updated AnnotationInstance + """ + + data = values.of( + { + "AnsweredBy": answered_by, + "ConnectivityIssue": connectivity_issue, + "QualityIssues": quality_issues, + "Spam": serialize.boolean_to_string(spam), + "CallScore": call_score, + "Comment": comment, + "Incident": incident, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AnnotationInstance( + self._version, payload, call_sid=self._solution["call_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AnnotationList(ListResource): + + def __init__(self, version: Version, call_sid: str): + """ + Initialize the AnnotationList + + :param version: Version that contains the resource + :param call_sid: The unique SID identifier of the Call. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "call_sid": call_sid, + } + + def get(self) -> AnnotationContext: + """ + Constructs a AnnotationContext + + """ + return AnnotationContext(self._version, call_sid=self._solution["call_sid"]) + + def __call__(self) -> AnnotationContext: + """ + Constructs a AnnotationContext + + """ + return AnnotationContext(self._version, call_sid=self._solution["call_sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/insights/v1/call/call_summary.py b/venv/Lib/site-packages/twilio/rest/insights/v1/call/call_summary.py new file mode 100644 index 00000000..e21af100 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/insights/v1/call/call_summary.py @@ -0,0 +1,321 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class CallSummaryInstance(InstanceResource): + + class AnsweredBy(object): + UNKNOWN = "unknown" + MACHINE_START = "machine_start" + MACHINE_END_BEEP = "machine_end_beep" + MACHINE_END_SILENCE = "machine_end_silence" + MACHINE_END_OTHER = "machine_end_other" + HUMAN = "human" + FAX = "fax" + + class CallState(object): + RINGING = "ringing" + COMPLETED = "completed" + BUSY = "busy" + FAIL = "fail" + NOANSWER = "noanswer" + CANCELED = "canceled" + ANSWERED = "answered" + UNDIALED = "undialed" + + class CallType(object): + CARRIER = "carrier" + SIP = "sip" + TRUNKING = "trunking" + CLIENT = "client" + WHATSAPP = "whatsapp" + + class ProcessingState(object): + COMPLETE = "complete" + PARTIAL = "partial" + + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar call_sid: The unique SID identifier of the Call. + :ivar call_type: + :ivar call_state: + :ivar answered_by: + :ivar processing_state: + :ivar created_time: The time at which the Call was created, given in ISO 8601 format. Can be different from `start_time` in the event of queueing due to CPS + :ivar start_time: The time at which the Call was started, given in ISO 8601 format. + :ivar end_time: The time at which the Call was ended, given in ISO 8601 format. + :ivar duration: Duration between when the call was initiated and the call was ended + :ivar connect_duration: Duration between when the call was answered and when it ended + :ivar _from: The calling party. + :ivar to: The called party. + :ivar carrier_edge: Contains metrics and properties for the Twilio media gateway of a PSTN call. + :ivar client_edge: Contains metrics and properties for the Twilio media gateway of a Client call. + :ivar sdk_edge: Contains metrics and properties for the SDK sensor library for Client calls. + :ivar sip_edge: Contains metrics and properties for the Twilio media gateway of a SIP Interface or Trunking call. + :ivar tags: Tags applied to calls by Voice Insights analysis indicating a condition that could result in subjective degradation of the call quality. + :ivar url: The URL of this resource. + :ivar attributes: Attributes capturing call-flow-specific details. + :ivar properties: Contains edge-agnostic call-level details. + :ivar trust: Contains trusted communications details including Branded Call and verified caller ID. + :ivar annotation: Programmatically labeled annotations for the Call. Developers can update the Call Summary records with Annotation during or after a Call. Annotations can be updated as long as the Call Summary record is addressable via the API. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.call_sid: Optional[str] = payload.get("call_sid") + self.call_type: Optional["CallSummaryInstance.CallType"] = payload.get( + "call_type" + ) + self.call_state: Optional["CallSummaryInstance.CallState"] = payload.get( + "call_state" + ) + self.answered_by: Optional["CallSummaryInstance.AnsweredBy"] = payload.get( + "answered_by" + ) + self.processing_state: Optional["CallSummaryInstance.ProcessingState"] = ( + payload.get("processing_state") + ) + self.created_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("created_time") + ) + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.duration: Optional[int] = deserialize.integer(payload.get("duration")) + self.connect_duration: Optional[int] = deserialize.integer( + payload.get("connect_duration") + ) + self._from: Optional[Dict[str, object]] = payload.get("from") + self.to: Optional[Dict[str, object]] = payload.get("to") + self.carrier_edge: Optional[Dict[str, object]] = payload.get("carrier_edge") + self.client_edge: Optional[Dict[str, object]] = payload.get("client_edge") + self.sdk_edge: Optional[Dict[str, object]] = payload.get("sdk_edge") + self.sip_edge: Optional[Dict[str, object]] = payload.get("sip_edge") + self.tags: Optional[List[str]] = payload.get("tags") + self.url: Optional[str] = payload.get("url") + self.attributes: Optional[Dict[str, object]] = payload.get("attributes") + self.properties: Optional[Dict[str, object]] = payload.get("properties") + self.trust: Optional[Dict[str, object]] = payload.get("trust") + self.annotation: Optional[Dict[str, object]] = payload.get("annotation") + + self._solution = { + "call_sid": call_sid, + } + self._context: Optional[CallSummaryContext] = None + + @property + def _proxy(self) -> "CallSummaryContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CallSummaryContext for this CallSummaryInstance + """ + if self._context is None: + self._context = CallSummaryContext( + self._version, + call_sid=self._solution["call_sid"], + ) + return self._context + + def fetch( + self, + processing_state: Union[ + "CallSummaryInstance.ProcessingState", object + ] = values.unset, + ) -> "CallSummaryInstance": + """ + Fetch the CallSummaryInstance + + :param processing_state: The Processing State of this Call Summary. One of `complete`, `partial` or `all`. + + :returns: The fetched CallSummaryInstance + """ + return self._proxy.fetch( + processing_state=processing_state, + ) + + async def fetch_async( + self, + processing_state: Union[ + "CallSummaryInstance.ProcessingState", object + ] = values.unset, + ) -> "CallSummaryInstance": + """ + Asynchronous coroutine to fetch the CallSummaryInstance + + :param processing_state: The Processing State of this Call Summary. One of `complete`, `partial` or `all`. + + :returns: The fetched CallSummaryInstance + """ + return await self._proxy.fetch_async( + processing_state=processing_state, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CallSummaryContext(InstanceContext): + + def __init__(self, version: Version, call_sid: str): + """ + Initialize the CallSummaryContext + + :param version: Version that contains the resource + :param call_sid: The unique SID identifier of the Call. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "call_sid": call_sid, + } + self._uri = "/Voice/{call_sid}/Summary".format(**self._solution) + + def fetch( + self, + processing_state: Union[ + "CallSummaryInstance.ProcessingState", object + ] = values.unset, + ) -> CallSummaryInstance: + """ + Fetch the CallSummaryInstance + + :param processing_state: The Processing State of this Call Summary. One of `complete`, `partial` or `all`. + + :returns: The fetched CallSummaryInstance + """ + + data = values.of( + { + "ProcessingState": processing_state, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return CallSummaryInstance( + self._version, + payload, + call_sid=self._solution["call_sid"], + ) + + async def fetch_async( + self, + processing_state: Union[ + "CallSummaryInstance.ProcessingState", object + ] = values.unset, + ) -> CallSummaryInstance: + """ + Asynchronous coroutine to fetch the CallSummaryInstance + + :param processing_state: The Processing State of this Call Summary. One of `complete`, `partial` or `all`. + + :returns: The fetched CallSummaryInstance + """ + + data = values.of( + { + "ProcessingState": processing_state, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return CallSummaryInstance( + self._version, + payload, + call_sid=self._solution["call_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CallSummaryList(ListResource): + + def __init__(self, version: Version, call_sid: str): + """ + Initialize the CallSummaryList + + :param version: Version that contains the resource + :param call_sid: The unique SID identifier of the Call. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "call_sid": call_sid, + } + + def get(self) -> CallSummaryContext: + """ + Constructs a CallSummaryContext + + """ + return CallSummaryContext(self._version, call_sid=self._solution["call_sid"]) + + def __call__(self) -> CallSummaryContext: + """ + Constructs a CallSummaryContext + + """ + return CallSummaryContext(self._version, call_sid=self._solution["call_sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/insights/v1/call/event.py b/venv/Lib/site-packages/twilio/rest/insights/v1/call/event.py new file mode 100644 index 00000000..98dce5eb --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/insights/v1/call/event.py @@ -0,0 +1,337 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class EventInstance(InstanceResource): + + class Level(object): + UNKNOWN = "UNKNOWN" + DEBUG = "DEBUG" + INFO = "INFO" + WARNING = "WARNING" + ERROR = "ERROR" + + class TwilioEdge(object): + UNKNOWN_EDGE = "unknown_edge" + CARRIER_EDGE = "carrier_edge" + SIP_EDGE = "sip_edge" + SDK_EDGE = "sdk_edge" + CLIENT_EDGE = "client_edge" + + """ + :ivar timestamp: Event time. + :ivar call_sid: The unique SID identifier of the Call. + :ivar account_sid: The unique SID identifier of the Account. + :ivar edge: + :ivar group: Event group. + :ivar level: + :ivar name: Event name. + :ivar carrier_edge: Represents the connection between Twilio and our immediate carrier partners. The events here describe the call lifecycle as reported by Twilio's carrier media gateways. + :ivar sip_edge: Represents the Twilio media gateway for SIP interface and SIP trunking calls. The events here describe the call lifecycle as reported by Twilio's public media gateways. + :ivar sdk_edge: Represents the Voice SDK running locally in the browser or in the Android/iOS application. The events here are emitted by the Voice SDK in response to certain call progress events, network changes, or call quality conditions. + :ivar client_edge: Represents the Twilio media gateway for Client calls. The events here describe the call lifecycle as reported by Twilio's Voice SDK media gateways. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): + super().__init__(version) + + self.timestamp: Optional[str] = payload.get("timestamp") + self.call_sid: Optional[str] = payload.get("call_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.edge: Optional["EventInstance.TwilioEdge"] = payload.get("edge") + self.group: Optional[str] = payload.get("group") + self.level: Optional["EventInstance.Level"] = payload.get("level") + self.name: Optional[str] = payload.get("name") + self.carrier_edge: Optional[Dict[str, object]] = payload.get("carrier_edge") + self.sip_edge: Optional[Dict[str, object]] = payload.get("sip_edge") + self.sdk_edge: Optional[Dict[str, object]] = payload.get("sdk_edge") + self.client_edge: Optional[Dict[str, object]] = payload.get("client_edge") + + self._solution = { + "call_sid": call_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EventPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EventInstance: + """ + Build an instance of EventInstance + + :param payload: Payload response from the API + """ + return EventInstance( + self._version, payload, call_sid=self._solution["call_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class EventList(ListResource): + + def __init__(self, version: Version, call_sid: str): + """ + Initialize the EventList + + :param version: Version that contains the resource + :param call_sid: The unique SID identifier of the Call. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "call_sid": call_sid, + } + self._uri = "/Voice/{call_sid}/Events".format(**self._solution) + + def stream( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EventInstance]: + """ + Streams EventInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "EventInstance.TwilioEdge" edge: The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(edge=edge, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EventInstance]: + """ + Asynchronously streams EventInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "EventInstance.TwilioEdge" edge: The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(edge=edge, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventInstance]: + """ + Lists EventInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "EventInstance.TwilioEdge" edge: The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + edge=edge, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventInstance]: + """ + Asynchronously lists EventInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "EventInstance.TwilioEdge" edge: The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + edge=edge, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EventPage: + """ + Retrieve a single page of EventInstance records from the API. + Request is executed immediately + + :param edge: The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EventInstance + """ + data = values.of( + { + "Edge": edge, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response, self._solution) + + async def page_async( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EventPage: + """ + Asynchronously retrieve a single page of EventInstance records from the API. + Request is executed immediately + + :param edge: The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EventInstance + """ + data = values.of( + { + "Edge": edge, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> EventPage: + """ + Retrieve a specific page of EventInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EventInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EventPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> EventPage: + """ + Asynchronously retrieve a specific page of EventInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EventInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EventPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/insights/v1/call/metric.py b/venv/Lib/site-packages/twilio/rest/insights/v1/call/metric.py new file mode 100644 index 00000000..77f770ae --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/insights/v1/call/metric.py @@ -0,0 +1,352 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MetricInstance(InstanceResource): + + class StreamDirection(object): + UNKNOWN = "unknown" + INBOUND = "inbound" + OUTBOUND = "outbound" + BOTH = "both" + + class TwilioEdge(object): + UNKNOWN_EDGE = "unknown_edge" + CARRIER_EDGE = "carrier_edge" + SIP_EDGE = "sip_edge" + SDK_EDGE = "sdk_edge" + CLIENT_EDGE = "client_edge" + + """ + :ivar timestamp: Timestamp of metric sample. Samples are taken every 10 seconds and contain the metrics for the previous 10 seconds. + :ivar call_sid: The unique SID identifier of the Call. + :ivar account_sid: The unique SID identifier of the Account. + :ivar edge: + :ivar direction: + :ivar carrier_edge: Contains metrics and properties for the Twilio media gateway of a PSTN call. + :ivar sip_edge: Contains metrics and properties for the Twilio media gateway of a SIP Interface or Trunking call. + :ivar sdk_edge: Contains metrics and properties for the SDK sensor library for Client calls. + :ivar client_edge: Contains metrics and properties for the Twilio media gateway of a Client call. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): + super().__init__(version) + + self.timestamp: Optional[str] = payload.get("timestamp") + self.call_sid: Optional[str] = payload.get("call_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.edge: Optional["MetricInstance.TwilioEdge"] = payload.get("edge") + self.direction: Optional["MetricInstance.StreamDirection"] = payload.get( + "direction" + ) + self.carrier_edge: Optional[Dict[str, object]] = payload.get("carrier_edge") + self.sip_edge: Optional[Dict[str, object]] = payload.get("sip_edge") + self.sdk_edge: Optional[Dict[str, object]] = payload.get("sdk_edge") + self.client_edge: Optional[Dict[str, object]] = payload.get("client_edge") + + self._solution = { + "call_sid": call_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MetricPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MetricInstance: + """ + Build an instance of MetricInstance + + :param payload: Payload response from the API + """ + return MetricInstance( + self._version, payload, call_sid=self._solution["call_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MetricList(ListResource): + + def __init__(self, version: Version, call_sid: str): + """ + Initialize the MetricList + + :param version: Version that contains the resource + :param call_sid: The unique SID identifier of the Call. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "call_sid": call_sid, + } + self._uri = "/Voice/{call_sid}/Metrics".format(**self._solution) + + def stream( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MetricInstance]: + """ + Streams MetricInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MetricInstance.TwilioEdge" edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param "MetricInstance.StreamDirection" direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(edge=edge, direction=direction, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MetricInstance]: + """ + Asynchronously streams MetricInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MetricInstance.TwilioEdge" edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param "MetricInstance.StreamDirection" direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + edge=edge, direction=direction, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MetricInstance]: + """ + Lists MetricInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MetricInstance.TwilioEdge" edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param "MetricInstance.StreamDirection" direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + edge=edge, + direction=direction, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MetricInstance]: + """ + Asynchronously lists MetricInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MetricInstance.TwilioEdge" edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param "MetricInstance.StreamDirection" direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + edge=edge, + direction=direction, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MetricPage: + """ + Retrieve a single page of MetricInstance records from the API. + Request is executed immediately + + :param edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MetricInstance + """ + data = values.of( + { + "Edge": edge, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MetricPage(self._version, response, self._solution) + + async def page_async( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MetricPage: + """ + Asynchronously retrieve a single page of MetricInstance records from the API. + Request is executed immediately + + :param edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MetricInstance + """ + data = values.of( + { + "Edge": edge, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MetricPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MetricPage: + """ + Retrieve a specific page of MetricInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MetricInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MetricPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MetricPage: + """ + Asynchronously retrieve a specific page of MetricInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MetricInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MetricPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/insights/v1/call_summaries.py b/venv/Lib/site-packages/twilio/rest/insights/v1/call_summaries.py new file mode 100644 index 00000000..0a75e384 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/insights/v1/call_summaries.py @@ -0,0 +1,973 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CallSummariesInstance(InstanceResource): + + class AnsweredBy(object): + UNKNOWN = "unknown" + MACHINE_START = "machine_start" + MACHINE_END_BEEP = "machine_end_beep" + MACHINE_END_SILENCE = "machine_end_silence" + MACHINE_END_OTHER = "machine_end_other" + HUMAN = "human" + FAX = "fax" + + class CallState(object): + RINGING = "ringing" + COMPLETED = "completed" + BUSY = "busy" + FAIL = "fail" + NOANSWER = "noanswer" + CANCELED = "canceled" + ANSWERED = "answered" + UNDIALED = "undialed" + + class CallType(object): + CARRIER = "carrier" + SIP = "sip" + TRUNKING = "trunking" + CLIENT = "client" + WHATSAPP = "whatsapp" + + class ProcessingState(object): + COMPLETE = "complete" + PARTIAL = "partial" + + class ProcessingStateRequest(object): + COMPLETED = "completed" + STARTED = "started" + PARTIAL = "partial" + ALL = "all" + + class SortBy(object): + START_TIME = "start_time" + END_TIME = "end_time" + + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar call_sid: The unique SID identifier of the Call. + :ivar answered_by: + :ivar call_type: + :ivar call_state: + :ivar processing_state: + :ivar created_time: The time at which the Call was created, given in ISO 8601 format. Can be different from `start_time` in the event of queueing due to CPS + :ivar start_time: The time at which the Call was started, given in ISO 8601 format. + :ivar end_time: The time at which the Call was ended, given in ISO 8601 format. + :ivar duration: Duration between when the call was initiated and the call was ended + :ivar connect_duration: Duration between when the call was answered and when it ended + :ivar _from: The calling party. + :ivar to: The called party. + :ivar carrier_edge: Contains metrics and properties for the Twilio media gateway of a PSTN call. + :ivar client_edge: Contains metrics and properties for the Twilio media gateway of a Client call. + :ivar sdk_edge: Contains metrics and properties for the SDK sensor library for Client calls. + :ivar sip_edge: Contains metrics and properties for the Twilio media gateway of a SIP Interface or Trunking call. + :ivar tags: Tags applied to calls by Voice Insights analysis indicating a condition that could result in subjective degradation of the call quality. + :ivar url: The URL of this resource. + :ivar attributes: Attributes capturing call-flow-specific details. + :ivar properties: Contains edge-agnostic call-level details. + :ivar trust: Contains trusted communications details including Branded Call and verified caller ID. + :ivar annotation: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.call_sid: Optional[str] = payload.get("call_sid") + self.answered_by: Optional["CallSummariesInstance.AnsweredBy"] = payload.get( + "answered_by" + ) + self.call_type: Optional["CallSummariesInstance.CallType"] = payload.get( + "call_type" + ) + self.call_state: Optional["CallSummariesInstance.CallState"] = payload.get( + "call_state" + ) + self.processing_state: Optional["CallSummariesInstance.ProcessingState"] = ( + payload.get("processing_state") + ) + self.created_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("created_time") + ) + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.duration: Optional[int] = deserialize.integer(payload.get("duration")) + self.connect_duration: Optional[int] = deserialize.integer( + payload.get("connect_duration") + ) + self._from: Optional[Dict[str, object]] = payload.get("from") + self.to: Optional[Dict[str, object]] = payload.get("to") + self.carrier_edge: Optional[Dict[str, object]] = payload.get("carrier_edge") + self.client_edge: Optional[Dict[str, object]] = payload.get("client_edge") + self.sdk_edge: Optional[Dict[str, object]] = payload.get("sdk_edge") + self.sip_edge: Optional[Dict[str, object]] = payload.get("sip_edge") + self.tags: Optional[List[str]] = payload.get("tags") + self.url: Optional[str] = payload.get("url") + self.attributes: Optional[Dict[str, object]] = payload.get("attributes") + self.properties: Optional[Dict[str, object]] = payload.get("properties") + self.trust: Optional[Dict[str, object]] = payload.get("trust") + self.annotation: Optional[Dict[str, object]] = payload.get("annotation") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class CallSummariesPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CallSummariesInstance: + """ + Build an instance of CallSummariesInstance + + :param payload: Payload response from the API + """ + return CallSummariesInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CallSummariesList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CallSummariesList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Voice/Summaries" + + def stream( + self, + from_: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_carrier: Union[str, object] = values.unset, + to_carrier: Union[str, object] = values.unset, + from_country_code: Union[str, object] = values.unset, + to_country_code: Union[str, object] = values.unset, + verified_caller: Union[bool, object] = values.unset, + has_tag: Union[bool, object] = values.unset, + start_time: Union[str, object] = values.unset, + end_time: Union[str, object] = values.unset, + call_type: Union[str, object] = values.unset, + call_state: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + processing_state: Union[ + "CallSummariesInstance.ProcessingStateRequest", object + ] = values.unset, + sort_by: Union["CallSummariesInstance.SortBy", object] = values.unset, + subaccount: Union[str, object] = values.unset, + abnormal_session: Union[bool, object] = values.unset, + answered_by: Union["CallSummariesInstance.AnsweredBy", object] = values.unset, + answered_by_annotation: Union[str, object] = values.unset, + connectivity_issue_annotation: Union[str, object] = values.unset, + quality_issue_annotation: Union[str, object] = values.unset, + spam_annotation: Union[bool, object] = values.unset, + call_score_annotation: Union[str, object] = values.unset, + branded_enabled: Union[bool, object] = values.unset, + voice_integrity_enabled: Union[bool, object] = values.unset, + branded_bundle_sid: Union[str, object] = values.unset, + voice_integrity_bundle_sid: Union[str, object] = values.unset, + voice_integrity_use_case: Union[str, object] = values.unset, + business_profile_identity: Union[str, object] = values.unset, + business_profile_industry: Union[str, object] = values.unset, + business_profile_bundle_sid: Union[str, object] = values.unset, + business_profile_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CallSummariesInstance]: + """ + Streams CallSummariesInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str from_: A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str to: A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str from_carrier: An origination carrier. + :param str to_carrier: A destination carrier. + :param str from_country_code: A source country code based on phone number in From. + :param str to_country_code: A destination country code. Based on phone number in To. + :param bool verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of 'true' or 'false'. + :param bool has_tag: A boolean flag indicating the presence of one or more [Voice Insights Call Tags](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-tags). + :param str start_time: A Start time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 4h. + :param str end_time: An End Time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 0m. + :param str call_type: A Call Type of the calls. One of `carrier`, `sip`, `trunking` or `client`. + :param str call_state: A Call State of the calls. One of `ringing`, `completed`, `busy`, `fail`, `noanswer`, `canceled`, `answered`, `undialed`. + :param str direction: A Direction of the calls. One of `outbound_api`, `outbound_dial`, `inbound`, `trunking_originating`, `trunking_terminating`. + :param "CallSummariesInstance.ProcessingStateRequest" processing_state: A Processing State of the Call Summaries. One of `completed`, `partial` or `all`. + :param "CallSummariesInstance.SortBy" sort_by: A Sort By criterion for the returned list of Call Summaries. One of `start_time` or `end_time`. + :param str subaccount: A unique SID identifier of a Subaccount. + :param bool abnormal_session: A boolean flag indicating an abnormal session where the last SIP response was not 200 OK. + :param "CallSummariesInstance.AnsweredBy" answered_by: An Answered By value for the calls based on `Answering Machine Detection (AMD)`. One of `unknown`, `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `human` or `fax`. + :param str answered_by_annotation: Either machine or human. + :param str connectivity_issue_annotation: A Connectivity Issue with the calls. One of `no_connectivity_issue`, `invalid_number`, `caller_id`, `dropped_call`, or `number_reachability`. + :param str quality_issue_annotation: A subjective Quality Issue with the calls. One of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. + :param bool spam_annotation: A boolean flag indicating spam calls. + :param str call_score_annotation: A Call Score of the calls. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for the rated call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param bool branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' + :param bool voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' + :param str branded_bundle_sid: A unique SID identifier of the Branded Call. + :param str voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. + :param str voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. + :param str business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. + :param str business_profile_industry: A Business Industry of the calls. Is of type enum. One of 'automotive', 'agriculture', 'banking', 'consumer', 'construction', 'education', 'engineering', 'energy', 'oil_and_gas', 'fast_moving_consumer_goods', 'financial', 'fintech', 'food_and_beverage', 'government', 'healthcare', 'hospitality', 'insurance', 'legal', 'manufacturing', 'media', 'online', 'professional_services', 'raw_materials', 'real_estate', 'religion', 'retail', 'jewelry', 'technology', 'telecommunications', 'transportation', 'travel', 'electronics', 'not_for_profit' + :param str business_profile_bundle_sid: A unique SID identifier of the Business Profile. + :param str business_profile_type: A Business Profile Type of the calls. Is of type enum. One of 'primary', 'secondary'. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + from_=from_, + to=to, + from_carrier=from_carrier, + to_carrier=to_carrier, + from_country_code=from_country_code, + to_country_code=to_country_code, + verified_caller=verified_caller, + has_tag=has_tag, + start_time=start_time, + end_time=end_time, + call_type=call_type, + call_state=call_state, + direction=direction, + processing_state=processing_state, + sort_by=sort_by, + subaccount=subaccount, + abnormal_session=abnormal_session, + answered_by=answered_by, + answered_by_annotation=answered_by_annotation, + connectivity_issue_annotation=connectivity_issue_annotation, + quality_issue_annotation=quality_issue_annotation, + spam_annotation=spam_annotation, + call_score_annotation=call_score_annotation, + branded_enabled=branded_enabled, + voice_integrity_enabled=voice_integrity_enabled, + branded_bundle_sid=branded_bundle_sid, + voice_integrity_bundle_sid=voice_integrity_bundle_sid, + voice_integrity_use_case=voice_integrity_use_case, + business_profile_identity=business_profile_identity, + business_profile_industry=business_profile_industry, + business_profile_bundle_sid=business_profile_bundle_sid, + business_profile_type=business_profile_type, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + from_: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_carrier: Union[str, object] = values.unset, + to_carrier: Union[str, object] = values.unset, + from_country_code: Union[str, object] = values.unset, + to_country_code: Union[str, object] = values.unset, + verified_caller: Union[bool, object] = values.unset, + has_tag: Union[bool, object] = values.unset, + start_time: Union[str, object] = values.unset, + end_time: Union[str, object] = values.unset, + call_type: Union[str, object] = values.unset, + call_state: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + processing_state: Union[ + "CallSummariesInstance.ProcessingStateRequest", object + ] = values.unset, + sort_by: Union["CallSummariesInstance.SortBy", object] = values.unset, + subaccount: Union[str, object] = values.unset, + abnormal_session: Union[bool, object] = values.unset, + answered_by: Union["CallSummariesInstance.AnsweredBy", object] = values.unset, + answered_by_annotation: Union[str, object] = values.unset, + connectivity_issue_annotation: Union[str, object] = values.unset, + quality_issue_annotation: Union[str, object] = values.unset, + spam_annotation: Union[bool, object] = values.unset, + call_score_annotation: Union[str, object] = values.unset, + branded_enabled: Union[bool, object] = values.unset, + voice_integrity_enabled: Union[bool, object] = values.unset, + branded_bundle_sid: Union[str, object] = values.unset, + voice_integrity_bundle_sid: Union[str, object] = values.unset, + voice_integrity_use_case: Union[str, object] = values.unset, + business_profile_identity: Union[str, object] = values.unset, + business_profile_industry: Union[str, object] = values.unset, + business_profile_bundle_sid: Union[str, object] = values.unset, + business_profile_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CallSummariesInstance]: + """ + Asynchronously streams CallSummariesInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str from_: A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str to: A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str from_carrier: An origination carrier. + :param str to_carrier: A destination carrier. + :param str from_country_code: A source country code based on phone number in From. + :param str to_country_code: A destination country code. Based on phone number in To. + :param bool verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of 'true' or 'false'. + :param bool has_tag: A boolean flag indicating the presence of one or more [Voice Insights Call Tags](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-tags). + :param str start_time: A Start time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 4h. + :param str end_time: An End Time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 0m. + :param str call_type: A Call Type of the calls. One of `carrier`, `sip`, `trunking` or `client`. + :param str call_state: A Call State of the calls. One of `ringing`, `completed`, `busy`, `fail`, `noanswer`, `canceled`, `answered`, `undialed`. + :param str direction: A Direction of the calls. One of `outbound_api`, `outbound_dial`, `inbound`, `trunking_originating`, `trunking_terminating`. + :param "CallSummariesInstance.ProcessingStateRequest" processing_state: A Processing State of the Call Summaries. One of `completed`, `partial` or `all`. + :param "CallSummariesInstance.SortBy" sort_by: A Sort By criterion for the returned list of Call Summaries. One of `start_time` or `end_time`. + :param str subaccount: A unique SID identifier of a Subaccount. + :param bool abnormal_session: A boolean flag indicating an abnormal session where the last SIP response was not 200 OK. + :param "CallSummariesInstance.AnsweredBy" answered_by: An Answered By value for the calls based on `Answering Machine Detection (AMD)`. One of `unknown`, `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `human` or `fax`. + :param str answered_by_annotation: Either machine or human. + :param str connectivity_issue_annotation: A Connectivity Issue with the calls. One of `no_connectivity_issue`, `invalid_number`, `caller_id`, `dropped_call`, or `number_reachability`. + :param str quality_issue_annotation: A subjective Quality Issue with the calls. One of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. + :param bool spam_annotation: A boolean flag indicating spam calls. + :param str call_score_annotation: A Call Score of the calls. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for the rated call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param bool branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' + :param bool voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' + :param str branded_bundle_sid: A unique SID identifier of the Branded Call. + :param str voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. + :param str voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. + :param str business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. + :param str business_profile_industry: A Business Industry of the calls. Is of type enum. One of 'automotive', 'agriculture', 'banking', 'consumer', 'construction', 'education', 'engineering', 'energy', 'oil_and_gas', 'fast_moving_consumer_goods', 'financial', 'fintech', 'food_and_beverage', 'government', 'healthcare', 'hospitality', 'insurance', 'legal', 'manufacturing', 'media', 'online', 'professional_services', 'raw_materials', 'real_estate', 'religion', 'retail', 'jewelry', 'technology', 'telecommunications', 'transportation', 'travel', 'electronics', 'not_for_profit' + :param str business_profile_bundle_sid: A unique SID identifier of the Business Profile. + :param str business_profile_type: A Business Profile Type of the calls. Is of type enum. One of 'primary', 'secondary'. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + from_=from_, + to=to, + from_carrier=from_carrier, + to_carrier=to_carrier, + from_country_code=from_country_code, + to_country_code=to_country_code, + verified_caller=verified_caller, + has_tag=has_tag, + start_time=start_time, + end_time=end_time, + call_type=call_type, + call_state=call_state, + direction=direction, + processing_state=processing_state, + sort_by=sort_by, + subaccount=subaccount, + abnormal_session=abnormal_session, + answered_by=answered_by, + answered_by_annotation=answered_by_annotation, + connectivity_issue_annotation=connectivity_issue_annotation, + quality_issue_annotation=quality_issue_annotation, + spam_annotation=spam_annotation, + call_score_annotation=call_score_annotation, + branded_enabled=branded_enabled, + voice_integrity_enabled=voice_integrity_enabled, + branded_bundle_sid=branded_bundle_sid, + voice_integrity_bundle_sid=voice_integrity_bundle_sid, + voice_integrity_use_case=voice_integrity_use_case, + business_profile_identity=business_profile_identity, + business_profile_industry=business_profile_industry, + business_profile_bundle_sid=business_profile_bundle_sid, + business_profile_type=business_profile_type, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + from_: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_carrier: Union[str, object] = values.unset, + to_carrier: Union[str, object] = values.unset, + from_country_code: Union[str, object] = values.unset, + to_country_code: Union[str, object] = values.unset, + verified_caller: Union[bool, object] = values.unset, + has_tag: Union[bool, object] = values.unset, + start_time: Union[str, object] = values.unset, + end_time: Union[str, object] = values.unset, + call_type: Union[str, object] = values.unset, + call_state: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + processing_state: Union[ + "CallSummariesInstance.ProcessingStateRequest", object + ] = values.unset, + sort_by: Union["CallSummariesInstance.SortBy", object] = values.unset, + subaccount: Union[str, object] = values.unset, + abnormal_session: Union[bool, object] = values.unset, + answered_by: Union["CallSummariesInstance.AnsweredBy", object] = values.unset, + answered_by_annotation: Union[str, object] = values.unset, + connectivity_issue_annotation: Union[str, object] = values.unset, + quality_issue_annotation: Union[str, object] = values.unset, + spam_annotation: Union[bool, object] = values.unset, + call_score_annotation: Union[str, object] = values.unset, + branded_enabled: Union[bool, object] = values.unset, + voice_integrity_enabled: Union[bool, object] = values.unset, + branded_bundle_sid: Union[str, object] = values.unset, + voice_integrity_bundle_sid: Union[str, object] = values.unset, + voice_integrity_use_case: Union[str, object] = values.unset, + business_profile_identity: Union[str, object] = values.unset, + business_profile_industry: Union[str, object] = values.unset, + business_profile_bundle_sid: Union[str, object] = values.unset, + business_profile_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CallSummariesInstance]: + """ + Lists CallSummariesInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str from_: A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str to: A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str from_carrier: An origination carrier. + :param str to_carrier: A destination carrier. + :param str from_country_code: A source country code based on phone number in From. + :param str to_country_code: A destination country code. Based on phone number in To. + :param bool verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of 'true' or 'false'. + :param bool has_tag: A boolean flag indicating the presence of one or more [Voice Insights Call Tags](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-tags). + :param str start_time: A Start time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 4h. + :param str end_time: An End Time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 0m. + :param str call_type: A Call Type of the calls. One of `carrier`, `sip`, `trunking` or `client`. + :param str call_state: A Call State of the calls. One of `ringing`, `completed`, `busy`, `fail`, `noanswer`, `canceled`, `answered`, `undialed`. + :param str direction: A Direction of the calls. One of `outbound_api`, `outbound_dial`, `inbound`, `trunking_originating`, `trunking_terminating`. + :param "CallSummariesInstance.ProcessingStateRequest" processing_state: A Processing State of the Call Summaries. One of `completed`, `partial` or `all`. + :param "CallSummariesInstance.SortBy" sort_by: A Sort By criterion for the returned list of Call Summaries. One of `start_time` or `end_time`. + :param str subaccount: A unique SID identifier of a Subaccount. + :param bool abnormal_session: A boolean flag indicating an abnormal session where the last SIP response was not 200 OK. + :param "CallSummariesInstance.AnsweredBy" answered_by: An Answered By value for the calls based on `Answering Machine Detection (AMD)`. One of `unknown`, `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `human` or `fax`. + :param str answered_by_annotation: Either machine or human. + :param str connectivity_issue_annotation: A Connectivity Issue with the calls. One of `no_connectivity_issue`, `invalid_number`, `caller_id`, `dropped_call`, or `number_reachability`. + :param str quality_issue_annotation: A subjective Quality Issue with the calls. One of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. + :param bool spam_annotation: A boolean flag indicating spam calls. + :param str call_score_annotation: A Call Score of the calls. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for the rated call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param bool branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' + :param bool voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' + :param str branded_bundle_sid: A unique SID identifier of the Branded Call. + :param str voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. + :param str voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. + :param str business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. + :param str business_profile_industry: A Business Industry of the calls. Is of type enum. One of 'automotive', 'agriculture', 'banking', 'consumer', 'construction', 'education', 'engineering', 'energy', 'oil_and_gas', 'fast_moving_consumer_goods', 'financial', 'fintech', 'food_and_beverage', 'government', 'healthcare', 'hospitality', 'insurance', 'legal', 'manufacturing', 'media', 'online', 'professional_services', 'raw_materials', 'real_estate', 'religion', 'retail', 'jewelry', 'technology', 'telecommunications', 'transportation', 'travel', 'electronics', 'not_for_profit' + :param str business_profile_bundle_sid: A unique SID identifier of the Business Profile. + :param str business_profile_type: A Business Profile Type of the calls. Is of type enum. One of 'primary', 'secondary'. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + from_=from_, + to=to, + from_carrier=from_carrier, + to_carrier=to_carrier, + from_country_code=from_country_code, + to_country_code=to_country_code, + verified_caller=verified_caller, + has_tag=has_tag, + start_time=start_time, + end_time=end_time, + call_type=call_type, + call_state=call_state, + direction=direction, + processing_state=processing_state, + sort_by=sort_by, + subaccount=subaccount, + abnormal_session=abnormal_session, + answered_by=answered_by, + answered_by_annotation=answered_by_annotation, + connectivity_issue_annotation=connectivity_issue_annotation, + quality_issue_annotation=quality_issue_annotation, + spam_annotation=spam_annotation, + call_score_annotation=call_score_annotation, + branded_enabled=branded_enabled, + voice_integrity_enabled=voice_integrity_enabled, + branded_bundle_sid=branded_bundle_sid, + voice_integrity_bundle_sid=voice_integrity_bundle_sid, + voice_integrity_use_case=voice_integrity_use_case, + business_profile_identity=business_profile_identity, + business_profile_industry=business_profile_industry, + business_profile_bundle_sid=business_profile_bundle_sid, + business_profile_type=business_profile_type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + from_: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_carrier: Union[str, object] = values.unset, + to_carrier: Union[str, object] = values.unset, + from_country_code: Union[str, object] = values.unset, + to_country_code: Union[str, object] = values.unset, + verified_caller: Union[bool, object] = values.unset, + has_tag: Union[bool, object] = values.unset, + start_time: Union[str, object] = values.unset, + end_time: Union[str, object] = values.unset, + call_type: Union[str, object] = values.unset, + call_state: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + processing_state: Union[ + "CallSummariesInstance.ProcessingStateRequest", object + ] = values.unset, + sort_by: Union["CallSummariesInstance.SortBy", object] = values.unset, + subaccount: Union[str, object] = values.unset, + abnormal_session: Union[bool, object] = values.unset, + answered_by: Union["CallSummariesInstance.AnsweredBy", object] = values.unset, + answered_by_annotation: Union[str, object] = values.unset, + connectivity_issue_annotation: Union[str, object] = values.unset, + quality_issue_annotation: Union[str, object] = values.unset, + spam_annotation: Union[bool, object] = values.unset, + call_score_annotation: Union[str, object] = values.unset, + branded_enabled: Union[bool, object] = values.unset, + voice_integrity_enabled: Union[bool, object] = values.unset, + branded_bundle_sid: Union[str, object] = values.unset, + voice_integrity_bundle_sid: Union[str, object] = values.unset, + voice_integrity_use_case: Union[str, object] = values.unset, + business_profile_identity: Union[str, object] = values.unset, + business_profile_industry: Union[str, object] = values.unset, + business_profile_bundle_sid: Union[str, object] = values.unset, + business_profile_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CallSummariesInstance]: + """ + Asynchronously lists CallSummariesInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str from_: A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str to: A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str from_carrier: An origination carrier. + :param str to_carrier: A destination carrier. + :param str from_country_code: A source country code based on phone number in From. + :param str to_country_code: A destination country code. Based on phone number in To. + :param bool verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of 'true' or 'false'. + :param bool has_tag: A boolean flag indicating the presence of one or more [Voice Insights Call Tags](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-tags). + :param str start_time: A Start time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 4h. + :param str end_time: An End Time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 0m. + :param str call_type: A Call Type of the calls. One of `carrier`, `sip`, `trunking` or `client`. + :param str call_state: A Call State of the calls. One of `ringing`, `completed`, `busy`, `fail`, `noanswer`, `canceled`, `answered`, `undialed`. + :param str direction: A Direction of the calls. One of `outbound_api`, `outbound_dial`, `inbound`, `trunking_originating`, `trunking_terminating`. + :param "CallSummariesInstance.ProcessingStateRequest" processing_state: A Processing State of the Call Summaries. One of `completed`, `partial` or `all`. + :param "CallSummariesInstance.SortBy" sort_by: A Sort By criterion for the returned list of Call Summaries. One of `start_time` or `end_time`. + :param str subaccount: A unique SID identifier of a Subaccount. + :param bool abnormal_session: A boolean flag indicating an abnormal session where the last SIP response was not 200 OK. + :param "CallSummariesInstance.AnsweredBy" answered_by: An Answered By value for the calls based on `Answering Machine Detection (AMD)`. One of `unknown`, `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `human` or `fax`. + :param str answered_by_annotation: Either machine or human. + :param str connectivity_issue_annotation: A Connectivity Issue with the calls. One of `no_connectivity_issue`, `invalid_number`, `caller_id`, `dropped_call`, or `number_reachability`. + :param str quality_issue_annotation: A subjective Quality Issue with the calls. One of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. + :param bool spam_annotation: A boolean flag indicating spam calls. + :param str call_score_annotation: A Call Score of the calls. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for the rated call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param bool branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' + :param bool voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' + :param str branded_bundle_sid: A unique SID identifier of the Branded Call. + :param str voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. + :param str voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. + :param str business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. + :param str business_profile_industry: A Business Industry of the calls. Is of type enum. One of 'automotive', 'agriculture', 'banking', 'consumer', 'construction', 'education', 'engineering', 'energy', 'oil_and_gas', 'fast_moving_consumer_goods', 'financial', 'fintech', 'food_and_beverage', 'government', 'healthcare', 'hospitality', 'insurance', 'legal', 'manufacturing', 'media', 'online', 'professional_services', 'raw_materials', 'real_estate', 'religion', 'retail', 'jewelry', 'technology', 'telecommunications', 'transportation', 'travel', 'electronics', 'not_for_profit' + :param str business_profile_bundle_sid: A unique SID identifier of the Business Profile. + :param str business_profile_type: A Business Profile Type of the calls. Is of type enum. One of 'primary', 'secondary'. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + from_=from_, + to=to, + from_carrier=from_carrier, + to_carrier=to_carrier, + from_country_code=from_country_code, + to_country_code=to_country_code, + verified_caller=verified_caller, + has_tag=has_tag, + start_time=start_time, + end_time=end_time, + call_type=call_type, + call_state=call_state, + direction=direction, + processing_state=processing_state, + sort_by=sort_by, + subaccount=subaccount, + abnormal_session=abnormal_session, + answered_by=answered_by, + answered_by_annotation=answered_by_annotation, + connectivity_issue_annotation=connectivity_issue_annotation, + quality_issue_annotation=quality_issue_annotation, + spam_annotation=spam_annotation, + call_score_annotation=call_score_annotation, + branded_enabled=branded_enabled, + voice_integrity_enabled=voice_integrity_enabled, + branded_bundle_sid=branded_bundle_sid, + voice_integrity_bundle_sid=voice_integrity_bundle_sid, + voice_integrity_use_case=voice_integrity_use_case, + business_profile_identity=business_profile_identity, + business_profile_industry=business_profile_industry, + business_profile_bundle_sid=business_profile_bundle_sid, + business_profile_type=business_profile_type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + from_: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_carrier: Union[str, object] = values.unset, + to_carrier: Union[str, object] = values.unset, + from_country_code: Union[str, object] = values.unset, + to_country_code: Union[str, object] = values.unset, + verified_caller: Union[bool, object] = values.unset, + has_tag: Union[bool, object] = values.unset, + start_time: Union[str, object] = values.unset, + end_time: Union[str, object] = values.unset, + call_type: Union[str, object] = values.unset, + call_state: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + processing_state: Union[ + "CallSummariesInstance.ProcessingStateRequest", object + ] = values.unset, + sort_by: Union["CallSummariesInstance.SortBy", object] = values.unset, + subaccount: Union[str, object] = values.unset, + abnormal_session: Union[bool, object] = values.unset, + answered_by: Union["CallSummariesInstance.AnsweredBy", object] = values.unset, + answered_by_annotation: Union[str, object] = values.unset, + connectivity_issue_annotation: Union[str, object] = values.unset, + quality_issue_annotation: Union[str, object] = values.unset, + spam_annotation: Union[bool, object] = values.unset, + call_score_annotation: Union[str, object] = values.unset, + branded_enabled: Union[bool, object] = values.unset, + voice_integrity_enabled: Union[bool, object] = values.unset, + branded_bundle_sid: Union[str, object] = values.unset, + voice_integrity_bundle_sid: Union[str, object] = values.unset, + voice_integrity_use_case: Union[str, object] = values.unset, + business_profile_identity: Union[str, object] = values.unset, + business_profile_industry: Union[str, object] = values.unset, + business_profile_bundle_sid: Union[str, object] = values.unset, + business_profile_type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CallSummariesPage: + """ + Retrieve a single page of CallSummariesInstance records from the API. + Request is executed immediately + + :param from_: A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param to: A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param from_carrier: An origination carrier. + :param to_carrier: A destination carrier. + :param from_country_code: A source country code based on phone number in From. + :param to_country_code: A destination country code. Based on phone number in To. + :param verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of 'true' or 'false'. + :param has_tag: A boolean flag indicating the presence of one or more [Voice Insights Call Tags](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-tags). + :param start_time: A Start time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 4h. + :param end_time: An End Time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 0m. + :param call_type: A Call Type of the calls. One of `carrier`, `sip`, `trunking` or `client`. + :param call_state: A Call State of the calls. One of `ringing`, `completed`, `busy`, `fail`, `noanswer`, `canceled`, `answered`, `undialed`. + :param direction: A Direction of the calls. One of `outbound_api`, `outbound_dial`, `inbound`, `trunking_originating`, `trunking_terminating`. + :param processing_state: A Processing State of the Call Summaries. One of `completed`, `partial` or `all`. + :param sort_by: A Sort By criterion for the returned list of Call Summaries. One of `start_time` or `end_time`. + :param subaccount: A unique SID identifier of a Subaccount. + :param abnormal_session: A boolean flag indicating an abnormal session where the last SIP response was not 200 OK. + :param answered_by: An Answered By value for the calls based on `Answering Machine Detection (AMD)`. One of `unknown`, `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `human` or `fax`. + :param answered_by_annotation: Either machine or human. + :param connectivity_issue_annotation: A Connectivity Issue with the calls. One of `no_connectivity_issue`, `invalid_number`, `caller_id`, `dropped_call`, or `number_reachability`. + :param quality_issue_annotation: A subjective Quality Issue with the calls. One of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. + :param spam_annotation: A boolean flag indicating spam calls. + :param call_score_annotation: A Call Score of the calls. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for the rated call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' + :param voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' + :param branded_bundle_sid: A unique SID identifier of the Branded Call. + :param voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. + :param voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. + :param business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. + :param business_profile_industry: A Business Industry of the calls. Is of type enum. One of 'automotive', 'agriculture', 'banking', 'consumer', 'construction', 'education', 'engineering', 'energy', 'oil_and_gas', 'fast_moving_consumer_goods', 'financial', 'fintech', 'food_and_beverage', 'government', 'healthcare', 'hospitality', 'insurance', 'legal', 'manufacturing', 'media', 'online', 'professional_services', 'raw_materials', 'real_estate', 'religion', 'retail', 'jewelry', 'technology', 'telecommunications', 'transportation', 'travel', 'electronics', 'not_for_profit' + :param business_profile_bundle_sid: A unique SID identifier of the Business Profile. + :param business_profile_type: A Business Profile Type of the calls. Is of type enum. One of 'primary', 'secondary'. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CallSummariesInstance + """ + data = values.of( + { + "From": from_, + "To": to, + "FromCarrier": from_carrier, + "ToCarrier": to_carrier, + "FromCountryCode": from_country_code, + "ToCountryCode": to_country_code, + "VerifiedCaller": serialize.boolean_to_string(verified_caller), + "HasTag": serialize.boolean_to_string(has_tag), + "StartTime": start_time, + "EndTime": end_time, + "CallType": call_type, + "CallState": call_state, + "Direction": direction, + "ProcessingState": processing_state, + "SortBy": sort_by, + "Subaccount": subaccount, + "AbnormalSession": serialize.boolean_to_string(abnormal_session), + "AnsweredBy": answered_by, + "AnsweredByAnnotation": answered_by_annotation, + "ConnectivityIssueAnnotation": connectivity_issue_annotation, + "QualityIssueAnnotation": quality_issue_annotation, + "SpamAnnotation": serialize.boolean_to_string(spam_annotation), + "CallScoreAnnotation": call_score_annotation, + "BrandedEnabled": serialize.boolean_to_string(branded_enabled), + "VoiceIntegrityEnabled": serialize.boolean_to_string( + voice_integrity_enabled + ), + "BrandedBundleSid": branded_bundle_sid, + "VoiceIntegrityBundleSid": voice_integrity_bundle_sid, + "VoiceIntegrityUseCase": voice_integrity_use_case, + "BusinessProfileIdentity": business_profile_identity, + "BusinessProfileIndustry": business_profile_industry, + "BusinessProfileBundleSid": business_profile_bundle_sid, + "BusinessProfileType": business_profile_type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CallSummariesPage(self._version, response) + + async def page_async( + self, + from_: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_carrier: Union[str, object] = values.unset, + to_carrier: Union[str, object] = values.unset, + from_country_code: Union[str, object] = values.unset, + to_country_code: Union[str, object] = values.unset, + verified_caller: Union[bool, object] = values.unset, + has_tag: Union[bool, object] = values.unset, + start_time: Union[str, object] = values.unset, + end_time: Union[str, object] = values.unset, + call_type: Union[str, object] = values.unset, + call_state: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + processing_state: Union[ + "CallSummariesInstance.ProcessingStateRequest", object + ] = values.unset, + sort_by: Union["CallSummariesInstance.SortBy", object] = values.unset, + subaccount: Union[str, object] = values.unset, + abnormal_session: Union[bool, object] = values.unset, + answered_by: Union["CallSummariesInstance.AnsweredBy", object] = values.unset, + answered_by_annotation: Union[str, object] = values.unset, + connectivity_issue_annotation: Union[str, object] = values.unset, + quality_issue_annotation: Union[str, object] = values.unset, + spam_annotation: Union[bool, object] = values.unset, + call_score_annotation: Union[str, object] = values.unset, + branded_enabled: Union[bool, object] = values.unset, + voice_integrity_enabled: Union[bool, object] = values.unset, + branded_bundle_sid: Union[str, object] = values.unset, + voice_integrity_bundle_sid: Union[str, object] = values.unset, + voice_integrity_use_case: Union[str, object] = values.unset, + business_profile_identity: Union[str, object] = values.unset, + business_profile_industry: Union[str, object] = values.unset, + business_profile_bundle_sid: Union[str, object] = values.unset, + business_profile_type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CallSummariesPage: + """ + Asynchronously retrieve a single page of CallSummariesInstance records from the API. + Request is executed immediately + + :param from_: A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param to: A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param from_carrier: An origination carrier. + :param to_carrier: A destination carrier. + :param from_country_code: A source country code based on phone number in From. + :param to_country_code: A destination country code. Based on phone number in To. + :param verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of 'true' or 'false'. + :param has_tag: A boolean flag indicating the presence of one or more [Voice Insights Call Tags](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-tags). + :param start_time: A Start time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 4h. + :param end_time: An End Time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 0m. + :param call_type: A Call Type of the calls. One of `carrier`, `sip`, `trunking` or `client`. + :param call_state: A Call State of the calls. One of `ringing`, `completed`, `busy`, `fail`, `noanswer`, `canceled`, `answered`, `undialed`. + :param direction: A Direction of the calls. One of `outbound_api`, `outbound_dial`, `inbound`, `trunking_originating`, `trunking_terminating`. + :param processing_state: A Processing State of the Call Summaries. One of `completed`, `partial` or `all`. + :param sort_by: A Sort By criterion for the returned list of Call Summaries. One of `start_time` or `end_time`. + :param subaccount: A unique SID identifier of a Subaccount. + :param abnormal_session: A boolean flag indicating an abnormal session where the last SIP response was not 200 OK. + :param answered_by: An Answered By value for the calls based on `Answering Machine Detection (AMD)`. One of `unknown`, `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `human` or `fax`. + :param answered_by_annotation: Either machine or human. + :param connectivity_issue_annotation: A Connectivity Issue with the calls. One of `no_connectivity_issue`, `invalid_number`, `caller_id`, `dropped_call`, or `number_reachability`. + :param quality_issue_annotation: A subjective Quality Issue with the calls. One of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. + :param spam_annotation: A boolean flag indicating spam calls. + :param call_score_annotation: A Call Score of the calls. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for the rated call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' + :param voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' + :param branded_bundle_sid: A unique SID identifier of the Branded Call. + :param voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. + :param voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. + :param business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. + :param business_profile_industry: A Business Industry of the calls. Is of type enum. One of 'automotive', 'agriculture', 'banking', 'consumer', 'construction', 'education', 'engineering', 'energy', 'oil_and_gas', 'fast_moving_consumer_goods', 'financial', 'fintech', 'food_and_beverage', 'government', 'healthcare', 'hospitality', 'insurance', 'legal', 'manufacturing', 'media', 'online', 'professional_services', 'raw_materials', 'real_estate', 'religion', 'retail', 'jewelry', 'technology', 'telecommunications', 'transportation', 'travel', 'electronics', 'not_for_profit' + :param business_profile_bundle_sid: A unique SID identifier of the Business Profile. + :param business_profile_type: A Business Profile Type of the calls. Is of type enum. One of 'primary', 'secondary'. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CallSummariesInstance + """ + data = values.of( + { + "From": from_, + "To": to, + "FromCarrier": from_carrier, + "ToCarrier": to_carrier, + "FromCountryCode": from_country_code, + "ToCountryCode": to_country_code, + "VerifiedCaller": serialize.boolean_to_string(verified_caller), + "HasTag": serialize.boolean_to_string(has_tag), + "StartTime": start_time, + "EndTime": end_time, + "CallType": call_type, + "CallState": call_state, + "Direction": direction, + "ProcessingState": processing_state, + "SortBy": sort_by, + "Subaccount": subaccount, + "AbnormalSession": serialize.boolean_to_string(abnormal_session), + "AnsweredBy": answered_by, + "AnsweredByAnnotation": answered_by_annotation, + "ConnectivityIssueAnnotation": connectivity_issue_annotation, + "QualityIssueAnnotation": quality_issue_annotation, + "SpamAnnotation": serialize.boolean_to_string(spam_annotation), + "CallScoreAnnotation": call_score_annotation, + "BrandedEnabled": serialize.boolean_to_string(branded_enabled), + "VoiceIntegrityEnabled": serialize.boolean_to_string( + voice_integrity_enabled + ), + "BrandedBundleSid": branded_bundle_sid, + "VoiceIntegrityBundleSid": voice_integrity_bundle_sid, + "VoiceIntegrityUseCase": voice_integrity_use_case, + "BusinessProfileIdentity": business_profile_identity, + "BusinessProfileIndustry": business_profile_industry, + "BusinessProfileBundleSid": business_profile_bundle_sid, + "BusinessProfileType": business_profile_type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CallSummariesPage(self._version, response) + + def get_page(self, target_url: str) -> CallSummariesPage: + """ + Retrieve a specific page of CallSummariesInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CallSummariesInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CallSummariesPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CallSummariesPage: + """ + Asynchronously retrieve a specific page of CallSummariesInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CallSummariesInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CallSummariesPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/insights/v1/conference/__init__.py b/venv/Lib/site-packages/twilio/rest/insights/v1/conference/__init__.py new file mode 100644 index 00000000..ef3c51da --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/insights/v1/conference/__init__.py @@ -0,0 +1,732 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.insights.v1.conference.conference_participant import ( + ConferenceParticipantList, +) + + +class ConferenceInstance(InstanceResource): + + class ConferenceEndReason(object): + LAST_PARTICIPANT_LEFT = "last_participant_left" + CONFERENCE_ENDED_VIA_API = "conference_ended_via_api" + PARTICIPANT_WITH_END_CONFERENCE_ON_EXIT_LEFT = ( + "participant_with_end_conference_on_exit_left" + ) + LAST_PARTICIPANT_KICKED = "last_participant_kicked" + PARTICIPANT_WITH_END_CONFERENCE_ON_EXIT_KICKED = ( + "participant_with_end_conference_on_exit_kicked" + ) + + class ConferenceStatus(object): + IN_PROGRESS = "in_progress" + NOT_STARTED = "not_started" + COMPLETED = "completed" + SUMMARY_TIMEOUT = "summary_timeout" + + class ProcessingState(object): + COMPLETE = "complete" + IN_PROGRESS = "in_progress" + TIMEOUT = "timeout" + + class Region(object): + US1 = "us1" + US2 = "us2" + AU1 = "au1" + BR1 = "br1" + IE1 = "ie1" + JP1 = "jp1" + SG1 = "sg1" + DE1 = "de1" + IN1 = "in1" + + class Tag(object): + INVALID_REQUESTED_REGION = "invalid_requested_region" + DUPLICATE_IDENTITY = "duplicate_identity" + START_FAILURE = "start_failure" + REGION_CONFIGURATION_ISSUES = "region_configuration_issues" + QUALITY_WARNINGS = "quality_warnings" + PARTICIPANT_BEHAVIOR_ISSUES = "participant_behavior_issues" + HIGH_PACKET_LOSS = "high_packet_loss" + HIGH_JITTER = "high_jitter" + HIGH_LATENCY = "high_latency" + LOW_MOS = "low_mos" + DETECTED_SILENCE = "detected_silence" + NO_CONCURRENT_PARTICIPANTS = "no_concurrent_participants" + + """ + :ivar conference_sid: The unique SID identifier of the Conference. + :ivar account_sid: The unique SID identifier of the Account. + :ivar friendly_name: Custom label for the conference resource, up to 64 characters. + :ivar create_time: Conference creation date and time in ISO 8601 format. + :ivar start_time: Timestamp in ISO 8601 format when the conference started. Conferences do not start until at least two participants join, at least one of whom has startConferenceOnEnter=true. + :ivar end_time: Conference end date and time in ISO 8601 format. + :ivar duration_seconds: Conference duration in seconds. + :ivar connect_duration_seconds: Duration of the between conference start event and conference end event in seconds. + :ivar status: + :ivar max_participants: Maximum number of concurrent participants as specified by the configuration. + :ivar max_concurrent_participants: Actual maximum number of concurrent participants in the conference. + :ivar unique_participants: Unique conference participants based on caller ID. + :ivar end_reason: + :ivar ended_by: Call SID of the participant whose actions ended the conference. + :ivar mixer_region: + :ivar mixer_region_requested: + :ivar recording_enabled: Boolean. Indicates whether recording was enabled at the conference mixer. + :ivar detected_issues: Potential issues detected by Twilio during the conference. + :ivar tags: Tags for detected conference conditions and participant behaviors which may be of interest. + :ivar tag_info: Object. Contains details about conference tags including severity. + :ivar processing_state: + :ivar url: The URL of this resource. + :ivar links: Contains a dictionary of URL links to nested resources of this Conference. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + conference_sid: Optional[str] = None, + ): + super().__init__(version) + + self.conference_sid: Optional[str] = payload.get("conference_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.create_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("create_time") + ) + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.duration_seconds: Optional[int] = deserialize.integer( + payload.get("duration_seconds") + ) + self.connect_duration_seconds: Optional[int] = deserialize.integer( + payload.get("connect_duration_seconds") + ) + self.status: Optional["ConferenceInstance.ConferenceStatus"] = payload.get( + "status" + ) + self.max_participants: Optional[int] = deserialize.integer( + payload.get("max_participants") + ) + self.max_concurrent_participants: Optional[int] = deserialize.integer( + payload.get("max_concurrent_participants") + ) + self.unique_participants: Optional[int] = deserialize.integer( + payload.get("unique_participants") + ) + self.end_reason: Optional["ConferenceInstance.ConferenceEndReason"] = ( + payload.get("end_reason") + ) + self.ended_by: Optional[str] = payload.get("ended_by") + self.mixer_region: Optional["ConferenceInstance.Region"] = payload.get( + "mixer_region" + ) + self.mixer_region_requested: Optional["ConferenceInstance.Region"] = ( + payload.get("mixer_region_requested") + ) + self.recording_enabled: Optional[bool] = payload.get("recording_enabled") + self.detected_issues: Optional[Dict[str, object]] = payload.get( + "detected_issues" + ) + self.tags: Optional[List["ConferenceInstance.Tag"]] = payload.get("tags") + self.tag_info: Optional[Dict[str, object]] = payload.get("tag_info") + self.processing_state: Optional["ConferenceInstance.ProcessingState"] = ( + payload.get("processing_state") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "conference_sid": conference_sid or self.conference_sid, + } + self._context: Optional[ConferenceContext] = None + + @property + def _proxy(self) -> "ConferenceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConferenceContext for this ConferenceInstance + """ + if self._context is None: + self._context = ConferenceContext( + self._version, + conference_sid=self._solution["conference_sid"], + ) + return self._context + + def fetch(self) -> "ConferenceInstance": + """ + Fetch the ConferenceInstance + + + :returns: The fetched ConferenceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConferenceInstance": + """ + Asynchronous coroutine to fetch the ConferenceInstance + + + :returns: The fetched ConferenceInstance + """ + return await self._proxy.fetch_async() + + @property + def conference_participants(self) -> ConferenceParticipantList: + """ + Access the conference_participants + """ + return self._proxy.conference_participants + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConferenceContext(InstanceContext): + + def __init__(self, version: Version, conference_sid: str): + """ + Initialize the ConferenceContext + + :param version: Version that contains the resource + :param conference_sid: The unique SID identifier of the Conference. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conference_sid": conference_sid, + } + self._uri = "/Conferences/{conference_sid}".format(**self._solution) + + self._conference_participants: Optional[ConferenceParticipantList] = None + + def fetch(self) -> ConferenceInstance: + """ + Fetch the ConferenceInstance + + + :returns: The fetched ConferenceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ConferenceInstance( + self._version, + payload, + conference_sid=self._solution["conference_sid"], + ) + + async def fetch_async(self) -> ConferenceInstance: + """ + Asynchronous coroutine to fetch the ConferenceInstance + + + :returns: The fetched ConferenceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ConferenceInstance( + self._version, + payload, + conference_sid=self._solution["conference_sid"], + ) + + @property + def conference_participants(self) -> ConferenceParticipantList: + """ + Access the conference_participants + """ + if self._conference_participants is None: + self._conference_participants = ConferenceParticipantList( + self._version, + self._solution["conference_sid"], + ) + return self._conference_participants + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConferencePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ConferenceInstance: + """ + Build an instance of ConferenceInstance + + :param payload: Payload response from the API + """ + return ConferenceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ConferenceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ConferenceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Conferences" + + def stream( + self, + conference_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + mixer_region: Union[str, object] = values.unset, + tags: Union[str, object] = values.unset, + subaccount: Union[str, object] = values.unset, + detected_issues: Union[str, object] = values.unset, + end_reason: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConferenceInstance]: + """ + Streams ConferenceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str conference_sid: The SID of the conference. + :param str friendly_name: Custom label for the conference resource, up to 64 characters. + :param str status: Conference status. + :param str created_after: Conferences created after the provided timestamp specified in ISO 8601 format + :param str created_before: Conferences created before the provided timestamp specified in ISO 8601 format. + :param str mixer_region: Twilio region where the conference media was mixed. + :param str tags: Tags applied by Twilio for common potential configuration, quality, or performance issues. + :param str subaccount: Account SID for the subaccount whose resources you wish to retrieve. + :param str detected_issues: Potential configuration, behavior, or performance issues detected during the conference. + :param str end_reason: Conference end reason; e.g. last participant left, modified by API, etc. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + conference_sid=conference_sid, + friendly_name=friendly_name, + status=status, + created_after=created_after, + created_before=created_before, + mixer_region=mixer_region, + tags=tags, + subaccount=subaccount, + detected_issues=detected_issues, + end_reason=end_reason, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + conference_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + mixer_region: Union[str, object] = values.unset, + tags: Union[str, object] = values.unset, + subaccount: Union[str, object] = values.unset, + detected_issues: Union[str, object] = values.unset, + end_reason: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConferenceInstance]: + """ + Asynchronously streams ConferenceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str conference_sid: The SID of the conference. + :param str friendly_name: Custom label for the conference resource, up to 64 characters. + :param str status: Conference status. + :param str created_after: Conferences created after the provided timestamp specified in ISO 8601 format + :param str created_before: Conferences created before the provided timestamp specified in ISO 8601 format. + :param str mixer_region: Twilio region where the conference media was mixed. + :param str tags: Tags applied by Twilio for common potential configuration, quality, or performance issues. + :param str subaccount: Account SID for the subaccount whose resources you wish to retrieve. + :param str detected_issues: Potential configuration, behavior, or performance issues detected during the conference. + :param str end_reason: Conference end reason; e.g. last participant left, modified by API, etc. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + conference_sid=conference_sid, + friendly_name=friendly_name, + status=status, + created_after=created_after, + created_before=created_before, + mixer_region=mixer_region, + tags=tags, + subaccount=subaccount, + detected_issues=detected_issues, + end_reason=end_reason, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + conference_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + mixer_region: Union[str, object] = values.unset, + tags: Union[str, object] = values.unset, + subaccount: Union[str, object] = values.unset, + detected_issues: Union[str, object] = values.unset, + end_reason: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConferenceInstance]: + """ + Lists ConferenceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str conference_sid: The SID of the conference. + :param str friendly_name: Custom label for the conference resource, up to 64 characters. + :param str status: Conference status. + :param str created_after: Conferences created after the provided timestamp specified in ISO 8601 format + :param str created_before: Conferences created before the provided timestamp specified in ISO 8601 format. + :param str mixer_region: Twilio region where the conference media was mixed. + :param str tags: Tags applied by Twilio for common potential configuration, quality, or performance issues. + :param str subaccount: Account SID for the subaccount whose resources you wish to retrieve. + :param str detected_issues: Potential configuration, behavior, or performance issues detected during the conference. + :param str end_reason: Conference end reason; e.g. last participant left, modified by API, etc. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + conference_sid=conference_sid, + friendly_name=friendly_name, + status=status, + created_after=created_after, + created_before=created_before, + mixer_region=mixer_region, + tags=tags, + subaccount=subaccount, + detected_issues=detected_issues, + end_reason=end_reason, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + conference_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + mixer_region: Union[str, object] = values.unset, + tags: Union[str, object] = values.unset, + subaccount: Union[str, object] = values.unset, + detected_issues: Union[str, object] = values.unset, + end_reason: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConferenceInstance]: + """ + Asynchronously lists ConferenceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str conference_sid: The SID of the conference. + :param str friendly_name: Custom label for the conference resource, up to 64 characters. + :param str status: Conference status. + :param str created_after: Conferences created after the provided timestamp specified in ISO 8601 format + :param str created_before: Conferences created before the provided timestamp specified in ISO 8601 format. + :param str mixer_region: Twilio region where the conference media was mixed. + :param str tags: Tags applied by Twilio for common potential configuration, quality, or performance issues. + :param str subaccount: Account SID for the subaccount whose resources you wish to retrieve. + :param str detected_issues: Potential configuration, behavior, or performance issues detected during the conference. + :param str end_reason: Conference end reason; e.g. last participant left, modified by API, etc. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + conference_sid=conference_sid, + friendly_name=friendly_name, + status=status, + created_after=created_after, + created_before=created_before, + mixer_region=mixer_region, + tags=tags, + subaccount=subaccount, + detected_issues=detected_issues, + end_reason=end_reason, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + conference_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + mixer_region: Union[str, object] = values.unset, + tags: Union[str, object] = values.unset, + subaccount: Union[str, object] = values.unset, + detected_issues: Union[str, object] = values.unset, + end_reason: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConferencePage: + """ + Retrieve a single page of ConferenceInstance records from the API. + Request is executed immediately + + :param conference_sid: The SID of the conference. + :param friendly_name: Custom label for the conference resource, up to 64 characters. + :param status: Conference status. + :param created_after: Conferences created after the provided timestamp specified in ISO 8601 format + :param created_before: Conferences created before the provided timestamp specified in ISO 8601 format. + :param mixer_region: Twilio region where the conference media was mixed. + :param tags: Tags applied by Twilio for common potential configuration, quality, or performance issues. + :param subaccount: Account SID for the subaccount whose resources you wish to retrieve. + :param detected_issues: Potential configuration, behavior, or performance issues detected during the conference. + :param end_reason: Conference end reason; e.g. last participant left, modified by API, etc. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConferenceInstance + """ + data = values.of( + { + "ConferenceSid": conference_sid, + "FriendlyName": friendly_name, + "Status": status, + "CreatedAfter": created_after, + "CreatedBefore": created_before, + "MixerRegion": mixer_region, + "Tags": tags, + "Subaccount": subaccount, + "DetectedIssues": detected_issues, + "EndReason": end_reason, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConferencePage(self._version, response) + + async def page_async( + self, + conference_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + mixer_region: Union[str, object] = values.unset, + tags: Union[str, object] = values.unset, + subaccount: Union[str, object] = values.unset, + detected_issues: Union[str, object] = values.unset, + end_reason: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConferencePage: + """ + Asynchronously retrieve a single page of ConferenceInstance records from the API. + Request is executed immediately + + :param conference_sid: The SID of the conference. + :param friendly_name: Custom label for the conference resource, up to 64 characters. + :param status: Conference status. + :param created_after: Conferences created after the provided timestamp specified in ISO 8601 format + :param created_before: Conferences created before the provided timestamp specified in ISO 8601 format. + :param mixer_region: Twilio region where the conference media was mixed. + :param tags: Tags applied by Twilio for common potential configuration, quality, or performance issues. + :param subaccount: Account SID for the subaccount whose resources you wish to retrieve. + :param detected_issues: Potential configuration, behavior, or performance issues detected during the conference. + :param end_reason: Conference end reason; e.g. last participant left, modified by API, etc. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConferenceInstance + """ + data = values.of( + { + "ConferenceSid": conference_sid, + "FriendlyName": friendly_name, + "Status": status, + "CreatedAfter": created_after, + "CreatedBefore": created_before, + "MixerRegion": mixer_region, + "Tags": tags, + "Subaccount": subaccount, + "DetectedIssues": detected_issues, + "EndReason": end_reason, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConferencePage(self._version, response) + + def get_page(self, target_url: str) -> ConferencePage: + """ + Retrieve a specific page of ConferenceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConferenceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConferencePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ConferencePage: + """ + Asynchronously retrieve a specific page of ConferenceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConferenceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConferencePage(self._version, response) + + def get(self, conference_sid: str) -> ConferenceContext: + """ + Constructs a ConferenceContext + + :param conference_sid: The unique SID identifier of the Conference. + """ + return ConferenceContext(self._version, conference_sid=conference_sid) + + def __call__(self, conference_sid: str) -> ConferenceContext: + """ + Constructs a ConferenceContext + + :param conference_sid: The unique SID identifier of the Conference. + """ + return ConferenceContext(self._version, conference_sid=conference_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/insights/v1/conference/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/insights/v1/conference/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..64d4d834 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/insights/v1/conference/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/insights/v1/conference/__pycache__/conference_participant.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/insights/v1/conference/__pycache__/conference_participant.cpython-312.pyc new file mode 100644 index 00000000..3d4e6d8c Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/insights/v1/conference/__pycache__/conference_participant.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/insights/v1/conference/conference_participant.py b/venv/Lib/site-packages/twilio/rest/insights/v1/conference/conference_participant.py new file mode 100644 index 00000000..171f4f1f --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/insights/v1/conference/conference_participant.py @@ -0,0 +1,655 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ConferenceParticipantInstance(InstanceResource): + + class CallDirection(object): + INBOUND = "inbound" + OUTBOUND = "outbound" + + class CallStatus(object): + ANSWERED = "answered" + COMPLETED = "completed" + BUSY = "busy" + FAIL = "fail" + NOANSWER = "noanswer" + RINGING = "ringing" + CANCELED = "canceled" + + class CallType(object): + CARRIER = "carrier" + CLIENT = "client" + SIP = "sip" + + class JitterBufferSize(object): + LARGE = "large" + SMALL = "small" + MEDIUM = "medium" + OFF = "off" + + class ProcessingState(object): + COMPLETE = "complete" + IN_PROGRESS = "in_progress" + TIMEOUT = "timeout" + + class Region(object): + US1 = "us1" + US2 = "us2" + AU1 = "au1" + BR1 = "br1" + IE1 = "ie1" + JP1 = "jp1" + SG1 = "sg1" + DE1 = "de1" + IN1 = "in1" + + """ + :ivar participant_sid: SID for this participant. + :ivar label: The user-specified label of this participant. + :ivar conference_sid: The unique SID identifier of the Conference. + :ivar call_sid: Unique SID identifier of the call that generated the Participant resource. + :ivar account_sid: The unique SID identifier of the Account. + :ivar call_direction: + :ivar _from: Caller ID of the calling party. + :ivar to: Called party. + :ivar call_status: + :ivar country_code: ISO alpha-2 country code of the participant based on caller ID or called number. + :ivar is_moderator: Boolean. Indicates whether participant had startConferenceOnEnter=true or endConferenceOnExit=true. + :ivar join_time: ISO 8601 timestamp of participant join event. + :ivar leave_time: ISO 8601 timestamp of participant leave event. + :ivar duration_seconds: Participant durations in seconds. + :ivar outbound_queue_length: Add Participant API only. Estimated time in queue at call creation. + :ivar outbound_time_in_queue: Add Participant API only. Actual time in queue in seconds. + :ivar jitter_buffer_size: + :ivar is_coach: Boolean. Indicated whether participant was a coach. + :ivar coached_participants: Call SIDs coached by this participant. + :ivar participant_region: + :ivar conference_region: + :ivar call_type: + :ivar processing_state: + :ivar properties: Participant properties and metadata. + :ivar events: Object containing information of actions taken by participants. Contains a dictionary of URL links to nested resources of this Conference Participant. + :ivar metrics: Object. Contains participant call quality metrics. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + conference_sid: str, + participant_sid: Optional[str] = None, + ): + super().__init__(version) + + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.label: Optional[str] = payload.get("label") + self.conference_sid: Optional[str] = payload.get("conference_sid") + self.call_sid: Optional[str] = payload.get("call_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.call_direction: Optional["ConferenceParticipantInstance.CallDirection"] = ( + payload.get("call_direction") + ) + self._from: Optional[str] = payload.get("from") + self.to: Optional[str] = payload.get("to") + self.call_status: Optional["ConferenceParticipantInstance.CallStatus"] = ( + payload.get("call_status") + ) + self.country_code: Optional[str] = payload.get("country_code") + self.is_moderator: Optional[bool] = payload.get("is_moderator") + self.join_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("join_time") + ) + self.leave_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("leave_time") + ) + self.duration_seconds: Optional[int] = deserialize.integer( + payload.get("duration_seconds") + ) + self.outbound_queue_length: Optional[int] = deserialize.integer( + payload.get("outbound_queue_length") + ) + self.outbound_time_in_queue: Optional[int] = deserialize.integer( + payload.get("outbound_time_in_queue") + ) + self.jitter_buffer_size: Optional[ + "ConferenceParticipantInstance.JitterBufferSize" + ] = payload.get("jitter_buffer_size") + self.is_coach: Optional[bool] = payload.get("is_coach") + self.coached_participants: Optional[List[str]] = payload.get( + "coached_participants" + ) + self.participant_region: Optional["ConferenceParticipantInstance.Region"] = ( + payload.get("participant_region") + ) + self.conference_region: Optional["ConferenceParticipantInstance.Region"] = ( + payload.get("conference_region") + ) + self.call_type: Optional["ConferenceParticipantInstance.CallType"] = ( + payload.get("call_type") + ) + self.processing_state: Optional[ + "ConferenceParticipantInstance.ProcessingState" + ] = payload.get("processing_state") + self.properties: Optional[Dict[str, object]] = payload.get("properties") + self.events: Optional[Dict[str, object]] = payload.get("events") + self.metrics: Optional[Dict[str, object]] = payload.get("metrics") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "conference_sid": conference_sid, + "participant_sid": participant_sid or self.participant_sid, + } + self._context: Optional[ConferenceParticipantContext] = None + + @property + def _proxy(self) -> "ConferenceParticipantContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConferenceParticipantContext for this ConferenceParticipantInstance + """ + if self._context is None: + self._context = ConferenceParticipantContext( + self._version, + conference_sid=self._solution["conference_sid"], + participant_sid=self._solution["participant_sid"], + ) + return self._context + + def fetch( + self, + events: Union[str, object] = values.unset, + metrics: Union[str, object] = values.unset, + ) -> "ConferenceParticipantInstance": + """ + Fetch the ConferenceParticipantInstance + + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param metrics: Object. Contains participant call quality metrics. + + :returns: The fetched ConferenceParticipantInstance + """ + return self._proxy.fetch( + events=events, + metrics=metrics, + ) + + async def fetch_async( + self, + events: Union[str, object] = values.unset, + metrics: Union[str, object] = values.unset, + ) -> "ConferenceParticipantInstance": + """ + Asynchronous coroutine to fetch the ConferenceParticipantInstance + + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param metrics: Object. Contains participant call quality metrics. + + :returns: The fetched ConferenceParticipantInstance + """ + return await self._proxy.fetch_async( + events=events, + metrics=metrics, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConferenceParticipantContext(InstanceContext): + + def __init__(self, version: Version, conference_sid: str, participant_sid: str): + """ + Initialize the ConferenceParticipantContext + + :param version: Version that contains the resource + :param conference_sid: The unique SID identifier of the Conference. + :param participant_sid: The unique SID identifier of the Participant. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conference_sid": conference_sid, + "participant_sid": participant_sid, + } + self._uri = ( + "/Conferences/{conference_sid}/Participants/{participant_sid}".format( + **self._solution + ) + ) + + def fetch( + self, + events: Union[str, object] = values.unset, + metrics: Union[str, object] = values.unset, + ) -> ConferenceParticipantInstance: + """ + Fetch the ConferenceParticipantInstance + + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param metrics: Object. Contains participant call quality metrics. + + :returns: The fetched ConferenceParticipantInstance + """ + + data = values.of( + { + "Events": events, + "Metrics": metrics, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return ConferenceParticipantInstance( + self._version, + payload, + conference_sid=self._solution["conference_sid"], + participant_sid=self._solution["participant_sid"], + ) + + async def fetch_async( + self, + events: Union[str, object] = values.unset, + metrics: Union[str, object] = values.unset, + ) -> ConferenceParticipantInstance: + """ + Asynchronous coroutine to fetch the ConferenceParticipantInstance + + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param metrics: Object. Contains participant call quality metrics. + + :returns: The fetched ConferenceParticipantInstance + """ + + data = values.of( + { + "Events": events, + "Metrics": metrics, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return ConferenceParticipantInstance( + self._version, + payload, + conference_sid=self._solution["conference_sid"], + participant_sid=self._solution["participant_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConferenceParticipantPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ConferenceParticipantInstance: + """ + Build an instance of ConferenceParticipantInstance + + :param payload: Payload response from the API + """ + return ConferenceParticipantInstance( + self._version, payload, conference_sid=self._solution["conference_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ConferenceParticipantList(ListResource): + + def __init__(self, version: Version, conference_sid: str): + """ + Initialize the ConferenceParticipantList + + :param version: Version that contains the resource + :param conference_sid: The unique SID identifier of the Conference. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conference_sid": conference_sid, + } + self._uri = "/Conferences/{conference_sid}/Participants".format( + **self._solution + ) + + def stream( + self, + participant_sid: Union[str, object] = values.unset, + label: Union[str, object] = values.unset, + events: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConferenceParticipantInstance]: + """ + Streams ConferenceParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str participant_sid: The unique SID identifier of the Participant. + :param str label: User-specified label for a participant. + :param str events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + participant_sid=participant_sid, + label=label, + events=events, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + participant_sid: Union[str, object] = values.unset, + label: Union[str, object] = values.unset, + events: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConferenceParticipantInstance]: + """ + Asynchronously streams ConferenceParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str participant_sid: The unique SID identifier of the Participant. + :param str label: User-specified label for a participant. + :param str events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + participant_sid=participant_sid, + label=label, + events=events, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + participant_sid: Union[str, object] = values.unset, + label: Union[str, object] = values.unset, + events: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConferenceParticipantInstance]: + """ + Lists ConferenceParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str participant_sid: The unique SID identifier of the Participant. + :param str label: User-specified label for a participant. + :param str events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + participant_sid=participant_sid, + label=label, + events=events, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + participant_sid: Union[str, object] = values.unset, + label: Union[str, object] = values.unset, + events: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConferenceParticipantInstance]: + """ + Asynchronously lists ConferenceParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str participant_sid: The unique SID identifier of the Participant. + :param str label: User-specified label for a participant. + :param str events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + participant_sid=participant_sid, + label=label, + events=events, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + participant_sid: Union[str, object] = values.unset, + label: Union[str, object] = values.unset, + events: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConferenceParticipantPage: + """ + Retrieve a single page of ConferenceParticipantInstance records from the API. + Request is executed immediately + + :param participant_sid: The unique SID identifier of the Participant. + :param label: User-specified label for a participant. + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConferenceParticipantInstance + """ + data = values.of( + { + "ParticipantSid": participant_sid, + "Label": label, + "Events": events, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConferenceParticipantPage(self._version, response, self._solution) + + async def page_async( + self, + participant_sid: Union[str, object] = values.unset, + label: Union[str, object] = values.unset, + events: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConferenceParticipantPage: + """ + Asynchronously retrieve a single page of ConferenceParticipantInstance records from the API. + Request is executed immediately + + :param participant_sid: The unique SID identifier of the Participant. + :param label: User-specified label for a participant. + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConferenceParticipantInstance + """ + data = values.of( + { + "ParticipantSid": participant_sid, + "Label": label, + "Events": events, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConferenceParticipantPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ConferenceParticipantPage: + """ + Retrieve a specific page of ConferenceParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConferenceParticipantInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConferenceParticipantPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ConferenceParticipantPage: + """ + Asynchronously retrieve a specific page of ConferenceParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConferenceParticipantInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConferenceParticipantPage(self._version, response, self._solution) + + def get(self, participant_sid: str) -> ConferenceParticipantContext: + """ + Constructs a ConferenceParticipantContext + + :param participant_sid: The unique SID identifier of the Participant. + """ + return ConferenceParticipantContext( + self._version, + conference_sid=self._solution["conference_sid"], + participant_sid=participant_sid, + ) + + def __call__(self, participant_sid: str) -> ConferenceParticipantContext: + """ + Constructs a ConferenceParticipantContext + + :param participant_sid: The unique SID identifier of the Participant. + """ + return ConferenceParticipantContext( + self._version, + conference_sid=self._solution["conference_sid"], + participant_sid=participant_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/insights/v1/room/__init__.py b/venv/Lib/site-packages/twilio/rest/insights/v1/room/__init__.py new file mode 100644 index 00000000..6fe0c476 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/insights/v1/room/__init__.py @@ -0,0 +1,664 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.insights.v1.room.participant import ParticipantList + + +class RoomInstance(InstanceResource): + + class Codec(object): + VP8 = "VP8" + H264 = "H264" + VP9 = "VP9" + OPUS = "opus" + + class CreatedMethod(object): + SDK = "sdk" + AD_HOC = "ad_hoc" + API = "api" + + class EdgeLocation(object): + ASHBURN = "ashburn" + DUBLIN = "dublin" + FRANKFURT = "frankfurt" + SINGAPORE = "singapore" + SYDNEY = "sydney" + SAO_PAULO = "sao_paulo" + ROAMING = "roaming" + UMATILLA = "umatilla" + TOKYO = "tokyo" + + class EndReason(object): + ROOM_ENDED_VIA_API = "room_ended_via_api" + TIMEOUT = "timeout" + + class ProcessingState(object): + COMPLETE = "complete" + IN_PROGRESS = "in_progress" + TIMEOUT = "timeout" + NOT_STARTED = "not_started" + + class RoomStatus(object): + IN_PROGRESS = "in_progress" + COMPLETED = "completed" + + class RoomType(object): + GO = "go" + PEER_TO_PEER = "peer_to_peer" + GROUP = "group" + GROUP_SMALL = "group_small" + + class TwilioRealm(object): + US1 = "us1" + US2 = "us2" + AU1 = "au1" + BR1 = "br1" + IE1 = "ie1" + JP1 = "jp1" + SG1 = "sg1" + IN1 = "in1" + DE1 = "de1" + GLL = "gll" + STAGE_US1 = "stage_us1" + STAGE_US2 = "stage_us2" + DEV_US1 = "dev_us1" + DEV_US2 = "dev_us2" + STAGE_DE1 = "stage_de1" + STAGE_IN1 = "stage_in1" + STAGE_IE1 = "stage_ie1" + STAGE_BR1 = "stage_br1" + STAGE_AU1 = "stage_au1" + STAGE_SG1 = "stage_sg1" + STAGE_JP1 = "stage_jp1" + OUTSIDE = "outside" + + """ + :ivar account_sid: Account SID associated with this room. + :ivar room_sid: Unique identifier for the room. + :ivar room_name: Room friendly name. + :ivar create_time: Creation time of the room. + :ivar end_time: End time for the room. + :ivar room_type: + :ivar room_status: + :ivar status_callback: Webhook provided for status callbacks. + :ivar status_callback_method: HTTP method provided for status callback URL. + :ivar created_method: + :ivar end_reason: + :ivar max_participants: Max number of total participants allowed by the application settings. + :ivar unique_participants: Number of participants. May include duplicate identities for participants who left and rejoined. + :ivar unique_participant_identities: Unique number of participant identities. + :ivar concurrent_participants: Actual number of concurrent participants. + :ivar max_concurrent_participants: Maximum number of participants allowed in the room at the same time allowed by the application settings. + :ivar codecs: Codecs used by participants in the room. Can be `VP8`, `H264`, or `VP9`. + :ivar media_region: + :ivar duration_sec: Total room duration from create time to end time. + :ivar total_participant_duration_sec: Combined amount of participant time in the room. + :ivar total_recording_duration_sec: Combined amount of recorded seconds for participants in the room. + :ivar processing_state: + :ivar recording_enabled: Boolean indicating if recording is enabled for the room. + :ivar edge_location: + :ivar url: URL for the room resource. + :ivar links: Room subresources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], room_sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.room_sid: Optional[str] = payload.get("room_sid") + self.room_name: Optional[str] = payload.get("room_name") + self.create_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("create_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.room_type: Optional["RoomInstance.RoomType"] = payload.get("room_type") + self.room_status: Optional["RoomInstance.RoomStatus"] = payload.get( + "room_status" + ) + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.created_method: Optional["RoomInstance.CreatedMethod"] = payload.get( + "created_method" + ) + self.end_reason: Optional["RoomInstance.EndReason"] = payload.get("end_reason") + self.max_participants: Optional[int] = deserialize.integer( + payload.get("max_participants") + ) + self.unique_participants: Optional[int] = deserialize.integer( + payload.get("unique_participants") + ) + self.unique_participant_identities: Optional[int] = deserialize.integer( + payload.get("unique_participant_identities") + ) + self.concurrent_participants: Optional[int] = deserialize.integer( + payload.get("concurrent_participants") + ) + self.max_concurrent_participants: Optional[int] = deserialize.integer( + payload.get("max_concurrent_participants") + ) + self.codecs: Optional[List["RoomInstance.Codec"]] = payload.get("codecs") + self.media_region: Optional["RoomInstance.TwilioRealm"] = payload.get( + "media_region" + ) + self.duration_sec: Optional[int] = payload.get("duration_sec") + self.total_participant_duration_sec: Optional[int] = payload.get( + "total_participant_duration_sec" + ) + self.total_recording_duration_sec: Optional[int] = payload.get( + "total_recording_duration_sec" + ) + self.processing_state: Optional["RoomInstance.ProcessingState"] = payload.get( + "processing_state" + ) + self.recording_enabled: Optional[bool] = payload.get("recording_enabled") + self.edge_location: Optional["RoomInstance.EdgeLocation"] = payload.get( + "edge_location" + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "room_sid": room_sid or self.room_sid, + } + self._context: Optional[RoomContext] = None + + @property + def _proxy(self) -> "RoomContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RoomContext for this RoomInstance + """ + if self._context is None: + self._context = RoomContext( + self._version, + room_sid=self._solution["room_sid"], + ) + return self._context + + def fetch(self) -> "RoomInstance": + """ + Fetch the RoomInstance + + + :returns: The fetched RoomInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RoomInstance": + """ + Asynchronous coroutine to fetch the RoomInstance + + + :returns: The fetched RoomInstance + """ + return await self._proxy.fetch_async() + + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + return self._proxy.participants + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RoomContext(InstanceContext): + + def __init__(self, version: Version, room_sid: str): + """ + Initialize the RoomContext + + :param version: Version that contains the resource + :param room_sid: The SID of the Room resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + } + self._uri = "/Video/Rooms/{room_sid}".format(**self._solution) + + self._participants: Optional[ParticipantList] = None + + def fetch(self) -> RoomInstance: + """ + Fetch the RoomInstance + + + :returns: The fetched RoomInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RoomInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ) + + async def fetch_async(self) -> RoomInstance: + """ + Asynchronous coroutine to fetch the RoomInstance + + + :returns: The fetched RoomInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RoomInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ) + + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + if self._participants is None: + self._participants = ParticipantList( + self._version, + self._solution["room_sid"], + ) + return self._participants + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RoomPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RoomInstance: + """ + Build an instance of RoomInstance + + :param payload: Payload response from the API + """ + return RoomInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RoomList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the RoomList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Video/Rooms" + + def stream( + self, + room_type: Union[List["RoomInstance.RoomType"], object] = values.unset, + codec: Union[List["RoomInstance.Codec"], object] = values.unset, + room_name: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoomInstance]: + """ + Streams RoomInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["RoomInstance.RoomType"] room_type: Type of room. Can be `go`, `peer_to_peer`, `group`, or `group_small`. + :param List["RoomInstance.Codec"] codec: Codecs used by participants in the room. Can be `VP8`, `H264`, or `VP9`. + :param str room_name: Room friendly name. + :param datetime created_after: Only read rooms that started on or after this ISO 8601 timestamp. + :param datetime created_before: Only read rooms that started before this ISO 8601 timestamp. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + room_type=room_type, + codec=codec, + room_name=room_name, + created_after=created_after, + created_before=created_before, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + room_type: Union[List["RoomInstance.RoomType"], object] = values.unset, + codec: Union[List["RoomInstance.Codec"], object] = values.unset, + room_name: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RoomInstance]: + """ + Asynchronously streams RoomInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["RoomInstance.RoomType"] room_type: Type of room. Can be `go`, `peer_to_peer`, `group`, or `group_small`. + :param List["RoomInstance.Codec"] codec: Codecs used by participants in the room. Can be `VP8`, `H264`, or `VP9`. + :param str room_name: Room friendly name. + :param datetime created_after: Only read rooms that started on or after this ISO 8601 timestamp. + :param datetime created_before: Only read rooms that started before this ISO 8601 timestamp. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + room_type=room_type, + codec=codec, + room_name=room_name, + created_after=created_after, + created_before=created_before, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + room_type: Union[List["RoomInstance.RoomType"], object] = values.unset, + codec: Union[List["RoomInstance.Codec"], object] = values.unset, + room_name: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoomInstance]: + """ + Lists RoomInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["RoomInstance.RoomType"] room_type: Type of room. Can be `go`, `peer_to_peer`, `group`, or `group_small`. + :param List["RoomInstance.Codec"] codec: Codecs used by participants in the room. Can be `VP8`, `H264`, or `VP9`. + :param str room_name: Room friendly name. + :param datetime created_after: Only read rooms that started on or after this ISO 8601 timestamp. + :param datetime created_before: Only read rooms that started before this ISO 8601 timestamp. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + room_type=room_type, + codec=codec, + room_name=room_name, + created_after=created_after, + created_before=created_before, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + room_type: Union[List["RoomInstance.RoomType"], object] = values.unset, + codec: Union[List["RoomInstance.Codec"], object] = values.unset, + room_name: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoomInstance]: + """ + Asynchronously lists RoomInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["RoomInstance.RoomType"] room_type: Type of room. Can be `go`, `peer_to_peer`, `group`, or `group_small`. + :param List["RoomInstance.Codec"] codec: Codecs used by participants in the room. Can be `VP8`, `H264`, or `VP9`. + :param str room_name: Room friendly name. + :param datetime created_after: Only read rooms that started on or after this ISO 8601 timestamp. + :param datetime created_before: Only read rooms that started before this ISO 8601 timestamp. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + room_type=room_type, + codec=codec, + room_name=room_name, + created_after=created_after, + created_before=created_before, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + room_type: Union[List["RoomInstance.RoomType"], object] = values.unset, + codec: Union[List["RoomInstance.Codec"], object] = values.unset, + room_name: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RoomPage: + """ + Retrieve a single page of RoomInstance records from the API. + Request is executed immediately + + :param room_type: Type of room. Can be `go`, `peer_to_peer`, `group`, or `group_small`. + :param codec: Codecs used by participants in the room. Can be `VP8`, `H264`, or `VP9`. + :param room_name: Room friendly name. + :param created_after: Only read rooms that started on or after this ISO 8601 timestamp. + :param created_before: Only read rooms that started before this ISO 8601 timestamp. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoomInstance + """ + data = values.of( + { + "RoomType": serialize.map(room_type, lambda e: e), + "Codec": serialize.map(codec, lambda e: e), + "RoomName": room_name, + "CreatedAfter": serialize.iso8601_datetime(created_after), + "CreatedBefore": serialize.iso8601_datetime(created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RoomPage(self._version, response) + + async def page_async( + self, + room_type: Union[List["RoomInstance.RoomType"], object] = values.unset, + codec: Union[List["RoomInstance.Codec"], object] = values.unset, + room_name: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RoomPage: + """ + Asynchronously retrieve a single page of RoomInstance records from the API. + Request is executed immediately + + :param room_type: Type of room. Can be `go`, `peer_to_peer`, `group`, or `group_small`. + :param codec: Codecs used by participants in the room. Can be `VP8`, `H264`, or `VP9`. + :param room_name: Room friendly name. + :param created_after: Only read rooms that started on or after this ISO 8601 timestamp. + :param created_before: Only read rooms that started before this ISO 8601 timestamp. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoomInstance + """ + data = values.of( + { + "RoomType": serialize.map(room_type, lambda e: e), + "Codec": serialize.map(codec, lambda e: e), + "RoomName": room_name, + "CreatedAfter": serialize.iso8601_datetime(created_after), + "CreatedBefore": serialize.iso8601_datetime(created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RoomPage(self._version, response) + + def get_page(self, target_url: str) -> RoomPage: + """ + Retrieve a specific page of RoomInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoomInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RoomPage(self._version, response) + + async def get_page_async(self, target_url: str) -> RoomPage: + """ + Asynchronously retrieve a specific page of RoomInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoomInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RoomPage(self._version, response) + + def get(self, room_sid: str) -> RoomContext: + """ + Constructs a RoomContext + + :param room_sid: The SID of the Room resource. + """ + return RoomContext(self._version, room_sid=room_sid) + + def __call__(self, room_sid: str) -> RoomContext: + """ + Constructs a RoomContext + + :param room_sid: The SID of the Room resource. + """ + return RoomContext(self._version, room_sid=room_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/insights/v1/room/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/insights/v1/room/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..6f65107e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/insights/v1/room/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/insights/v1/room/__pycache__/participant.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/insights/v1/room/__pycache__/participant.cpython-312.pyc new file mode 100644 index 00000000..6b73a6b7 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/insights/v1/room/__pycache__/participant.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/insights/v1/room/participant.py b/venv/Lib/site-packages/twilio/rest/insights/v1/room/participant.py new file mode 100644 index 00000000..d0d3e592 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/insights/v1/room/participant.py @@ -0,0 +1,516 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ParticipantInstance(InstanceResource): + + class Codec(object): + VP8 = "VP8" + H264 = "H264" + VP9 = "VP9" + OPUS = "opus" + + class EdgeLocation(object): + ASHBURN = "ashburn" + DUBLIN = "dublin" + FRANKFURT = "frankfurt" + SINGAPORE = "singapore" + SYDNEY = "sydney" + SAO_PAULO = "sao_paulo" + ROAMING = "roaming" + UMATILLA = "umatilla" + TOKYO = "tokyo" + + class RoomStatus(object): + IN_PROGRESS = "in_progress" + CONNECTED = "connected" + COMPLETED = "completed" + DISCONNECTED = "disconnected" + + class TwilioRealm(object): + US1 = "us1" + US2 = "us2" + AU1 = "au1" + BR1 = "br1" + IE1 = "ie1" + JP1 = "jp1" + SG1 = "sg1" + IN1 = "in1" + DE1 = "de1" + GLL = "gll" + STAGE_US1 = "stage_us1" + DEV_US1 = "dev_us1" + STAGE_AU1 = "stage_au1" + STAGE_SG1 = "stage_sg1" + STAGE_BR1 = "stage_br1" + STAGE_IN1 = "stage_in1" + STAGE_JP1 = "stage_jp1" + STAGE_DE1 = "stage_de1" + STAGE_IE1 = "stage_ie1" + STAGE_US2 = "stage_us2" + DEV_US2 = "dev_us2" + OUTSIDE = "outside" + + """ + :ivar participant_sid: Unique identifier for the participant. + :ivar participant_identity: The application-defined string that uniquely identifies the participant within a Room. + :ivar join_time: When the participant joined the room. + :ivar leave_time: When the participant left the room. + :ivar duration_sec: Amount of time in seconds the participant was in the room. + :ivar account_sid: Account SID associated with the room. + :ivar room_sid: Unique identifier for the room. + :ivar status: + :ivar codecs: Codecs detected from the participant. Can be `VP8`, `H264`, or `VP9`. + :ivar end_reason: Reason the participant left the room. See [the list of possible values here](https://www.twilio.com/docs/video/troubleshooting/video-log-analyzer-api#end_reason). + :ivar error_code: Errors encountered by the participant. + :ivar error_code_url: Twilio error code dictionary link. + :ivar media_region: + :ivar properties: Object containing information about the participant's data from the room. See [below](https://www.twilio.com/docs/video/troubleshooting/video-log-analyzer-api#properties) for more information. + :ivar edge_location: + :ivar publisher_info: Object containing information about the SDK name and version. See [below](https://www.twilio.com/docs/video/troubleshooting/video-log-analyzer-api#publisher_info) for more information. + :ivar url: URL of the participant resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + room_sid: str, + participant_sid: Optional[str] = None, + ): + super().__init__(version) + + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.participant_identity: Optional[str] = payload.get("participant_identity") + self.join_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("join_time") + ) + self.leave_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("leave_time") + ) + self.duration_sec: Optional[int] = payload.get("duration_sec") + self.account_sid: Optional[str] = payload.get("account_sid") + self.room_sid: Optional[str] = payload.get("room_sid") + self.status: Optional["ParticipantInstance.RoomStatus"] = payload.get("status") + self.codecs: Optional[List["ParticipantInstance.Codec"]] = payload.get("codecs") + self.end_reason: Optional[str] = payload.get("end_reason") + self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) + self.error_code_url: Optional[str] = payload.get("error_code_url") + self.media_region: Optional["ParticipantInstance.TwilioRealm"] = payload.get( + "media_region" + ) + self.properties: Optional[Dict[str, object]] = payload.get("properties") + self.edge_location: Optional["ParticipantInstance.EdgeLocation"] = payload.get( + "edge_location" + ) + self.publisher_info: Optional[Dict[str, object]] = payload.get("publisher_info") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "room_sid": room_sid, + "participant_sid": participant_sid or self.participant_sid, + } + self._context: Optional[ParticipantContext] = None + + @property + def _proxy(self) -> "ParticipantContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ParticipantContext for this ParticipantInstance + """ + if self._context is None: + self._context = ParticipantContext( + self._version, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + return self._context + + def fetch(self) -> "ParticipantInstance": + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ParticipantInstance": + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ParticipantContext(InstanceContext): + + def __init__(self, version: Version, room_sid: str, participant_sid: str): + """ + Initialize the ParticipantContext + + :param version: Version that contains the resource + :param room_sid: The SID of the Room resource. + :param participant_sid: The SID of the Participant resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + "participant_sid": participant_sid, + } + self._uri = "/Video/Rooms/{room_sid}/Participants/{participant_sid}".format( + **self._solution + ) + + def fetch(self) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + + async def fetch_async(self) -> ParticipantInstance: + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ParticipantPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: + """ + Build an instance of ParticipantInstance + + :param payload: Payload response from the API + """ + return ParticipantInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ParticipantList(ListResource): + + def __init__(self, version: Version, room_sid: str): + """ + Initialize the ParticipantList + + :param version: Version that contains the resource + :param room_sid: The SID of the Room resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + } + self._uri = "/Video/Rooms/{room_sid}/Participants".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ParticipantInstance]: + """ + Streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ParticipantInstance]: + """ + Asynchronously streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Asynchronously lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Asynchronously retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ParticipantPage: + """ + Retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ParticipantPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ParticipantPage: + """ + Asynchronously retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ParticipantPage(self._version, response, self._solution) + + def get(self, participant_sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param participant_sid: The SID of the Participant resource. + """ + return ParticipantContext( + self._version, + room_sid=self._solution["room_sid"], + participant_sid=participant_sid, + ) + + def __call__(self, participant_sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param participant_sid: The SID of the Participant resource. + """ + return ParticipantContext( + self._version, + room_sid=self._solution["room_sid"], + participant_sid=participant_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/insights/v1/setting.py b/venv/Lib/site-packages/twilio/rest/insights/v1/setting.py new file mode 100644 index 00000000..3c6b746f --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/insights/v1/setting.py @@ -0,0 +1,318 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class SettingInstance(InstanceResource): + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar advanced_features: A boolean flag indicating whether Advanced Features for Voice Insights are enabled. + :ivar voice_trace: A boolean flag indicating whether Voice Trace is enabled. + :ivar url: The URL of this resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.advanced_features: Optional[bool] = payload.get("advanced_features") + self.voice_trace: Optional[bool] = payload.get("voice_trace") + self.url: Optional[str] = payload.get("url") + + self._context: Optional[SettingContext] = None + + @property + def _proxy(self) -> "SettingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SettingContext for this SettingInstance + """ + if self._context is None: + self._context = SettingContext( + self._version, + ) + return self._context + + def fetch( + self, subaccount_sid: Union[str, object] = values.unset + ) -> "SettingInstance": + """ + Fetch the SettingInstance + + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: The fetched SettingInstance + """ + return self._proxy.fetch( + subaccount_sid=subaccount_sid, + ) + + async def fetch_async( + self, subaccount_sid: Union[str, object] = values.unset + ) -> "SettingInstance": + """ + Asynchronous coroutine to fetch the SettingInstance + + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: The fetched SettingInstance + """ + return await self._proxy.fetch_async( + subaccount_sid=subaccount_sid, + ) + + def update( + self, + advanced_features: Union[bool, object] = values.unset, + voice_trace: Union[bool, object] = values.unset, + subaccount_sid: Union[str, object] = values.unset, + ) -> "SettingInstance": + """ + Update the SettingInstance + + :param advanced_features: A boolean flag to enable Advanced Features for Voice Insights. + :param voice_trace: A boolean flag to enable Voice Trace. + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: The updated SettingInstance + """ + return self._proxy.update( + advanced_features=advanced_features, + voice_trace=voice_trace, + subaccount_sid=subaccount_sid, + ) + + async def update_async( + self, + advanced_features: Union[bool, object] = values.unset, + voice_trace: Union[bool, object] = values.unset, + subaccount_sid: Union[str, object] = values.unset, + ) -> "SettingInstance": + """ + Asynchronous coroutine to update the SettingInstance + + :param advanced_features: A boolean flag to enable Advanced Features for Voice Insights. + :param voice_trace: A boolean flag to enable Voice Trace. + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: The updated SettingInstance + """ + return await self._proxy.update_async( + advanced_features=advanced_features, + voice_trace=voice_trace, + subaccount_sid=subaccount_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class SettingContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the SettingContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/Voice/Settings" + + def fetch( + self, subaccount_sid: Union[str, object] = values.unset + ) -> SettingInstance: + """ + Fetch the SettingInstance + + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: The fetched SettingInstance + """ + + data = values.of( + { + "SubaccountSid": subaccount_sid, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return SettingInstance( + self._version, + payload, + ) + + async def fetch_async( + self, subaccount_sid: Union[str, object] = values.unset + ) -> SettingInstance: + """ + Asynchronous coroutine to fetch the SettingInstance + + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: The fetched SettingInstance + """ + + data = values.of( + { + "SubaccountSid": subaccount_sid, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return SettingInstance( + self._version, + payload, + ) + + def update( + self, + advanced_features: Union[bool, object] = values.unset, + voice_trace: Union[bool, object] = values.unset, + subaccount_sid: Union[str, object] = values.unset, + ) -> SettingInstance: + """ + Update the SettingInstance + + :param advanced_features: A boolean flag to enable Advanced Features for Voice Insights. + :param voice_trace: A boolean flag to enable Voice Trace. + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: The updated SettingInstance + """ + + data = values.of( + { + "AdvancedFeatures": serialize.boolean_to_string(advanced_features), + "VoiceTrace": serialize.boolean_to_string(voice_trace), + "SubaccountSid": subaccount_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SettingInstance(self._version, payload) + + async def update_async( + self, + advanced_features: Union[bool, object] = values.unset, + voice_trace: Union[bool, object] = values.unset, + subaccount_sid: Union[str, object] = values.unset, + ) -> SettingInstance: + """ + Asynchronous coroutine to update the SettingInstance + + :param advanced_features: A boolean flag to enable Advanced Features for Voice Insights. + :param voice_trace: A boolean flag to enable Voice Trace. + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: The updated SettingInstance + """ + + data = values.of( + { + "AdvancedFeatures": serialize.boolean_to_string(advanced_features), + "VoiceTrace": serialize.boolean_to_string(voice_trace), + "SubaccountSid": subaccount_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SettingInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class SettingList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SettingList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> SettingContext: + """ + Constructs a SettingContext + + """ + return SettingContext(self._version) + + def __call__(self) -> SettingContext: + """ + Constructs a SettingContext + + """ + return SettingContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/IntelligenceBase.py b/venv/Lib/site-packages/twilio/rest/intelligence/IntelligenceBase.py new file mode 100644 index 00000000..0546bc15 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/intelligence/IntelligenceBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.intelligence.v2 import V2 + + +class IntelligenceBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Intelligence Domain + + :returns: Domain for Intelligence + """ + super().__init__(twilio, "https://intelligence.twilio.com") + self._v2: Optional[V2] = None + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Intelligence + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/__init__.py b/venv/Lib/site-packages/twilio/rest/intelligence/__init__.py new file mode 100644 index 00000000..6d565b43 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/intelligence/__init__.py @@ -0,0 +1,13 @@ +from twilio.rest.intelligence.IntelligenceBase import IntelligenceBase +from twilio.rest.intelligence.v2.service import ServiceList +from twilio.rest.intelligence.v2.transcript import TranscriptList + + +class Intelligence(IntelligenceBase): + @property + def transcripts(self) -> TranscriptList: + return self.v2.transcripts + + @property + def services(self) -> ServiceList: + return self.v2.services diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/__pycache__/IntelligenceBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/intelligence/__pycache__/IntelligenceBase.cpython-312.pyc new file mode 100644 index 00000000..18106714 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/intelligence/__pycache__/IntelligenceBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/intelligence/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..41b82ceb Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/intelligence/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/v2/__init__.py b/venv/Lib/site-packages/twilio/rest/intelligence/v2/__init__.py new file mode 100644 index 00000000..4999146f --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/intelligence/v2/__init__.py @@ -0,0 +1,99 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.intelligence.v2.custom_operator import CustomOperatorList +from twilio.rest.intelligence.v2.operator import OperatorList +from twilio.rest.intelligence.v2.operator_attachment import OperatorAttachmentList +from twilio.rest.intelligence.v2.operator_attachments import OperatorAttachmentsList +from twilio.rest.intelligence.v2.operator_type import OperatorTypeList +from twilio.rest.intelligence.v2.prebuilt_operator import PrebuiltOperatorList +from twilio.rest.intelligence.v2.service import ServiceList +from twilio.rest.intelligence.v2.transcript import TranscriptList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Intelligence + + :param domain: The Twilio.intelligence domain + """ + super().__init__(domain, "v2") + self._custom_operators: Optional[CustomOperatorList] = None + self._operators: Optional[OperatorList] = None + self._operator_attachment: Optional[OperatorAttachmentList] = None + self._operator_attachments: Optional[OperatorAttachmentsList] = None + self._operator_type: Optional[OperatorTypeList] = None + self._prebuilt_operators: Optional[PrebuiltOperatorList] = None + self._services: Optional[ServiceList] = None + self._transcripts: Optional[TranscriptList] = None + + @property + def custom_operators(self) -> CustomOperatorList: + if self._custom_operators is None: + self._custom_operators = CustomOperatorList(self) + return self._custom_operators + + @property + def operators(self) -> OperatorList: + if self._operators is None: + self._operators = OperatorList(self) + return self._operators + + @property + def operator_attachment(self) -> OperatorAttachmentList: + if self._operator_attachment is None: + self._operator_attachment = OperatorAttachmentList(self) + return self._operator_attachment + + @property + def operator_attachments(self) -> OperatorAttachmentsList: + if self._operator_attachments is None: + self._operator_attachments = OperatorAttachmentsList(self) + return self._operator_attachments + + @property + def operator_type(self) -> OperatorTypeList: + if self._operator_type is None: + self._operator_type = OperatorTypeList(self) + return self._operator_type + + @property + def prebuilt_operators(self) -> PrebuiltOperatorList: + if self._prebuilt_operators is None: + self._prebuilt_operators = PrebuiltOperatorList(self) + return self._prebuilt_operators + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + @property + def transcripts(self) -> TranscriptList: + if self._transcripts is None: + self._transcripts = TranscriptList(self) + return self._transcripts + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/v2/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/intelligence/v2/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..3723431d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/intelligence/v2/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/v2/__pycache__/custom_operator.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/intelligence/v2/__pycache__/custom_operator.cpython-312.pyc new file mode 100644 index 00000000..66c50297 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/intelligence/v2/__pycache__/custom_operator.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/v2/__pycache__/operator.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/intelligence/v2/__pycache__/operator.cpython-312.pyc new file mode 100644 index 00000000..84eb7230 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/intelligence/v2/__pycache__/operator.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/v2/__pycache__/operator_attachment.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/intelligence/v2/__pycache__/operator_attachment.cpython-312.pyc new file mode 100644 index 00000000..7fa6abfb Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/intelligence/v2/__pycache__/operator_attachment.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/v2/__pycache__/operator_attachments.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/intelligence/v2/__pycache__/operator_attachments.cpython-312.pyc new file mode 100644 index 00000000..1186ae56 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/intelligence/v2/__pycache__/operator_attachments.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/v2/__pycache__/operator_type.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/intelligence/v2/__pycache__/operator_type.cpython-312.pyc new file mode 100644 index 00000000..571af7d7 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/intelligence/v2/__pycache__/operator_type.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/v2/__pycache__/prebuilt_operator.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/intelligence/v2/__pycache__/prebuilt_operator.cpython-312.pyc new file mode 100644 index 00000000..59544cb0 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/intelligence/v2/__pycache__/prebuilt_operator.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/v2/__pycache__/service.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/intelligence/v2/__pycache__/service.cpython-312.pyc new file mode 100644 index 00000000..b1b46c49 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/intelligence/v2/__pycache__/service.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/v2/custom_operator.py b/venv/Lib/site-packages/twilio/rest/intelligence/v2/custom_operator.py new file mode 100644 index 00000000..3dd73d47 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/intelligence/v2/custom_operator.py @@ -0,0 +1,716 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CustomOperatorInstance(InstanceResource): + + class Availability(object): + INTERNAL = "internal" + BETA = "beta" + PUBLIC = "public" + RETIRED = "retired" + + """ + :ivar account_sid: The unique SID identifier of the Account the Custom Operator belongs to. + :ivar sid: A 34 character string that uniquely identifies this Custom Operator. + :ivar friendly_name: A human-readable name of this resource, up to 64 characters. + :ivar description: A human-readable description of this resource, longer than the friendly name. + :ivar author: The creator of the Custom Operator. Custom Operators can only be created by a Twilio Account. + :ivar operator_type: Operator Type for this Operator. References an existing Operator Type resource. + :ivar version: Numeric Custom Operator version. Incremented with each update on the resource, used to ensure integrity when updating the Custom Operator. + :ivar availability: + :ivar config: Operator configuration, following the schema defined by the Operator Type. Only available on Operators created by the Account. + :ivar date_created: The date that this Custom Operator was created, given in ISO 8601 format. + :ivar date_updated: The date that this Custom Operator was updated, given in ISO 8601 format. + :ivar url: The URL of this resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.author: Optional[str] = payload.get("author") + self.operator_type: Optional[str] = payload.get("operator_type") + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.availability: Optional["CustomOperatorInstance.Availability"] = ( + payload.get("availability") + ) + self.config: Optional[Dict[str, object]] = payload.get("config") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CustomOperatorContext] = None + + @property + def _proxy(self) -> "CustomOperatorContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CustomOperatorContext for this CustomOperatorInstance + """ + if self._context is None: + self._context = CustomOperatorContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CustomOperatorInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CustomOperatorInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CustomOperatorInstance": + """ + Fetch the CustomOperatorInstance + + + :returns: The fetched CustomOperatorInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CustomOperatorInstance": + """ + Asynchronous coroutine to fetch the CustomOperatorInstance + + + :returns: The fetched CustomOperatorInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: str, + config: object, + if_match: Union[str, object] = values.unset, + ) -> "CustomOperatorInstance": + """ + Update the CustomOperatorInstance + + :param friendly_name: A human-readable name of this resource, up to 64 characters. + :param config: Operator configuration, following the schema defined by the Operator Type. + :param if_match: The If-Match HTTP request header + + :returns: The updated CustomOperatorInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + config=config, + if_match=if_match, + ) + + async def update_async( + self, + friendly_name: str, + config: object, + if_match: Union[str, object] = values.unset, + ) -> "CustomOperatorInstance": + """ + Asynchronous coroutine to update the CustomOperatorInstance + + :param friendly_name: A human-readable name of this resource, up to 64 characters. + :param config: Operator configuration, following the schema defined by the Operator Type. + :param if_match: The If-Match HTTP request header + + :returns: The updated CustomOperatorInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + config=config, + if_match=if_match, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CustomOperatorContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CustomOperatorContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this Custom Operator. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Operators/Custom/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the CustomOperatorInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CustomOperatorInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CustomOperatorInstance: + """ + Fetch the CustomOperatorInstance + + + :returns: The fetched CustomOperatorInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CustomOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CustomOperatorInstance: + """ + Asynchronous coroutine to fetch the CustomOperatorInstance + + + :returns: The fetched CustomOperatorInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CustomOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: str, + config: object, + if_match: Union[str, object] = values.unset, + ) -> CustomOperatorInstance: + """ + Update the CustomOperatorInstance + + :param friendly_name: A human-readable name of this resource, up to 64 characters. + :param config: Operator configuration, following the schema defined by the Operator Type. + :param if_match: The If-Match HTTP request header + + :returns: The updated CustomOperatorInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Config": serialize.object(config), + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomOperatorInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: str, + config: object, + if_match: Union[str, object] = values.unset, + ) -> CustomOperatorInstance: + """ + Asynchronous coroutine to update the CustomOperatorInstance + + :param friendly_name: A human-readable name of this resource, up to 64 characters. + :param config: Operator configuration, following the schema defined by the Operator Type. + :param if_match: The If-Match HTTP request header + + :returns: The updated CustomOperatorInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Config": serialize.object(config), + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomOperatorInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CustomOperatorPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CustomOperatorInstance: + """ + Build an instance of CustomOperatorInstance + + :param payload: Payload response from the API + """ + return CustomOperatorInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CustomOperatorList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CustomOperatorList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Operators/Custom" + + def create( + self, friendly_name: str, operator_type: str, config: object + ) -> CustomOperatorInstance: + """ + Create the CustomOperatorInstance + + :param friendly_name: A human readable description of the new Operator, up to 64 characters. + :param operator_type: Operator Type for this Operator. References an existing Operator Type resource. + :param config: Operator configuration, following the schema defined by the Operator Type. + + :returns: The created CustomOperatorInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "OperatorType": operator_type, + "Config": serialize.object(config), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomOperatorInstance(self._version, payload) + + async def create_async( + self, friendly_name: str, operator_type: str, config: object + ) -> CustomOperatorInstance: + """ + Asynchronously create the CustomOperatorInstance + + :param friendly_name: A human readable description of the new Operator, up to 64 characters. + :param operator_type: Operator Type for this Operator. References an existing Operator Type resource. + :param config: Operator configuration, following the schema defined by the Operator Type. + + :returns: The created CustomOperatorInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "OperatorType": operator_type, + "Config": serialize.object(config), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomOperatorInstance(self._version, payload) + + def stream( + self, + availability: Union[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CustomOperatorInstance]: + """ + Streams CustomOperatorInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "CustomOperatorInstance.Availability" availability: Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Custom Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + availability: Union[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CustomOperatorInstance]: + """ + Asynchronously streams CustomOperatorInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "CustomOperatorInstance.Availability" availability: Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Custom Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + availability: Union[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CustomOperatorInstance]: + """ + Lists CustomOperatorInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "CustomOperatorInstance.Availability" availability: Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Custom Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + availability: Union[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CustomOperatorInstance]: + """ + Asynchronously lists CustomOperatorInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "CustomOperatorInstance.Availability" availability: Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Custom Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + availability: Union[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CustomOperatorPage: + """ + Retrieve a single page of CustomOperatorInstance records from the API. + Request is executed immediately + + :param availability: Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param language_code: Returns Custom Operators that support the provided language code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CustomOperatorInstance + """ + data = values.of( + { + "Availability": availability, + "LanguageCode": language_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CustomOperatorPage(self._version, response) + + async def page_async( + self, + availability: Union[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CustomOperatorPage: + """ + Asynchronously retrieve a single page of CustomOperatorInstance records from the API. + Request is executed immediately + + :param availability: Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param language_code: Returns Custom Operators that support the provided language code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CustomOperatorInstance + """ + data = values.of( + { + "Availability": availability, + "LanguageCode": language_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CustomOperatorPage(self._version, response) + + def get_page(self, target_url: str) -> CustomOperatorPage: + """ + Retrieve a specific page of CustomOperatorInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CustomOperatorInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CustomOperatorPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CustomOperatorPage: + """ + Asynchronously retrieve a specific page of CustomOperatorInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CustomOperatorInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CustomOperatorPage(self._version, response) + + def get(self, sid: str) -> CustomOperatorContext: + """ + Constructs a CustomOperatorContext + + :param sid: A 34 character string that uniquely identifies this Custom Operator. + """ + return CustomOperatorContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CustomOperatorContext: + """ + Constructs a CustomOperatorContext + + :param sid: A 34 character string that uniquely identifies this Custom Operator. + """ + return CustomOperatorContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/v2/operator.py b/venv/Lib/site-packages/twilio/rest/intelligence/v2/operator.py new file mode 100644 index 00000000..984c46d7 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/intelligence/v2/operator.py @@ -0,0 +1,476 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class OperatorInstance(InstanceResource): + + class Availability(object): + INTERNAL = "internal" + BETA = "beta" + PUBLIC = "public" + RETIRED = "retired" + + """ + :ivar account_sid: The unique SID identifier of the Account the Operator belongs to. + :ivar sid: A 34 character string that uniquely identifies this Operator. + :ivar friendly_name: A human-readable name of this resource, up to 64 characters. + :ivar description: A human-readable description of this resource, longer than the friendly name. + :ivar author: The creator of the Operator. Either Twilio or the creating Account. + :ivar operator_type: Operator Type for this Operator. References an existing Operator Type resource. + :ivar version: Numeric Operator version. Incremented with each update on the resource, used to ensure integrity when updating the Operator. + :ivar availability: + :ivar config: Operator configuration, following the schema defined by the Operator Type. Only available on Custom Operators created by the Account. + :ivar date_created: The date that this Operator was created, given in ISO 8601 format. + :ivar date_updated: The date that this Operator was updated, given in ISO 8601 format. + :ivar url: The URL of this resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.author: Optional[str] = payload.get("author") + self.operator_type: Optional[str] = payload.get("operator_type") + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.availability: Optional["OperatorInstance.Availability"] = payload.get( + "availability" + ) + self.config: Optional[Dict[str, object]] = payload.get("config") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[OperatorContext] = None + + @property + def _proxy(self) -> "OperatorContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OperatorContext for this OperatorInstance + """ + if self._context is None: + self._context = OperatorContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "OperatorInstance": + """ + Fetch the OperatorInstance + + + :returns: The fetched OperatorInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "OperatorInstance": + """ + Asynchronous coroutine to fetch the OperatorInstance + + + :returns: The fetched OperatorInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OperatorContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the OperatorContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this Operator. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Operators/{sid}".format(**self._solution) + + def fetch(self) -> OperatorInstance: + """ + Fetch the OperatorInstance + + + :returns: The fetched OperatorInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return OperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> OperatorInstance: + """ + Asynchronous coroutine to fetch the OperatorInstance + + + :returns: The fetched OperatorInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return OperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OperatorPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> OperatorInstance: + """ + Build an instance of OperatorInstance + + :param payload: Payload response from the API + """ + return OperatorInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class OperatorList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OperatorList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Operators" + + def stream( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[OperatorInstance]: + """ + Streams OperatorInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "OperatorInstance.Availability" availability: Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[OperatorInstance]: + """ + Asynchronously streams OperatorInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "OperatorInstance.Availability" availability: Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OperatorInstance]: + """ + Lists OperatorInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "OperatorInstance.Availability" availability: Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OperatorInstance]: + """ + Asynchronously lists OperatorInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "OperatorInstance.Availability" availability: Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OperatorPage: + """ + Retrieve a single page of OperatorInstance records from the API. + Request is executed immediately + + :param availability: Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param language_code: Returns Operators that support the provided language code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of OperatorInstance + """ + data = values.of( + { + "Availability": availability, + "LanguageCode": language_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OperatorPage(self._version, response) + + async def page_async( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OperatorPage: + """ + Asynchronously retrieve a single page of OperatorInstance records from the API. + Request is executed immediately + + :param availability: Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param language_code: Returns Operators that support the provided language code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of OperatorInstance + """ + data = values.of( + { + "Availability": availability, + "LanguageCode": language_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OperatorPage(self._version, response) + + def get_page(self, target_url: str) -> OperatorPage: + """ + Retrieve a specific page of OperatorInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OperatorInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return OperatorPage(self._version, response) + + async def get_page_async(self, target_url: str) -> OperatorPage: + """ + Asynchronously retrieve a specific page of OperatorInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OperatorInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return OperatorPage(self._version, response) + + def get(self, sid: str) -> OperatorContext: + """ + Constructs a OperatorContext + + :param sid: A 34 character string that uniquely identifies this Operator. + """ + return OperatorContext(self._version, sid=sid) + + def __call__(self, sid: str) -> OperatorContext: + """ + Constructs a OperatorContext + + :param sid: A 34 character string that uniquely identifies this Operator. + """ + return OperatorContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/v2/operator_attachment.py b/venv/Lib/site-packages/twilio/rest/intelligence/v2/operator_attachment.py new file mode 100644 index 00000000..6080bc5e --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/intelligence/v2/operator_attachment.py @@ -0,0 +1,247 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class OperatorAttachmentInstance(InstanceResource): + """ + :ivar service_sid: The unique SID identifier of the Service. + :ivar operator_sid: The unique SID identifier of the Operator. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: Optional[str] = None, + operator_sid: Optional[str] = None, + ): + super().__init__(version) + + self.service_sid: Optional[str] = payload.get("service_sid") + self.operator_sid: Optional[str] = payload.get("operator_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid or self.service_sid, + "operator_sid": operator_sid or self.operator_sid, + } + self._context: Optional[OperatorAttachmentContext] = None + + @property + def _proxy(self) -> "OperatorAttachmentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OperatorAttachmentContext for this OperatorAttachmentInstance + """ + if self._context is None: + self._context = OperatorAttachmentContext( + self._version, + service_sid=self._solution["service_sid"], + operator_sid=self._solution["operator_sid"], + ) + return self._context + + def create(self) -> "OperatorAttachmentInstance": + """ + Create the OperatorAttachmentInstance + + + :returns: The created OperatorAttachmentInstance + """ + return self._proxy.create() + + async def create_async(self) -> "OperatorAttachmentInstance": + """ + Asynchronous coroutine to create the OperatorAttachmentInstance + + + :returns: The created OperatorAttachmentInstance + """ + return await self._proxy.create_async() + + def delete(self) -> bool: + """ + Deletes the OperatorAttachmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OperatorAttachmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OperatorAttachmentContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, operator_sid: str): + """ + Initialize the OperatorAttachmentContext + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param operator_sid: The unique SID identifier of the Operator. Allows both Custom and Pre-built Operators. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "operator_sid": operator_sid, + } + self._uri = "/Services/{service_sid}/Operators/{operator_sid}".format( + **self._solution + ) + + def create(self) -> OperatorAttachmentInstance: + """ + Create the OperatorAttachmentInstance + + + :returns: The created OperatorAttachmentInstance + """ + data = values.of({}) + + payload = self._version.create(method="POST", uri=self._uri, data=data) + + return OperatorAttachmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + operator_sid=self._solution["operator_sid"], + ) + + async def create_async(self) -> OperatorAttachmentInstance: + """ + Asynchronous coroutine to create the OperatorAttachmentInstance + + + :returns: The created OperatorAttachmentInstance + """ + data = values.of({}) + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data + ) + + return OperatorAttachmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + operator_sid=self._solution["operator_sid"], + ) + + def delete(self) -> bool: + """ + Deletes the OperatorAttachmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OperatorAttachmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OperatorAttachmentList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OperatorAttachmentList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, service_sid: str, operator_sid: str) -> OperatorAttachmentContext: + """ + Constructs a OperatorAttachmentContext + + :param service_sid: The unique SID identifier of the Service. + :param operator_sid: The unique SID identifier of the Operator. Allows both Custom and Pre-built Operators. + """ + return OperatorAttachmentContext( + self._version, service_sid=service_sid, operator_sid=operator_sid + ) + + def __call__( + self, service_sid: str, operator_sid: str + ) -> OperatorAttachmentContext: + """ + Constructs a OperatorAttachmentContext + + :param service_sid: The unique SID identifier of the Service. + :param operator_sid: The unique SID identifier of the Operator. Allows both Custom and Pre-built Operators. + """ + return OperatorAttachmentContext( + self._version, service_sid=service_sid, operator_sid=operator_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/v2/operator_attachments.py b/venv/Lib/site-packages/twilio/rest/intelligence/v2/operator_attachments.py new file mode 100644 index 00000000..19a875f7 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/intelligence/v2/operator_attachments.py @@ -0,0 +1,192 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class OperatorAttachmentsInstance(InstanceResource): + """ + :ivar service_sid: The unique SID identifier of the Service. + :ivar operator_sids: List of Operator SIDs attached to the service. Includes both Custom and Pre-built Operators. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: Optional[str] = None, + ): + super().__init__(version) + + self.service_sid: Optional[str] = payload.get("service_sid") + self.operator_sids: Optional[List[str]] = payload.get("operator_sids") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid or self.service_sid, + } + self._context: Optional[OperatorAttachmentsContext] = None + + @property + def _proxy(self) -> "OperatorAttachmentsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OperatorAttachmentsContext for this OperatorAttachmentsInstance + """ + if self._context is None: + self._context = OperatorAttachmentsContext( + self._version, + service_sid=self._solution["service_sid"], + ) + return self._context + + def fetch(self) -> "OperatorAttachmentsInstance": + """ + Fetch the OperatorAttachmentsInstance + + + :returns: The fetched OperatorAttachmentsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "OperatorAttachmentsInstance": + """ + Asynchronous coroutine to fetch the OperatorAttachmentsInstance + + + :returns: The fetched OperatorAttachmentsInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OperatorAttachmentsContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the OperatorAttachmentsContext + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Operators".format(**self._solution) + + def fetch(self) -> OperatorAttachmentsInstance: + """ + Fetch the OperatorAttachmentsInstance + + + :returns: The fetched OperatorAttachmentsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return OperatorAttachmentsInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + ) + + async def fetch_async(self) -> OperatorAttachmentsInstance: + """ + Asynchronous coroutine to fetch the OperatorAttachmentsInstance + + + :returns: The fetched OperatorAttachmentsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return OperatorAttachmentsInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OperatorAttachmentsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OperatorAttachmentsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, service_sid: str) -> OperatorAttachmentsContext: + """ + Constructs a OperatorAttachmentsContext + + :param service_sid: The unique SID identifier of the Service. + """ + return OperatorAttachmentsContext(self._version, service_sid=service_sid) + + def __call__(self, service_sid: str) -> OperatorAttachmentsContext: + """ + Constructs a OperatorAttachmentsContext + + :param service_sid: The unique SID identifier of the Service. + """ + return OperatorAttachmentsContext(self._version, service_sid=service_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/v2/operator_type.py b/venv/Lib/site-packages/twilio/rest/intelligence/v2/operator_type.py new file mode 100644 index 00000000..b14e677a --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/intelligence/v2/operator_type.py @@ -0,0 +1,458 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class OperatorTypeInstance(InstanceResource): + + class Availability(object): + INTERNAL = "internal" + BETA = "beta" + GENERAL_AVAILABILITY = "general-availability" + RETIRED = "retired" + DEPRECATED = "deprecated" + + class OutputType(object): + TEXT_CLASSIFICATION = "text-classification" + TEXT_EXTRACTION = "text-extraction" + TEXT_EXTRACTION_NORMALIZED = "text-extraction-normalized" + TEXT_GENERATION = "text-generation" + + class Provider(object): + TWILIO = "twilio" + AMAZON = "amazon" + OPENAI = "openai" + + """ + :ivar name: A unique name that references an Operator's Operator Type. + :ivar sid: A 34 character string that uniquely identifies this Operator Type. + :ivar friendly_name: A human-readable name of this resource, up to 64 characters. + :ivar description: A human-readable description of this resource, longer than the friendly name. + :ivar docs_link: Additional documentation for the Operator Type. + :ivar output_type: + :ivar supported_languages: List of languages this Operator Type supports. + :ivar provider: + :ivar availability: + :ivar configurable: Operators can be created from configurable Operator Types. + :ivar config_schema: JSON Schema for configuring an Operator with this Operator Type. Following https://json-schema.org/ + :ivar date_created: The date that this Operator Type was created, given in ISO 8601 format. + :ivar date_updated: The date that this Operator Type was updated, given in ISO 8601 format. + :ivar url: The URL of this resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.name: Optional[str] = payload.get("name") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.docs_link: Optional[str] = payload.get("docs_link") + self.output_type: Optional["OperatorTypeInstance.OutputType"] = payload.get( + "output_type" + ) + self.supported_languages: Optional[List[str]] = payload.get( + "supported_languages" + ) + self.provider: Optional["OperatorTypeInstance.Provider"] = payload.get( + "provider" + ) + self.availability: Optional["OperatorTypeInstance.Availability"] = payload.get( + "availability" + ) + self.configurable: Optional[bool] = payload.get("configurable") + self.config_schema: Optional[Dict[str, object]] = payload.get("config_schema") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[OperatorTypeContext] = None + + @property + def _proxy(self) -> "OperatorTypeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OperatorTypeContext for this OperatorTypeInstance + """ + if self._context is None: + self._context = OperatorTypeContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "OperatorTypeInstance": + """ + Fetch the OperatorTypeInstance + + + :returns: The fetched OperatorTypeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "OperatorTypeInstance": + """ + Asynchronous coroutine to fetch the OperatorTypeInstance + + + :returns: The fetched OperatorTypeInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OperatorTypeContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the OperatorTypeContext + + :param version: Version that contains the resource + :param sid: Either a 34 character string that uniquely identifies this Operator Type or the unique name that references an Operator Type. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/OperatorTypes/{sid}".format(**self._solution) + + def fetch(self) -> OperatorTypeInstance: + """ + Fetch the OperatorTypeInstance + + + :returns: The fetched OperatorTypeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return OperatorTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> OperatorTypeInstance: + """ + Asynchronous coroutine to fetch the OperatorTypeInstance + + + :returns: The fetched OperatorTypeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return OperatorTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OperatorTypePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> OperatorTypeInstance: + """ + Build an instance of OperatorTypeInstance + + :param payload: Payload response from the API + """ + return OperatorTypeInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class OperatorTypeList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OperatorTypeList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/OperatorTypes" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[OperatorTypeInstance]: + """ + Streams OperatorTypeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[OperatorTypeInstance]: + """ + Asynchronously streams OperatorTypeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OperatorTypeInstance]: + """ + Lists OperatorTypeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OperatorTypeInstance]: + """ + Asynchronously lists OperatorTypeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OperatorTypePage: + """ + Retrieve a single page of OperatorTypeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of OperatorTypeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OperatorTypePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OperatorTypePage: + """ + Asynchronously retrieve a single page of OperatorTypeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of OperatorTypeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OperatorTypePage(self._version, response) + + def get_page(self, target_url: str) -> OperatorTypePage: + """ + Retrieve a specific page of OperatorTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OperatorTypeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return OperatorTypePage(self._version, response) + + async def get_page_async(self, target_url: str) -> OperatorTypePage: + """ + Asynchronously retrieve a specific page of OperatorTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OperatorTypeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return OperatorTypePage(self._version, response) + + def get(self, sid: str) -> OperatorTypeContext: + """ + Constructs a OperatorTypeContext + + :param sid: Either a 34 character string that uniquely identifies this Operator Type or the unique name that references an Operator Type. + """ + return OperatorTypeContext(self._version, sid=sid) + + def __call__(self, sid: str) -> OperatorTypeContext: + """ + Constructs a OperatorTypeContext + + :param sid: Either a 34 character string that uniquely identifies this Operator Type or the unique name that references an Operator Type. + """ + return OperatorTypeContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/v2/prebuilt_operator.py b/venv/Lib/site-packages/twilio/rest/intelligence/v2/prebuilt_operator.py new file mode 100644 index 00000000..50693f29 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/intelligence/v2/prebuilt_operator.py @@ -0,0 +1,488 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class PrebuiltOperatorInstance(InstanceResource): + + class Availability(object): + INTERNAL = "internal" + BETA = "beta" + PUBLIC = "public" + RETIRED = "retired" + + """ + :ivar account_sid: The unique SID identifier of the Account the Pre-built Operator belongs to. + :ivar sid: A 34 character string that uniquely identifies this Pre-built Operator. + :ivar friendly_name: A human-readable name of this resource, up to 64 characters. + :ivar description: A human-readable description of this resource, longer than the friendly name. + :ivar author: The creator of the Operator. Pre-built Operators can only be created by Twilio. + :ivar operator_type: Operator Type for this Operator. References an existing Operator Type resource. + :ivar version: Numeric Operator version. Incremented with each update on the resource, used to ensure integrity when updating the Operator. + :ivar availability: + :ivar config: Operator configuration, following the schema defined by the Operator Type. Only available on Custom Operators created by the Account, will be empty for Pre-Built Operators. + :ivar date_created: The date that this Pre-built Operator was created, given in ISO 8601 format. + :ivar date_updated: The date that this Pre-built Operator was updated, given in ISO 8601 format. + :ivar url: The URL of this resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.author: Optional[str] = payload.get("author") + self.operator_type: Optional[str] = payload.get("operator_type") + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.availability: Optional["PrebuiltOperatorInstance.Availability"] = ( + payload.get("availability") + ) + self.config: Optional[Dict[str, object]] = payload.get("config") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[PrebuiltOperatorContext] = None + + @property + def _proxy(self) -> "PrebuiltOperatorContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PrebuiltOperatorContext for this PrebuiltOperatorInstance + """ + if self._context is None: + self._context = PrebuiltOperatorContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "PrebuiltOperatorInstance": + """ + Fetch the PrebuiltOperatorInstance + + + :returns: The fetched PrebuiltOperatorInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PrebuiltOperatorInstance": + """ + Asynchronous coroutine to fetch the PrebuiltOperatorInstance + + + :returns: The fetched PrebuiltOperatorInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PrebuiltOperatorContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the PrebuiltOperatorContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this Pre-built Operator. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Operators/PreBuilt/{sid}".format(**self._solution) + + def fetch(self) -> PrebuiltOperatorInstance: + """ + Fetch the PrebuiltOperatorInstance + + + :returns: The fetched PrebuiltOperatorInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PrebuiltOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> PrebuiltOperatorInstance: + """ + Asynchronous coroutine to fetch the PrebuiltOperatorInstance + + + :returns: The fetched PrebuiltOperatorInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PrebuiltOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PrebuiltOperatorPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PrebuiltOperatorInstance: + """ + Build an instance of PrebuiltOperatorInstance + + :param payload: Payload response from the API + """ + return PrebuiltOperatorInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class PrebuiltOperatorList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PrebuiltOperatorList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Operators/PreBuilt" + + def stream( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PrebuiltOperatorInstance]: + """ + Streams PrebuiltOperatorInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "PrebuiltOperatorInstance.Availability" availability: Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Pre-built Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PrebuiltOperatorInstance]: + """ + Asynchronously streams PrebuiltOperatorInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "PrebuiltOperatorInstance.Availability" availability: Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Pre-built Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PrebuiltOperatorInstance]: + """ + Lists PrebuiltOperatorInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "PrebuiltOperatorInstance.Availability" availability: Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Pre-built Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PrebuiltOperatorInstance]: + """ + Asynchronously lists PrebuiltOperatorInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "PrebuiltOperatorInstance.Availability" availability: Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Pre-built Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PrebuiltOperatorPage: + """ + Retrieve a single page of PrebuiltOperatorInstance records from the API. + Request is executed immediately + + :param availability: Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param language_code: Returns Pre-built Operators that support the provided language code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PrebuiltOperatorInstance + """ + data = values.of( + { + "Availability": availability, + "LanguageCode": language_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PrebuiltOperatorPage(self._version, response) + + async def page_async( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PrebuiltOperatorPage: + """ + Asynchronously retrieve a single page of PrebuiltOperatorInstance records from the API. + Request is executed immediately + + :param availability: Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param language_code: Returns Pre-built Operators that support the provided language code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PrebuiltOperatorInstance + """ + data = values.of( + { + "Availability": availability, + "LanguageCode": language_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PrebuiltOperatorPage(self._version, response) + + def get_page(self, target_url: str) -> PrebuiltOperatorPage: + """ + Retrieve a specific page of PrebuiltOperatorInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PrebuiltOperatorInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PrebuiltOperatorPage(self._version, response) + + async def get_page_async(self, target_url: str) -> PrebuiltOperatorPage: + """ + Asynchronously retrieve a specific page of PrebuiltOperatorInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PrebuiltOperatorInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PrebuiltOperatorPage(self._version, response) + + def get(self, sid: str) -> PrebuiltOperatorContext: + """ + Constructs a PrebuiltOperatorContext + + :param sid: A 34 character string that uniquely identifies this Pre-built Operator. + """ + return PrebuiltOperatorContext(self._version, sid=sid) + + def __call__(self, sid: str) -> PrebuiltOperatorContext: + """ + Constructs a PrebuiltOperatorContext + + :param sid: A 34 character string that uniquely identifies this Pre-built Operator. + """ + return PrebuiltOperatorContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/v2/service.py b/venv/Lib/site-packages/twilio/rest/intelligence/v2/service.py new file mode 100644 index 00000000..fac3eb84 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/intelligence/v2/service.py @@ -0,0 +1,787 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ServiceInstance(InstanceResource): + + class HttpMethod(object): + GET = "GET" + POST = "POST" + NULL = "NULL" + + """ + :ivar account_sid: The unique SID identifier of the Account the Service belongs to. + :ivar auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :ivar media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :ivar auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :ivar data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :ivar date_created: The date that this Service was created, given in ISO 8601 format. + :ivar date_updated: The date that this Service was updated, given in ISO 8601 format. + :ivar friendly_name: A human readable description of this resource, up to 64 characters. + :ivar language_code: The language code set during Service creation determines the Transcription language for all call recordings processed by that Service. The default is en-US if no language code is set. A Service can only support one language code, and it cannot be updated once it's set. + :ivar sid: A 34 character string that uniquely identifies this Service. + :ivar unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :ivar url: The URL of this resource. + :ivar webhook_url: The URL Twilio will request when executing the Webhook. + :ivar webhook_http_method: + :ivar read_only_attached_operator_sids: Operator sids attached to this service, read only + :ivar version: The version number of this Service. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.auto_redaction: Optional[bool] = payload.get("auto_redaction") + self.media_redaction: Optional[bool] = payload.get("media_redaction") + self.auto_transcribe: Optional[bool] = payload.get("auto_transcribe") + self.data_logging: Optional[bool] = payload.get("data_logging") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.language_code: Optional[str] = payload.get("language_code") + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.url: Optional[str] = payload.get("url") + self.webhook_url: Optional[str] = payload.get("webhook_url") + self.webhook_http_method: Optional["ServiceInstance.HttpMethod"] = payload.get( + "webhook_http_method" + ) + self.read_only_attached_operator_sids: Optional[List[str]] = payload.get( + "read_only_attached_operator_sids" + ) + self.version: Optional[int] = deserialize.integer(payload.get("version")) + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + if_match: Union[str, object] = values.unset, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param if_match: The If-Match HTTP request header + :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :param webhook_url: The URL Twilio will request when executing the Webhook. + :param webhook_http_method: + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + if_match=if_match, + auto_transcribe=auto_transcribe, + data_logging=data_logging, + friendly_name=friendly_name, + unique_name=unique_name, + auto_redaction=auto_redaction, + media_redaction=media_redaction, + webhook_url=webhook_url, + webhook_http_method=webhook_http_method, + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param if_match: The If-Match HTTP request header + :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :param webhook_url: The URL Twilio will request when executing the Webhook. + :param webhook_http_method: + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + if_match=if_match, + auto_transcribe=auto_transcribe, + data_logging=data_logging, + friendly_name=friendly_name, + unique_name=unique_name, + auto_redaction=auto_redaction, + media_redaction=media_redaction, + webhook_url=webhook_url, + webhook_http_method=webhook_http_method, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this Service. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + if_match: Union[str, object] = values.unset, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param if_match: The If-Match HTTP request header + :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :param webhook_url: The URL Twilio will request when executing the Webhook. + :param webhook_http_method: + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "AutoTranscribe": serialize.boolean_to_string(auto_transcribe), + "DataLogging": serialize.boolean_to_string(data_logging), + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "AutoRedaction": serialize.boolean_to_string(auto_redaction), + "MediaRedaction": serialize.boolean_to_string(media_redaction), + "WebhookUrl": webhook_url, + "WebhookHttpMethod": webhook_http_method, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param if_match: The If-Match HTTP request header + :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :param webhook_url: The URL Twilio will request when executing the Webhook. + :param webhook_http_method: + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "AutoTranscribe": serialize.boolean_to_string(auto_transcribe), + "DataLogging": serialize.boolean_to_string(data_logging), + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "AutoRedaction": serialize.boolean_to_string(auto_redaction), + "MediaRedaction": serialize.boolean_to_string(media_redaction), + "WebhookUrl": webhook_url, + "WebhookHttpMethod": webhook_http_method, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def create( + self, + unique_name: str, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + ) -> ServiceInstance: + """ + Create the ServiceInstance + + :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param language_code: The language code set during Service creation determines the Transcription language for all call recordings processed by that Service. The default is en-US if no language code is set. A Service can only support one language code, and it cannot be updated once it's set. + :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :param webhook_url: The URL Twilio will request when executing the Webhook. + :param webhook_http_method: + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "AutoTranscribe": serialize.boolean_to_string(auto_transcribe), + "DataLogging": serialize.boolean_to_string(data_logging), + "FriendlyName": friendly_name, + "LanguageCode": language_code, + "AutoRedaction": serialize.boolean_to_string(auto_redaction), + "MediaRedaction": serialize.boolean_to_string(media_redaction), + "WebhookUrl": webhook_url, + "WebhookHttpMethod": webhook_http_method, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async( + self, + unique_name: str, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param language_code: The language code set during Service creation determines the Transcription language for all call recordings processed by that Service. The default is en-US if no language code is set. A Service can only support one language code, and it cannot be updated once it's set. + :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :param webhook_url: The URL Twilio will request when executing the Webhook. + :param webhook_http_method: + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "AutoTranscribe": serialize.boolean_to_string(auto_transcribe), + "DataLogging": serialize.boolean_to_string(data_logging), + "FriendlyName": friendly_name, + "LanguageCode": language_code, + "AutoRedaction": serialize.boolean_to_string(auto_redaction), + "MediaRedaction": serialize.boolean_to_string(media_redaction), + "WebhookUrl": webhook_url, + "WebhookHttpMethod": webhook_http_method, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: A 34 character string that uniquely identifies this Service. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: A 34 character string that uniquely identifies this Service. + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/v2/transcript/__init__.py b/venv/Lib/site-packages/twilio/rest/intelligence/v2/transcript/__init__.py new file mode 100644 index 00000000..c2141bb5 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/intelligence/v2/transcript/__init__.py @@ -0,0 +1,775 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.intelligence.v2.transcript.media import MediaList +from twilio.rest.intelligence.v2.transcript.operator_result import OperatorResultList +from twilio.rest.intelligence.v2.transcript.sentence import SentenceList + + +class TranscriptInstance(InstanceResource): + + class Status(object): + QUEUED = "queued" + IN_PROGRESS = "in-progress" + COMPLETED = "completed" + FAILED = "failed" + CANCELED = "canceled" + + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar service_sid: The unique SID identifier of the Service. + :ivar sid: A 34 character string that uniquely identifies this Transcript. + :ivar date_created: The date that this Transcript was created, given in ISO 8601 format. + :ivar date_updated: The date that this Transcript was updated, given in ISO 8601 format. + :ivar status: + :ivar channel: Media Channel describing Transcript Source and Participant Mapping + :ivar data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :ivar language_code: The default language code of the audio. + :ivar customer_key: + :ivar media_start_time: The date that this Transcript's media was started, given in ISO 8601 format. + :ivar duration: The duration of this Transcript's source + :ivar url: The URL of this resource. + :ivar redaction: If the transcript has been redacted, a redacted alternative of the transcript will be available. + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.sid: Optional[str] = payload.get("sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.status: Optional["TranscriptInstance.Status"] = payload.get("status") + self.channel: Optional[Dict[str, object]] = payload.get("channel") + self.data_logging: Optional[bool] = payload.get("data_logging") + self.language_code: Optional[str] = payload.get("language_code") + self.customer_key: Optional[str] = payload.get("customer_key") + self.media_start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("media_start_time") + ) + self.duration: Optional[int] = deserialize.integer(payload.get("duration")) + self.url: Optional[str] = payload.get("url") + self.redaction: Optional[bool] = payload.get("redaction") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[TranscriptContext] = None + + @property + def _proxy(self) -> "TranscriptContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TranscriptContext for this TranscriptInstance + """ + if self._context is None: + self._context = TranscriptContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TranscriptInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TranscriptInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "TranscriptInstance": + """ + Fetch the TranscriptInstance + + + :returns: The fetched TranscriptInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TranscriptInstance": + """ + Asynchronous coroutine to fetch the TranscriptInstance + + + :returns: The fetched TranscriptInstance + """ + return await self._proxy.fetch_async() + + @property + def media(self) -> MediaList: + """ + Access the media + """ + return self._proxy.media + + @property + def operator_results(self) -> OperatorResultList: + """ + Access the operator_results + """ + return self._proxy.operator_results + + @property + def sentences(self) -> SentenceList: + """ + Access the sentences + """ + return self._proxy.sentences + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TranscriptContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the TranscriptContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this Transcript. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Transcripts/{sid}".format(**self._solution) + + self._media: Optional[MediaList] = None + self._operator_results: Optional[OperatorResultList] = None + self._sentences: Optional[SentenceList] = None + + def delete(self) -> bool: + """ + Deletes the TranscriptInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TranscriptInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TranscriptInstance: + """ + Fetch the TranscriptInstance + + + :returns: The fetched TranscriptInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TranscriptInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TranscriptInstance: + """ + Asynchronous coroutine to fetch the TranscriptInstance + + + :returns: The fetched TranscriptInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TranscriptInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + @property + def media(self) -> MediaList: + """ + Access the media + """ + if self._media is None: + self._media = MediaList( + self._version, + self._solution["sid"], + ) + return self._media + + @property + def operator_results(self) -> OperatorResultList: + """ + Access the operator_results + """ + if self._operator_results is None: + self._operator_results = OperatorResultList( + self._version, + self._solution["sid"], + ) + return self._operator_results + + @property + def sentences(self) -> SentenceList: + """ + Access the sentences + """ + if self._sentences is None: + self._sentences = SentenceList( + self._version, + self._solution["sid"], + ) + return self._sentences + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TranscriptPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TranscriptInstance: + """ + Build an instance of TranscriptInstance + + :param payload: Payload response from the API + """ + return TranscriptInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TranscriptList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TranscriptList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Transcripts" + + def create( + self, + service_sid: str, + channel: object, + customer_key: Union[str, object] = values.unset, + media_start_time: Union[datetime, object] = values.unset, + ) -> TranscriptInstance: + """ + Create the TranscriptInstance + + :param service_sid: The unique SID identifier of the Service. + :param channel: JSON object describing Media Channel including Source and Participants + :param customer_key: Used to store client provided metadata. Maximum of 64 double-byte UTF8 characters. + :param media_start_time: The date that this Transcript's media was started, given in ISO 8601 format. + + :returns: The created TranscriptInstance + """ + + data = values.of( + { + "ServiceSid": service_sid, + "Channel": serialize.object(channel), + "CustomerKey": customer_key, + "MediaStartTime": serialize.iso8601_datetime(media_start_time), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TranscriptInstance(self._version, payload) + + async def create_async( + self, + service_sid: str, + channel: object, + customer_key: Union[str, object] = values.unset, + media_start_time: Union[datetime, object] = values.unset, + ) -> TranscriptInstance: + """ + Asynchronously create the TranscriptInstance + + :param service_sid: The unique SID identifier of the Service. + :param channel: JSON object describing Media Channel including Source and Participants + :param customer_key: Used to store client provided metadata. Maximum of 64 double-byte UTF8 characters. + :param media_start_time: The date that this Transcript's media was started, given in ISO 8601 format. + + :returns: The created TranscriptInstance + """ + + data = values.of( + { + "ServiceSid": service_sid, + "Channel": serialize.object(channel), + "CustomerKey": customer_key, + "MediaStartTime": serialize.iso8601_datetime(media_start_time), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TranscriptInstance(self._version, payload) + + def stream( + self, + service_sid: Union[str, object] = values.unset, + before_start_time: Union[str, object] = values.unset, + after_start_time: Union[str, object] = values.unset, + before_date_created: Union[str, object] = values.unset, + after_date_created: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + source_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TranscriptInstance]: + """ + Streams TranscriptInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str service_sid: The unique SID identifier of the Service. + :param str before_start_time: Filter by before StartTime. + :param str after_start_time: Filter by after StartTime. + :param str before_date_created: Filter by before DateCreated. + :param str after_date_created: Filter by after DateCreated. + :param str status: Filter by status. + :param str language_code: Filter by Language Code. + :param str source_sid: Filter by SourceSid. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + service_sid=service_sid, + before_start_time=before_start_time, + after_start_time=after_start_time, + before_date_created=before_date_created, + after_date_created=after_date_created, + status=status, + language_code=language_code, + source_sid=source_sid, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + service_sid: Union[str, object] = values.unset, + before_start_time: Union[str, object] = values.unset, + after_start_time: Union[str, object] = values.unset, + before_date_created: Union[str, object] = values.unset, + after_date_created: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + source_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TranscriptInstance]: + """ + Asynchronously streams TranscriptInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str service_sid: The unique SID identifier of the Service. + :param str before_start_time: Filter by before StartTime. + :param str after_start_time: Filter by after StartTime. + :param str before_date_created: Filter by before DateCreated. + :param str after_date_created: Filter by after DateCreated. + :param str status: Filter by status. + :param str language_code: Filter by Language Code. + :param str source_sid: Filter by SourceSid. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + service_sid=service_sid, + before_start_time=before_start_time, + after_start_time=after_start_time, + before_date_created=before_date_created, + after_date_created=after_date_created, + status=status, + language_code=language_code, + source_sid=source_sid, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + service_sid: Union[str, object] = values.unset, + before_start_time: Union[str, object] = values.unset, + after_start_time: Union[str, object] = values.unset, + before_date_created: Union[str, object] = values.unset, + after_date_created: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + source_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TranscriptInstance]: + """ + Lists TranscriptInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str service_sid: The unique SID identifier of the Service. + :param str before_start_time: Filter by before StartTime. + :param str after_start_time: Filter by after StartTime. + :param str before_date_created: Filter by before DateCreated. + :param str after_date_created: Filter by after DateCreated. + :param str status: Filter by status. + :param str language_code: Filter by Language Code. + :param str source_sid: Filter by SourceSid. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + service_sid=service_sid, + before_start_time=before_start_time, + after_start_time=after_start_time, + before_date_created=before_date_created, + after_date_created=after_date_created, + status=status, + language_code=language_code, + source_sid=source_sid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + service_sid: Union[str, object] = values.unset, + before_start_time: Union[str, object] = values.unset, + after_start_time: Union[str, object] = values.unset, + before_date_created: Union[str, object] = values.unset, + after_date_created: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + source_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TranscriptInstance]: + """ + Asynchronously lists TranscriptInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str service_sid: The unique SID identifier of the Service. + :param str before_start_time: Filter by before StartTime. + :param str after_start_time: Filter by after StartTime. + :param str before_date_created: Filter by before DateCreated. + :param str after_date_created: Filter by after DateCreated. + :param str status: Filter by status. + :param str language_code: Filter by Language Code. + :param str source_sid: Filter by SourceSid. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + service_sid=service_sid, + before_start_time=before_start_time, + after_start_time=after_start_time, + before_date_created=before_date_created, + after_date_created=after_date_created, + status=status, + language_code=language_code, + source_sid=source_sid, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + service_sid: Union[str, object] = values.unset, + before_start_time: Union[str, object] = values.unset, + after_start_time: Union[str, object] = values.unset, + before_date_created: Union[str, object] = values.unset, + after_date_created: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + source_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TranscriptPage: + """ + Retrieve a single page of TranscriptInstance records from the API. + Request is executed immediately + + :param service_sid: The unique SID identifier of the Service. + :param before_start_time: Filter by before StartTime. + :param after_start_time: Filter by after StartTime. + :param before_date_created: Filter by before DateCreated. + :param after_date_created: Filter by after DateCreated. + :param status: Filter by status. + :param language_code: Filter by Language Code. + :param source_sid: Filter by SourceSid. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TranscriptInstance + """ + data = values.of( + { + "ServiceSid": service_sid, + "BeforeStartTime": before_start_time, + "AfterStartTime": after_start_time, + "BeforeDateCreated": before_date_created, + "AfterDateCreated": after_date_created, + "Status": status, + "LanguageCode": language_code, + "SourceSid": source_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TranscriptPage(self._version, response) + + async def page_async( + self, + service_sid: Union[str, object] = values.unset, + before_start_time: Union[str, object] = values.unset, + after_start_time: Union[str, object] = values.unset, + before_date_created: Union[str, object] = values.unset, + after_date_created: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + source_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TranscriptPage: + """ + Asynchronously retrieve a single page of TranscriptInstance records from the API. + Request is executed immediately + + :param service_sid: The unique SID identifier of the Service. + :param before_start_time: Filter by before StartTime. + :param after_start_time: Filter by after StartTime. + :param before_date_created: Filter by before DateCreated. + :param after_date_created: Filter by after DateCreated. + :param status: Filter by status. + :param language_code: Filter by Language Code. + :param source_sid: Filter by SourceSid. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TranscriptInstance + """ + data = values.of( + { + "ServiceSid": service_sid, + "BeforeStartTime": before_start_time, + "AfterStartTime": after_start_time, + "BeforeDateCreated": before_date_created, + "AfterDateCreated": after_date_created, + "Status": status, + "LanguageCode": language_code, + "SourceSid": source_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TranscriptPage(self._version, response) + + def get_page(self, target_url: str) -> TranscriptPage: + """ + Retrieve a specific page of TranscriptInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TranscriptInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TranscriptPage(self._version, response) + + async def get_page_async(self, target_url: str) -> TranscriptPage: + """ + Asynchronously retrieve a specific page of TranscriptInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TranscriptInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TranscriptPage(self._version, response) + + def get(self, sid: str) -> TranscriptContext: + """ + Constructs a TranscriptContext + + :param sid: A 34 character string that uniquely identifies this Transcript. + """ + return TranscriptContext(self._version, sid=sid) + + def __call__(self, sid: str) -> TranscriptContext: + """ + Constructs a TranscriptContext + + :param sid: A 34 character string that uniquely identifies this Transcript. + """ + return TranscriptContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/v2/transcript/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/intelligence/v2/transcript/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..c0778d9b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/intelligence/v2/transcript/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/v2/transcript/__pycache__/media.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/intelligence/v2/transcript/__pycache__/media.cpython-312.pyc new file mode 100644 index 00000000..cde1c767 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/intelligence/v2/transcript/__pycache__/media.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/v2/transcript/__pycache__/operator_result.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/intelligence/v2/transcript/__pycache__/operator_result.cpython-312.pyc new file mode 100644 index 00000000..24f7877d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/intelligence/v2/transcript/__pycache__/operator_result.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/v2/transcript/__pycache__/sentence.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/intelligence/v2/transcript/__pycache__/sentence.cpython-312.pyc new file mode 100644 index 00000000..b3b3b75a Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/intelligence/v2/transcript/__pycache__/sentence.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/v2/transcript/media.py b/venv/Lib/site-packages/twilio/rest/intelligence/v2/transcript/media.py new file mode 100644 index 00000000..76bc448e --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/intelligence/v2/transcript/media.py @@ -0,0 +1,221 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class MediaInstance(InstanceResource): + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar media_url: Downloadable URL for media, if stored in Twilio AI. + :ivar service_sid: The unique SID identifier of the Service. + :ivar sid: The unique SID identifier of the Transcript. + :ivar url: The URL of this resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.media_url: Optional[str] = payload.get("media_url") + self.service_sid: Optional[str] = payload.get("service_sid") + self.sid: Optional[str] = payload.get("sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid, + } + self._context: Optional[MediaContext] = None + + @property + def _proxy(self) -> "MediaContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MediaContext for this MediaInstance + """ + if self._context is None: + self._context = MediaContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self, redacted: Union[bool, object] = values.unset) -> "MediaInstance": + """ + Fetch the MediaInstance + + :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. + + :returns: The fetched MediaInstance + """ + return self._proxy.fetch( + redacted=redacted, + ) + + async def fetch_async( + self, redacted: Union[bool, object] = values.unset + ) -> "MediaInstance": + """ + Asynchronous coroutine to fetch the MediaInstance + + :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. + + :returns: The fetched MediaInstance + """ + return await self._proxy.fetch_async( + redacted=redacted, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MediaContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the MediaContext + + :param version: Version that contains the resource + :param sid: The unique SID identifier of the Transcript. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Transcripts/{sid}/Media".format(**self._solution) + + def fetch(self, redacted: Union[bool, object] = values.unset) -> MediaInstance: + """ + Fetch the MediaInstance + + :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. + + :returns: The fetched MediaInstance + """ + + data = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return MediaInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async( + self, redacted: Union[bool, object] = values.unset + ) -> MediaInstance: + """ + Asynchronous coroutine to fetch the MediaInstance + + :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. + + :returns: The fetched MediaInstance + """ + + data = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return MediaInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MediaList(ListResource): + + def __init__(self, version: Version, sid: str): + """ + Initialize the MediaList + + :param version: Version that contains the resource + :param sid: The unique SID identifier of the Transcript. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + + def get(self) -> MediaContext: + """ + Constructs a MediaContext + + """ + return MediaContext(self._version, sid=self._solution["sid"]) + + def __call__(self) -> MediaContext: + """ + Constructs a MediaContext + + """ + return MediaContext(self._version, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/v2/transcript/operator_result.py b/venv/Lib/site-packages/twilio/rest/intelligence/v2/transcript/operator_result.py new file mode 100644 index 00000000..9ba2c57f --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/intelligence/v2/transcript/operator_result.py @@ -0,0 +1,531 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class OperatorResultInstance(InstanceResource): + + class OperatorType(object): + CONVERSATION_CLASSIFY = "conversation_classify" + UTTERANCE_CLASSIFY = "utterance_classify" + EXTRACT = "extract" + EXTRACT_NORMALIZE = "extract_normalize" + PII_EXTRACT = "pii_extract" + TEXT_GENERATION = "text_generation" + JSON = "json" + + """ + :ivar operator_type: + :ivar name: The name of the applied Language Understanding. + :ivar operator_sid: A 34 character string that identifies this Language Understanding operator sid. + :ivar extract_match: Boolean to tell if extract Language Understanding Processing model matches results. + :ivar match_probability: Percentage of 'matching' class needed to consider a sentence matches + :ivar normalized_result: Normalized output of extraction stage which matches Label. + :ivar utterance_results: List of mapped utterance object which matches sentences. + :ivar utterance_match: Boolean to tell if Utterance matches results. + :ivar predicted_label: The 'matching' class. This might be available on conversation classify model outputs. + :ivar predicted_probability: Percentage of 'matching' class needed to consider a sentence matches. + :ivar label_probabilities: The labels probabilities. This might be available on conversation classify model outputs. + :ivar extract_results: List of text extraction results. This might be available on classify-extract model outputs. + :ivar text_generation_results: Output of a text generation operator for example Conversation Sumamary. + :ivar json_results: + :ivar transcript_sid: A 34 character string that uniquely identifies this Transcript. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + transcript_sid: str, + operator_sid: Optional[str] = None, + ): + super().__init__(version) + + self.operator_type: Optional["OperatorResultInstance.OperatorType"] = ( + payload.get("operator_type") + ) + self.name: Optional[str] = payload.get("name") + self.operator_sid: Optional[str] = payload.get("operator_sid") + self.extract_match: Optional[bool] = payload.get("extract_match") + self.match_probability: Optional[float] = deserialize.decimal( + payload.get("match_probability") + ) + self.normalized_result: Optional[str] = payload.get("normalized_result") + self.utterance_results: Optional[List[Dict[str, object]]] = payload.get( + "utterance_results" + ) + self.utterance_match: Optional[bool] = payload.get("utterance_match") + self.predicted_label: Optional[str] = payload.get("predicted_label") + self.predicted_probability: Optional[float] = deserialize.decimal( + payload.get("predicted_probability") + ) + self.label_probabilities: Optional[Dict[str, object]] = payload.get( + "label_probabilities" + ) + self.extract_results: Optional[Dict[str, object]] = payload.get( + "extract_results" + ) + self.text_generation_results: Optional[Dict[str, object]] = payload.get( + "text_generation_results" + ) + self.json_results: Optional[Dict[str, object]] = payload.get("json_results") + self.transcript_sid: Optional[str] = payload.get("transcript_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "transcript_sid": transcript_sid, + "operator_sid": operator_sid or self.operator_sid, + } + self._context: Optional[OperatorResultContext] = None + + @property + def _proxy(self) -> "OperatorResultContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OperatorResultContext for this OperatorResultInstance + """ + if self._context is None: + self._context = OperatorResultContext( + self._version, + transcript_sid=self._solution["transcript_sid"], + operator_sid=self._solution["operator_sid"], + ) + return self._context + + def fetch( + self, redacted: Union[bool, object] = values.unset + ) -> "OperatorResultInstance": + """ + Fetch the OperatorResultInstance + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + + :returns: The fetched OperatorResultInstance + """ + return self._proxy.fetch( + redacted=redacted, + ) + + async def fetch_async( + self, redacted: Union[bool, object] = values.unset + ) -> "OperatorResultInstance": + """ + Asynchronous coroutine to fetch the OperatorResultInstance + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + + :returns: The fetched OperatorResultInstance + """ + return await self._proxy.fetch_async( + redacted=redacted, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OperatorResultContext(InstanceContext): + + def __init__(self, version: Version, transcript_sid: str, operator_sid: str): + """ + Initialize the OperatorResultContext + + :param version: Version that contains the resource + :param transcript_sid: A 34 character string that uniquely identifies this Transcript. + :param operator_sid: A 34 character string that identifies this Language Understanding operator sid. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "transcript_sid": transcript_sid, + "operator_sid": operator_sid, + } + self._uri = ( + "/Transcripts/{transcript_sid}/OperatorResults/{operator_sid}".format( + **self._solution + ) + ) + + def fetch( + self, redacted: Union[bool, object] = values.unset + ) -> OperatorResultInstance: + """ + Fetch the OperatorResultInstance + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + + :returns: The fetched OperatorResultInstance + """ + + data = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return OperatorResultInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + operator_sid=self._solution["operator_sid"], + ) + + async def fetch_async( + self, redacted: Union[bool, object] = values.unset + ) -> OperatorResultInstance: + """ + Asynchronous coroutine to fetch the OperatorResultInstance + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + + :returns: The fetched OperatorResultInstance + """ + + data = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return OperatorResultInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + operator_sid=self._solution["operator_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OperatorResultPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> OperatorResultInstance: + """ + Build an instance of OperatorResultInstance + + :param payload: Payload response from the API + """ + return OperatorResultInstance( + self._version, payload, transcript_sid=self._solution["transcript_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class OperatorResultList(ListResource): + + def __init__(self, version: Version, transcript_sid: str): + """ + Initialize the OperatorResultList + + :param version: Version that contains the resource + :param transcript_sid: A 34 character string that uniquely identifies this Transcript. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "transcript_sid": transcript_sid, + } + self._uri = "/Transcripts/{transcript_sid}/OperatorResults".format( + **self._solution + ) + + def stream( + self, + redacted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[OperatorResultInstance]: + """ + Streams OperatorResultInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(redacted=redacted, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + redacted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[OperatorResultInstance]: + """ + Asynchronously streams OperatorResultInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(redacted=redacted, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + redacted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OperatorResultInstance]: + """ + Lists OperatorResultInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + redacted=redacted, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + redacted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OperatorResultInstance]: + """ + Asynchronously lists OperatorResultInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + redacted=redacted, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + redacted: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OperatorResultPage: + """ + Retrieve a single page of OperatorResultInstance records from the API. + Request is executed immediately + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of OperatorResultInstance + """ + data = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OperatorResultPage(self._version, response, self._solution) + + async def page_async( + self, + redacted: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OperatorResultPage: + """ + Asynchronously retrieve a single page of OperatorResultInstance records from the API. + Request is executed immediately + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of OperatorResultInstance + """ + data = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OperatorResultPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> OperatorResultPage: + """ + Retrieve a specific page of OperatorResultInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OperatorResultInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return OperatorResultPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> OperatorResultPage: + """ + Asynchronously retrieve a specific page of OperatorResultInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OperatorResultInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return OperatorResultPage(self._version, response, self._solution) + + def get(self, operator_sid: str) -> OperatorResultContext: + """ + Constructs a OperatorResultContext + + :param operator_sid: A 34 character string that identifies this Language Understanding operator sid. + """ + return OperatorResultContext( + self._version, + transcript_sid=self._solution["transcript_sid"], + operator_sid=operator_sid, + ) + + def __call__(self, operator_sid: str) -> OperatorResultContext: + """ + Constructs a OperatorResultContext + + :param operator_sid: A 34 character string that identifies this Language Understanding operator sid. + """ + return OperatorResultContext( + self._version, + transcript_sid=self._solution["transcript_sid"], + operator_sid=operator_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/intelligence/v2/transcript/sentence.py b/venv/Lib/site-packages/twilio/rest/intelligence/v2/transcript/sentence.py new file mode 100644 index 00000000..f4fb0b3b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/intelligence/v2/transcript/sentence.py @@ -0,0 +1,348 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SentenceInstance(InstanceResource): + """ + :ivar media_channel: The channel number. + :ivar sentence_index: The index of the sentence in the transcript. + :ivar start_time: Offset from the beginning of the transcript when this sentence starts. + :ivar end_time: Offset from the beginning of the transcript when this sentence ends. + :ivar transcript: Transcript text. + :ivar sid: A 34 character string that uniquely identifies this Sentence. + :ivar confidence: + :ivar words: Detailed information for each of the words of the given Sentence. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], transcript_sid: str): + super().__init__(version) + + self.media_channel: Optional[int] = deserialize.integer( + payload.get("media_channel") + ) + self.sentence_index: Optional[int] = deserialize.integer( + payload.get("sentence_index") + ) + self.start_time: Optional[float] = deserialize.decimal( + payload.get("start_time") + ) + self.end_time: Optional[float] = deserialize.decimal(payload.get("end_time")) + self.transcript: Optional[str] = payload.get("transcript") + self.sid: Optional[str] = payload.get("sid") + self.confidence: Optional[float] = deserialize.decimal( + payload.get("confidence") + ) + self.words: Optional[List[Dict[str, object]]] = payload.get("words") + + self._solution = { + "transcript_sid": transcript_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SentencePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SentenceInstance: + """ + Build an instance of SentenceInstance + + :param payload: Payload response from the API + """ + return SentenceInstance( + self._version, payload, transcript_sid=self._solution["transcript_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SentenceList(ListResource): + + def __init__(self, version: Version, transcript_sid: str): + """ + Initialize the SentenceList + + :param version: Version that contains the resource + :param transcript_sid: The unique SID identifier of the Transcript. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "transcript_sid": transcript_sid, + } + self._uri = "/Transcripts/{transcript_sid}/Sentences".format(**self._solution) + + def stream( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SentenceInstance]: + """ + Streams SentenceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + :param bool word_timestamps: Returns word level timestamps information, if word_timestamps is enabled. The default is `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + redacted=redacted, + word_timestamps=word_timestamps, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SentenceInstance]: + """ + Asynchronously streams SentenceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + :param bool word_timestamps: Returns word level timestamps information, if word_timestamps is enabled. The default is `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + redacted=redacted, + word_timestamps=word_timestamps, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SentenceInstance]: + """ + Lists SentenceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + :param bool word_timestamps: Returns word level timestamps information, if word_timestamps is enabled. The default is `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + redacted=redacted, + word_timestamps=word_timestamps, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SentenceInstance]: + """ + Asynchronously lists SentenceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + :param bool word_timestamps: Returns word level timestamps information, if word_timestamps is enabled. The default is `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + redacted=redacted, + word_timestamps=word_timestamps, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SentencePage: + """ + Retrieve a single page of SentenceInstance records from the API. + Request is executed immediately + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + :param word_timestamps: Returns word level timestamps information, if word_timestamps is enabled. The default is `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SentenceInstance + """ + data = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + "WordTimestamps": serialize.boolean_to_string(word_timestamps), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SentencePage(self._version, response, self._solution) + + async def page_async( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SentencePage: + """ + Asynchronously retrieve a single page of SentenceInstance records from the API. + Request is executed immediately + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + :param word_timestamps: Returns word level timestamps information, if word_timestamps is enabled. The default is `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SentenceInstance + """ + data = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + "WordTimestamps": serialize.boolean_to_string(word_timestamps), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SentencePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SentencePage: + """ + Retrieve a specific page of SentenceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SentenceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SentencePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SentencePage: + """ + Asynchronously retrieve a specific page of SentenceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SentenceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SentencePage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/IpMessagingBase.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/IpMessagingBase.py new file mode 100644 index 00000000..752d41ad --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/IpMessagingBase.py @@ -0,0 +1,55 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.ip_messaging.v1 import V1 +from twilio.rest.ip_messaging.v2 import V2 + + +class IpMessagingBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the IpMessaging Domain + + :returns: Domain for IpMessaging + """ + super().__init__(twilio, "https://ip-messaging.twilio.com") + self._v1: Optional[V1] = None + self._v2: Optional[V2] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of IpMessaging + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of IpMessaging + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/__init__.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/__init__.py new file mode 100644 index 00000000..61158f8e --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/__init__.py @@ -0,0 +1,25 @@ +from warnings import warn + +from twilio.rest.ip_messaging.IpMessagingBase import IpMessagingBase +from twilio.rest.ip_messaging.v2.credential import CredentialList +from twilio.rest.ip_messaging.v2.service import ServiceList + + +class IpMessaging(IpMessagingBase): + @property + def credentials(self) -> CredentialList: + warn( + "credentials is deprecated. Use v2.credentials instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.credentials + + @property + def services(self) -> ServiceList: + warn( + "services is deprecated. Use v2.services instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.services diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/__pycache__/IpMessagingBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/__pycache__/IpMessagingBase.cpython-312.pyc new file mode 100644 index 00000000..aa07cb1a Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/__pycache__/IpMessagingBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..7e93e52b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/__init__.py new file mode 100644 index 00000000..d1f40c79 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.ip_messaging.v1.credential import CredentialList +from twilio.rest.ip_messaging.v1.service import ServiceList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of IpMessaging + + :param domain: The Twilio.ip_messaging domain + """ + super().__init__(domain, "v1") + self._credentials: Optional[CredentialList] = None + self._services: Optional[ServiceList] = None + + @property + def credentials(self) -> CredentialList: + if self._credentials is None: + self._credentials = CredentialList(self) + return self._credentials + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..58da81da Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/__pycache__/credential.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/__pycache__/credential.cpython-312.pyc new file mode 100644 index 00000000..475a0d68 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/__pycache__/credential.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/credential.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/credential.py new file mode 100644 index 00000000..4aa6d3fc --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/credential.py @@ -0,0 +1,711 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CredentialInstance(InstanceResource): + + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: + :ivar account_sid: + :ivar friendly_name: + :ivar type: + :ivar sandbox: + :ivar date_created: + :ivar date_updated: + :ivar url: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["CredentialInstance.PushService"] = payload.get("type") + self.sandbox: Optional[str] = payload.get("sandbox") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CredentialContext] = None + + @property + def _proxy(self) -> "CredentialContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CredentialInstance": + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CredentialInstance": + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Update the CredentialInstance + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The updated CredentialInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The updated CredentialInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CredentialContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialInstance: + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Update the CredentialInstance + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: + """ + Build an instance of CredentialInstance + + :param payload: Payload response from the API + """ + return CredentialInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CredentialList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CredentialList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Credentials" + + def create( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Create the CredentialInstance + + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload) + + async def create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialInstance]: + """ + Streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialInstance]: + """ + Asynchronously streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Asynchronously lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Asynchronously retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response) + + def get_page(self, target_url: str) -> CredentialPage: + """ + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CredentialPage: + """ + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response) + + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: + """ + return CredentialContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: + """ + return CredentialContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/__init__.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/__init__.py new file mode 100644 index 00000000..3a77cf76 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/__init__.py @@ -0,0 +1,1359 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.ip_messaging.v1.service.channel import ChannelList +from twilio.rest.ip_messaging.v1.service.role import RoleList +from twilio.rest.ip_messaging.v1.service.user import UserList + + +class ServiceInstance(InstanceResource): + """ + :ivar sid: + :ivar account_sid: + :ivar friendly_name: + :ivar date_created: + :ivar date_updated: + :ivar default_service_role_sid: + :ivar default_channel_role_sid: + :ivar default_channel_creator_role_sid: + :ivar read_status_enabled: + :ivar reachability_enabled: + :ivar typing_indicator_timeout: + :ivar consumption_report_interval: + :ivar limits: + :ivar webhooks: + :ivar pre_webhook_url: + :ivar post_webhook_url: + :ivar webhook_method: + :ivar webhook_filters: + :ivar notifications: + :ivar url: + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.default_service_role_sid: Optional[str] = payload.get( + "default_service_role_sid" + ) + self.default_channel_role_sid: Optional[str] = payload.get( + "default_channel_role_sid" + ) + self.default_channel_creator_role_sid: Optional[str] = payload.get( + "default_channel_creator_role_sid" + ) + self.read_status_enabled: Optional[bool] = payload.get("read_status_enabled") + self.reachability_enabled: Optional[bool] = payload.get("reachability_enabled") + self.typing_indicator_timeout: Optional[int] = deserialize.integer( + payload.get("typing_indicator_timeout") + ) + self.consumption_report_interval: Optional[int] = deserialize.integer( + payload.get("consumption_report_interval") + ) + self.limits: Optional[Dict[str, object]] = payload.get("limits") + self.webhooks: Optional[Dict[str, object]] = payload.get("webhooks") + self.pre_webhook_url: Optional[str] = payload.get("pre_webhook_url") + self.post_webhook_url: Optional[str] = payload.get("post_webhook_url") + self.webhook_method: Optional[str] = payload.get("webhook_method") + self.webhook_filters: Optional[List[str]] = payload.get("webhook_filters") + self.notifications: Optional[Dict[str, object]] = payload.get("notifications") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param webhooks_on_message_send_url: + :param webhooks_on_message_send_method: + :param webhooks_on_message_update_url: + :param webhooks_on_message_update_method: + :param webhooks_on_message_remove_url: + :param webhooks_on_message_remove_method: + :param webhooks_on_channel_add_url: + :param webhooks_on_channel_add_method: + :param webhooks_on_channel_destroy_url: + :param webhooks_on_channel_destroy_method: + :param webhooks_on_channel_update_url: + :param webhooks_on_channel_update_method: + :param webhooks_on_member_add_url: + :param webhooks_on_member_add_method: + :param webhooks_on_member_remove_url: + :param webhooks_on_member_remove_method: + :param webhooks_on_message_sent_url: + :param webhooks_on_message_sent_method: + :param webhooks_on_message_updated_url: + :param webhooks_on_message_updated_method: + :param webhooks_on_message_removed_url: + :param webhooks_on_message_removed_method: + :param webhooks_on_channel_added_url: + :param webhooks_on_channel_added_method: + :param webhooks_on_channel_destroyed_url: + :param webhooks_on_channel_destroyed_method: + :param webhooks_on_channel_updated_url: + :param webhooks_on_channel_updated_method: + :param webhooks_on_member_added_url: + :param webhooks_on_member_added_method: + :param webhooks_on_member_removed_url: + :param webhooks_on_member_removed_method: + :param limits_channel_members: + :param limits_user_channels: + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param webhooks_on_message_send_url: + :param webhooks_on_message_send_method: + :param webhooks_on_message_update_url: + :param webhooks_on_message_update_method: + :param webhooks_on_message_remove_url: + :param webhooks_on_message_remove_method: + :param webhooks_on_channel_add_url: + :param webhooks_on_channel_add_method: + :param webhooks_on_channel_destroy_url: + :param webhooks_on_channel_destroy_method: + :param webhooks_on_channel_update_url: + :param webhooks_on_channel_update_method: + :param webhooks_on_member_add_url: + :param webhooks_on_member_add_method: + :param webhooks_on_member_remove_url: + :param webhooks_on_member_remove_method: + :param webhooks_on_message_sent_url: + :param webhooks_on_message_sent_method: + :param webhooks_on_message_updated_url: + :param webhooks_on_message_updated_method: + :param webhooks_on_message_removed_url: + :param webhooks_on_message_removed_method: + :param webhooks_on_channel_added_url: + :param webhooks_on_channel_added_method: + :param webhooks_on_channel_destroyed_url: + :param webhooks_on_channel_destroyed_method: + :param webhooks_on_channel_updated_url: + :param webhooks_on_channel_updated_method: + :param webhooks_on_member_added_url: + :param webhooks_on_member_added_method: + :param webhooks_on_member_removed_url: + :param webhooks_on_member_removed_method: + :param limits_channel_members: + :param limits_user_channels: + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + return self._proxy.channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + return self._proxy.roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + return self._proxy.users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._channels: Optional[ChannelList] = None + self._roles: Optional[RoleList] = None + self._users: Optional[UserList] = None + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param webhooks_on_message_send_url: + :param webhooks_on_message_send_method: + :param webhooks_on_message_update_url: + :param webhooks_on_message_update_method: + :param webhooks_on_message_remove_url: + :param webhooks_on_message_remove_method: + :param webhooks_on_channel_add_url: + :param webhooks_on_channel_add_method: + :param webhooks_on_channel_destroy_url: + :param webhooks_on_channel_destroy_method: + :param webhooks_on_channel_update_url: + :param webhooks_on_channel_update_method: + :param webhooks_on_member_add_url: + :param webhooks_on_member_add_method: + :param webhooks_on_member_remove_url: + :param webhooks_on_member_remove_method: + :param webhooks_on_message_sent_url: + :param webhooks_on_message_sent_method: + :param webhooks_on_message_updated_url: + :param webhooks_on_message_updated_method: + :param webhooks_on_message_removed_url: + :param webhooks_on_message_removed_method: + :param webhooks_on_channel_added_url: + :param webhooks_on_channel_added_method: + :param webhooks_on_channel_destroyed_url: + :param webhooks_on_channel_destroyed_method: + :param webhooks_on_channel_updated_url: + :param webhooks_on_channel_updated_method: + :param webhooks_on_member_added_url: + :param webhooks_on_member_added_method: + :param webhooks_on_member_removed_url: + :param webhooks_on_member_removed_method: + :param limits_channel_members: + :param limits_user_channels: + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Webhooks.OnMessageSend.Url": webhooks_on_message_send_url, + "Webhooks.OnMessageSend.Method": webhooks_on_message_send_method, + "Webhooks.OnMessageUpdate.Url": webhooks_on_message_update_url, + "Webhooks.OnMessageUpdate.Method": webhooks_on_message_update_method, + "Webhooks.OnMessageRemove.Url": webhooks_on_message_remove_url, + "Webhooks.OnMessageRemove.Method": webhooks_on_message_remove_method, + "Webhooks.OnChannelAdd.Url": webhooks_on_channel_add_url, + "Webhooks.OnChannelAdd.Method": webhooks_on_channel_add_method, + "Webhooks.OnChannelDestroy.Url": webhooks_on_channel_destroy_url, + "Webhooks.OnChannelDestroy.Method": webhooks_on_channel_destroy_method, + "Webhooks.OnChannelUpdate.Url": webhooks_on_channel_update_url, + "Webhooks.OnChannelUpdate.Method": webhooks_on_channel_update_method, + "Webhooks.OnMemberAdd.Url": webhooks_on_member_add_url, + "Webhooks.OnMemberAdd.Method": webhooks_on_member_add_method, + "Webhooks.OnMemberRemove.Url": webhooks_on_member_remove_url, + "Webhooks.OnMemberRemove.Method": webhooks_on_member_remove_method, + "Webhooks.OnMessageSent.Url": webhooks_on_message_sent_url, + "Webhooks.OnMessageSent.Method": webhooks_on_message_sent_method, + "Webhooks.OnMessageUpdated.Url": webhooks_on_message_updated_url, + "Webhooks.OnMessageUpdated.Method": webhooks_on_message_updated_method, + "Webhooks.OnMessageRemoved.Url": webhooks_on_message_removed_url, + "Webhooks.OnMessageRemoved.Method": webhooks_on_message_removed_method, + "Webhooks.OnChannelAdded.Url": webhooks_on_channel_added_url, + "Webhooks.OnChannelAdded.Method": webhooks_on_channel_added_method, + "Webhooks.OnChannelDestroyed.Url": webhooks_on_channel_destroyed_url, + "Webhooks.OnChannelDestroyed.Method": webhooks_on_channel_destroyed_method, + "Webhooks.OnChannelUpdated.Url": webhooks_on_channel_updated_url, + "Webhooks.OnChannelUpdated.Method": webhooks_on_channel_updated_method, + "Webhooks.OnMemberAdded.Url": webhooks_on_member_added_url, + "Webhooks.OnMemberAdded.Method": webhooks_on_member_added_method, + "Webhooks.OnMemberRemoved.Url": webhooks_on_member_removed_url, + "Webhooks.OnMemberRemoved.Method": webhooks_on_member_removed_method, + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param webhooks_on_message_send_url: + :param webhooks_on_message_send_method: + :param webhooks_on_message_update_url: + :param webhooks_on_message_update_method: + :param webhooks_on_message_remove_url: + :param webhooks_on_message_remove_method: + :param webhooks_on_channel_add_url: + :param webhooks_on_channel_add_method: + :param webhooks_on_channel_destroy_url: + :param webhooks_on_channel_destroy_method: + :param webhooks_on_channel_update_url: + :param webhooks_on_channel_update_method: + :param webhooks_on_member_add_url: + :param webhooks_on_member_add_method: + :param webhooks_on_member_remove_url: + :param webhooks_on_member_remove_method: + :param webhooks_on_message_sent_url: + :param webhooks_on_message_sent_method: + :param webhooks_on_message_updated_url: + :param webhooks_on_message_updated_method: + :param webhooks_on_message_removed_url: + :param webhooks_on_message_removed_method: + :param webhooks_on_channel_added_url: + :param webhooks_on_channel_added_method: + :param webhooks_on_channel_destroyed_url: + :param webhooks_on_channel_destroyed_method: + :param webhooks_on_channel_updated_url: + :param webhooks_on_channel_updated_method: + :param webhooks_on_member_added_url: + :param webhooks_on_member_added_method: + :param webhooks_on_member_removed_url: + :param webhooks_on_member_removed_method: + :param limits_channel_members: + :param limits_user_channels: + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Webhooks.OnMessageSend.Url": webhooks_on_message_send_url, + "Webhooks.OnMessageSend.Method": webhooks_on_message_send_method, + "Webhooks.OnMessageUpdate.Url": webhooks_on_message_update_url, + "Webhooks.OnMessageUpdate.Method": webhooks_on_message_update_method, + "Webhooks.OnMessageRemove.Url": webhooks_on_message_remove_url, + "Webhooks.OnMessageRemove.Method": webhooks_on_message_remove_method, + "Webhooks.OnChannelAdd.Url": webhooks_on_channel_add_url, + "Webhooks.OnChannelAdd.Method": webhooks_on_channel_add_method, + "Webhooks.OnChannelDestroy.Url": webhooks_on_channel_destroy_url, + "Webhooks.OnChannelDestroy.Method": webhooks_on_channel_destroy_method, + "Webhooks.OnChannelUpdate.Url": webhooks_on_channel_update_url, + "Webhooks.OnChannelUpdate.Method": webhooks_on_channel_update_method, + "Webhooks.OnMemberAdd.Url": webhooks_on_member_add_url, + "Webhooks.OnMemberAdd.Method": webhooks_on_member_add_method, + "Webhooks.OnMemberRemove.Url": webhooks_on_member_remove_url, + "Webhooks.OnMemberRemove.Method": webhooks_on_member_remove_method, + "Webhooks.OnMessageSent.Url": webhooks_on_message_sent_url, + "Webhooks.OnMessageSent.Method": webhooks_on_message_sent_method, + "Webhooks.OnMessageUpdated.Url": webhooks_on_message_updated_url, + "Webhooks.OnMessageUpdated.Method": webhooks_on_message_updated_method, + "Webhooks.OnMessageRemoved.Url": webhooks_on_message_removed_url, + "Webhooks.OnMessageRemoved.Method": webhooks_on_message_removed_method, + "Webhooks.OnChannelAdded.Url": webhooks_on_channel_added_url, + "Webhooks.OnChannelAdded.Method": webhooks_on_channel_added_method, + "Webhooks.OnChannelDestroyed.Url": webhooks_on_channel_destroyed_url, + "Webhooks.OnChannelDestroyed.Method": webhooks_on_channel_destroyed_method, + "Webhooks.OnChannelUpdated.Url": webhooks_on_channel_updated_url, + "Webhooks.OnChannelUpdated.Method": webhooks_on_channel_updated_method, + "Webhooks.OnMemberAdded.Url": webhooks_on_member_added_url, + "Webhooks.OnMemberAdded.Method": webhooks_on_member_added_method, + "Webhooks.OnMemberRemoved.Url": webhooks_on_member_removed_url, + "Webhooks.OnMemberRemoved.Method": webhooks_on_member_removed_method, + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + if self._channels is None: + self._channels = ChannelList( + self._version, + self._solution["sid"], + ) + return self._channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + if self._roles is None: + self._roles = RoleList( + self._version, + self._solution["sid"], + ) + return self._roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + if self._users is None: + self._users = UserList( + self._version, + self._solution["sid"], + ) + return self._users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def create(self, friendly_name: str) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async(self, friendly_name: str) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..4c56aa3e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/__pycache__/role.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/__pycache__/role.cpython-312.pyc new file mode 100644 index 00000000..47639368 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/__pycache__/role.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/channel/__init__.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/channel/__init__.py new file mode 100644 index 00000000..14423c9e --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/channel/__init__.py @@ -0,0 +1,790 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.ip_messaging.v1.service.channel.invite import InviteList +from twilio.rest.ip_messaging.v1.service.channel.member import MemberList +from twilio.rest.ip_messaging.v1.service.channel.message import MessageList + + +class ChannelInstance(InstanceResource): + + class ChannelType(object): + PUBLIC = "public" + PRIVATE = "private" + + """ + :ivar sid: + :ivar account_sid: + :ivar service_sid: + :ivar friendly_name: + :ivar unique_name: + :ivar attributes: + :ivar type: + :ivar date_created: + :ivar date_updated: + :ivar created_by: + :ivar members_count: + :ivar messages_count: + :ivar url: + :ivar links: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.attributes: Optional[str] = payload.get("attributes") + self.type: Optional["ChannelInstance.ChannelType"] = payload.get("type") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + self.members_count: Optional[int] = deserialize.integer( + payload.get("members_count") + ) + self.messages_count: Optional[int] = deserialize.integer( + payload.get("messages_count") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ChannelContext] = None + + @property + def _proxy(self) -> "ChannelContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ChannelContext for this ChannelInstance + """ + if self._context is None: + self._context = ChannelContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ChannelInstance": + """ + Fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ChannelInstance": + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Update the ChannelInstance + + :param friendly_name: + :param unique_name: + :param attributes: + + :returns: The updated ChannelInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Asynchronous coroutine to update the ChannelInstance + + :param friendly_name: + :param unique_name: + :param attributes: + + :returns: The updated ChannelInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + ) + + @property + def invites(self) -> InviteList: + """ + Access the invites + """ + return self._proxy.invites + + @property + def members(self) -> MemberList: + """ + Access the members + """ + return self._proxy.members + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ChannelContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the ChannelContext + + :param version: Version that contains the resource + :param service_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Channels/{sid}".format(**self._solution) + + self._invites: Optional[InviteList] = None + self._members: Optional[MemberList] = None + self._messages: Optional[MessageList] = None + + def delete(self) -> bool: + """ + Deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChannelInstance: + """ + Fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ChannelInstance: + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Update the ChannelInstance + + :param friendly_name: + :param unique_name: + :param attributes: + + :returns: The updated ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronous coroutine to update the ChannelInstance + + :param friendly_name: + :param unique_name: + :param attributes: + + :returns: The updated ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def invites(self) -> InviteList: + """ + Access the invites + """ + if self._invites is None: + self._invites = InviteList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._invites + + @property + def members(self) -> MemberList: + """ + Access the members + """ + if self._members is None: + self._members = MemberList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._members + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + if self._messages is None: + self._messages = MessageList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._messages + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: + """ + Build an instance of ChannelInstance + + :param payload: Payload response from the API + """ + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ChannelList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the ChannelList + + :param version: Version that contains the resource + :param service_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Channels".format(**self._solution) + + def create( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> ChannelInstance: + """ + Create the ChannelInstance + + :param friendly_name: + :param unique_name: + :param attributes: + :param type: + + :returns: The created ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "Type": type, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronously create the ChannelInstance + + :param friendly_name: + :param unique_name: + :param attributes: + :param type: + + :returns: The created ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "Type": type, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChannelInstance]: + """ + Streams ChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(type=type, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ChannelInstance]: + """ + Asynchronously streams ChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(type=type, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: + """ + Lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + type=type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: + """ + Asynchronously lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + type=type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: + """ + Retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param type: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, self._solution) + + async def page_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: + """ + Asynchronously retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param type: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ChannelPage: + """ + Retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ChannelPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ChannelPage: + """ + Asynchronously retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelPage(self._version, response, self._solution) + + def get(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: + """ + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: + """ + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/channel/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/channel/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..0a51f22e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/channel/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/channel/__pycache__/invite.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/channel/__pycache__/invite.cpython-312.pyc new file mode 100644 index 00000000..ca1ac06d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/channel/__pycache__/invite.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/channel/__pycache__/member.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/channel/__pycache__/member.cpython-312.pyc new file mode 100644 index 00000000..d4c8479b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/channel/__pycache__/member.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/channel/__pycache__/message.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/channel/__pycache__/message.cpython-312.pyc new file mode 100644 index 00000000..b6a92932 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/channel/__pycache__/message.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/channel/invite.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/channel/invite.py new file mode 100644 index 00000000..d3485403 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/channel/invite.py @@ -0,0 +1,598 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InviteInstance(InstanceResource): + """ + :ivar sid: + :ivar account_sid: + :ivar channel_sid: + :ivar service_sid: + :ivar identity: + :ivar date_created: + :ivar date_updated: + :ivar role_sid: + :ivar created_by: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.created_by: Optional[str] = payload.get("created_by") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[InviteContext] = None + + @property + def _proxy(self) -> "InviteContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InviteContext for this InviteInstance + """ + if self._context is None: + self._context = InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "InviteInstance": + """ + Fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InviteInstance": + """ + Asynchronous coroutine to fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InviteContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the InviteContext + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Invites/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> InviteInstance: + """ + Fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> InviteInstance: + """ + Asynchronous coroutine to fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InvitePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: + """ + Build an instance of InviteInstance + + :param payload: Payload response from the API + """ + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class InviteList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the InviteList + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Invites".format( + **self._solution + ) + + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Create the InviteInstance + + :param identity: + :param role_sid: + + :returns: The created InviteInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Asynchronously create the InviteInstance + + :param identity: + :param role_sid: + + :returns: The created InviteInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InviteInstance]: + """ + Streams InviteInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InviteInstance]: + """ + Asynchronously streams InviteInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: + """ + Lists InviteInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: + """ + Asynchronously lists InviteInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InvitePage: + """ + Retrieve a single page of InviteInstance records from the API. + Request is executed immediately + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InviteInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InvitePage(self._version, response, self._solution) + + async def page_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InvitePage: + """ + Asynchronously retrieve a single page of InviteInstance records from the API. + Request is executed immediately + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InviteInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InvitePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> InvitePage: + """ + Retrieve a specific page of InviteInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InviteInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InvitePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> InvitePage: + """ + Asynchronously retrieve a specific page of InviteInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InviteInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InvitePage(self._version, response, self._solution) + + def get(self, sid: str) -> InviteContext: + """ + Constructs a InviteContext + + :param sid: + """ + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InviteContext: + """ + Constructs a InviteContext + + :param sid: + """ + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/channel/member.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/channel/member.py new file mode 100644 index 00000000..26a68650 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/channel/member.py @@ -0,0 +1,716 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MemberInstance(InstanceResource): + """ + :ivar sid: + :ivar account_sid: + :ivar channel_sid: + :ivar service_sid: + :ivar identity: + :ivar date_created: + :ivar date_updated: + :ivar role_sid: + :ivar last_consumed_message_index: + :ivar last_consumption_timestamp: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.last_consumed_message_index: Optional[int] = deserialize.integer( + payload.get("last_consumed_message_index") + ) + self.last_consumption_timestamp: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("last_consumption_timestamp")) + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[MemberContext] = None + + @property + def _proxy(self) -> "MemberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MemberContext for this MemberInstance + """ + if self._context is None: + self._context = MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the MemberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MemberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "MemberInstance": + """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MemberInstance": + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> "MemberInstance": + """ + Update the MemberInstance + + :param role_sid: + :param last_consumed_message_index: + + :returns: The updated MemberInstance + """ + return self._proxy.update( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + ) + + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> "MemberInstance": + """ + Asynchronous coroutine to update the MemberInstance + + :param role_sid: + :param last_consumed_message_index: + + :returns: The updated MemberInstance + """ + return await self._proxy.update_async( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MemberContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the MemberContext + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Members/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the MemberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MemberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MemberInstance: + """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MemberInstance: + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> MemberInstance: + """ + Update the MemberInstance + + :param role_sid: + :param last_consumed_message_index: + + :returns: The updated MemberInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> MemberInstance: + """ + Asynchronous coroutine to update the MemberInstance + + :param role_sid: + :param last_consumed_message_index: + + :returns: The updated MemberInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MemberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: + """ + Build an instance of MemberInstance + + :param payload: Payload response from the API + """ + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MemberList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MemberList + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Members".format( + **self._solution + ) + + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> MemberInstance: + """ + Create the MemberInstance + + :param identity: + :param role_sid: + + :returns: The created MemberInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> MemberInstance: + """ + Asynchronously create the MemberInstance + + :param identity: + :param role_sid: + + :returns: The created MemberInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MemberInstance]: + """ + Streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MemberInstance]: + """ + Asynchronously streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: + """ + Lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: + """ + Asynchronously lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: + """ + Retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, self._solution) + + async def page_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: + """ + Asynchronously retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MemberPage: + """ + Retrieve a specific page of MemberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MemberPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MemberPage: + """ + Asynchronously retrieve a specific page of MemberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MemberPage(self._version, response, self._solution) + + def get(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param sid: + """ + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param sid: + """ + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/channel/message.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/channel/message.py new file mode 100644 index 00000000..ad7c05d8 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/channel/message.py @@ -0,0 +1,731 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MessageInstance(InstanceResource): + + class OrderType(object): + ASC = "asc" + DESC = "desc" + + """ + :ivar sid: + :ivar account_sid: + :ivar attributes: + :ivar service_sid: + :ivar to: + :ivar channel_sid: + :ivar date_created: + :ivar date_updated: + :ivar was_edited: + :ivar _from: + :ivar body: + :ivar index: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.attributes: Optional[str] = payload.get("attributes") + self.service_sid: Optional[str] = payload.get("service_sid") + self.to: Optional[str] = payload.get("to") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.was_edited: Optional[bool] = payload.get("was_edited") + self._from: Optional[str] = payload.get("from") + self.body: Optional[str] = payload.get("body") + self.index: Optional[int] = deserialize.integer(payload.get("index")) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[MessageContext] = None + + @property + def _proxy(self) -> "MessageContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MessageContext for this MessageInstance + """ + if self._context is None: + self._context = MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "MessageInstance": + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MessageInstance": + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Update the MessageInstance + + :param body: + :param attributes: + + :returns: The updated MessageInstance + """ + return self._proxy.update( + body=body, + attributes=attributes, + ) + + async def update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Asynchronous coroutine to update the MessageInstance + + :param body: + :param attributes: + + :returns: The updated MessageInstance + """ + return await self._proxy.update_async( + body=body, + attributes=attributes, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MessageContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the MessageContext + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Messages/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Update the MessageInstance + + :param body: + :param attributes: + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Body": body, + "Attributes": attributes, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronous coroutine to update the MessageInstance + + :param body: + :param attributes: + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Body": body, + "Attributes": attributes, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MessagePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: + """ + Build an instance of MessageInstance + + :param payload: Payload response from the API + """ + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MessageList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MessageList + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Messages".format( + **self._solution + ) + + def create( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Create the MessageInstance + + :param body: + :param from_: + :param attributes: + + :returns: The created MessageInstance + """ + + data = values.of( + { + "Body": body, + "From": from_, + "Attributes": attributes, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param body: + :param from_: + :param attributes: + + :returns: The created MessageInstance + """ + + data = values.of( + { + "Body": body, + "From": from_, + "Attributes": attributes, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: + """ + Streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(order=order, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessageInstance]: + """ + Asynchronously streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(order=order, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + order=order, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Asynchronously lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + order=order, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + async def page_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MessagePage: + """ + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MessagePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MessagePage: + """ + Asynchronously retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagePage(self._version, response, self._solution) + + def get(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: + """ + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: + """ + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/role.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/role.py new file mode 100644 index 00000000..d5d06280 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/role.py @@ -0,0 +1,645 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RoleInstance(InstanceResource): + + class RoleType(object): + CHANNEL = "channel" + DEPLOYMENT = "deployment" + + """ + :ivar sid: + :ivar account_sid: + :ivar service_sid: + :ivar friendly_name: + :ivar type: + :ivar permissions: + :ivar date_created: + :ivar date_updated: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["RoleInstance.RoleType"] = payload.get("type") + self.permissions: Optional[List[str]] = payload.get("permissions") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[RoleContext] = None + + @property + def _proxy(self) -> "RoleContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RoleContext for this RoleInstance + """ + if self._context is None: + self._context = RoleContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RoleInstance": + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RoleInstance": + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + return await self._proxy.fetch_async() + + def update(self, permission: List[str]) -> "RoleInstance": + """ + Update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + return self._proxy.update( + permission=permission, + ) + + async def update_async(self, permission: List[str]) -> "RoleInstance": + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + return await self._proxy.update_async( + permission=permission, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RoleContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the RoleContext + + :param version: Version that contains the resource + :param service_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Roles/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RoleInstance: + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update(self, permission: List[str]) -> RoleInstance: + """ + Update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, permission: List[str]) -> RoleInstance: + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RolePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: + """ + Build an instance of RoleInstance + + :param payload: Payload response from the API + """ + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RoleList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the RoleList + + :param version: Version that contains the resource + :param service_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Roles".format(**self._solution) + + def create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Create the RoleInstance + + :param friendly_name: + :param type: + :param permission: + + :returns: The created RoleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Asynchronously create the RoleInstance + + :param friendly_name: + :param type: + :param permission: + + :returns: The created RoleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoleInstance]: + """ + Streams RoleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RoleInstance]: + """ + Asynchronously streams RoleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: + """ + Lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: + """ + Asynchronously lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePage: + """ + Retrieve a single page of RoleInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePage: + """ + Asynchronously retrieve a single page of RoleInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RolePage: + """ + Retrieve a specific page of RoleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RolePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RolePage: + """ + Asynchronously retrieve a specific page of RoleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RolePage(self._version, response, self._solution) + + def get(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: + """ + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: + """ + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/user/__init__.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/user/__init__.py new file mode 100644 index 00000000..5f37f2d3 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/user/__init__.py @@ -0,0 +1,723 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.ip_messaging.v1.service.user.user_channel import UserChannelList + + +class UserInstance(InstanceResource): + """ + :ivar sid: + :ivar account_sid: + :ivar service_sid: + :ivar attributes: + :ivar friendly_name: + :ivar role_sid: + :ivar identity: + :ivar is_online: + :ivar is_notifiable: + :ivar date_created: + :ivar date_updated: + :ivar joined_channels_count: + :ivar links: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.attributes: Optional[str] = payload.get("attributes") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.role_sid: Optional[str] = payload.get("role_sid") + self.identity: Optional[str] = payload.get("identity") + self.is_online: Optional[bool] = payload.get("is_online") + self.is_notifiable: Optional[bool] = payload.get("is_notifiable") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.joined_channels_count: Optional[int] = deserialize.integer( + payload.get("joined_channels_count") + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[UserContext] = None + + @property + def _proxy(self) -> "UserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserContext for this UserInstance + """ + if self._context is None: + self._context = UserContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "UserInstance": + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserInstance": + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Update the UserInstance + + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The updated UserInstance + """ + return self._proxy.update( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Asynchronous coroutine to update the UserInstance + + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The updated UserInstance + """ + return await self._proxy.update_async( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + @property + def user_channels(self) -> UserChannelList: + """ + Access the user_channels + """ + return self._proxy.user_channels + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the UserContext + + :param version: Version that contains the resource + :param service_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Users/{sid}".format(**self._solution) + + self._user_channels: Optional[UserChannelList] = None + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Update the UserInstance + + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The updated UserInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The updated UserInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def user_channels(self) -> UserChannelList: + """ + Access the user_channels + """ + if self._user_channels is None: + self._user_channels = UserChannelList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._user_channels + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: + """ + Build an instance of UserInstance + + :param payload: Payload response from the API + """ + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class UserList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the UserList + + :param version: Version that contains the resource + :param service_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Users".format(**self._solution) + + def create( + self, + identity: str, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Create the UserInstance + + :param identity: + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The created UserInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + identity: str, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param identity: + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The created UserInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserInstance]: + """ + Streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserInstance]: + """ + Asynchronously streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Asynchronously lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Asynchronously retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserPage: + """ + Retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserPage: + """ + Asynchronously retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserPage(self._version, response, self._solution) + + def get(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: + """ + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: + """ + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/user/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/user/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..154ecf7d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/user/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/user/__pycache__/user_channel.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/user/__pycache__/user_channel.cpython-312.pyc new file mode 100644 index 00000000..3d641887 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/user/__pycache__/user_channel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/user/user_channel.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/user/user_channel.py new file mode 100644 index 00000000..42454498 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/v1/service/user/user_channel.py @@ -0,0 +1,322 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UserChannelInstance(InstanceResource): + + class ChannelStatus(object): + JOINED = "joined" + INVITED = "invited" + NOT_PARTICIPATING = "not_participating" + + """ + :ivar account_sid: + :ivar service_sid: + :ivar channel_sid: + :ivar member_sid: + :ivar status: + :ivar last_consumed_message_index: + :ivar unread_messages_count: + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], service_sid: str, user_sid: str + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.member_sid: Optional[str] = payload.get("member_sid") + self.status: Optional["UserChannelInstance.ChannelStatus"] = payload.get( + "status" + ) + self.last_consumed_message_index: Optional[int] = deserialize.integer( + payload.get("last_consumed_message_index") + ) + self.unread_messages_count: Optional[int] = deserialize.integer( + payload.get("unread_messages_count") + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: + """ + Build an instance of UserChannelInstance + + :param payload: Payload response from the API + """ + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class UserChannelList(ListResource): + + def __init__(self, version: Version, service_sid: str, user_sid: str): + """ + Initialize the UserChannelList + + :param version: Version that contains the resource + :param service_sid: + :param user_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + } + self._uri = "/Services/{service_sid}/Users/{user_sid}/Channels".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserChannelInstance]: + """ + Streams UserChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserChannelInstance]: + """ + Asynchronously streams UserChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: + """ + Lists UserChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: + """ + Asynchronously lists UserChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserChannelPage: + """ + Retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserChannelPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserChannelPage: + """ + Asynchronously retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserChannelPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserChannelPage: + """ + Retrieve a specific page of UserChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserChannelPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserChannelPage: + """ + Asynchronously retrieve a specific page of UserChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserChannelPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/__init__.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/__init__.py new file mode 100644 index 00000000..6003c86b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.ip_messaging.v2.credential import CredentialList +from twilio.rest.ip_messaging.v2.service import ServiceList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of IpMessaging + + :param domain: The Twilio.ip_messaging domain + """ + super().__init__(domain, "v2") + self._credentials: Optional[CredentialList] = None + self._services: Optional[ServiceList] = None + + @property + def credentials(self) -> CredentialList: + if self._credentials is None: + self._credentials = CredentialList(self) + return self._credentials + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..69a4b37c Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/__pycache__/credential.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/__pycache__/credential.cpython-312.pyc new file mode 100644 index 00000000..c104cef9 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/__pycache__/credential.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/credential.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/credential.py new file mode 100644 index 00000000..065c5048 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/credential.py @@ -0,0 +1,711 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CredentialInstance(InstanceResource): + + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: + :ivar account_sid: + :ivar friendly_name: + :ivar type: + :ivar sandbox: + :ivar date_created: + :ivar date_updated: + :ivar url: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["CredentialInstance.PushService"] = payload.get("type") + self.sandbox: Optional[str] = payload.get("sandbox") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CredentialContext] = None + + @property + def _proxy(self) -> "CredentialContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CredentialInstance": + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CredentialInstance": + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Update the CredentialInstance + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The updated CredentialInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The updated CredentialInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CredentialContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialInstance: + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Update the CredentialInstance + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: + """ + Build an instance of CredentialInstance + + :param payload: Payload response from the API + """ + return CredentialInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CredentialList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CredentialList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Credentials" + + def create( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Create the CredentialInstance + + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload) + + async def create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialInstance]: + """ + Streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialInstance]: + """ + Asynchronously streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Asynchronously lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Asynchronously retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response) + + def get_page(self, target_url: str) -> CredentialPage: + """ + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CredentialPage: + """ + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response) + + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: + """ + return CredentialContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: + """ + return CredentialContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/__init__.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/__init__.py new file mode 100644 index 00000000..a303f10f --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/__init__.py @@ -0,0 +1,1128 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.ip_messaging.v2.service.binding import BindingList +from twilio.rest.ip_messaging.v2.service.channel import ChannelList +from twilio.rest.ip_messaging.v2.service.role import RoleList +from twilio.rest.ip_messaging.v2.service.user import UserList + + +class ServiceInstance(InstanceResource): + """ + :ivar sid: + :ivar account_sid: + :ivar friendly_name: + :ivar date_created: + :ivar date_updated: + :ivar default_service_role_sid: + :ivar default_channel_role_sid: + :ivar default_channel_creator_role_sid: + :ivar read_status_enabled: + :ivar reachability_enabled: + :ivar typing_indicator_timeout: + :ivar consumption_report_interval: + :ivar limits: + :ivar pre_webhook_url: + :ivar post_webhook_url: + :ivar webhook_method: + :ivar webhook_filters: + :ivar pre_webhook_retry_count: + :ivar post_webhook_retry_count: + :ivar notifications: + :ivar media: + :ivar url: + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.default_service_role_sid: Optional[str] = payload.get( + "default_service_role_sid" + ) + self.default_channel_role_sid: Optional[str] = payload.get( + "default_channel_role_sid" + ) + self.default_channel_creator_role_sid: Optional[str] = payload.get( + "default_channel_creator_role_sid" + ) + self.read_status_enabled: Optional[bool] = payload.get("read_status_enabled") + self.reachability_enabled: Optional[bool] = payload.get("reachability_enabled") + self.typing_indicator_timeout: Optional[int] = deserialize.integer( + payload.get("typing_indicator_timeout") + ) + self.consumption_report_interval: Optional[int] = deserialize.integer( + payload.get("consumption_report_interval") + ) + self.limits: Optional[Dict[str, object]] = payload.get("limits") + self.pre_webhook_url: Optional[str] = payload.get("pre_webhook_url") + self.post_webhook_url: Optional[str] = payload.get("post_webhook_url") + self.webhook_method: Optional[str] = payload.get("webhook_method") + self.webhook_filters: Optional[List[str]] = payload.get("webhook_filters") + self.pre_webhook_retry_count: Optional[int] = deserialize.integer( + payload.get("pre_webhook_retry_count") + ) + self.post_webhook_retry_count: Optional[int] = deserialize.integer( + payload.get("post_webhook_retry_count") + ) + self.notifications: Optional[Dict[str, object]] = payload.get("notifications") + self.media: Optional[Dict[str, object]] = payload.get("media") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_new_message_sound: + :param notifications_new_message_badge_count_enabled: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_added_to_channel_sound: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_removed_from_channel_sound: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param notifications_invited_to_channel_sound: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param limits_channel_members: + :param limits_user_channels: + :param media_compatibility_message: + :param pre_webhook_retry_count: + :param post_webhook_retry_count: + :param notifications_log_enabled: + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_new_message_sound: + :param notifications_new_message_badge_count_enabled: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_added_to_channel_sound: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_removed_from_channel_sound: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param notifications_invited_to_channel_sound: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param limits_channel_members: + :param limits_user_channels: + :param media_compatibility_message: + :param pre_webhook_retry_count: + :param post_webhook_retry_count: + :param notifications_log_enabled: + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, + ) + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + return self._proxy.bindings + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + return self._proxy.channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + return self._proxy.roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + return self._proxy.users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._bindings: Optional[BindingList] = None + self._channels: Optional[ChannelList] = None + self._roles: Optional[RoleList] = None + self._users: Optional[UserList] = None + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_new_message_sound: + :param notifications_new_message_badge_count_enabled: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_added_to_channel_sound: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_removed_from_channel_sound: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param notifications_invited_to_channel_sound: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param limits_channel_members: + :param limits_user_channels: + :param media_compatibility_message: + :param pre_webhook_retry_count: + :param post_webhook_retry_count: + :param notifications_log_enabled: + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.NewMessage.Sound": notifications_new_message_sound, + "Notifications.NewMessage.BadgeCountEnabled": serialize.boolean_to_string( + notifications_new_message_badge_count_enabled + ), + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.AddedToChannel.Sound": notifications_added_to_channel_sound, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.RemovedFromChannel.Sound": notifications_removed_from_channel_sound, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "Notifications.InvitedToChannel.Sound": notifications_invited_to_channel_sound, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + "Media.CompatibilityMessage": media_compatibility_message, + "PreWebhookRetryCount": pre_webhook_retry_count, + "PostWebhookRetryCount": post_webhook_retry_count, + "Notifications.LogEnabled": serialize.boolean_to_string( + notifications_log_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_new_message_sound: + :param notifications_new_message_badge_count_enabled: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_added_to_channel_sound: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_removed_from_channel_sound: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param notifications_invited_to_channel_sound: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param limits_channel_members: + :param limits_user_channels: + :param media_compatibility_message: + :param pre_webhook_retry_count: + :param post_webhook_retry_count: + :param notifications_log_enabled: + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.NewMessage.Sound": notifications_new_message_sound, + "Notifications.NewMessage.BadgeCountEnabled": serialize.boolean_to_string( + notifications_new_message_badge_count_enabled + ), + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.AddedToChannel.Sound": notifications_added_to_channel_sound, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.RemovedFromChannel.Sound": notifications_removed_from_channel_sound, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "Notifications.InvitedToChannel.Sound": notifications_invited_to_channel_sound, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + "Media.CompatibilityMessage": media_compatibility_message, + "PreWebhookRetryCount": pre_webhook_retry_count, + "PostWebhookRetryCount": post_webhook_retry_count, + "Notifications.LogEnabled": serialize.boolean_to_string( + notifications_log_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + if self._bindings is None: + self._bindings = BindingList( + self._version, + self._solution["sid"], + ) + return self._bindings + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + if self._channels is None: + self._channels = ChannelList( + self._version, + self._solution["sid"], + ) + return self._channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + if self._roles is None: + self._roles = RoleList( + self._version, + self._solution["sid"], + ) + return self._roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + if self._users is None: + self._users = UserList( + self._version, + self._solution["sid"], + ) + return self._users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def create(self, friendly_name: str) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async(self, friendly_name: str) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..4581e14f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/__pycache__/binding.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/__pycache__/binding.cpython-312.pyc new file mode 100644 index 00000000..434ea0a9 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/__pycache__/binding.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/__pycache__/role.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/__pycache__/role.cpython-312.pyc new file mode 100644 index 00000000..e21fccb1 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/__pycache__/role.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/binding.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/binding.py new file mode 100644 index 00000000..af9018af --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/binding.py @@ -0,0 +1,536 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class BindingInstance(InstanceResource): + + class BindingType(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: + :ivar account_sid: + :ivar service_sid: + :ivar date_created: + :ivar date_updated: + :ivar endpoint: + :ivar identity: + :ivar credential_sid: + :ivar binding_type: + :ivar message_types: + :ivar url: + :ivar links: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.endpoint: Optional[str] = payload.get("endpoint") + self.identity: Optional[str] = payload.get("identity") + self.credential_sid: Optional[str] = payload.get("credential_sid") + self.binding_type: Optional["BindingInstance.BindingType"] = payload.get( + "binding_type" + ) + self.message_types: Optional[List[str]] = payload.get("message_types") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[BindingContext] = None + + @property + def _proxy(self) -> "BindingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BindingContext for this BindingInstance + """ + if self._context is None: + self._context = BindingContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "BindingInstance": + """ + Fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BindingInstance": + """ + Asynchronous coroutine to fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BindingContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the BindingContext + + :param version: Version that contains the resource + :param service_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Bindings/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> BindingInstance: + """ + Fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> BindingInstance: + """ + Asynchronous coroutine to fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BindingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> BindingInstance: + """ + Build an instance of BindingInstance + + :param payload: Payload response from the API + """ + return BindingInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class BindingList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the BindingList + + :param version: Version that contains the resource + :param service_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Bindings".format(**self._solution) + + def stream( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BindingInstance]: + """ + Streams BindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["BindingInstance.BindingType"] binding_type: + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BindingInstance]: + """ + Asynchronously streams BindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["BindingInstance.BindingType"] binding_type: + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BindingInstance]: + """ + Lists BindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["BindingInstance.BindingType"] binding_type: + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BindingInstance]: + """ + Asynchronously lists BindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["BindingInstance.BindingType"] binding_type: + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BindingPage: + """ + Retrieve a single page of BindingInstance records from the API. + Request is executed immediately + + :param binding_type: + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BindingInstance + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BindingPage(self._version, response, self._solution) + + async def page_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BindingPage: + """ + Asynchronously retrieve a single page of BindingInstance records from the API. + Request is executed immediately + + :param binding_type: + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BindingInstance + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BindingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> BindingPage: + """ + Retrieve a specific page of BindingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BindingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return BindingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> BindingPage: + """ + Asynchronously retrieve a specific page of BindingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BindingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return BindingPage(self._version, response, self._solution) + + def get(self, sid: str) -> BindingContext: + """ + Constructs a BindingContext + + :param sid: + """ + return BindingContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> BindingContext: + """ + Constructs a BindingContext + + :param sid: + """ + return BindingContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/__init__.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/__init__.py new file mode 100644 index 00000000..8220a4be --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/__init__.py @@ -0,0 +1,962 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.ip_messaging.v2.service.channel.invite import InviteList +from twilio.rest.ip_messaging.v2.service.channel.member import MemberList +from twilio.rest.ip_messaging.v2.service.channel.message import MessageList +from twilio.rest.ip_messaging.v2.service.channel.webhook import WebhookList + + +class ChannelInstance(InstanceResource): + + class ChannelType(object): + PUBLIC = "public" + PRIVATE = "private" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: + :ivar account_sid: + :ivar service_sid: + :ivar friendly_name: + :ivar unique_name: + :ivar attributes: + :ivar type: + :ivar date_created: + :ivar date_updated: + :ivar created_by: + :ivar members_count: + :ivar messages_count: + :ivar url: + :ivar links: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.attributes: Optional[str] = payload.get("attributes") + self.type: Optional["ChannelInstance.ChannelType"] = payload.get("type") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + self.members_count: Optional[int] = deserialize.integer( + payload.get("members_count") + ) + self.messages_count: Optional[int] = deserialize.integer( + payload.get("messages_count") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ChannelContext] = None + + @property + def _proxy(self) -> "ChannelContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ChannelContext for this ChannelInstance + """ + if self._context is None: + self._context = ChannelContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "ChannelInstance": + """ + Fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ChannelInstance": + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param date_created: + :param date_updated: + :param created_by: + + :returns: The updated ChannelInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Asynchronous coroutine to update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param date_created: + :param date_updated: + :param created_by: + + :returns: The updated ChannelInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + + @property + def invites(self) -> InviteList: + """ + Access the invites + """ + return self._proxy.invites + + @property + def members(self) -> MemberList: + """ + Access the members + """ + return self._proxy.members + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages + + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + return self._proxy.webhooks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ChannelContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the ChannelContext + + :param version: Version that contains the resource + :param service_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Channels/{sid}".format(**self._solution) + + self._invites: Optional[InviteList] = None + self._members: Optional[MemberList] = None + self._messages: Optional[MessageList] = None + self._webhooks: Optional[WebhookList] = None + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChannelInstance: + """ + Fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ChannelInstance: + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param date_created: + :param date_updated: + :param created_by: + + :returns: The updated ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "CreatedBy": created_by, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronous coroutine to update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param date_created: + :param date_updated: + :param created_by: + + :returns: The updated ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "CreatedBy": created_by, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def invites(self) -> InviteList: + """ + Access the invites + """ + if self._invites is None: + self._invites = InviteList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._invites + + @property + def members(self) -> MemberList: + """ + Access the members + """ + if self._members is None: + self._members = MemberList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._members + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + if self._messages is None: + self._messages = MessageList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._messages + + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + if self._webhooks is None: + self._webhooks = WebhookList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._webhooks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: + """ + Build an instance of ChannelInstance + + :param payload: Payload response from the API + """ + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ChannelList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the ChannelList + + :param version: Version that contains the resource + :param service_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Channels".format(**self._solution) + + def create( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Create the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param type: + :param date_created: + :param date_updated: + :param created_by: + + :returns: The created ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "Type": type, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "CreatedBy": created_by, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronously create the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param type: + :param date_created: + :param date_updated: + :param created_by: + + :returns: The created ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "Type": type, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "CreatedBy": created_by, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChannelInstance]: + """ + Streams ChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(type=type, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ChannelInstance]: + """ + Asynchronously streams ChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(type=type, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: + """ + Lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + type=type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: + """ + Asynchronously lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + type=type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: + """ + Retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param type: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, self._solution) + + async def page_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: + """ + Asynchronously retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param type: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ChannelPage: + """ + Retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ChannelPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ChannelPage: + """ + Asynchronously retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelPage(self._version, response, self._solution) + + def get(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: + """ + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: + """ + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..9afc36f8 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/__pycache__/invite.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/__pycache__/invite.cpython-312.pyc new file mode 100644 index 00000000..9eed124b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/__pycache__/invite.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/__pycache__/member.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/__pycache__/member.cpython-312.pyc new file mode 100644 index 00000000..70fab23a Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/__pycache__/member.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/__pycache__/message.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/__pycache__/message.cpython-312.pyc new file mode 100644 index 00000000..3b548b2b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/__pycache__/message.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/__pycache__/webhook.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/__pycache__/webhook.cpython-312.pyc new file mode 100644 index 00000000..7a7b904f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/__pycache__/webhook.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/invite.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/invite.py new file mode 100644 index 00000000..4fa3c187 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/invite.py @@ -0,0 +1,598 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InviteInstance(InstanceResource): + """ + :ivar sid: + :ivar account_sid: + :ivar channel_sid: + :ivar service_sid: + :ivar identity: + :ivar date_created: + :ivar date_updated: + :ivar role_sid: + :ivar created_by: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.created_by: Optional[str] = payload.get("created_by") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[InviteContext] = None + + @property + def _proxy(self) -> "InviteContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InviteContext for this InviteInstance + """ + if self._context is None: + self._context = InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "InviteInstance": + """ + Fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InviteInstance": + """ + Asynchronous coroutine to fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InviteContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the InviteContext + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Invites/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> InviteInstance: + """ + Fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> InviteInstance: + """ + Asynchronous coroutine to fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InvitePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: + """ + Build an instance of InviteInstance + + :param payload: Payload response from the API + """ + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class InviteList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the InviteList + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Invites".format( + **self._solution + ) + + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Create the InviteInstance + + :param identity: + :param role_sid: + + :returns: The created InviteInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Asynchronously create the InviteInstance + + :param identity: + :param role_sid: + + :returns: The created InviteInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InviteInstance]: + """ + Streams InviteInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InviteInstance]: + """ + Asynchronously streams InviteInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: + """ + Lists InviteInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: + """ + Asynchronously lists InviteInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InvitePage: + """ + Retrieve a single page of InviteInstance records from the API. + Request is executed immediately + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InviteInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InvitePage(self._version, response, self._solution) + + async def page_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InvitePage: + """ + Asynchronously retrieve a single page of InviteInstance records from the API. + Request is executed immediately + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InviteInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InvitePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> InvitePage: + """ + Retrieve a specific page of InviteInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InviteInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InvitePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> InvitePage: + """ + Asynchronously retrieve a specific page of InviteInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InviteInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InvitePage(self._version, response, self._solution) + + def get(self, sid: str) -> InviteContext: + """ + Constructs a InviteContext + + :param sid: + """ + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InviteContext: + """ + Constructs a InviteContext + + :param sid: + """ + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/member.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/member.py new file mode 100644 index 00000000..6456d3be --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/member.py @@ -0,0 +1,905 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MemberInstance(InstanceResource): + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: + :ivar account_sid: + :ivar channel_sid: + :ivar service_sid: + :ivar identity: + :ivar date_created: + :ivar date_updated: + :ivar role_sid: + :ivar last_consumed_message_index: + :ivar last_consumption_timestamp: + :ivar url: + :ivar attributes: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.last_consumed_message_index: Optional[int] = deserialize.integer( + payload.get("last_consumed_message_index") + ) + self.last_consumption_timestamp: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("last_consumption_timestamp")) + ) + self.url: Optional[str] = payload.get("url") + self.attributes: Optional[str] = payload.get("attributes") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[MemberContext] = None + + @property + def _proxy(self) -> "MemberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MemberContext for this MemberInstance + """ + if self._context is None: + self._context = MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "MemberInstance": + """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MemberInstance": + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MemberInstance": + """ + Update the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: + + :returns: The updated MemberInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MemberInstance": + """ + Asynchronous coroutine to update the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: + + :returns: The updated MemberInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MemberContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the MemberContext + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Members/{sid}".format( + **self._solution + ) + ) + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MemberInstance: + """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MemberInstance: + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MemberInstance: + """ + Update the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: + + :returns: The updated MemberInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MemberInstance: + """ + Asynchronous coroutine to update the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: + + :returns: The updated MemberInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MemberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: + """ + Build an instance of MemberInstance + + :param payload: Payload response from the API + """ + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MemberList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MemberList + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Members".format( + **self._solution + ) + + def create( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MemberInstance: + """ + Create the MemberInstance + + :param identity: + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: + + :returns: The created MemberInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MemberInstance: + """ + Asynchronously create the MemberInstance + + :param identity: + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: + + :returns: The created MemberInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MemberInstance]: + """ + Streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MemberInstance]: + """ + Asynchronously streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: + """ + Lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: + """ + Asynchronously lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: + """ + Retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, self._solution) + + async def page_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: + """ + Asynchronously retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MemberPage: + """ + Retrieve a specific page of MemberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MemberPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MemberPage: + """ + Asynchronously retrieve a specific page of MemberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MemberPage(self._version, response, self._solution) + + def get(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param sid: + """ + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param sid: + """ + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/message.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/message.py new file mode 100644 index 00000000..838b3c72 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/message.py @@ -0,0 +1,905 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MessageInstance(InstanceResource): + + class OrderType(object): + ASC = "asc" + DESC = "desc" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: + :ivar account_sid: + :ivar attributes: + :ivar service_sid: + :ivar to: + :ivar channel_sid: + :ivar date_created: + :ivar date_updated: + :ivar last_updated_by: + :ivar was_edited: + :ivar _from: + :ivar body: + :ivar index: + :ivar type: + :ivar media: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.attributes: Optional[str] = payload.get("attributes") + self.service_sid: Optional[str] = payload.get("service_sid") + self.to: Optional[str] = payload.get("to") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.last_updated_by: Optional[str] = payload.get("last_updated_by") + self.was_edited: Optional[bool] = payload.get("was_edited") + self._from: Optional[str] = payload.get("from") + self.body: Optional[str] = payload.get("body") + self.index: Optional[int] = deserialize.integer(payload.get("index")) + self.type: Optional[str] = payload.get("type") + self.media: Optional[Dict[str, object]] = payload.get("media") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[MessageContext] = None + + @property + def _proxy(self) -> "MessageContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MessageContext for this MessageInstance + """ + if self._context is None: + self._context = MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "MessageInstance": + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MessageInstance": + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param from_: + + :returns: The updated MessageInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Asynchronous coroutine to update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param from_: + + :returns: The updated MessageInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MessageContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the MessageContext + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Messages/{sid}".format( + **self._solution + ) + ) + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param from_: + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Body": body, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "LastUpdatedBy": last_updated_by, + "From": from_, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronous coroutine to update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param from_: + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Body": body, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "LastUpdatedBy": last_updated_by, + "From": from_, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MessagePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: + """ + Build an instance of MessageInstance + + :param payload: Payload response from the API + """ + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MessageList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MessageList + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Messages".format( + **self._solution + ) + + def create( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param from_: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param body: + :param media_sid: + + :returns: The created MessageInstance + """ + + data = values.of( + { + "From": from_, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "LastUpdatedBy": last_updated_by, + "Body": body, + "MediaSid": media_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param from_: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param body: + :param media_sid: + + :returns: The created MessageInstance + """ + + data = values.of( + { + "From": from_, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "LastUpdatedBy": last_updated_by, + "Body": body, + "MediaSid": media_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: + """ + Streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(order=order, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessageInstance]: + """ + Asynchronously streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(order=order, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + order=order, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Asynchronously lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + order=order, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + async def page_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MessagePage: + """ + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MessagePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MessagePage: + """ + Asynchronously retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagePage(self._version, response, self._solution) + + def get(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: + """ + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: + """ + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/webhook.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/webhook.py new file mode 100644 index 00000000..3c7570fd --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/channel/webhook.py @@ -0,0 +1,800 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class WebhookInstance(InstanceResource): + + class Method(object): + GET = "GET" + POST = "POST" + + class Type(object): + WEBHOOK = "webhook" + TRIGGER = "trigger" + STUDIO = "studio" + + """ + :ivar sid: + :ivar account_sid: + :ivar service_sid: + :ivar channel_sid: + :ivar type: + :ivar url: + :ivar configuration: + :ivar date_created: + :ivar date_updated: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.type: Optional[str] = payload.get("type") + self.url: Optional[str] = payload.get("url") + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[WebhookContext] = None + + @property + def _proxy(self) -> "WebhookContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WebhookContext for this WebhookInstance + """ + if self._context is None: + self._context = WebhookContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "WebhookInstance": + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "WebhookInstance": + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> "WebhookInstance": + """ + Update the WebhookInstance + + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: The updated WebhookInstance + """ + return self._proxy.update( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + + async def update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> "WebhookInstance": + """ + Asynchronous coroutine to update the WebhookInstance + + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: The updated WebhookInstance + """ + return await self._proxy.update_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WebhookContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the WebhookContext + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Webhooks/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Update the WebhookInstance + + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + "Configuration.RetryCount": configuration_retry_count, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronous coroutine to update the WebhookInstance + + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + "Configuration.RetryCount": configuration_retry_count, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WebhookPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: + """ + Build an instance of WebhookInstance + + :param payload: Payload response from the API + """ + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class WebhookList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the WebhookList + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Webhooks".format( + **self._solution + ) + + def create( + self, + type: "WebhookInstance.Type", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Create the WebhookInstance + + :param type: + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: The created WebhookInstance + """ + + data = values.of( + { + "Type": type, + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + "Configuration.RetryCount": configuration_retry_count, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, + type: "WebhookInstance.Type", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronously create the WebhookInstance + + :param type: + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: The created WebhookInstance + """ + + data = values.of( + { + "Type": type, + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + "Configuration.RetryCount": configuration_retry_count, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WebhookInstance]: + """ + Streams WebhookInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WebhookInstance]: + """ + Asynchronously streams WebhookInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: + """ + Lists WebhookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: + """ + Asynchronously lists WebhookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebhookPage: + """ + Retrieve a single page of WebhookInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebhookInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebhookPage: + """ + Asynchronously retrieve a single page of WebhookInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebhookInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> WebhookPage: + """ + Retrieve a specific page of WebhookInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebhookInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return WebhookPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> WebhookPage: + """ + Asynchronously retrieve a specific page of WebhookInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebhookInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return WebhookPage(self._version, response, self._solution) + + def get(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: + """ + return WebhookContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: + """ + return WebhookContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/role.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/role.py new file mode 100644 index 00000000..32f70c22 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/role.py @@ -0,0 +1,645 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RoleInstance(InstanceResource): + + class RoleType(object): + CHANNEL = "channel" + DEPLOYMENT = "deployment" + + """ + :ivar sid: + :ivar account_sid: + :ivar service_sid: + :ivar friendly_name: + :ivar type: + :ivar permissions: + :ivar date_created: + :ivar date_updated: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["RoleInstance.RoleType"] = payload.get("type") + self.permissions: Optional[List[str]] = payload.get("permissions") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[RoleContext] = None + + @property + def _proxy(self) -> "RoleContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RoleContext for this RoleInstance + """ + if self._context is None: + self._context = RoleContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RoleInstance": + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RoleInstance": + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + return await self._proxy.fetch_async() + + def update(self, permission: List[str]) -> "RoleInstance": + """ + Update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + return self._proxy.update( + permission=permission, + ) + + async def update_async(self, permission: List[str]) -> "RoleInstance": + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + return await self._proxy.update_async( + permission=permission, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RoleContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the RoleContext + + :param version: Version that contains the resource + :param service_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Roles/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RoleInstance: + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update(self, permission: List[str]) -> RoleInstance: + """ + Update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, permission: List[str]) -> RoleInstance: + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RolePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: + """ + Build an instance of RoleInstance + + :param payload: Payload response from the API + """ + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RoleList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the RoleList + + :param version: Version that contains the resource + :param service_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Roles".format(**self._solution) + + def create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Create the RoleInstance + + :param friendly_name: + :param type: + :param permission: + + :returns: The created RoleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Asynchronously create the RoleInstance + + :param friendly_name: + :param type: + :param permission: + + :returns: The created RoleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoleInstance]: + """ + Streams RoleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RoleInstance]: + """ + Asynchronously streams RoleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: + """ + Lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: + """ + Asynchronously lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePage: + """ + Retrieve a single page of RoleInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePage: + """ + Asynchronously retrieve a single page of RoleInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RolePage: + """ + Retrieve a specific page of RoleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RolePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RolePage: + """ + Asynchronously retrieve a specific page of RoleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RolePage(self._version, response, self._solution) + + def get(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: + """ + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: + """ + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/user/__init__.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/user/__init__.py new file mode 100644 index 00000000..f5f1454c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/user/__init__.py @@ -0,0 +1,804 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.ip_messaging.v2.service.user.user_binding import UserBindingList +from twilio.rest.ip_messaging.v2.service.user.user_channel import UserChannelList + + +class UserInstance(InstanceResource): + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: + :ivar account_sid: + :ivar service_sid: + :ivar attributes: + :ivar friendly_name: + :ivar role_sid: + :ivar identity: + :ivar is_online: + :ivar is_notifiable: + :ivar date_created: + :ivar date_updated: + :ivar joined_channels_count: + :ivar links: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.attributes: Optional[str] = payload.get("attributes") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.role_sid: Optional[str] = payload.get("role_sid") + self.identity: Optional[str] = payload.get("identity") + self.is_online: Optional[bool] = payload.get("is_online") + self.is_notifiable: Optional[bool] = payload.get("is_notifiable") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.joined_channels_count: Optional[int] = deserialize.integer( + payload.get("joined_channels_count") + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[UserContext] = None + + @property + def _proxy(self) -> "UserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserContext for this UserInstance + """ + if self._context is None: + self._context = UserContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "UserInstance": + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserInstance": + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The updated UserInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Asynchronous coroutine to update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The updated UserInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + @property + def user_bindings(self) -> UserBindingList: + """ + Access the user_bindings + """ + return self._proxy.user_bindings + + @property + def user_channels(self) -> UserChannelList: + """ + Access the user_channels + """ + return self._proxy.user_channels + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the UserContext + + :param version: Version that contains the resource + :param service_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Users/{sid}".format(**self._solution) + + self._user_bindings: Optional[UserBindingList] = None + self._user_channels: Optional[UserChannelList] = None + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The updated UserInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The updated UserInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def user_bindings(self) -> UserBindingList: + """ + Access the user_bindings + """ + if self._user_bindings is None: + self._user_bindings = UserBindingList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._user_bindings + + @property + def user_channels(self) -> UserChannelList: + """ + Access the user_channels + """ + if self._user_channels is None: + self._user_channels = UserChannelList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._user_channels + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: + """ + Build an instance of UserInstance + + :param payload: Payload response from the API + """ + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class UserList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the UserList + + :param version: Version that contains the resource + :param service_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Users".format(**self._solution) + + def create( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Create the UserInstance + + :param identity: + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The created UserInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param identity: + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The created UserInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserInstance]: + """ + Streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserInstance]: + """ + Asynchronously streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Asynchronously lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Asynchronously retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserPage: + """ + Retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserPage: + """ + Asynchronously retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserPage(self._version, response, self._solution) + + def get(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: + """ + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: + """ + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/user/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/user/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..3cc77c54 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/user/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/user/__pycache__/user_binding.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/user/__pycache__/user_binding.cpython-312.pyc new file mode 100644 index 00000000..ea93b202 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/user/__pycache__/user_binding.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/user/__pycache__/user_channel.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/user/__pycache__/user_channel.cpython-312.pyc new file mode 100644 index 00000000..313f963e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/user/__pycache__/user_channel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/user/user_binding.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/user/user_binding.py new file mode 100644 index 00000000..4f1d9f10 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/user/user_binding.py @@ -0,0 +1,552 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UserBindingInstance(InstanceResource): + + class BindingType(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: + :ivar account_sid: + :ivar service_sid: + :ivar date_created: + :ivar date_updated: + :ivar endpoint: + :ivar identity: + :ivar user_sid: + :ivar credential_sid: + :ivar binding_type: + :ivar message_types: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + user_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.endpoint: Optional[str] = payload.get("endpoint") + self.identity: Optional[str] = payload.get("identity") + self.user_sid: Optional[str] = payload.get("user_sid") + self.credential_sid: Optional[str] = payload.get("credential_sid") + self.binding_type: Optional["UserBindingInstance.BindingType"] = payload.get( + "binding_type" + ) + self.message_types: Optional[List[str]] = payload.get("message_types") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "sid": sid or self.sid, + } + self._context: Optional[UserBindingContext] = None + + @property + def _proxy(self) -> "UserBindingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserBindingContext for this UserBindingInstance + """ + if self._context is None: + self._context = UserBindingContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UserBindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserBindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "UserBindingInstance": + """ + Fetch the UserBindingInstance + + + :returns: The fetched UserBindingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserBindingInstance": + """ + Asynchronous coroutine to fetch the UserBindingInstance + + + :returns: The fetched UserBindingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserBindingContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, user_sid: str, sid: str): + """ + Initialize the UserBindingContext + + :param version: Version that contains the resource + :param service_sid: + :param user_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Users/{user_sid}/Bindings/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the UserBindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserBindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserBindingInstance: + """ + Fetch the UserBindingInstance + + + :returns: The fetched UserBindingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> UserBindingInstance: + """ + Asynchronous coroutine to fetch the UserBindingInstance + + + :returns: The fetched UserBindingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserBindingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserBindingInstance: + """ + Build an instance of UserBindingInstance + + :param payload: Payload response from the API + """ + return UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class UserBindingList(ListResource): + + def __init__(self, version: Version, service_sid: str, user_sid: str): + """ + Initialize the UserBindingList + + :param version: Version that contains the resource + :param service_sid: + :param user_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + } + self._uri = "/Services/{service_sid}/Users/{user_sid}/Bindings".format( + **self._solution + ) + + def stream( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserBindingInstance]: + """ + Streams UserBindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["UserBindingInstance.BindingType"] binding_type: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(binding_type=binding_type, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserBindingInstance]: + """ + Asynchronously streams UserBindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["UserBindingInstance.BindingType"] binding_type: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + binding_type=binding_type, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserBindingInstance]: + """ + Lists UserBindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["UserBindingInstance.BindingType"] binding_type: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + binding_type=binding_type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserBindingInstance]: + """ + Asynchronously lists UserBindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["UserBindingInstance.BindingType"] binding_type: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + binding_type=binding_type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserBindingPage: + """ + Retrieve a single page of UserBindingInstance records from the API. + Request is executed immediately + + :param binding_type: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserBindingInstance + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserBindingPage(self._version, response, self._solution) + + async def page_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserBindingPage: + """ + Asynchronously retrieve a single page of UserBindingInstance records from the API. + Request is executed immediately + + :param binding_type: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserBindingInstance + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserBindingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserBindingPage: + """ + Retrieve a specific page of UserBindingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserBindingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserBindingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserBindingPage: + """ + Asynchronously retrieve a specific page of UserBindingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserBindingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserBindingPage(self._version, response, self._solution) + + def get(self, sid: str) -> UserBindingContext: + """ + Constructs a UserBindingContext + + :param sid: + """ + return UserBindingContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> UserBindingContext: + """ + Constructs a UserBindingContext + + :param sid: + """ + return UserBindingContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/user/user_channel.py b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/user/user_channel.py new file mode 100644 index 00000000..5cb544fc --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/ip_messaging/v2/service/user/user_channel.py @@ -0,0 +1,666 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UserChannelInstance(InstanceResource): + + class ChannelStatus(object): + JOINED = "joined" + INVITED = "invited" + NOT_PARTICIPATING = "not_participating" + + class NotificationLevel(object): + DEFAULT = "default" + MUTED = "muted" + + """ + :ivar account_sid: + :ivar service_sid: + :ivar channel_sid: + :ivar user_sid: + :ivar member_sid: + :ivar status: + :ivar last_consumed_message_index: + :ivar unread_messages_count: + :ivar links: + :ivar url: + :ivar notification_level: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + user_sid: str, + channel_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.user_sid: Optional[str] = payload.get("user_sid") + self.member_sid: Optional[str] = payload.get("member_sid") + self.status: Optional["UserChannelInstance.ChannelStatus"] = payload.get( + "status" + ) + self.last_consumed_message_index: Optional[int] = deserialize.integer( + payload.get("last_consumed_message_index") + ) + self.unread_messages_count: Optional[int] = deserialize.integer( + payload.get("unread_messages_count") + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + self.url: Optional[str] = payload.get("url") + self.notification_level: Optional["UserChannelInstance.NotificationLevel"] = ( + payload.get("notification_level") + ) + + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "channel_sid": channel_sid or self.channel_sid, + } + self._context: Optional[UserChannelContext] = None + + @property + def _proxy(self) -> "UserChannelContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserChannelContext for this UserChannelInstance + """ + if self._context is None: + self._context = UserChannelContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UserChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "UserChannelInstance": + """ + Fetch the UserChannelInstance + + + :returns: The fetched UserChannelInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserChannelInstance": + """ + Asynchronous coroutine to fetch the UserChannelInstance + + + :returns: The fetched UserChannelInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> "UserChannelInstance": + """ + Update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: + + :returns: The updated UserChannelInstance + """ + return self._proxy.update( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + + async def update_async( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> "UserChannelInstance": + """ + Asynchronous coroutine to update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: + + :returns: The updated UserChannelInstance + """ + return await self._proxy.update_async( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserChannelContext(InstanceContext): + + def __init__( + self, version: Version, service_sid: str, user_sid: str, channel_sid: str + ): + """ + Initialize the UserChannelContext + + :param version: Version that contains the resource + :param service_sid: + :param user_sid: + :param channel_sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "channel_sid": channel_sid, + } + self._uri = ( + "/Services/{service_sid}/Users/{user_sid}/Channels/{channel_sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the UserChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserChannelInstance: + """ + Fetch the UserChannelInstance + + + :returns: The fetched UserChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def fetch_async(self) -> UserChannelInstance: + """ + Asynchronous coroutine to fetch the UserChannelInstance + + + :returns: The fetched UserChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def update( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> UserChannelInstance: + """ + Update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: + + :returns: The updated UserChannelInstance + """ + + data = values.of( + { + "NotificationLevel": notification_level, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def update_async( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> UserChannelInstance: + """ + Asynchronous coroutine to update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: + + :returns: The updated UserChannelInstance + """ + + data = values.of( + { + "NotificationLevel": notification_level, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: + """ + Build an instance of UserChannelInstance + + :param payload: Payload response from the API + """ + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class UserChannelList(ListResource): + + def __init__(self, version: Version, service_sid: str, user_sid: str): + """ + Initialize the UserChannelList + + :param version: Version that contains the resource + :param service_sid: + :param user_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + } + self._uri = "/Services/{service_sid}/Users/{user_sid}/Channels".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserChannelInstance]: + """ + Streams UserChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserChannelInstance]: + """ + Asynchronously streams UserChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: + """ + Lists UserChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: + """ + Asynchronously lists UserChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserChannelPage: + """ + Retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserChannelPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserChannelPage: + """ + Asynchronously retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserChannelPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserChannelPage: + """ + Retrieve a specific page of UserChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserChannelPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserChannelPage: + """ + Asynchronously retrieve a specific page of UserChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserChannelPage(self._version, response, self._solution) + + def get(self, channel_sid: str) -> UserChannelContext: + """ + Constructs a UserChannelContext + + :param channel_sid: + """ + return UserChannelContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=channel_sid, + ) + + def __call__(self, channel_sid: str) -> UserChannelContext: + """ + Constructs a UserChannelContext + + :param channel_sid: + """ + return UserChannelContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=channel_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/lookups/LookupsBase.py b/venv/Lib/site-packages/twilio/rest/lookups/LookupsBase.py new file mode 100644 index 00000000..e24f8dc6 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/lookups/LookupsBase.py @@ -0,0 +1,55 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.lookups.v1 import V1 +from twilio.rest.lookups.v2 import V2 + + +class LookupsBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Lookups Domain + + :returns: Domain for Lookups + """ + super().__init__(twilio, "https://lookups.twilio.com") + self._v1: Optional[V1] = None + self._v2: Optional[V2] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Lookups + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Lookups + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/lookups/__init__.py b/venv/Lib/site-packages/twilio/rest/lookups/__init__.py new file mode 100644 index 00000000..6a984f81 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/lookups/__init__.py @@ -0,0 +1,15 @@ +from warnings import warn + +from twilio.rest.lookups.LookupsBase import LookupsBase +from twilio.rest.lookups.v1.phone_number import PhoneNumberList + + +class Lookups(LookupsBase): + @property + def phone_numbers(self) -> PhoneNumberList: + warn( + "phone_numbers is deprecated. Use v1.phone_numbers instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.phone_numbers diff --git a/venv/Lib/site-packages/twilio/rest/lookups/__pycache__/LookupsBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/lookups/__pycache__/LookupsBase.cpython-312.pyc new file mode 100644 index 00000000..9fd9dadc Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/lookups/__pycache__/LookupsBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/lookups/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/lookups/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..c405b4e7 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/lookups/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/lookups/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/lookups/v1/__init__.py new file mode 100644 index 00000000..72204da3 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/lookups/v1/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Lookups + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.lookups.v1.phone_number import PhoneNumberList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Lookups + + :param domain: The Twilio.lookups domain + """ + super().__init__(domain, "v1") + self._phone_numbers: Optional[PhoneNumberList] = None + + @property + def phone_numbers(self) -> PhoneNumberList: + if self._phone_numbers is None: + self._phone_numbers = PhoneNumberList(self) + return self._phone_numbers + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/lookups/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/lookups/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..c15056db Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/lookups/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/lookups/v1/__pycache__/phone_number.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/lookups/v1/__pycache__/phone_number.cpython-312.pyc new file mode 100644 index 00000000..9d7bd1c2 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/lookups/v1/__pycache__/phone_number.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/lookups/v1/phone_number.py b/venv/Lib/site-packages/twilio/rest/lookups/v1/phone_number.py new file mode 100644 index 00000000..304b89ab --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/lookups/v1/phone_number.py @@ -0,0 +1,272 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Lookups + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PhoneNumberInstance(InstanceResource): + """ + :ivar caller_name: The name of the phone number's owner. If `null`, that information was not available. + :ivar country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) for the phone number. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar national_format: The phone number, in national format. + :ivar carrier: The telecom company that provides the phone number. + :ivar add_ons: A JSON string with the results of the Add-ons you specified in the `add_ons` parameters. For the format of the object, see [Using Add-ons](https://www.twilio.com/docs/add-ons). + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + phone_number: Optional[str] = None, + ): + super().__init__(version) + + self.caller_name: Optional[Dict[str, object]] = payload.get("caller_name") + self.country_code: Optional[str] = payload.get("country_code") + self.phone_number: Optional[str] = payload.get("phone_number") + self.national_format: Optional[str] = payload.get("national_format") + self.carrier: Optional[Dict[str, object]] = payload.get("carrier") + self.add_ons: Optional[Dict[str, object]] = payload.get("add_ons") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "phone_number": phone_number or self.phone_number, + } + self._context: Optional[PhoneNumberContext] = None + + @property + def _proxy(self) -> "PhoneNumberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PhoneNumberContext for this PhoneNumberInstance + """ + if self._context is None: + self._context = PhoneNumberContext( + self._version, + phone_number=self._solution["phone_number"], + ) + return self._context + + def fetch( + self, + country_code: Union[str, object] = values.unset, + type: Union[List[str], object] = values.unset, + add_ons: Union[List[str], object] = values.unset, + add_ons_data: Union[Dict[str, object], object] = values.unset, + ) -> "PhoneNumberInstance": + """ + Fetch the PhoneNumberInstance + + :param country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the phone number to fetch. This is used to specify the country when the phone number is provided in a national format. + :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. To retrieve both types of information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. + :param add_ons: The `unique_name` of an Add-on you would like to invoke. Can be the `unique_name` of an Add-on that is installed on your account. You can specify multiple instances of this parameter to invoke multiple Add-ons. For more information about Add-ons, see the [Add-ons documentation](https://www.twilio.com/docs/add-ons). + :param add_ons_data: Data specific to the add-on you would like to invoke. The content and format of this value depends on the add-on. + + :returns: The fetched PhoneNumberInstance + """ + return self._proxy.fetch( + country_code=country_code, + type=type, + add_ons=add_ons, + add_ons_data=add_ons_data, + ) + + async def fetch_async( + self, + country_code: Union[str, object] = values.unset, + type: Union[List[str], object] = values.unset, + add_ons: Union[List[str], object] = values.unset, + add_ons_data: Union[Dict[str, object], object] = values.unset, + ) -> "PhoneNumberInstance": + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + :param country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the phone number to fetch. This is used to specify the country when the phone number is provided in a national format. + :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. To retrieve both types of information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. + :param add_ons: The `unique_name` of an Add-on you would like to invoke. Can be the `unique_name` of an Add-on that is installed on your account. You can specify multiple instances of this parameter to invoke multiple Add-ons. For more information about Add-ons, see the [Add-ons documentation](https://www.twilio.com/docs/add-ons). + :param add_ons_data: Data specific to the add-on you would like to invoke. The content and format of this value depends on the add-on. + + :returns: The fetched PhoneNumberInstance + """ + return await self._proxy.fetch_async( + country_code=country_code, + type=type, + add_ons=add_ons, + add_ons_data=add_ons_data, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PhoneNumberContext(InstanceContext): + + def __init__(self, version: Version, phone_number: str): + """ + Initialize the PhoneNumberContext + + :param version: Version that contains the resource + :param phone_number: The phone number to lookup in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "phone_number": phone_number, + } + self._uri = "/PhoneNumbers/{phone_number}".format(**self._solution) + + def fetch( + self, + country_code: Union[str, object] = values.unset, + type: Union[List[str], object] = values.unset, + add_ons: Union[List[str], object] = values.unset, + add_ons_data: Union[Dict[str, object], object] = values.unset, + ) -> PhoneNumberInstance: + """ + Fetch the PhoneNumberInstance + + :param country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the phone number to fetch. This is used to specify the country when the phone number is provided in a national format. + :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. To retrieve both types of information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. + :param add_ons: The `unique_name` of an Add-on you would like to invoke. Can be the `unique_name` of an Add-on that is installed on your account. You can specify multiple instances of this parameter to invoke multiple Add-ons. For more information about Add-ons, see the [Add-ons documentation](https://www.twilio.com/docs/add-ons). + :param add_ons_data: Data specific to the add-on you would like to invoke. The content and format of this value depends on the add-on. + + :returns: The fetched PhoneNumberInstance + """ + + data = values.of( + { + "CountryCode": country_code, + "Type": serialize.map(type, lambda e: e), + "AddOns": serialize.map(add_ons, lambda e: e), + } + ) + + data.update(serialize.prefixed_collapsible_map(add_ons_data, "AddOns")) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + async def fetch_async( + self, + country_code: Union[str, object] = values.unset, + type: Union[List[str], object] = values.unset, + add_ons: Union[List[str], object] = values.unset, + add_ons_data: Union[Dict[str, object], object] = values.unset, + ) -> PhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + :param country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the phone number to fetch. This is used to specify the country when the phone number is provided in a national format. + :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. To retrieve both types of information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. + :param add_ons: The `unique_name` of an Add-on you would like to invoke. Can be the `unique_name` of an Add-on that is installed on your account. You can specify multiple instances of this parameter to invoke multiple Add-ons. For more information about Add-ons, see the [Add-ons documentation](https://www.twilio.com/docs/add-ons). + :param add_ons_data: Data specific to the add-on you would like to invoke. The content and format of this value depends on the add-on. + + :returns: The fetched PhoneNumberInstance + """ + + data = values.of( + { + "CountryCode": country_code, + "Type": serialize.map(type, lambda e: e), + "AddOns": serialize.map(add_ons, lambda e: e), + } + ) + + data.update(serialize.prefixed_collapsible_map(add_ons_data, "AddOns")) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PhoneNumberList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PhoneNumberList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, phone_number: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param phone_number: The phone number to lookup in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + """ + return PhoneNumberContext(self._version, phone_number=phone_number) + + def __call__(self, phone_number: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param phone_number: The phone number to lookup in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + """ + return PhoneNumberContext(self._version, phone_number=phone_number) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/lookups/v2/__init__.py b/venv/Lib/site-packages/twilio/rest/lookups/v2/__init__.py new file mode 100644 index 00000000..d795aea1 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/lookups/v2/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Lookups + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.lookups.v2.phone_number import PhoneNumberList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Lookups + + :param domain: The Twilio.lookups domain + """ + super().__init__(domain, "v2") + self._phone_numbers: Optional[PhoneNumberList] = None + + @property + def phone_numbers(self) -> PhoneNumberList: + if self._phone_numbers is None: + self._phone_numbers = PhoneNumberList(self) + return self._phone_numbers + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/lookups/v2/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/lookups/v2/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..42b88d6b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/lookups/v2/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/lookups/v2/__pycache__/phone_number.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/lookups/v2/__pycache__/phone_number.cpython-312.pyc new file mode 100644 index 00000000..5d929e4f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/lookups/v2/__pycache__/phone_number.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/lookups/v2/phone_number.py b/venv/Lib/site-packages/twilio/rest/lookups/v2/phone_number.py new file mode 100644 index 00000000..fc60eed6 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/lookups/v2/phone_number.py @@ -0,0 +1,443 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Lookups + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PhoneNumberInstance(InstanceResource): + + class ValidationError(object): + TOO_SHORT = "TOO_SHORT" + TOO_LONG = "TOO_LONG" + INVALID_BUT_POSSIBLE = "INVALID_BUT_POSSIBLE" + INVALID_COUNTRY_CODE = "INVALID_COUNTRY_CODE" + INVALID_LENGTH = "INVALID_LENGTH" + NOT_A_NUMBER = "NOT_A_NUMBER" + + """ + :ivar calling_country_code: International dialing prefix of the phone number defined in the E.164 standard. + :ivar country_code: The phone number's [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar national_format: The phone number in [national format](https://en.wikipedia.org/wiki/National_conventions_for_writing_telephone_numbers). + :ivar valid: Boolean which indicates if the phone number is in a valid range that can be freely assigned by a carrier to a user. + :ivar validation_errors: Contains reasons why a phone number is invalid. Possible values: TOO_SHORT, TOO_LONG, INVALID_BUT_POSSIBLE, INVALID_COUNTRY_CODE, INVALID_LENGTH, NOT_A_NUMBER. + :ivar caller_name: An object that contains caller name information based on [CNAM](https://support.twilio.com/hc/en-us/articles/360051670533-Getting-Started-with-CNAM-Caller-ID). + :ivar sim_swap: An object that contains information on the last date the subscriber identity module (SIM) was changed for a mobile phone number. + :ivar call_forwarding: An object that contains information on the unconditional call forwarding status of mobile phone number. + :ivar line_status: An object that contains line status information for a mobile phone number. + :ivar line_type_intelligence: An object that contains line type information including the carrier name, mobile country code, and mobile network code. + :ivar identity_match: An object that contains identity match information. The result of comparing user-provided information including name, address, date of birth, national ID, against authoritative phone-based data sources + :ivar reassigned_number: An object that contains reassigned number information. Reassigned Numbers will return a phone number's reassignment status given a phone number and date + :ivar sms_pumping_risk: An object that contains information on if a phone number has been currently or previously blocked by Verify Fraud Guard for receiving malicious SMS pumping traffic as well as other signals associated with risky carriers and low conversion rates. + :ivar phone_number_quality_score: An object that contains information of a mobile phone number quality score. Quality score will return a risk score about the phone number. + :ivar pre_fill: An object that contains pre fill information. pre_fill will return PII information associated with the phone number like first name, last name, address line, country code, state and postal code. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + phone_number: Optional[str] = None, + ): + super().__init__(version) + + self.calling_country_code: Optional[str] = payload.get("calling_country_code") + self.country_code: Optional[str] = payload.get("country_code") + self.phone_number: Optional[str] = payload.get("phone_number") + self.national_format: Optional[str] = payload.get("national_format") + self.valid: Optional[bool] = payload.get("valid") + self.validation_errors: Optional[ + List["PhoneNumberInstance.ValidationError"] + ] = payload.get("validation_errors") + self.caller_name: Optional[Dict[str, object]] = payload.get("caller_name") + self.sim_swap: Optional[Dict[str, object]] = payload.get("sim_swap") + self.call_forwarding: Optional[Dict[str, object]] = payload.get( + "call_forwarding" + ) + self.line_status: Optional[Dict[str, object]] = payload.get("line_status") + self.line_type_intelligence: Optional[Dict[str, object]] = payload.get( + "line_type_intelligence" + ) + self.identity_match: Optional[Dict[str, object]] = payload.get("identity_match") + self.reassigned_number: Optional[Dict[str, object]] = payload.get( + "reassigned_number" + ) + self.sms_pumping_risk: Optional[Dict[str, object]] = payload.get( + "sms_pumping_risk" + ) + self.phone_number_quality_score: Optional[Dict[str, object]] = payload.get( + "phone_number_quality_score" + ) + self.pre_fill: Optional[Dict[str, object]] = payload.get("pre_fill") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "phone_number": phone_number or self.phone_number, + } + self._context: Optional[PhoneNumberContext] = None + + @property + def _proxy(self) -> "PhoneNumberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PhoneNumberContext for this PhoneNumberInstance + """ + if self._context is None: + self._context = PhoneNumberContext( + self._version, + phone_number=self._solution["phone_number"], + ) + return self._context + + def fetch( + self, + fields: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + address_line1: Union[str, object] = values.unset, + address_line2: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + national_id: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + last_verified_date: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + partner_sub_id: Union[str, object] = values.unset, + ) -> "PhoneNumberInstance": + """ + Fetch the PhoneNumberInstance + + :param fields: A comma-separated list of fields to return. Possible values are validation, caller_name, sim_swap, call_forwarding, line_status, line_type_intelligence, identity_match, reassigned_number, sms_pumping_risk, phone_number_quality_score, pre_fill. + :param country_code: The [country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) used if the phone number provided is in national format. + :param first_name: User’s first name. This query parameter is only used (optionally) for identity_match package requests. + :param last_name: User’s last name. This query parameter is only used (optionally) for identity_match package requests. + :param address_line1: User’s first address line. This query parameter is only used (optionally) for identity_match package requests. + :param address_line2: User’s second address line. This query parameter is only used (optionally) for identity_match package requests. + :param city: User’s city. This query parameter is only used (optionally) for identity_match package requests. + :param state: User’s country subdivision, such as state, province, or locality. This query parameter is only used (optionally) for identity_match package requests. + :param postal_code: User’s postal zip code. This query parameter is only used (optionally) for identity_match package requests. + :param address_country_code: User’s country, up to two characters. This query parameter is only used (optionally) for identity_match package requests. + :param national_id: User’s national ID, such as SSN or Passport ID. This query parameter is only used (optionally) for identity_match package requests. + :param date_of_birth: User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests. + :param last_verified_date: The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests. + :param verification_sid: The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests. + :param partner_sub_id: The optional partnerSubId parameter to provide context for your sub-accounts, tenantIDs, sender IDs or other segmentation, enhancing the accuracy of the risk analysis. + + :returns: The fetched PhoneNumberInstance + """ + return self._proxy.fetch( + fields=fields, + country_code=country_code, + first_name=first_name, + last_name=last_name, + address_line1=address_line1, + address_line2=address_line2, + city=city, + state=state, + postal_code=postal_code, + address_country_code=address_country_code, + national_id=national_id, + date_of_birth=date_of_birth, + last_verified_date=last_verified_date, + verification_sid=verification_sid, + partner_sub_id=partner_sub_id, + ) + + async def fetch_async( + self, + fields: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + address_line1: Union[str, object] = values.unset, + address_line2: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + national_id: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + last_verified_date: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + partner_sub_id: Union[str, object] = values.unset, + ) -> "PhoneNumberInstance": + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + :param fields: A comma-separated list of fields to return. Possible values are validation, caller_name, sim_swap, call_forwarding, line_status, line_type_intelligence, identity_match, reassigned_number, sms_pumping_risk, phone_number_quality_score, pre_fill. + :param country_code: The [country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) used if the phone number provided is in national format. + :param first_name: User’s first name. This query parameter is only used (optionally) for identity_match package requests. + :param last_name: User’s last name. This query parameter is only used (optionally) for identity_match package requests. + :param address_line1: User’s first address line. This query parameter is only used (optionally) for identity_match package requests. + :param address_line2: User’s second address line. This query parameter is only used (optionally) for identity_match package requests. + :param city: User’s city. This query parameter is only used (optionally) for identity_match package requests. + :param state: User’s country subdivision, such as state, province, or locality. This query parameter is only used (optionally) for identity_match package requests. + :param postal_code: User’s postal zip code. This query parameter is only used (optionally) for identity_match package requests. + :param address_country_code: User’s country, up to two characters. This query parameter is only used (optionally) for identity_match package requests. + :param national_id: User’s national ID, such as SSN or Passport ID. This query parameter is only used (optionally) for identity_match package requests. + :param date_of_birth: User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests. + :param last_verified_date: The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests. + :param verification_sid: The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests. + :param partner_sub_id: The optional partnerSubId parameter to provide context for your sub-accounts, tenantIDs, sender IDs or other segmentation, enhancing the accuracy of the risk analysis. + + :returns: The fetched PhoneNumberInstance + """ + return await self._proxy.fetch_async( + fields=fields, + country_code=country_code, + first_name=first_name, + last_name=last_name, + address_line1=address_line1, + address_line2=address_line2, + city=city, + state=state, + postal_code=postal_code, + address_country_code=address_country_code, + national_id=national_id, + date_of_birth=date_of_birth, + last_verified_date=last_verified_date, + verification_sid=verification_sid, + partner_sub_id=partner_sub_id, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PhoneNumberContext(InstanceContext): + + def __init__(self, version: Version, phone_number: str): + """ + Initialize the PhoneNumberContext + + :param version: Version that contains the resource + :param phone_number: The phone number to lookup in E.164 or national format. Default country code is +1 (North America). + """ + super().__init__(version) + + # Path Solution + self._solution = { + "phone_number": phone_number, + } + self._uri = "/PhoneNumbers/{phone_number}".format(**self._solution) + + def fetch( + self, + fields: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + address_line1: Union[str, object] = values.unset, + address_line2: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + national_id: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + last_verified_date: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + partner_sub_id: Union[str, object] = values.unset, + ) -> PhoneNumberInstance: + """ + Fetch the PhoneNumberInstance + + :param fields: A comma-separated list of fields to return. Possible values are validation, caller_name, sim_swap, call_forwarding, line_status, line_type_intelligence, identity_match, reassigned_number, sms_pumping_risk, phone_number_quality_score, pre_fill. + :param country_code: The [country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) used if the phone number provided is in national format. + :param first_name: User’s first name. This query parameter is only used (optionally) for identity_match package requests. + :param last_name: User’s last name. This query parameter is only used (optionally) for identity_match package requests. + :param address_line1: User’s first address line. This query parameter is only used (optionally) for identity_match package requests. + :param address_line2: User’s second address line. This query parameter is only used (optionally) for identity_match package requests. + :param city: User’s city. This query parameter is only used (optionally) for identity_match package requests. + :param state: User’s country subdivision, such as state, province, or locality. This query parameter is only used (optionally) for identity_match package requests. + :param postal_code: User’s postal zip code. This query parameter is only used (optionally) for identity_match package requests. + :param address_country_code: User’s country, up to two characters. This query parameter is only used (optionally) for identity_match package requests. + :param national_id: User’s national ID, such as SSN or Passport ID. This query parameter is only used (optionally) for identity_match package requests. + :param date_of_birth: User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests. + :param last_verified_date: The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests. + :param verification_sid: The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests. + :param partner_sub_id: The optional partnerSubId parameter to provide context for your sub-accounts, tenantIDs, sender IDs or other segmentation, enhancing the accuracy of the risk analysis. + + :returns: The fetched PhoneNumberInstance + """ + + data = values.of( + { + "Fields": fields, + "CountryCode": country_code, + "FirstName": first_name, + "LastName": last_name, + "AddressLine1": address_line1, + "AddressLine2": address_line2, + "City": city, + "State": state, + "PostalCode": postal_code, + "AddressCountryCode": address_country_code, + "NationalId": national_id, + "DateOfBirth": date_of_birth, + "LastVerifiedDate": last_verified_date, + "VerificationSid": verification_sid, + "PartnerSubId": partner_sub_id, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + async def fetch_async( + self, + fields: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + address_line1: Union[str, object] = values.unset, + address_line2: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + national_id: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + last_verified_date: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + partner_sub_id: Union[str, object] = values.unset, + ) -> PhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + :param fields: A comma-separated list of fields to return. Possible values are validation, caller_name, sim_swap, call_forwarding, line_status, line_type_intelligence, identity_match, reassigned_number, sms_pumping_risk, phone_number_quality_score, pre_fill. + :param country_code: The [country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) used if the phone number provided is in national format. + :param first_name: User’s first name. This query parameter is only used (optionally) for identity_match package requests. + :param last_name: User’s last name. This query parameter is only used (optionally) for identity_match package requests. + :param address_line1: User’s first address line. This query parameter is only used (optionally) for identity_match package requests. + :param address_line2: User’s second address line. This query parameter is only used (optionally) for identity_match package requests. + :param city: User’s city. This query parameter is only used (optionally) for identity_match package requests. + :param state: User’s country subdivision, such as state, province, or locality. This query parameter is only used (optionally) for identity_match package requests. + :param postal_code: User’s postal zip code. This query parameter is only used (optionally) for identity_match package requests. + :param address_country_code: User’s country, up to two characters. This query parameter is only used (optionally) for identity_match package requests. + :param national_id: User’s national ID, such as SSN or Passport ID. This query parameter is only used (optionally) for identity_match package requests. + :param date_of_birth: User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests. + :param last_verified_date: The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests. + :param verification_sid: The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests. + :param partner_sub_id: The optional partnerSubId parameter to provide context for your sub-accounts, tenantIDs, sender IDs or other segmentation, enhancing the accuracy of the risk analysis. + + :returns: The fetched PhoneNumberInstance + """ + + data = values.of( + { + "Fields": fields, + "CountryCode": country_code, + "FirstName": first_name, + "LastName": last_name, + "AddressLine1": address_line1, + "AddressLine2": address_line2, + "City": city, + "State": state, + "PostalCode": postal_code, + "AddressCountryCode": address_country_code, + "NationalId": national_id, + "DateOfBirth": date_of_birth, + "LastVerifiedDate": last_verified_date, + "VerificationSid": verification_sid, + "PartnerSubId": partner_sub_id, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PhoneNumberList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PhoneNumberList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, phone_number: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param phone_number: The phone number to lookup in E.164 or national format. Default country code is +1 (North America). + """ + return PhoneNumberContext(self._version, phone_number=phone_number) + + def __call__(self, phone_number: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param phone_number: The phone number to lookup in E.164 or national format. Default country code is +1 (North America). + """ + return PhoneNumberContext(self._version, phone_number=phone_number) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/marketplace/MarketplaceBase.py b/venv/Lib/site-packages/twilio/rest/marketplace/MarketplaceBase.py new file mode 100644 index 00000000..9fbe193d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/marketplace/MarketplaceBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.marketplace.v1 import V1 + + +class MarketplaceBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Marketplace Domain + + :returns: Domain for Marketplace + """ + super().__init__(twilio, "https://marketplace.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Marketplace + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/marketplace/__init__.py b/venv/Lib/site-packages/twilio/rest/marketplace/__init__.py new file mode 100644 index 00000000..f0276a8f --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/marketplace/__init__.py @@ -0,0 +1,9 @@ +from twilio.rest.marketplace.MarketplaceBase import MarketplaceBase + + +class Marketplace(MarketplaceBase): + def available_add_ons(self): + return self.v1.available_add_ons + + def installed_add_ons(self): + return self.v1.installed_add_ons diff --git a/venv/Lib/site-packages/twilio/rest/marketplace/__pycache__/MarketplaceBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/marketplace/__pycache__/MarketplaceBase.cpython-312.pyc new file mode 100644 index 00000000..72357561 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/marketplace/__pycache__/MarketplaceBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/marketplace/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/marketplace/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..06f2dd4d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/marketplace/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/marketplace/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/marketplace/v1/__init__.py new file mode 100644 index 00000000..6a84b31c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/marketplace/v1/__init__.py @@ -0,0 +1,75 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.marketplace.v1.available_add_on import AvailableAddOnList +from twilio.rest.marketplace.v1.installed_add_on import InstalledAddOnList +from twilio.rest.marketplace.v1.module_data import ModuleDataList +from twilio.rest.marketplace.v1.module_data_management import ModuleDataManagementList +from twilio.rest.marketplace.v1.referral_conversion import ReferralConversionList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Marketplace + + :param domain: The Twilio.marketplace domain + """ + super().__init__(domain, "v1") + self._available_add_ons: Optional[AvailableAddOnList] = None + self._installed_add_ons: Optional[InstalledAddOnList] = None + self._module_data: Optional[ModuleDataList] = None + self._module_data_management: Optional[ModuleDataManagementList] = None + self._referral_conversion: Optional[ReferralConversionList] = None + + @property + def available_add_ons(self) -> AvailableAddOnList: + if self._available_add_ons is None: + self._available_add_ons = AvailableAddOnList(self) + return self._available_add_ons + + @property + def installed_add_ons(self) -> InstalledAddOnList: + if self._installed_add_ons is None: + self._installed_add_ons = InstalledAddOnList(self) + return self._installed_add_ons + + @property + def module_data(self) -> ModuleDataList: + if self._module_data is None: + self._module_data = ModuleDataList(self) + return self._module_data + + @property + def module_data_management(self) -> ModuleDataManagementList: + if self._module_data_management is None: + self._module_data_management = ModuleDataManagementList(self) + return self._module_data_management + + @property + def referral_conversion(self) -> ReferralConversionList: + if self._referral_conversion is None: + self._referral_conversion = ReferralConversionList(self) + return self._referral_conversion + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/marketplace/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/marketplace/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..a902da62 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/marketplace/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/marketplace/v1/__pycache__/module_data.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/marketplace/v1/__pycache__/module_data.cpython-312.pyc new file mode 100644 index 00000000..231658e8 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/marketplace/v1/__pycache__/module_data.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/marketplace/v1/__pycache__/module_data_management.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/marketplace/v1/__pycache__/module_data_management.cpython-312.pyc new file mode 100644 index 00000000..c396d8af Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/marketplace/v1/__pycache__/module_data_management.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/marketplace/v1/__pycache__/referral_conversion.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/marketplace/v1/__pycache__/referral_conversion.cpython-312.pyc new file mode 100644 index 00000000..d62c60e6 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/marketplace/v1/__pycache__/referral_conversion.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/marketplace/v1/available_add_on/__init__.py b/venv/Lib/site-packages/twilio/rest/marketplace/v1/available_add_on/__init__.py new file mode 100644 index 00000000..297d5dd6 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/marketplace/v1/available_add_on/__init__.py @@ -0,0 +1,438 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.marketplace.v1.available_add_on.available_add_on_extension import ( + AvailableAddOnExtensionList, +) + + +class AvailableAddOnInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the AvailableAddOn resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar description: A short description of the Add-on's functionality. + :ivar pricing_type: How customers are charged for using this Add-on. + :ivar configuration_schema: The JSON object with the configuration that must be provided when installing a given Add-on. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.pricing_type: Optional[str] = payload.get("pricing_type") + self.configuration_schema: Optional[Dict[str, object]] = payload.get( + "configuration_schema" + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[AvailableAddOnContext] = None + + @property + def _proxy(self) -> "AvailableAddOnContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AvailableAddOnContext for this AvailableAddOnInstance + """ + if self._context is None: + self._context = AvailableAddOnContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "AvailableAddOnInstance": + """ + Fetch the AvailableAddOnInstance + + + :returns: The fetched AvailableAddOnInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AvailableAddOnInstance": + """ + Asynchronous coroutine to fetch the AvailableAddOnInstance + + + :returns: The fetched AvailableAddOnInstance + """ + return await self._proxy.fetch_async() + + @property + def extensions(self) -> AvailableAddOnExtensionList: + """ + Access the extensions + """ + return self._proxy.extensions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AvailableAddOnContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the AvailableAddOnContext + + :param version: Version that contains the resource + :param sid: The SID of the AvailableAddOn resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/AvailableAddOns/{sid}".format(**self._solution) + + self._extensions: Optional[AvailableAddOnExtensionList] = None + + def fetch(self) -> AvailableAddOnInstance: + """ + Fetch the AvailableAddOnInstance + + + :returns: The fetched AvailableAddOnInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AvailableAddOnInstance: + """ + Asynchronous coroutine to fetch the AvailableAddOnInstance + + + :returns: The fetched AvailableAddOnInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + @property + def extensions(self) -> AvailableAddOnExtensionList: + """ + Access the extensions + """ + if self._extensions is None: + self._extensions = AvailableAddOnExtensionList( + self._version, + self._solution["sid"], + ) + return self._extensions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AvailableAddOnPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AvailableAddOnInstance: + """ + Build an instance of AvailableAddOnInstance + + :param payload: Payload response from the API + """ + return AvailableAddOnInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AvailableAddOnList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AvailableAddOnList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/AvailableAddOns" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AvailableAddOnInstance]: + """ + Streams AvailableAddOnInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AvailableAddOnInstance]: + """ + Asynchronously streams AvailableAddOnInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnInstance]: + """ + Lists AvailableAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnInstance]: + """ + Asynchronously lists AvailableAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AvailableAddOnPage: + """ + Retrieve a single page of AvailableAddOnInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AvailableAddOnInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailableAddOnPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AvailableAddOnPage: + """ + Asynchronously retrieve a single page of AvailableAddOnInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AvailableAddOnInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailableAddOnPage(self._version, response) + + def get_page(self, target_url: str) -> AvailableAddOnPage: + """ + Retrieve a specific page of AvailableAddOnInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailableAddOnInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AvailableAddOnPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AvailableAddOnPage: + """ + Asynchronously retrieve a specific page of AvailableAddOnInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailableAddOnInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AvailableAddOnPage(self._version, response) + + def get(self, sid: str) -> AvailableAddOnContext: + """ + Constructs a AvailableAddOnContext + + :param sid: The SID of the AvailableAddOn resource to fetch. + """ + return AvailableAddOnContext(self._version, sid=sid) + + def __call__(self, sid: str) -> AvailableAddOnContext: + """ + Constructs a AvailableAddOnContext + + :param sid: The SID of the AvailableAddOn resource to fetch. + """ + return AvailableAddOnContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/marketplace/v1/available_add_on/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/marketplace/v1/available_add_on/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..64c73789 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/marketplace/v1/available_add_on/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/marketplace/v1/available_add_on/__pycache__/available_add_on_extension.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/marketplace/v1/available_add_on/__pycache__/available_add_on_extension.cpython-312.pyc new file mode 100644 index 00000000..835d0532 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/marketplace/v1/available_add_on/__pycache__/available_add_on_extension.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/marketplace/v1/available_add_on/available_add_on_extension.py b/venv/Lib/site-packages/twilio/rest/marketplace/v1/available_add_on/available_add_on_extension.py new file mode 100644 index 00000000..a8973a08 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/marketplace/v1/available_add_on/available_add_on_extension.py @@ -0,0 +1,445 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AvailableAddOnExtensionInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the AvailableAddOnExtension resource. + :ivar available_add_on_sid: The SID of the AvailableAddOn resource to which this extension applies. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar product_name: The name of the Product this Extension is used within. + :ivar unique_name: An application-defined string that uniquely identifies the resource. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + available_add_on_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.available_add_on_sid: Optional[str] = payload.get("available_add_on_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.product_name: Optional[str] = payload.get("product_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "available_add_on_sid": available_add_on_sid, + "sid": sid or self.sid, + } + self._context: Optional[AvailableAddOnExtensionContext] = None + + @property + def _proxy(self) -> "AvailableAddOnExtensionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AvailableAddOnExtensionContext for this AvailableAddOnExtensionInstance + """ + if self._context is None: + self._context = AvailableAddOnExtensionContext( + self._version, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "AvailableAddOnExtensionInstance": + """ + Fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AvailableAddOnExtensionInstance": + """ + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class AvailableAddOnExtensionContext(InstanceContext): + + def __init__(self, version: Version, available_add_on_sid: str, sid: str): + """ + Initialize the AvailableAddOnExtensionContext + + :param version: Version that contains the resource + :param available_add_on_sid: The SID of the AvailableAddOn resource with the extension to fetch. + :param sid: The SID of the AvailableAddOn Extension resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "available_add_on_sid": available_add_on_sid, + "sid": sid, + } + self._uri = "/AvailableAddOns/{available_add_on_sid}/Extensions/{sid}".format( + **self._solution + ) + + def fetch(self) -> AvailableAddOnExtensionInstance: + """ + Fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AvailableAddOnExtensionInstance: + """ + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class AvailableAddOnExtensionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AvailableAddOnExtensionInstance: + """ + Build an instance of AvailableAddOnExtensionInstance + + :param payload: Payload response from the API + """ + return AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AvailableAddOnExtensionList(ListResource): + + def __init__(self, version: Version, available_add_on_sid: str): + """ + Initialize the AvailableAddOnExtensionList + + :param version: Version that contains the resource + :param available_add_on_sid: The SID of the AvailableAddOn resource with the extensions to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "available_add_on_sid": available_add_on_sid, + } + self._uri = "/AvailableAddOns/{available_add_on_sid}/Extensions".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AvailableAddOnExtensionInstance]: + """ + Streams AvailableAddOnExtensionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AvailableAddOnExtensionInstance]: + """ + Asynchronously streams AvailableAddOnExtensionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnExtensionInstance]: + """ + Lists AvailableAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnExtensionInstance]: + """ + Asynchronously lists AvailableAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AvailableAddOnExtensionPage: + """ + Retrieve a single page of AvailableAddOnExtensionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AvailableAddOnExtensionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailableAddOnExtensionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AvailableAddOnExtensionPage: + """ + Asynchronously retrieve a single page of AvailableAddOnExtensionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AvailableAddOnExtensionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailableAddOnExtensionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AvailableAddOnExtensionPage: + """ + Retrieve a specific page of AvailableAddOnExtensionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailableAddOnExtensionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AvailableAddOnExtensionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AvailableAddOnExtensionPage: + """ + Asynchronously retrieve a specific page of AvailableAddOnExtensionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailableAddOnExtensionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AvailableAddOnExtensionPage(self._version, response, self._solution) + + def get(self, sid: str) -> AvailableAddOnExtensionContext: + """ + Constructs a AvailableAddOnExtensionContext + + :param sid: The SID of the AvailableAddOn Extension resource to fetch. + """ + return AvailableAddOnExtensionContext( + self._version, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> AvailableAddOnExtensionContext: + """ + Constructs a AvailableAddOnExtensionContext + + :param sid: The SID of the AvailableAddOn Extension resource to fetch. + """ + return AvailableAddOnExtensionContext( + self._version, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/marketplace/v1/installed_add_on/__init__.py b/venv/Lib/site-packages/twilio/rest/marketplace/v1/installed_add_on/__init__.py new file mode 100644 index 00000000..8fedfb9b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/marketplace/v1/installed_add_on/__init__.py @@ -0,0 +1,694 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.marketplace.v1.installed_add_on.installed_add_on_extension import ( + InstalledAddOnExtensionList, +) +from twilio.rest.marketplace.v1.installed_add_on.installed_add_on_usage import ( + InstalledAddOnUsageList, +) + + +class InstalledAddOnInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the InstalledAddOn resource. This Sid can also be found in the Console on that specific Add-ons page as the 'Available Add-on Sid'. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the InstalledAddOn resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar description: A short description of the Add-on's functionality. + :ivar configuration: The JSON object that represents the current configuration of installed Add-on. + :ivar unique_name: An application-defined string that uniquely identifies the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + self.unique_name: Optional[str] = payload.get("unique_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[InstalledAddOnContext] = None + + @property + def _proxy(self) -> "InstalledAddOnContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InstalledAddOnContext for this InstalledAddOnInstance + """ + if self._context is None: + self._context = InstalledAddOnContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the InstalledAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InstalledAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "InstalledAddOnInstance": + """ + Fetch the InstalledAddOnInstance + + + :returns: The fetched InstalledAddOnInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InstalledAddOnInstance": + """ + Asynchronous coroutine to fetch the InstalledAddOnInstance + + + :returns: The fetched InstalledAddOnInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> "InstalledAddOnInstance": + """ + Update the InstalledAddOnInstance + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The updated InstalledAddOnInstance + """ + return self._proxy.update( + configuration=configuration, + unique_name=unique_name, + ) + + async def update_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> "InstalledAddOnInstance": + """ + Asynchronous coroutine to update the InstalledAddOnInstance + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The updated InstalledAddOnInstance + """ + return await self._proxy.update_async( + configuration=configuration, + unique_name=unique_name, + ) + + @property + def extensions(self) -> InstalledAddOnExtensionList: + """ + Access the extensions + """ + return self._proxy.extensions + + @property + def usage(self) -> InstalledAddOnUsageList: + """ + Access the usage + """ + return self._proxy.usage + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InstalledAddOnContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the InstalledAddOnContext + + :param version: Version that contains the resource + :param sid: The SID of the InstalledAddOn resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/InstalledAddOns/{sid}".format(**self._solution) + + self._extensions: Optional[InstalledAddOnExtensionList] = None + self._usage: Optional[InstalledAddOnUsageList] = None + + def delete(self) -> bool: + """ + Deletes the InstalledAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InstalledAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> InstalledAddOnInstance: + """ + Fetch the InstalledAddOnInstance + + + :returns: The fetched InstalledAddOnInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> InstalledAddOnInstance: + """ + Asynchronous coroutine to fetch the InstalledAddOnInstance + + + :returns: The fetched InstalledAddOnInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> InstalledAddOnInstance: + """ + Update the InstalledAddOnInstance + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The updated InstalledAddOnInstance + """ + + data = values.of( + { + "Configuration": serialize.object(configuration), + "UniqueName": unique_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> InstalledAddOnInstance: + """ + Asynchronous coroutine to update the InstalledAddOnInstance + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The updated InstalledAddOnInstance + """ + + data = values.of( + { + "Configuration": serialize.object(configuration), + "UniqueName": unique_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def extensions(self) -> InstalledAddOnExtensionList: + """ + Access the extensions + """ + if self._extensions is None: + self._extensions = InstalledAddOnExtensionList( + self._version, + self._solution["sid"], + ) + return self._extensions + + @property + def usage(self) -> InstalledAddOnUsageList: + """ + Access the usage + """ + if self._usage is None: + self._usage = InstalledAddOnUsageList( + self._version, + self._solution["sid"], + ) + return self._usage + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InstalledAddOnPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InstalledAddOnInstance: + """ + Build an instance of InstalledAddOnInstance + + :param payload: Payload response from the API + """ + return InstalledAddOnInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class InstalledAddOnList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InstalledAddOnList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/InstalledAddOns" + + def create( + self, + available_add_on_sid: str, + accept_terms_of_service: bool, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> InstalledAddOnInstance: + """ + Create the InstalledAddOnInstance + + :param available_add_on_sid: The SID of the AvaliableAddOn to install. + :param accept_terms_of_service: Whether the Terms of Service were accepted. + :param configuration: The JSON object that represents the configuration of the new Add-on being installed. + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The created InstalledAddOnInstance + """ + + data = values.of( + { + "AvailableAddOnSid": available_add_on_sid, + "AcceptTermsOfService": serialize.boolean_to_string( + accept_terms_of_service + ), + "Configuration": serialize.object(configuration), + "UniqueName": unique_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnInstance(self._version, payload) + + async def create_async( + self, + available_add_on_sid: str, + accept_terms_of_service: bool, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> InstalledAddOnInstance: + """ + Asynchronously create the InstalledAddOnInstance + + :param available_add_on_sid: The SID of the AvaliableAddOn to install. + :param accept_terms_of_service: Whether the Terms of Service were accepted. + :param configuration: The JSON object that represents the configuration of the new Add-on being installed. + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The created InstalledAddOnInstance + """ + + data = values.of( + { + "AvailableAddOnSid": available_add_on_sid, + "AcceptTermsOfService": serialize.boolean_to_string( + accept_terms_of_service + ), + "Configuration": serialize.object(configuration), + "UniqueName": unique_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InstalledAddOnInstance]: + """ + Streams InstalledAddOnInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InstalledAddOnInstance]: + """ + Asynchronously streams InstalledAddOnInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InstalledAddOnInstance]: + """ + Lists InstalledAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InstalledAddOnInstance]: + """ + Asynchronously lists InstalledAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InstalledAddOnPage: + """ + Retrieve a single page of InstalledAddOnInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InstalledAddOnInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InstalledAddOnPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InstalledAddOnPage: + """ + Asynchronously retrieve a single page of InstalledAddOnInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InstalledAddOnInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InstalledAddOnPage(self._version, response) + + def get_page(self, target_url: str) -> InstalledAddOnPage: + """ + Retrieve a specific page of InstalledAddOnInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InstalledAddOnInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InstalledAddOnPage(self._version, response) + + async def get_page_async(self, target_url: str) -> InstalledAddOnPage: + """ + Asynchronously retrieve a specific page of InstalledAddOnInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InstalledAddOnInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InstalledAddOnPage(self._version, response) + + def get(self, sid: str) -> InstalledAddOnContext: + """ + Constructs a InstalledAddOnContext + + :param sid: The SID of the InstalledAddOn resource to update. + """ + return InstalledAddOnContext(self._version, sid=sid) + + def __call__(self, sid: str) -> InstalledAddOnContext: + """ + Constructs a InstalledAddOnContext + + :param sid: The SID of the InstalledAddOn resource to update. + """ + return InstalledAddOnContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/marketplace/v1/installed_add_on/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/marketplace/v1/installed_add_on/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..89734b7b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/marketplace/v1/installed_add_on/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/marketplace/v1/installed_add_on/__pycache__/installed_add_on_extension.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/marketplace/v1/installed_add_on/__pycache__/installed_add_on_extension.cpython-312.pyc new file mode 100644 index 00000000..ba0cdded Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/marketplace/v1/installed_add_on/__pycache__/installed_add_on_extension.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/marketplace/v1/installed_add_on/__pycache__/installed_add_on_usage.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/marketplace/v1/installed_add_on/__pycache__/installed_add_on_usage.cpython-312.pyc new file mode 100644 index 00000000..e4a2f119 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/marketplace/v1/installed_add_on/__pycache__/installed_add_on_usage.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_extension.py b/venv/Lib/site-packages/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_extension.py new file mode 100644 index 00000000..88f160ed --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_extension.py @@ -0,0 +1,533 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InstalledAddOnExtensionInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the InstalledAddOn Extension resource. + :ivar installed_add_on_sid: The SID of the InstalledAddOn resource to which this extension applies. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar product_name: The name of the Product this Extension is used within. + :ivar unique_name: An application-defined string that uniquely identifies the resource. + :ivar enabled: Whether the Extension will be invoked. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + installed_add_on_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.installed_add_on_sid: Optional[str] = payload.get("installed_add_on_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.product_name: Optional[str] = payload.get("product_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.enabled: Optional[bool] = payload.get("enabled") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "installed_add_on_sid": installed_add_on_sid, + "sid": sid or self.sid, + } + self._context: Optional[InstalledAddOnExtensionContext] = None + + @property + def _proxy(self) -> "InstalledAddOnExtensionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InstalledAddOnExtensionContext for this InstalledAddOnExtensionInstance + """ + if self._context is None: + self._context = InstalledAddOnExtensionContext( + self._version, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "InstalledAddOnExtensionInstance": + """ + Fetch the InstalledAddOnExtensionInstance + + + :returns: The fetched InstalledAddOnExtensionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InstalledAddOnExtensionInstance": + """ + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance + + + :returns: The fetched InstalledAddOnExtensionInstance + """ + return await self._proxy.fetch_async() + + def update(self, enabled: bool) -> "InstalledAddOnExtensionInstance": + """ + Update the InstalledAddOnExtensionInstance + + :param enabled: Whether the Extension should be invoked. + + :returns: The updated InstalledAddOnExtensionInstance + """ + return self._proxy.update( + enabled=enabled, + ) + + async def update_async(self, enabled: bool) -> "InstalledAddOnExtensionInstance": + """ + Asynchronous coroutine to update the InstalledAddOnExtensionInstance + + :param enabled: Whether the Extension should be invoked. + + :returns: The updated InstalledAddOnExtensionInstance + """ + return await self._proxy.update_async( + enabled=enabled, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class InstalledAddOnExtensionContext(InstanceContext): + + def __init__(self, version: Version, installed_add_on_sid: str, sid: str): + """ + Initialize the InstalledAddOnExtensionContext + + :param version: Version that contains the resource + :param installed_add_on_sid: The SID of the InstalledAddOn resource with the extension to update. + :param sid: The SID of the InstalledAddOn Extension resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "installed_add_on_sid": installed_add_on_sid, + "sid": sid, + } + self._uri = "/InstalledAddOns/{installed_add_on_sid}/Extensions/{sid}".format( + **self._solution + ) + + def fetch(self) -> InstalledAddOnExtensionInstance: + """ + Fetch the InstalledAddOnExtensionInstance + + + :returns: The fetched InstalledAddOnExtensionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> InstalledAddOnExtensionInstance: + """ + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance + + + :returns: The fetched InstalledAddOnExtensionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + + def update(self, enabled: bool) -> InstalledAddOnExtensionInstance: + """ + Update the InstalledAddOnExtensionInstance + + :param enabled: Whether the Extension should be invoked. + + :returns: The updated InstalledAddOnExtensionInstance + """ + + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, enabled: bool) -> InstalledAddOnExtensionInstance: + """ + Asynchronous coroutine to update the InstalledAddOnExtensionInstance + + :param enabled: Whether the Extension should be invoked. + + :returns: The updated InstalledAddOnExtensionInstance + """ + + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class InstalledAddOnExtensionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InstalledAddOnExtensionInstance: + """ + Build an instance of InstalledAddOnExtensionInstance + + :param payload: Payload response from the API + """ + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class InstalledAddOnExtensionList(ListResource): + + def __init__(self, version: Version, installed_add_on_sid: str): + """ + Initialize the InstalledAddOnExtensionList + + :param version: Version that contains the resource + :param installed_add_on_sid: The SID of the InstalledAddOn resource with the extensions to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "installed_add_on_sid": installed_add_on_sid, + } + self._uri = "/InstalledAddOns/{installed_add_on_sid}/Extensions".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InstalledAddOnExtensionInstance]: + """ + Streams InstalledAddOnExtensionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InstalledAddOnExtensionInstance]: + """ + Asynchronously streams InstalledAddOnExtensionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InstalledAddOnExtensionInstance]: + """ + Lists InstalledAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InstalledAddOnExtensionInstance]: + """ + Asynchronously lists InstalledAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InstalledAddOnExtensionPage: + """ + Retrieve a single page of InstalledAddOnExtensionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InstalledAddOnExtensionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InstalledAddOnExtensionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InstalledAddOnExtensionPage: + """ + Asynchronously retrieve a single page of InstalledAddOnExtensionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InstalledAddOnExtensionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InstalledAddOnExtensionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> InstalledAddOnExtensionPage: + """ + Retrieve a specific page of InstalledAddOnExtensionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InstalledAddOnExtensionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InstalledAddOnExtensionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> InstalledAddOnExtensionPage: + """ + Asynchronously retrieve a specific page of InstalledAddOnExtensionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InstalledAddOnExtensionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InstalledAddOnExtensionPage(self._version, response, self._solution) + + def get(self, sid: str) -> InstalledAddOnExtensionContext: + """ + Constructs a InstalledAddOnExtensionContext + + :param sid: The SID of the InstalledAddOn Extension resource to update. + """ + return InstalledAddOnExtensionContext( + self._version, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InstalledAddOnExtensionContext: + """ + Constructs a InstalledAddOnExtensionContext + + :param sid: The SID of the InstalledAddOn Extension resource to update. + """ + return InstalledAddOnExtensionContext( + self._version, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_usage.py b/venv/Lib/site-packages/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_usage.py new file mode 100644 index 00000000..1a547564 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_usage.py @@ -0,0 +1,234 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class InstalledAddOnUsageInstance(InstanceResource): + + class MarketplaceV1InstalledAddOnInstalledAddOnUsage(object): + """ + :ivar total_submitted: Total amount in local currency that was billed in this request. Aggregates all billable_items that were successfully submitted. + :ivar billable_items: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.total_submitted: Optional[float] = deserialize.decimal( + payload.get("total_submitted") + ) + self.billable_items: Optional[ + List[ + InstalledAddOnUsageList.MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems + ] + ] = payload.get("billable_items") + + def to_dict(self): + return { + "total_submitted": self.total_submitted, + "billable_items": ( + [billable_items.to_dict() for billable_items in self.billable_items] + if self.billable_items is not None + else None + ), + } + + class MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems(object): + """ + :ivar quantity: Total amount in local currency that was billed for this Billing Item. Can be any floating number greater than 0. + :ivar sid: BillingSid to use for billing. + :ivar submitted: Whether the billing event was successfully generated for this Billable Item. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.quantity: Optional[float] = payload.get("quantity") + self.sid: Optional[str] = payload.get("sid") + self.submitted: Optional[bool] = payload.get("submitted") + + def to_dict(self): + return { + "quantity": self.quantity, + "sid": self.sid, + "submitted": self.submitted, + } + + """ + :ivar total_submitted: Total amount in local currency that was billed in this request. Aggregates all billable_items that were successfully submitted. + :ivar billable_items: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], installed_add_on_sid: str + ): + super().__init__(version) + + self.total_submitted: Optional[float] = deserialize.decimal( + payload.get("total_submitted") + ) + self.billable_items: Optional[List[InstalledAddOnUsageList.str]] = payload.get( + "billable_items" + ) + + self._solution = { + "installed_add_on_sid": installed_add_on_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InstalledAddOnUsageList(ListResource): + + class MarketplaceV1InstalledAddOnInstalledAddOnUsage(object): + """ + :ivar total_submitted: Total amount in local currency that was billed in this request. Aggregates all billable_items that were successfully submitted. + :ivar billable_items: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.total_submitted: Optional[float] = deserialize.decimal( + payload.get("total_submitted") + ) + self.billable_items: Optional[ + List[ + InstalledAddOnUsageList.MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems + ] + ] = payload.get("billable_items") + + def to_dict(self): + return { + "total_submitted": self.total_submitted, + "billable_items": ( + [billable_items.to_dict() for billable_items in self.billable_items] + if self.billable_items is not None + else None + ), + } + + class MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems(object): + """ + :ivar quantity: Total amount in local currency that was billed for this Billing Item. Can be any floating number greater than 0. + :ivar sid: BillingSid to use for billing. + :ivar submitted: Whether the billing event was successfully generated for this Billable Item. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.quantity: Optional[float] = payload.get("quantity") + self.sid: Optional[str] = payload.get("sid") + self.submitted: Optional[bool] = payload.get("submitted") + + def to_dict(self): + return { + "quantity": self.quantity, + "sid": self.sid, + "submitted": self.submitted, + } + + def __init__(self, version: Version, installed_add_on_sid: str): + """ + Initialize the InstalledAddOnUsageList + + :param version: Version that contains the resource + :param installed_add_on_sid: Customer Installation SID to report usage on. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "installed_add_on_sid": installed_add_on_sid, + } + self._uri = "/InstalledAddOns/{installed_add_on_sid}/Usage".format( + **self._solution + ) + + def create( + self, + marketplace_v1_installed_add_on_installed_add_on_usage: MarketplaceV1InstalledAddOnInstalledAddOnUsage, + ) -> InstalledAddOnUsageInstance: + """ + Create the InstalledAddOnUsageInstance + + :param marketplace_v1_installed_add_on_installed_add_on_usage: + + :returns: The created InstalledAddOnUsageInstance + """ + data = marketplace_v1_installed_add_on_installed_add_on_usage.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnUsageInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + ) + + async def create_async( + self, + marketplace_v1_installed_add_on_installed_add_on_usage: MarketplaceV1InstalledAddOnInstalledAddOnUsage, + ) -> InstalledAddOnUsageInstance: + """ + Asynchronously create the InstalledAddOnUsageInstance + + :param marketplace_v1_installed_add_on_installed_add_on_usage: + + :returns: The created InstalledAddOnUsageInstance + """ + data = marketplace_v1_installed_add_on_installed_add_on_usage.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnUsageInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/marketplace/v1/module_data.py b/venv/Lib/site-packages/twilio/rest/marketplace/v1/module_data.py new file mode 100644 index 00000000..1308c17a --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/marketplace/v1/module_data.py @@ -0,0 +1,176 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ModuleDataInstance(InstanceResource): + """ + :ivar url: URL to query the subresource. + :ivar sid: ModuleSid that identifies this Listing. + :ivar description: A JSON object describing the module and is displayed under the Description tab of the Module detail page. You can define the main body of the description, highlight key features or aspects of the module and if applicable, provide code samples for developers + :ivar support: A JSON object containing information on how customers can obtain support for the module. Use this parameter to provide details such as contact information and support description. + :ivar policies: A JSON object describing the module's privacy and legal policies and is displayed under the Policies tab of the Module detail page. The maximum file size for Policies is 5MB + :ivar module_info: A JSON object containing essential attributes that define a module. This information is presented on the Module detail page in the Twilio Marketplace Catalog. You can pass the following attributes in the JSON object + :ivar documentation: A JSON object for providing comprehensive information, instructions, and resources related to the module + :ivar configuration: A JSON object for providing listing specific configuration. Contains button setup, notification url, among others. + :ivar pricing: A JSON object for providing Listing specific pricing information. + :ivar listings: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.url: Optional[str] = payload.get("url") + self.sid: Optional[str] = payload.get("sid") + self.description: Optional[Dict[str, object]] = payload.get("description") + self.support: Optional[Dict[str, object]] = payload.get("support") + self.policies: Optional[Dict[str, object]] = payload.get("policies") + self.module_info: Optional[Dict[str, object]] = payload.get("module_info") + self.documentation: Optional[Dict[str, object]] = payload.get("documentation") + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + self.pricing: Optional[Dict[str, object]] = payload.get("pricing") + self.listings: Optional[List[Dict[str, object]]] = payload.get("listings") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class ModuleDataList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ModuleDataList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Listings" + + def create( + self, + module_info: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + ) -> ModuleDataInstance: + """ + Create the ModuleDataInstance + + :param module_info: A JSON object containing essential attributes that define a Listing. + :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. + + :returns: The created ModuleDataInstance + """ + + data = values.of( + { + "ModuleInfo": module_info, + "Configuration": configuration, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ModuleDataInstance(self._version, payload) + + async def create_async( + self, + module_info: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + ) -> ModuleDataInstance: + """ + Asynchronously create the ModuleDataInstance + + :param module_info: A JSON object containing essential attributes that define a Listing. + :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. + + :returns: The created ModuleDataInstance + """ + + data = values.of( + { + "ModuleInfo": module_info, + "Configuration": configuration, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ModuleDataInstance(self._version, payload) + + def fetch(self) -> ModuleDataInstance: + """ + Asynchronously fetch the ModuleDataInstance + + + :returns: The fetched ModuleDataInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ModuleDataInstance(self._version, payload) + + async def fetch_async(self) -> ModuleDataInstance: + """ + Asynchronously fetch the ModuleDataInstance + + + :returns: The fetched ModuleDataInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ModuleDataInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/marketplace/v1/module_data_management.py b/venv/Lib/site-packages/twilio/rest/marketplace/v1/module_data_management.py new file mode 100644 index 00000000..6ed82d84 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/marketplace/v1/module_data_management.py @@ -0,0 +1,367 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ModuleDataManagementInstance(InstanceResource): + """ + :ivar url: URL to query the subresource. + :ivar sid: ModuleSid that identifies this Listing. + :ivar description: A JSON object describing the module and is displayed under the Description tab of the Module detail page. You can define the main body of the description, highlight key features or aspects of the module and if applicable, provide code samples for developers + :ivar support: A JSON object containing information on how customers can obtain support for the module. Use this parameter to provide details such as contact information and support description. + :ivar policies: A JSON object describing the module's privacy and legal policies and is displayed under the Policies tab of the Module detail page. The maximum file size for Policies is 5MB + :ivar module_info: A JSON object containing essential attributes that define a module. This information is presented on the Module detail page in the Twilio Marketplace Catalog. You can pass the following attributes in the JSON object + :ivar documentation: A JSON object for providing comprehensive information, instructions, and resources related to the module + :ivar configuration: A JSON object for providing listing specific configuration. Contains button setup, notification url, among others. + :ivar pricing: A JSON object for providing Listing specific pricing information. + :ivar listings: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.url: Optional[str] = payload.get("url") + self.sid: Optional[str] = payload.get("sid") + self.description: Optional[Dict[str, object]] = payload.get("description") + self.support: Optional[Dict[str, object]] = payload.get("support") + self.policies: Optional[Dict[str, object]] = payload.get("policies") + self.module_info: Optional[Dict[str, object]] = payload.get("module_info") + self.documentation: Optional[Dict[str, object]] = payload.get("documentation") + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + self.pricing: Optional[Dict[str, object]] = payload.get("pricing") + self.listings: Optional[List[Dict[str, object]]] = payload.get("listings") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ModuleDataManagementContext] = None + + @property + def _proxy(self) -> "ModuleDataManagementContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ModuleDataManagementContext for this ModuleDataManagementInstance + """ + if self._context is None: + self._context = ModuleDataManagementContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "ModuleDataManagementInstance": + """ + Fetch the ModuleDataManagementInstance + + + :returns: The fetched ModuleDataManagementInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ModuleDataManagementInstance": + """ + Asynchronous coroutine to fetch the ModuleDataManagementInstance + + + :returns: The fetched ModuleDataManagementInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + module_info: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + documentation: Union[str, object] = values.unset, + policies: Union[str, object] = values.unset, + support: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + pricing: Union[str, object] = values.unset, + ) -> "ModuleDataManagementInstance": + """ + Update the ModuleDataManagementInstance + + :param module_info: A JSON object containing essential attributes that define a Listing. + :param description: A JSON object describing the Listing. You can define the main body of the description, highlight key features or aspects of the Listing, and provide code samples for developers if applicable. + :param documentation: A JSON object for providing comprehensive information, instructions, and resources related to the Listing. + :param policies: A JSON object describing the Listing's privacy and legal policies. The maximum file size for Policies is 5MB. + :param support: A JSON object containing information on how Marketplace users can obtain support for the Listing. Use this parameter to provide details such as contact information and support description. + :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. + :param pricing: A JSON object for providing Listing's purchase options. + + :returns: The updated ModuleDataManagementInstance + """ + return self._proxy.update( + module_info=module_info, + description=description, + documentation=documentation, + policies=policies, + support=support, + configuration=configuration, + pricing=pricing, + ) + + async def update_async( + self, + module_info: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + documentation: Union[str, object] = values.unset, + policies: Union[str, object] = values.unset, + support: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + pricing: Union[str, object] = values.unset, + ) -> "ModuleDataManagementInstance": + """ + Asynchronous coroutine to update the ModuleDataManagementInstance + + :param module_info: A JSON object containing essential attributes that define a Listing. + :param description: A JSON object describing the Listing. You can define the main body of the description, highlight key features or aspects of the Listing, and provide code samples for developers if applicable. + :param documentation: A JSON object for providing comprehensive information, instructions, and resources related to the Listing. + :param policies: A JSON object describing the Listing's privacy and legal policies. The maximum file size for Policies is 5MB. + :param support: A JSON object containing information on how Marketplace users can obtain support for the Listing. Use this parameter to provide details such as contact information and support description. + :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. + :param pricing: A JSON object for providing Listing's purchase options. + + :returns: The updated ModuleDataManagementInstance + """ + return await self._proxy.update_async( + module_info=module_info, + description=description, + documentation=documentation, + policies=policies, + support=support, + configuration=configuration, + pricing=pricing, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ModuleDataManagementContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ModuleDataManagementContext + + :param version: Version that contains the resource + :param sid: SID that uniquely identifies the Listing. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Listing/{sid}".format(**self._solution) + + def fetch(self) -> ModuleDataManagementInstance: + """ + Fetch the ModuleDataManagementInstance + + + :returns: The fetched ModuleDataManagementInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ModuleDataManagementInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ModuleDataManagementInstance: + """ + Asynchronous coroutine to fetch the ModuleDataManagementInstance + + + :returns: The fetched ModuleDataManagementInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ModuleDataManagementInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + module_info: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + documentation: Union[str, object] = values.unset, + policies: Union[str, object] = values.unset, + support: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + pricing: Union[str, object] = values.unset, + ) -> ModuleDataManagementInstance: + """ + Update the ModuleDataManagementInstance + + :param module_info: A JSON object containing essential attributes that define a Listing. + :param description: A JSON object describing the Listing. You can define the main body of the description, highlight key features or aspects of the Listing, and provide code samples for developers if applicable. + :param documentation: A JSON object for providing comprehensive information, instructions, and resources related to the Listing. + :param policies: A JSON object describing the Listing's privacy and legal policies. The maximum file size for Policies is 5MB. + :param support: A JSON object containing information on how Marketplace users can obtain support for the Listing. Use this parameter to provide details such as contact information and support description. + :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. + :param pricing: A JSON object for providing Listing's purchase options. + + :returns: The updated ModuleDataManagementInstance + """ + + data = values.of( + { + "ModuleInfo": module_info, + "Description": description, + "Documentation": documentation, + "Policies": policies, + "Support": support, + "Configuration": configuration, + "Pricing": pricing, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ModuleDataManagementInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, + module_info: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + documentation: Union[str, object] = values.unset, + policies: Union[str, object] = values.unset, + support: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + pricing: Union[str, object] = values.unset, + ) -> ModuleDataManagementInstance: + """ + Asynchronous coroutine to update the ModuleDataManagementInstance + + :param module_info: A JSON object containing essential attributes that define a Listing. + :param description: A JSON object describing the Listing. You can define the main body of the description, highlight key features or aspects of the Listing, and provide code samples for developers if applicable. + :param documentation: A JSON object for providing comprehensive information, instructions, and resources related to the Listing. + :param policies: A JSON object describing the Listing's privacy and legal policies. The maximum file size for Policies is 5MB. + :param support: A JSON object containing information on how Marketplace users can obtain support for the Listing. Use this parameter to provide details such as contact information and support description. + :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. + :param pricing: A JSON object for providing Listing's purchase options. + + :returns: The updated ModuleDataManagementInstance + """ + + data = values.of( + { + "ModuleInfo": module_info, + "Description": description, + "Documentation": documentation, + "Policies": policies, + "Support": support, + "Configuration": configuration, + "Pricing": pricing, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ModuleDataManagementInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ModuleDataManagementList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ModuleDataManagementList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, sid: str) -> ModuleDataManagementContext: + """ + Constructs a ModuleDataManagementContext + + :param sid: SID that uniquely identifies the Listing. + """ + return ModuleDataManagementContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ModuleDataManagementContext: + """ + Constructs a ModuleDataManagementContext + + :param sid: SID that uniquely identifies the Listing. + """ + return ModuleDataManagementContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/marketplace/v1/referral_conversion.py b/venv/Lib/site-packages/twilio/rest/marketplace/v1/referral_conversion.py new file mode 100644 index 00000000..9d9f3c2f --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/marketplace/v1/referral_conversion.py @@ -0,0 +1,143 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ReferralConversionInstance(InstanceResource): + + class CreateReferralConversionRequest(object): + """ + :ivar referral_account_sid: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.referral_account_sid: Optional[str] = payload.get( + "referral_account_sid" + ) + + def to_dict(self): + return { + "referral_account_sid": self.referral_account_sid, + } + + """ + :ivar converted_account_sid: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.converted_account_sid: Optional[str] = payload.get("converted_account_sid") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class ReferralConversionList(ListResource): + + class CreateReferralConversionRequest(object): + """ + :ivar referral_account_sid: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.referral_account_sid: Optional[str] = payload.get( + "referral_account_sid" + ) + + def to_dict(self): + return { + "referral_account_sid": self.referral_account_sid, + } + + def __init__(self, version: Version): + """ + Initialize the ReferralConversionList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ReferralConversion" + + def create( + self, create_referral_conversion_request: CreateReferralConversionRequest + ) -> ReferralConversionInstance: + """ + Create the ReferralConversionInstance + + :param create_referral_conversion_request: + + :returns: The created ReferralConversionInstance + """ + data = create_referral_conversion_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ReferralConversionInstance(self._version, payload) + + async def create_async( + self, create_referral_conversion_request: CreateReferralConversionRequest + ) -> ReferralConversionInstance: + """ + Asynchronously create the ReferralConversionInstance + + :param create_referral_conversion_request: + + :returns: The created ReferralConversionInstance + """ + data = create_referral_conversion_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ReferralConversionInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/messaging/MessagingBase.py b/venv/Lib/site-packages/twilio/rest/messaging/MessagingBase.py new file mode 100644 index 00000000..e45ed56f --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/MessagingBase.py @@ -0,0 +1,55 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.messaging.v1 import V1 +from twilio.rest.messaging.v2 import V2 + + +class MessagingBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Messaging Domain + + :returns: Domain for Messaging + """ + super().__init__(twilio, "https://messaging.twilio.com") + self._v1: Optional[V1] = None + self._v2: Optional[V2] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Messaging + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Messaging + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/messaging/__init__.py b/venv/Lib/site-packages/twilio/rest/messaging/__init__.py new file mode 100644 index 00000000..4e628325 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/__init__.py @@ -0,0 +1,99 @@ +from warnings import warn + +from twilio.rest.messaging.MessagingBase import MessagingBase +from twilio.rest.messaging.v1.brand_registration import BrandRegistrationList +from twilio.rest.messaging.v1.deactivations import DeactivationsList +from twilio.rest.messaging.v1.domain_certs import DomainCertsList +from twilio.rest.messaging.v1.domain_config import DomainConfigList +from twilio.rest.messaging.v1.domain_config_messaging_service import ( + DomainConfigMessagingServiceList, +) +from twilio.rest.messaging.v1.external_campaign import ExternalCampaignList +from twilio.rest.messaging.v1.linkshortening_messaging_service import ( + LinkshorteningMessagingServiceList, +) +from twilio.rest.messaging.v1.service import ServiceList +from twilio.rest.messaging.v1.usecase import UsecaseList + + +class Messaging(MessagingBase): + @property + def brand_registrations(self) -> BrandRegistrationList: + warn( + "brand_registrations is deprecated. Use v1.brand_registrations instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.brand_registrations + + @property + def deactivations(self) -> DeactivationsList: + warn( + "deactivations is deprecated. Use v1.deactivations instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.deactivations + + @property + def domain_certs(self) -> DomainCertsList: + warn( + "domain_certs is deprecated. Use v1.domain_certs instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.domain_certs + + @property + def domain_config(self) -> DomainConfigList: + warn( + "domain_config is deprecated. Use v1.domain_config instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.domain_config + + @property + def domain_config_messaging_service(self) -> DomainConfigMessagingServiceList: + warn( + "domain_config_messaging_service is deprecated. Use v1.domain_config_messaging_service instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.domain_config_messaging_service + + @property + def external_campaign(self) -> ExternalCampaignList: + warn( + "external_campaign is deprecated. Use v1.external_campaign instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.external_campaign + + @property + def linkshortening_messaging_service(self) -> LinkshorteningMessagingServiceList: + warn( + "linkshortening_messaging_service is deprecated. Use v1.linkshortening_messaging_service instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.linkshortening_messaging_service + + @property + def services(self) -> ServiceList: + warn( + "services is deprecated. Use v1.services instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.services + + @property + def usecases(self) -> UsecaseList: + warn( + "usecases is deprecated. Use v1.usecases instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.usecases diff --git a/venv/Lib/site-packages/twilio/rest/messaging/__pycache__/MessagingBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/__pycache__/MessagingBase.cpython-312.pyc new file mode 100644 index 00000000..dab8beeb Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/__pycache__/MessagingBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..a52fecf1 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/messaging/v1/__init__.py new file mode 100644 index 00000000..6bd630fb --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/v1/__init__.py @@ -0,0 +1,151 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.messaging.v1.brand_registration import BrandRegistrationList +from twilio.rest.messaging.v1.deactivations import DeactivationsList +from twilio.rest.messaging.v1.domain_certs import DomainCertsList +from twilio.rest.messaging.v1.domain_config import DomainConfigList +from twilio.rest.messaging.v1.domain_config_messaging_service import ( + DomainConfigMessagingServiceList, +) +from twilio.rest.messaging.v1.external_campaign import ExternalCampaignList +from twilio.rest.messaging.v1.linkshortening_messaging_service import ( + LinkshorteningMessagingServiceList, +) +from twilio.rest.messaging.v1.linkshortening_messaging_service_domain_association import ( + LinkshorteningMessagingServiceDomainAssociationList, +) +from twilio.rest.messaging.v1.request_managed_cert import RequestManagedCertList +from twilio.rest.messaging.v1.service import ServiceList +from twilio.rest.messaging.v1.tollfree_verification import TollfreeVerificationList +from twilio.rest.messaging.v1.usecase import UsecaseList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Messaging + + :param domain: The Twilio.messaging domain + """ + super().__init__(domain, "v1") + self._brand_registrations: Optional[BrandRegistrationList] = None + self._deactivations: Optional[DeactivationsList] = None + self._domain_certs: Optional[DomainCertsList] = None + self._domain_config: Optional[DomainConfigList] = None + self._domain_config_messaging_service: Optional[ + DomainConfigMessagingServiceList + ] = None + self._external_campaign: Optional[ExternalCampaignList] = None + self._linkshortening_messaging_service: Optional[ + LinkshorteningMessagingServiceList + ] = None + self._linkshortening_messaging_service_domain_association: Optional[ + LinkshorteningMessagingServiceDomainAssociationList + ] = None + self._request_managed_cert: Optional[RequestManagedCertList] = None + self._services: Optional[ServiceList] = None + self._tollfree_verifications: Optional[TollfreeVerificationList] = None + self._usecases: Optional[UsecaseList] = None + + @property + def brand_registrations(self) -> BrandRegistrationList: + if self._brand_registrations is None: + self._brand_registrations = BrandRegistrationList(self) + return self._brand_registrations + + @property + def deactivations(self) -> DeactivationsList: + if self._deactivations is None: + self._deactivations = DeactivationsList(self) + return self._deactivations + + @property + def domain_certs(self) -> DomainCertsList: + if self._domain_certs is None: + self._domain_certs = DomainCertsList(self) + return self._domain_certs + + @property + def domain_config(self) -> DomainConfigList: + if self._domain_config is None: + self._domain_config = DomainConfigList(self) + return self._domain_config + + @property + def domain_config_messaging_service(self) -> DomainConfigMessagingServiceList: + if self._domain_config_messaging_service is None: + self._domain_config_messaging_service = DomainConfigMessagingServiceList( + self + ) + return self._domain_config_messaging_service + + @property + def external_campaign(self) -> ExternalCampaignList: + if self._external_campaign is None: + self._external_campaign = ExternalCampaignList(self) + return self._external_campaign + + @property + def linkshortening_messaging_service(self) -> LinkshorteningMessagingServiceList: + if self._linkshortening_messaging_service is None: + self._linkshortening_messaging_service = LinkshorteningMessagingServiceList( + self + ) + return self._linkshortening_messaging_service + + @property + def linkshortening_messaging_service_domain_association( + self, + ) -> LinkshorteningMessagingServiceDomainAssociationList: + if self._linkshortening_messaging_service_domain_association is None: + self._linkshortening_messaging_service_domain_association = ( + LinkshorteningMessagingServiceDomainAssociationList(self) + ) + return self._linkshortening_messaging_service_domain_association + + @property + def request_managed_cert(self) -> RequestManagedCertList: + if self._request_managed_cert is None: + self._request_managed_cert = RequestManagedCertList(self) + return self._request_managed_cert + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + @property + def tollfree_verifications(self) -> TollfreeVerificationList: + if self._tollfree_verifications is None: + self._tollfree_verifications = TollfreeVerificationList(self) + return self._tollfree_verifications + + @property + def usecases(self) -> UsecaseList: + if self._usecases is None: + self._usecases = UsecaseList(self) + return self._usecases + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..97089eea Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/deactivations.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/deactivations.cpython-312.pyc new file mode 100644 index 00000000..3ea290d4 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/deactivations.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/domain_certs.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/domain_certs.cpython-312.pyc new file mode 100644 index 00000000..4e103eab Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/domain_certs.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/domain_config.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/domain_config.cpython-312.pyc new file mode 100644 index 00000000..0caba94d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/domain_config.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/domain_config_messaging_service.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/domain_config_messaging_service.cpython-312.pyc new file mode 100644 index 00000000..29e2ec23 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/domain_config_messaging_service.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/external_campaign.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/external_campaign.cpython-312.pyc new file mode 100644 index 00000000..0bb720d3 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/external_campaign.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/linkshortening_messaging_service.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/linkshortening_messaging_service.cpython-312.pyc new file mode 100644 index 00000000..46abedcd Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/linkshortening_messaging_service.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/linkshortening_messaging_service_domain_association.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/linkshortening_messaging_service_domain_association.cpython-312.pyc new file mode 100644 index 00000000..8a5e1346 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/linkshortening_messaging_service_domain_association.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/request_managed_cert.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/request_managed_cert.cpython-312.pyc new file mode 100644 index 00000000..89a3775b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/request_managed_cert.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/tollfree_verification.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/tollfree_verification.cpython-312.pyc new file mode 100644 index 00000000..2d08da41 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/tollfree_verification.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/usecase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/usecase.cpython-312.pyc new file mode 100644 index 00000000..d41a4a7a Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/v1/__pycache__/usecase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/brand_registration/__init__.py b/venv/Lib/site-packages/twilio/rest/messaging/v1/brand_registration/__init__.py new file mode 100644 index 00000000..939cba60 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/v1/brand_registration/__init__.py @@ -0,0 +1,673 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.messaging.v1.brand_registration.brand_registration_otp import ( + BrandRegistrationOtpList, +) +from twilio.rest.messaging.v1.brand_registration.brand_vetting import BrandVettingList + + +class BrandRegistrationInstance(InstanceResource): + + class BrandFeedback(object): + TAX_ID = "TAX_ID" + STOCK_SYMBOL = "STOCK_SYMBOL" + NONPROFIT = "NONPROFIT" + GOVERNMENT_ENTITY = "GOVERNMENT_ENTITY" + OTHERS = "OTHERS" + + class IdentityStatus(object): + SELF_DECLARED = "SELF_DECLARED" + UNVERIFIED = "UNVERIFIED" + VERIFIED = "VERIFIED" + VETTED_VERIFIED = "VETTED_VERIFIED" + + class Status(object): + PENDING = "PENDING" + APPROVED = "APPROVED" + FAILED = "FAILED" + IN_REVIEW = "IN_REVIEW" + DELETION_PENDING = "DELETION_PENDING" + DELETION_FAILED = "DELETION_FAILED" + SUSPENDED = "SUSPENDED" + + """ + :ivar sid: The unique string to identify Brand Registration. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Brand Registration resource. + :ivar customer_profile_bundle_sid: A2P Messaging Profile Bundle BundleSid. + :ivar a2p_profile_bundle_sid: A2P Messaging Profile Bundle BundleSid. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar brand_type: Type of brand. One of: \"STANDARD\", \"SOLE_PROPRIETOR\". SOLE_PROPRIETOR is for the low volume, SOLE_PROPRIETOR campaign use case. There can only be one SOLE_PROPRIETOR campaign created per SOLE_PROPRIETOR brand. STANDARD is for all other campaign use cases. Multiple campaign use cases can be created per STANDARD brand. + :ivar status: + :ivar tcr_id: Campaign Registry (TCR) Brand ID. Assigned only after successful brand registration. + :ivar failure_reason: DEPRECATED. A reason why brand registration has failed. Only applicable when status is FAILED. + :ivar errors: A list of errors that occurred during the brand registration process. + :ivar url: The absolute URL of the Brand Registration resource. + :ivar brand_score: The secondary vetting score if it was done. Otherwise, it will be the brand score if it's returned from TCR. It may be null if no score is available. + :ivar brand_feedback: DEPRECATED. Feedback on how to improve brand score + :ivar identity_status: + :ivar russell_3000: Publicly traded company identified in the Russell 3000 Index + :ivar government_entity: Identified as a government entity + :ivar tax_exempt_status: Nonprofit organization tax-exempt status per section 501 of the U.S. tax code. + :ivar skip_automatic_sec_vet: A flag to disable automatic secondary vetting for brands which it would otherwise be done. + :ivar mock: A boolean that specifies whether brand should be a mock or not. If true, brand will be registered as a mock brand. Defaults to false if no value is provided. + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.customer_profile_bundle_sid: Optional[str] = payload.get( + "customer_profile_bundle_sid" + ) + self.a2p_profile_bundle_sid: Optional[str] = payload.get( + "a2p_profile_bundle_sid" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.brand_type: Optional[str] = payload.get("brand_type") + self.status: Optional["BrandRegistrationInstance.Status"] = payload.get( + "status" + ) + self.tcr_id: Optional[str] = payload.get("tcr_id") + self.failure_reason: Optional[str] = payload.get("failure_reason") + self.errors: Optional[List[Dict[str, object]]] = payload.get("errors") + self.url: Optional[str] = payload.get("url") + self.brand_score: Optional[int] = deserialize.integer( + payload.get("brand_score") + ) + self.brand_feedback: Optional[ + List["BrandRegistrationInstance.BrandFeedback"] + ] = payload.get("brand_feedback") + self.identity_status: Optional["BrandRegistrationInstance.IdentityStatus"] = ( + payload.get("identity_status") + ) + self.russell_3000: Optional[bool] = payload.get("russell_3000") + self.government_entity: Optional[bool] = payload.get("government_entity") + self.tax_exempt_status: Optional[str] = payload.get("tax_exempt_status") + self.skip_automatic_sec_vet: Optional[bool] = payload.get( + "skip_automatic_sec_vet" + ) + self.mock: Optional[bool] = payload.get("mock") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[BrandRegistrationContext] = None + + @property + def _proxy(self) -> "BrandRegistrationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BrandRegistrationContext for this BrandRegistrationInstance + """ + if self._context is None: + self._context = BrandRegistrationContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "BrandRegistrationInstance": + """ + Fetch the BrandRegistrationInstance + + + :returns: The fetched BrandRegistrationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BrandRegistrationInstance": + """ + Asynchronous coroutine to fetch the BrandRegistrationInstance + + + :returns: The fetched BrandRegistrationInstance + """ + return await self._proxy.fetch_async() + + def update(self) -> "BrandRegistrationInstance": + """ + Update the BrandRegistrationInstance + + + :returns: The updated BrandRegistrationInstance + """ + return self._proxy.update() + + async def update_async(self) -> "BrandRegistrationInstance": + """ + Asynchronous coroutine to update the BrandRegistrationInstance + + + :returns: The updated BrandRegistrationInstance + """ + return await self._proxy.update_async() + + @property + def brand_registration_otps(self) -> BrandRegistrationOtpList: + """ + Access the brand_registration_otps + """ + return self._proxy.brand_registration_otps + + @property + def brand_vettings(self) -> BrandVettingList: + """ + Access the brand_vettings + """ + return self._proxy.brand_vettings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BrandRegistrationContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the BrandRegistrationContext + + :param version: Version that contains the resource + :param sid: The SID of the Brand Registration resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/a2p/BrandRegistrations/{sid}".format(**self._solution) + + self._brand_registration_otps: Optional[BrandRegistrationOtpList] = None + self._brand_vettings: Optional[BrandVettingList] = None + + def fetch(self) -> BrandRegistrationInstance: + """ + Fetch the BrandRegistrationInstance + + + :returns: The fetched BrandRegistrationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return BrandRegistrationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> BrandRegistrationInstance: + """ + Asynchronous coroutine to fetch the BrandRegistrationInstance + + + :returns: The fetched BrandRegistrationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return BrandRegistrationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update(self) -> BrandRegistrationInstance: + """ + Update the BrandRegistrationInstance + + + :returns: The updated BrandRegistrationInstance + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BrandRegistrationInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async(self) -> BrandRegistrationInstance: + """ + Asynchronous coroutine to update the BrandRegistrationInstance + + + :returns: The updated BrandRegistrationInstance + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BrandRegistrationInstance( + self._version, payload, sid=self._solution["sid"] + ) + + @property + def brand_registration_otps(self) -> BrandRegistrationOtpList: + """ + Access the brand_registration_otps + """ + if self._brand_registration_otps is None: + self._brand_registration_otps = BrandRegistrationOtpList( + self._version, + self._solution["sid"], + ) + return self._brand_registration_otps + + @property + def brand_vettings(self) -> BrandVettingList: + """ + Access the brand_vettings + """ + if self._brand_vettings is None: + self._brand_vettings = BrandVettingList( + self._version, + self._solution["sid"], + ) + return self._brand_vettings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BrandRegistrationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> BrandRegistrationInstance: + """ + Build an instance of BrandRegistrationInstance + + :param payload: Payload response from the API + """ + return BrandRegistrationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class BrandRegistrationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the BrandRegistrationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/a2p/BrandRegistrations" + + def create( + self, + customer_profile_bundle_sid: str, + a2p_profile_bundle_sid: str, + brand_type: Union[str, object] = values.unset, + mock: Union[bool, object] = values.unset, + skip_automatic_sec_vet: Union[bool, object] = values.unset, + ) -> BrandRegistrationInstance: + """ + Create the BrandRegistrationInstance + + :param customer_profile_bundle_sid: Customer Profile Bundle Sid. + :param a2p_profile_bundle_sid: A2P Messaging Profile Bundle Sid. + :param brand_type: Type of brand being created. One of: \\\"STANDARD\\\", \\\"SOLE_PROPRIETOR\\\". SOLE_PROPRIETOR is for low volume, SOLE_PROPRIETOR use cases. STANDARD is for all other use cases. + :param mock: A boolean that specifies whether brand should be a mock or not. If true, brand will be registered as a mock brand. Defaults to false if no value is provided. + :param skip_automatic_sec_vet: A flag to disable automatic secondary vetting for brands which it would otherwise be done. + + :returns: The created BrandRegistrationInstance + """ + + data = values.of( + { + "CustomerProfileBundleSid": customer_profile_bundle_sid, + "A2PProfileBundleSid": a2p_profile_bundle_sid, + "BrandType": brand_type, + "Mock": serialize.boolean_to_string(mock), + "SkipAutomaticSecVet": serialize.boolean_to_string( + skip_automatic_sec_vet + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BrandRegistrationInstance(self._version, payload) + + async def create_async( + self, + customer_profile_bundle_sid: str, + a2p_profile_bundle_sid: str, + brand_type: Union[str, object] = values.unset, + mock: Union[bool, object] = values.unset, + skip_automatic_sec_vet: Union[bool, object] = values.unset, + ) -> BrandRegistrationInstance: + """ + Asynchronously create the BrandRegistrationInstance + + :param customer_profile_bundle_sid: Customer Profile Bundle Sid. + :param a2p_profile_bundle_sid: A2P Messaging Profile Bundle Sid. + :param brand_type: Type of brand being created. One of: \\\"STANDARD\\\", \\\"SOLE_PROPRIETOR\\\". SOLE_PROPRIETOR is for low volume, SOLE_PROPRIETOR use cases. STANDARD is for all other use cases. + :param mock: A boolean that specifies whether brand should be a mock or not. If true, brand will be registered as a mock brand. Defaults to false if no value is provided. + :param skip_automatic_sec_vet: A flag to disable automatic secondary vetting for brands which it would otherwise be done. + + :returns: The created BrandRegistrationInstance + """ + + data = values.of( + { + "CustomerProfileBundleSid": customer_profile_bundle_sid, + "A2PProfileBundleSid": a2p_profile_bundle_sid, + "BrandType": brand_type, + "Mock": serialize.boolean_to_string(mock), + "SkipAutomaticSecVet": serialize.boolean_to_string( + skip_automatic_sec_vet + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BrandRegistrationInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BrandRegistrationInstance]: + """ + Streams BrandRegistrationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BrandRegistrationInstance]: + """ + Asynchronously streams BrandRegistrationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BrandRegistrationInstance]: + """ + Lists BrandRegistrationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BrandRegistrationInstance]: + """ + Asynchronously lists BrandRegistrationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BrandRegistrationPage: + """ + Retrieve a single page of BrandRegistrationInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BrandRegistrationInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BrandRegistrationPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BrandRegistrationPage: + """ + Asynchronously retrieve a single page of BrandRegistrationInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BrandRegistrationInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BrandRegistrationPage(self._version, response) + + def get_page(self, target_url: str) -> BrandRegistrationPage: + """ + Retrieve a specific page of BrandRegistrationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BrandRegistrationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return BrandRegistrationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> BrandRegistrationPage: + """ + Asynchronously retrieve a specific page of BrandRegistrationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BrandRegistrationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return BrandRegistrationPage(self._version, response) + + def get(self, sid: str) -> BrandRegistrationContext: + """ + Constructs a BrandRegistrationContext + + :param sid: The SID of the Brand Registration resource to update. + """ + return BrandRegistrationContext(self._version, sid=sid) + + def __call__(self, sid: str) -> BrandRegistrationContext: + """ + Constructs a BrandRegistrationContext + + :param sid: The SID of the Brand Registration resource to update. + """ + return BrandRegistrationContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/brand_registration/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/v1/brand_registration/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..e2832946 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/v1/brand_registration/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/brand_registration/__pycache__/brand_registration_otp.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/v1/brand_registration/__pycache__/brand_registration_otp.cpython-312.pyc new file mode 100644 index 00000000..260902b4 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/v1/brand_registration/__pycache__/brand_registration_otp.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/brand_registration/__pycache__/brand_vetting.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/v1/brand_registration/__pycache__/brand_vetting.cpython-312.pyc new file mode 100644 index 00000000..e9411a62 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/v1/brand_registration/__pycache__/brand_vetting.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/brand_registration/brand_registration_otp.py b/venv/Lib/site-packages/twilio/rest/messaging/v1/brand_registration/brand_registration_otp.py new file mode 100644 index 00000000..415dec95 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/v1/brand_registration/brand_registration_otp.py @@ -0,0 +1,121 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class BrandRegistrationOtpInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Brand Registration resource. + :ivar brand_registration_sid: The unique string to identify Brand Registration of Sole Proprietor Brand + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], brand_registration_sid: str + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.brand_registration_sid: Optional[str] = payload.get( + "brand_registration_sid" + ) + + self._solution = { + "brand_registration_sid": brand_registration_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BrandRegistrationOtpList(ListResource): + + def __init__(self, version: Version, brand_registration_sid: str): + """ + Initialize the BrandRegistrationOtpList + + :param version: Version that contains the resource + :param brand_registration_sid: Brand Registration Sid of Sole Proprietor Brand. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "brand_registration_sid": brand_registration_sid, + } + self._uri = "/a2p/BrandRegistrations/{brand_registration_sid}/SmsOtp".format( + **self._solution + ) + + def create(self) -> BrandRegistrationOtpInstance: + """ + Create the BrandRegistrationOtpInstance + + + :returns: The created BrandRegistrationOtpInstance + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = self._version.create(method="POST", uri=self._uri, headers=headers) + + return BrandRegistrationOtpInstance( + self._version, + payload, + brand_registration_sid=self._solution["brand_registration_sid"], + ) + + async def create_async(self) -> BrandRegistrationOtpInstance: + """ + Asynchronously create the BrandRegistrationOtpInstance + + + :returns: The created BrandRegistrationOtpInstance + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, headers=headers + ) + + return BrandRegistrationOtpInstance( + self._version, + payload, + brand_registration_sid=self._solution["brand_registration_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/brand_registration/brand_vetting.py b/venv/Lib/site-packages/twilio/rest/messaging/v1/brand_registration/brand_vetting.py new file mode 100644 index 00000000..b633144a --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/v1/brand_registration/brand_vetting.py @@ -0,0 +1,561 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class BrandVettingInstance(InstanceResource): + + class VettingProvider(object): + CAMPAIGN_VERIFY = "campaign-verify" + AEGIS = "aegis" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the vetting record. + :ivar brand_sid: The unique string to identify Brand Registration. + :ivar brand_vetting_sid: The Twilio SID of the third-party vetting record. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar vetting_id: The unique identifier of the vetting from the third-party provider. + :ivar vetting_class: The type of vetting that has been conducted. One of “STANDARD” (Aegis) or “POLITICAL” (Campaign Verify). + :ivar vetting_status: The status of the import vetting attempt. One of “PENDING,” “SUCCESS,” or “FAILED”. + :ivar vetting_provider: + :ivar url: The absolute URL of the Brand Vetting resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + brand_sid: str, + brand_vetting_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.brand_sid: Optional[str] = payload.get("brand_sid") + self.brand_vetting_sid: Optional[str] = payload.get("brand_vetting_sid") + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.vetting_id: Optional[str] = payload.get("vetting_id") + self.vetting_class: Optional[str] = payload.get("vetting_class") + self.vetting_status: Optional[str] = payload.get("vetting_status") + self.vetting_provider: Optional["BrandVettingInstance.VettingProvider"] = ( + payload.get("vetting_provider") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "brand_sid": brand_sid, + "brand_vetting_sid": brand_vetting_sid or self.brand_vetting_sid, + } + self._context: Optional[BrandVettingContext] = None + + @property + def _proxy(self) -> "BrandVettingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BrandVettingContext for this BrandVettingInstance + """ + if self._context is None: + self._context = BrandVettingContext( + self._version, + brand_sid=self._solution["brand_sid"], + brand_vetting_sid=self._solution["brand_vetting_sid"], + ) + return self._context + + def fetch(self) -> "BrandVettingInstance": + """ + Fetch the BrandVettingInstance + + + :returns: The fetched BrandVettingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BrandVettingInstance": + """ + Asynchronous coroutine to fetch the BrandVettingInstance + + + :returns: The fetched BrandVettingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BrandVettingContext(InstanceContext): + + def __init__(self, version: Version, brand_sid: str, brand_vetting_sid: str): + """ + Initialize the BrandVettingContext + + :param version: Version that contains the resource + :param brand_sid: The SID of the Brand Registration resource of the vettings to read . + :param brand_vetting_sid: The Twilio SID of the third-party vetting record. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "brand_sid": brand_sid, + "brand_vetting_sid": brand_vetting_sid, + } + self._uri = ( + "/a2p/BrandRegistrations/{brand_sid}/Vettings/{brand_vetting_sid}".format( + **self._solution + ) + ) + + def fetch(self) -> BrandVettingInstance: + """ + Fetch the BrandVettingInstance + + + :returns: The fetched BrandVettingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return BrandVettingInstance( + self._version, + payload, + brand_sid=self._solution["brand_sid"], + brand_vetting_sid=self._solution["brand_vetting_sid"], + ) + + async def fetch_async(self) -> BrandVettingInstance: + """ + Asynchronous coroutine to fetch the BrandVettingInstance + + + :returns: The fetched BrandVettingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return BrandVettingInstance( + self._version, + payload, + brand_sid=self._solution["brand_sid"], + brand_vetting_sid=self._solution["brand_vetting_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BrandVettingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> BrandVettingInstance: + """ + Build an instance of BrandVettingInstance + + :param payload: Payload response from the API + """ + return BrandVettingInstance( + self._version, payload, brand_sid=self._solution["brand_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class BrandVettingList(ListResource): + + def __init__(self, version: Version, brand_sid: str): + """ + Initialize the BrandVettingList + + :param version: Version that contains the resource + :param brand_sid: The SID of the Brand Registration resource of the vettings to read . + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "brand_sid": brand_sid, + } + self._uri = "/a2p/BrandRegistrations/{brand_sid}/Vettings".format( + **self._solution + ) + + def create( + self, + vetting_provider: "BrandVettingInstance.VettingProvider", + vetting_id: Union[str, object] = values.unset, + ) -> BrandVettingInstance: + """ + Create the BrandVettingInstance + + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: The created BrandVettingInstance + """ + + data = values.of( + { + "VettingProvider": vetting_provider, + "VettingId": vetting_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BrandVettingInstance( + self._version, payload, brand_sid=self._solution["brand_sid"] + ) + + async def create_async( + self, + vetting_provider: "BrandVettingInstance.VettingProvider", + vetting_id: Union[str, object] = values.unset, + ) -> BrandVettingInstance: + """ + Asynchronously create the BrandVettingInstance + + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: The created BrandVettingInstance + """ + + data = values.of( + { + "VettingProvider": vetting_provider, + "VettingId": vetting_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BrandVettingInstance( + self._version, payload, brand_sid=self._solution["brand_sid"] + ) + + def stream( + self, + vetting_provider: Union[ + "BrandVettingInstance.VettingProvider", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BrandVettingInstance]: + """ + Streams BrandVettingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "BrandVettingInstance.VettingProvider" vetting_provider: The third-party provider of the vettings to read + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + vetting_provider=vetting_provider, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + vetting_provider: Union[ + "BrandVettingInstance.VettingProvider", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BrandVettingInstance]: + """ + Asynchronously streams BrandVettingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "BrandVettingInstance.VettingProvider" vetting_provider: The third-party provider of the vettings to read + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + vetting_provider=vetting_provider, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + vetting_provider: Union[ + "BrandVettingInstance.VettingProvider", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BrandVettingInstance]: + """ + Lists BrandVettingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "BrandVettingInstance.VettingProvider" vetting_provider: The third-party provider of the vettings to read + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + vetting_provider=vetting_provider, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + vetting_provider: Union[ + "BrandVettingInstance.VettingProvider", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BrandVettingInstance]: + """ + Asynchronously lists BrandVettingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "BrandVettingInstance.VettingProvider" vetting_provider: The third-party provider of the vettings to read + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + vetting_provider=vetting_provider, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + vetting_provider: Union[ + "BrandVettingInstance.VettingProvider", object + ] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BrandVettingPage: + """ + Retrieve a single page of BrandVettingInstance records from the API. + Request is executed immediately + + :param vetting_provider: The third-party provider of the vettings to read + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BrandVettingInstance + """ + data = values.of( + { + "VettingProvider": vetting_provider, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BrandVettingPage(self._version, response, self._solution) + + async def page_async( + self, + vetting_provider: Union[ + "BrandVettingInstance.VettingProvider", object + ] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BrandVettingPage: + """ + Asynchronously retrieve a single page of BrandVettingInstance records from the API. + Request is executed immediately + + :param vetting_provider: The third-party provider of the vettings to read + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BrandVettingInstance + """ + data = values.of( + { + "VettingProvider": vetting_provider, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BrandVettingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> BrandVettingPage: + """ + Retrieve a specific page of BrandVettingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BrandVettingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return BrandVettingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> BrandVettingPage: + """ + Asynchronously retrieve a specific page of BrandVettingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BrandVettingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return BrandVettingPage(self._version, response, self._solution) + + def get(self, brand_vetting_sid: str) -> BrandVettingContext: + """ + Constructs a BrandVettingContext + + :param brand_vetting_sid: The Twilio SID of the third-party vetting record. + """ + return BrandVettingContext( + self._version, + brand_sid=self._solution["brand_sid"], + brand_vetting_sid=brand_vetting_sid, + ) + + def __call__(self, brand_vetting_sid: str) -> BrandVettingContext: + """ + Constructs a BrandVettingContext + + :param brand_vetting_sid: The Twilio SID of the third-party vetting record. + """ + return BrandVettingContext( + self._version, + brand_sid=self._solution["brand_sid"], + brand_vetting_sid=brand_vetting_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/deactivations.py b/venv/Lib/site-packages/twilio/rest/messaging/v1/deactivations.py new file mode 100644 index 00000000..e2cbf17a --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/v1/deactivations.py @@ -0,0 +1,199 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class DeactivationsInstance(InstanceResource): + """ + :ivar redirect_to: Returns an authenticated url that redirects to a file containing the deactivated numbers for the requested day. This url is valid for up to two minutes. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.redirect_to: Optional[str] = payload.get("redirect_to") + + self._context: Optional[DeactivationsContext] = None + + @property + def _proxy(self) -> "DeactivationsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DeactivationsContext for this DeactivationsInstance + """ + if self._context is None: + self._context = DeactivationsContext( + self._version, + ) + return self._context + + def fetch( + self, date: Union[date, object] = values.unset + ) -> "DeactivationsInstance": + """ + Fetch the DeactivationsInstance + + :param date: The request will return a list of all United States Phone Numbers that were deactivated on the day specified by this parameter. This date should be specified in YYYY-MM-DD format. + + :returns: The fetched DeactivationsInstance + """ + return self._proxy.fetch( + date=date, + ) + + async def fetch_async( + self, date: Union[date, object] = values.unset + ) -> "DeactivationsInstance": + """ + Asynchronous coroutine to fetch the DeactivationsInstance + + :param date: The request will return a list of all United States Phone Numbers that were deactivated on the day specified by this parameter. This date should be specified in YYYY-MM-DD format. + + :returns: The fetched DeactivationsInstance + """ + return await self._proxy.fetch_async( + date=date, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class DeactivationsContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the DeactivationsContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/Deactivations" + + def fetch(self, date: Union[date, object] = values.unset) -> DeactivationsInstance: + """ + Fetch the DeactivationsInstance + + :param date: The request will return a list of all United States Phone Numbers that were deactivated on the day specified by this parameter. This date should be specified in YYYY-MM-DD format. + + :returns: The fetched DeactivationsInstance + """ + + data = values.of( + { + "Date": serialize.iso8601_date(date), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return DeactivationsInstance( + self._version, + payload, + ) + + async def fetch_async( + self, date: Union[date, object] = values.unset + ) -> DeactivationsInstance: + """ + Asynchronous coroutine to fetch the DeactivationsInstance + + :param date: The request will return a list of all United States Phone Numbers that were deactivated on the day specified by this parameter. This date should be specified in YYYY-MM-DD format. + + :returns: The fetched DeactivationsInstance + """ + + data = values.of( + { + "Date": serialize.iso8601_date(date), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return DeactivationsInstance( + self._version, + payload, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class DeactivationsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the DeactivationsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> DeactivationsContext: + """ + Constructs a DeactivationsContext + + """ + return DeactivationsContext(self._version) + + def __call__(self) -> DeactivationsContext: + """ + Constructs a DeactivationsContext + + """ + return DeactivationsContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/domain_certs.py b/venv/Lib/site-packages/twilio/rest/messaging/v1/domain_certs.py new file mode 100644 index 00000000..6da256cd --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/v1/domain_certs.py @@ -0,0 +1,337 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class DomainCertsInstance(InstanceResource): + """ + :ivar domain_sid: The unique string that we created to identify the Domain resource. + :ivar date_updated: Date that this Domain was last updated. + :ivar date_expires: Date that the private certificate associated with this domain expires. You will need to update the certificate before that date to ensure your shortened links will continue to work. + :ivar date_created: Date that this Domain was registered to the Twilio platform to create a new Domain object. + :ivar domain_name: Full url path for this domain. + :ivar certificate_sid: The unique string that we created to identify this Certificate resource. + :ivar url: + :ivar cert_in_validation: Optional JSON field describing the status and upload date of a new certificate in the process of validation + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + domain_sid: Optional[str] = None, + ): + super().__init__(version) + + self.domain_sid: Optional[str] = payload.get("domain_sid") + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.date_expires: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_expires") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.domain_name: Optional[str] = payload.get("domain_name") + self.certificate_sid: Optional[str] = payload.get("certificate_sid") + self.url: Optional[str] = payload.get("url") + self.cert_in_validation: Optional[Dict[str, object]] = payload.get( + "cert_in_validation" + ) + + self._solution = { + "domain_sid": domain_sid or self.domain_sid, + } + self._context: Optional[DomainCertsContext] = None + + @property + def _proxy(self) -> "DomainCertsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DomainCertsContext for this DomainCertsInstance + """ + if self._context is None: + self._context = DomainCertsContext( + self._version, + domain_sid=self._solution["domain_sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the DomainCertsInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DomainCertsInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "DomainCertsInstance": + """ + Fetch the DomainCertsInstance + + + :returns: The fetched DomainCertsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DomainCertsInstance": + """ + Asynchronous coroutine to fetch the DomainCertsInstance + + + :returns: The fetched DomainCertsInstance + """ + return await self._proxy.fetch_async() + + def update(self, tls_cert: str) -> "DomainCertsInstance": + """ + Update the DomainCertsInstance + + :param tls_cert: Contains the full TLS certificate and private for this domain in PEM format: https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail. Twilio uses this information to process HTTPS traffic sent to your domain. + + :returns: The updated DomainCertsInstance + """ + return self._proxy.update( + tls_cert=tls_cert, + ) + + async def update_async(self, tls_cert: str) -> "DomainCertsInstance": + """ + Asynchronous coroutine to update the DomainCertsInstance + + :param tls_cert: Contains the full TLS certificate and private for this domain in PEM format: https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail. Twilio uses this information to process HTTPS traffic sent to your domain. + + :returns: The updated DomainCertsInstance + """ + return await self._proxy.update_async( + tls_cert=tls_cert, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DomainCertsContext(InstanceContext): + + def __init__(self, version: Version, domain_sid: str): + """ + Initialize the DomainCertsContext + + :param version: Version that contains the resource + :param domain_sid: Unique string used to identify the domain that this certificate should be associated with. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "domain_sid": domain_sid, + } + self._uri = "/LinkShortening/Domains/{domain_sid}/Certificate".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the DomainCertsInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DomainCertsInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> DomainCertsInstance: + """ + Fetch the DomainCertsInstance + + + :returns: The fetched DomainCertsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DomainCertsInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + + async def fetch_async(self) -> DomainCertsInstance: + """ + Asynchronous coroutine to fetch the DomainCertsInstance + + + :returns: The fetched DomainCertsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DomainCertsInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + + def update(self, tls_cert: str) -> DomainCertsInstance: + """ + Update the DomainCertsInstance + + :param tls_cert: Contains the full TLS certificate and private for this domain in PEM format: https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail. Twilio uses this information to process HTTPS traffic sent to your domain. + + :returns: The updated DomainCertsInstance + """ + + data = values.of( + { + "TlsCert": tls_cert, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DomainCertsInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + + async def update_async(self, tls_cert: str) -> DomainCertsInstance: + """ + Asynchronous coroutine to update the DomainCertsInstance + + :param tls_cert: Contains the full TLS certificate and private for this domain in PEM format: https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail. Twilio uses this information to process HTTPS traffic sent to your domain. + + :returns: The updated DomainCertsInstance + """ + + data = values.of( + { + "TlsCert": tls_cert, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DomainCertsInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DomainCertsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the DomainCertsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, domain_sid: str) -> DomainCertsContext: + """ + Constructs a DomainCertsContext + + :param domain_sid: Unique string used to identify the domain that this certificate should be associated with. + """ + return DomainCertsContext(self._version, domain_sid=domain_sid) + + def __call__(self, domain_sid: str) -> DomainCertsContext: + """ + Constructs a DomainCertsContext + + :param domain_sid: Unique string used to identify the domain that this certificate should be associated with. + """ + return DomainCertsContext(self._version, domain_sid=domain_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/domain_config.py b/venv/Lib/site-packages/twilio/rest/messaging/v1/domain_config.py new file mode 100644 index 00000000..ed703510 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/v1/domain_config.py @@ -0,0 +1,339 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class DomainConfigInstance(InstanceResource): + """ + :ivar domain_sid: The unique string that we created to identify the Domain resource. + :ivar config_sid: The unique string that we created to identify the Domain config (prefix ZK). + :ivar fallback_url: Any requests we receive to this domain that do not match an existing shortened message will be redirected to the fallback url. These will likely be either expired messages, random misdirected traffic, or intentional scraping. + :ivar callback_url: URL to receive click events to your webhook whenever the recipients click on the shortened links. + :ivar continue_on_failure: Boolean field to set customer delivery preference when there is a failure in linkShortening service + :ivar date_created: Date this Domain Config was created. + :ivar date_updated: Date that this Domain Config was last updated. + :ivar url: + :ivar disable_https: Customer's choice to send links with/without \"https://\" attached to shortened url. If true, messages will not be sent with https:// at the beginning of the url. If false, messages will be sent with https:// at the beginning of the url. False is the default behavior if it is not specified. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + domain_sid: Optional[str] = None, + ): + super().__init__(version) + + self.domain_sid: Optional[str] = payload.get("domain_sid") + self.config_sid: Optional[str] = payload.get("config_sid") + self.fallback_url: Optional[str] = payload.get("fallback_url") + self.callback_url: Optional[str] = payload.get("callback_url") + self.continue_on_failure: Optional[bool] = payload.get("continue_on_failure") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.disable_https: Optional[bool] = payload.get("disable_https") + + self._solution = { + "domain_sid": domain_sid or self.domain_sid, + } + self._context: Optional[DomainConfigContext] = None + + @property + def _proxy(self) -> "DomainConfigContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DomainConfigContext for this DomainConfigInstance + """ + if self._context is None: + self._context = DomainConfigContext( + self._version, + domain_sid=self._solution["domain_sid"], + ) + return self._context + + def fetch(self) -> "DomainConfigInstance": + """ + Fetch the DomainConfigInstance + + + :returns: The fetched DomainConfigInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DomainConfigInstance": + """ + Asynchronous coroutine to fetch the DomainConfigInstance + + + :returns: The fetched DomainConfigInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + fallback_url: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + continue_on_failure: Union[bool, object] = values.unset, + disable_https: Union[bool, object] = values.unset, + ) -> "DomainConfigInstance": + """ + Update the DomainConfigInstance + + :param fallback_url: Any requests we receive to this domain that do not match an existing shortened message will be redirected to the fallback url. These will likely be either expired messages, random misdirected traffic, or intentional scraping. + :param callback_url: URL to receive click events to your webhook whenever the recipients click on the shortened links + :param continue_on_failure: Boolean field to set customer delivery preference when there is a failure in linkShortening service + :param disable_https: Customer's choice to send links with/without \\\"https://\\\" attached to shortened url. If true, messages will not be sent with https:// at the beginning of the url. If false, messages will be sent with https:// at the beginning of the url. False is the default behavior if it is not specified. + + :returns: The updated DomainConfigInstance + """ + return self._proxy.update( + fallback_url=fallback_url, + callback_url=callback_url, + continue_on_failure=continue_on_failure, + disable_https=disable_https, + ) + + async def update_async( + self, + fallback_url: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + continue_on_failure: Union[bool, object] = values.unset, + disable_https: Union[bool, object] = values.unset, + ) -> "DomainConfigInstance": + """ + Asynchronous coroutine to update the DomainConfigInstance + + :param fallback_url: Any requests we receive to this domain that do not match an existing shortened message will be redirected to the fallback url. These will likely be either expired messages, random misdirected traffic, or intentional scraping. + :param callback_url: URL to receive click events to your webhook whenever the recipients click on the shortened links + :param continue_on_failure: Boolean field to set customer delivery preference when there is a failure in linkShortening service + :param disable_https: Customer's choice to send links with/without \\\"https://\\\" attached to shortened url. If true, messages will not be sent with https:// at the beginning of the url. If false, messages will be sent with https:// at the beginning of the url. False is the default behavior if it is not specified. + + :returns: The updated DomainConfigInstance + """ + return await self._proxy.update_async( + fallback_url=fallback_url, + callback_url=callback_url, + continue_on_failure=continue_on_failure, + disable_https=disable_https, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DomainConfigContext(InstanceContext): + + def __init__(self, version: Version, domain_sid: str): + """ + Initialize the DomainConfigContext + + :param version: Version that contains the resource + :param domain_sid: Unique string used to identify the domain that this config should be associated with. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "domain_sid": domain_sid, + } + self._uri = "/LinkShortening/Domains/{domain_sid}/Config".format( + **self._solution + ) + + def fetch(self) -> DomainConfigInstance: + """ + Fetch the DomainConfigInstance + + + :returns: The fetched DomainConfigInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DomainConfigInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + + async def fetch_async(self) -> DomainConfigInstance: + """ + Asynchronous coroutine to fetch the DomainConfigInstance + + + :returns: The fetched DomainConfigInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DomainConfigInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + + def update( + self, + fallback_url: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + continue_on_failure: Union[bool, object] = values.unset, + disable_https: Union[bool, object] = values.unset, + ) -> DomainConfigInstance: + """ + Update the DomainConfigInstance + + :param fallback_url: Any requests we receive to this domain that do not match an existing shortened message will be redirected to the fallback url. These will likely be either expired messages, random misdirected traffic, or intentional scraping. + :param callback_url: URL to receive click events to your webhook whenever the recipients click on the shortened links + :param continue_on_failure: Boolean field to set customer delivery preference when there is a failure in linkShortening service + :param disable_https: Customer's choice to send links with/without \\\"https://\\\" attached to shortened url. If true, messages will not be sent with https:// at the beginning of the url. If false, messages will be sent with https:// at the beginning of the url. False is the default behavior if it is not specified. + + :returns: The updated DomainConfigInstance + """ + + data = values.of( + { + "FallbackUrl": fallback_url, + "CallbackUrl": callback_url, + "ContinueOnFailure": serialize.boolean_to_string(continue_on_failure), + "DisableHttps": serialize.boolean_to_string(disable_https), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DomainConfigInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + + async def update_async( + self, + fallback_url: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + continue_on_failure: Union[bool, object] = values.unset, + disable_https: Union[bool, object] = values.unset, + ) -> DomainConfigInstance: + """ + Asynchronous coroutine to update the DomainConfigInstance + + :param fallback_url: Any requests we receive to this domain that do not match an existing shortened message will be redirected to the fallback url. These will likely be either expired messages, random misdirected traffic, or intentional scraping. + :param callback_url: URL to receive click events to your webhook whenever the recipients click on the shortened links + :param continue_on_failure: Boolean field to set customer delivery preference when there is a failure in linkShortening service + :param disable_https: Customer's choice to send links with/without \\\"https://\\\" attached to shortened url. If true, messages will not be sent with https:// at the beginning of the url. If false, messages will be sent with https:// at the beginning of the url. False is the default behavior if it is not specified. + + :returns: The updated DomainConfigInstance + """ + + data = values.of( + { + "FallbackUrl": fallback_url, + "CallbackUrl": callback_url, + "ContinueOnFailure": serialize.boolean_to_string(continue_on_failure), + "DisableHttps": serialize.boolean_to_string(disable_https), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DomainConfigInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DomainConfigList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the DomainConfigList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, domain_sid: str) -> DomainConfigContext: + """ + Constructs a DomainConfigContext + + :param domain_sid: Unique string used to identify the domain that this config should be associated with. + """ + return DomainConfigContext(self._version, domain_sid=domain_sid) + + def __call__(self, domain_sid: str) -> DomainConfigContext: + """ + Constructs a DomainConfigContext + + :param domain_sid: Unique string used to identify the domain that this config should be associated with. + """ + return DomainConfigContext(self._version, domain_sid=domain_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/domain_config_messaging_service.py b/venv/Lib/site-packages/twilio/rest/messaging/v1/domain_config_messaging_service.py new file mode 100644 index 00000000..2bcd4aa8 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/v1/domain_config_messaging_service.py @@ -0,0 +1,222 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class DomainConfigMessagingServiceInstance(InstanceResource): + """ + :ivar domain_sid: The unique string that we created to identify the Domain resource. + :ivar config_sid: The unique string that we created to identify the Domain config (prefix ZK). + :ivar messaging_service_sid: The unique string that identifies the messaging service + :ivar fallback_url: Any requests we receive to this domain that do not match an existing shortened message will be redirected to the fallback url. These will likely be either expired messages, random misdirected traffic, or intentional scraping. + :ivar callback_url: URL to receive click events to your webhook whenever the recipients click on the shortened links. + :ivar continue_on_failure: Boolean field to set customer delivery preference when there is a failure in linkShortening service + :ivar date_created: Date this Domain Config was created. + :ivar date_updated: Date that this Domain Config was last updated. + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + messaging_service_sid: Optional[str] = None, + ): + super().__init__(version) + + self.domain_sid: Optional[str] = payload.get("domain_sid") + self.config_sid: Optional[str] = payload.get("config_sid") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.fallback_url: Optional[str] = payload.get("fallback_url") + self.callback_url: Optional[str] = payload.get("callback_url") + self.continue_on_failure: Optional[bool] = payload.get("continue_on_failure") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "messaging_service_sid": messaging_service_sid + or self.messaging_service_sid, + } + self._context: Optional[DomainConfigMessagingServiceContext] = None + + @property + def _proxy(self) -> "DomainConfigMessagingServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DomainConfigMessagingServiceContext for this DomainConfigMessagingServiceInstance + """ + if self._context is None: + self._context = DomainConfigMessagingServiceContext( + self._version, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return self._context + + def fetch(self) -> "DomainConfigMessagingServiceInstance": + """ + Fetch the DomainConfigMessagingServiceInstance + + + :returns: The fetched DomainConfigMessagingServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DomainConfigMessagingServiceInstance": + """ + Asynchronous coroutine to fetch the DomainConfigMessagingServiceInstance + + + :returns: The fetched DomainConfigMessagingServiceInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class DomainConfigMessagingServiceContext(InstanceContext): + + def __init__(self, version: Version, messaging_service_sid: str): + """ + Initialize the DomainConfigMessagingServiceContext + + :param version: Version that contains the resource + :param messaging_service_sid: Unique string used to identify the Messaging service that this domain should be associated with. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "messaging_service_sid": messaging_service_sid, + } + self._uri = "/LinkShortening/MessagingService/{messaging_service_sid}/DomainConfig".format( + **self._solution + ) + + def fetch(self) -> DomainConfigMessagingServiceInstance: + """ + Fetch the DomainConfigMessagingServiceInstance + + + :returns: The fetched DomainConfigMessagingServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DomainConfigMessagingServiceInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + async def fetch_async(self) -> DomainConfigMessagingServiceInstance: + """ + Asynchronous coroutine to fetch the DomainConfigMessagingServiceInstance + + + :returns: The fetched DomainConfigMessagingServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DomainConfigMessagingServiceInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class DomainConfigMessagingServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the DomainConfigMessagingServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, messaging_service_sid: str) -> DomainConfigMessagingServiceContext: + """ + Constructs a DomainConfigMessagingServiceContext + + :param messaging_service_sid: Unique string used to identify the Messaging service that this domain should be associated with. + """ + return DomainConfigMessagingServiceContext( + self._version, messaging_service_sid=messaging_service_sid + ) + + def __call__( + self, messaging_service_sid: str + ) -> DomainConfigMessagingServiceContext: + """ + Constructs a DomainConfigMessagingServiceContext + + :param messaging_service_sid: Unique string used to identify the Messaging service that this domain should be associated with. + """ + return DomainConfigMessagingServiceContext( + self._version, messaging_service_sid=messaging_service_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/external_campaign.py b/venv/Lib/site-packages/twilio/rest/messaging/v1/external_campaign.py new file mode 100644 index 00000000..eed039a6 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/v1/external_campaign.py @@ -0,0 +1,143 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ExternalCampaignInstance(InstanceResource): + """ + :ivar sid: The unique string that identifies a US A2P Compliance resource `QE2c6890da8086d771620e9b13fadeba0b`. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the Campaign belongs to. + :ivar campaign_id: ID of the preregistered campaign. + :ivar messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) that the resource is associated with. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.campaign_id: Optional[str] = payload.get("campaign_id") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class ExternalCampaignList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ExternalCampaignList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services/PreregisteredUsa2p" + + def create( + self, + campaign_id: str, + messaging_service_sid: str, + cnp_migration: Union[bool, object] = values.unset, + ) -> ExternalCampaignInstance: + """ + Create the ExternalCampaignInstance + + :param campaign_id: ID of the preregistered campaign. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) that the resource is associated with. + :param cnp_migration: Customers should use this flag during the ERC registration process to indicate to Twilio that the campaign being registered is undergoing CNP migration. It is important for the user to first trigger the CNP migration process for said campaign in their CSP portal and have Twilio accept the sharing request, before making this api call. + + :returns: The created ExternalCampaignInstance + """ + + data = values.of( + { + "CampaignId": campaign_id, + "MessagingServiceSid": messaging_service_sid, + "CnpMigration": serialize.boolean_to_string(cnp_migration), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExternalCampaignInstance(self._version, payload) + + async def create_async( + self, + campaign_id: str, + messaging_service_sid: str, + cnp_migration: Union[bool, object] = values.unset, + ) -> ExternalCampaignInstance: + """ + Asynchronously create the ExternalCampaignInstance + + :param campaign_id: ID of the preregistered campaign. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) that the resource is associated with. + :param cnp_migration: Customers should use this flag during the ERC registration process to indicate to Twilio that the campaign being registered is undergoing CNP migration. It is important for the user to first trigger the CNP migration process for said campaign in their CSP portal and have Twilio accept the sharing request, before making this api call. + + :returns: The created ExternalCampaignInstance + """ + + data = values.of( + { + "CampaignId": campaign_id, + "MessagingServiceSid": messaging_service_sid, + "CnpMigration": serialize.boolean_to_string(cnp_migration), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExternalCampaignInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/linkshortening_messaging_service.py b/venv/Lib/site-packages/twilio/rest/messaging/v1/linkshortening_messaging_service.py new file mode 100644 index 00000000..ac69842a --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/v1/linkshortening_messaging_service.py @@ -0,0 +1,258 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class LinkshorteningMessagingServiceInstance(InstanceResource): + """ + :ivar domain_sid: The unique string identifies the domain resource + :ivar messaging_service_sid: The unique string that identifies the messaging service + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + domain_sid: Optional[str] = None, + messaging_service_sid: Optional[str] = None, + ): + super().__init__(version) + + self.domain_sid: Optional[str] = payload.get("domain_sid") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "domain_sid": domain_sid or self.domain_sid, + "messaging_service_sid": messaging_service_sid + or self.messaging_service_sid, + } + self._context: Optional[LinkshorteningMessagingServiceContext] = None + + @property + def _proxy(self) -> "LinkshorteningMessagingServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: LinkshorteningMessagingServiceContext for this LinkshorteningMessagingServiceInstance + """ + if self._context is None: + self._context = LinkshorteningMessagingServiceContext( + self._version, + domain_sid=self._solution["domain_sid"], + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return self._context + + def create(self) -> "LinkshorteningMessagingServiceInstance": + """ + Create the LinkshorteningMessagingServiceInstance + + + :returns: The created LinkshorteningMessagingServiceInstance + """ + return self._proxy.create() + + async def create_async(self) -> "LinkshorteningMessagingServiceInstance": + """ + Asynchronous coroutine to create the LinkshorteningMessagingServiceInstance + + + :returns: The created LinkshorteningMessagingServiceInstance + """ + return await self._proxy.create_async() + + def delete(self) -> bool: + """ + Deletes the LinkshorteningMessagingServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the LinkshorteningMessagingServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class LinkshorteningMessagingServiceContext(InstanceContext): + + def __init__(self, version: Version, domain_sid: str, messaging_service_sid: str): + """ + Initialize the LinkshorteningMessagingServiceContext + + :param version: Version that contains the resource + :param domain_sid: The domain SID to dissociate from a messaging service. With URL shortening enabled, links in messages sent with the associated messaging service will be shortened to the provided domain + :param messaging_service_sid: A messaging service SID to dissociate from a domain. With URL shortening enabled, links in messages sent with the provided messaging service will be shortened to the associated domain + """ + super().__init__(version) + + # Path Solution + self._solution = { + "domain_sid": domain_sid, + "messaging_service_sid": messaging_service_sid, + } + self._uri = "/LinkShortening/Domains/{domain_sid}/MessagingServices/{messaging_service_sid}".format( + **self._solution + ) + + def create(self) -> LinkshorteningMessagingServiceInstance: + """ + Create the LinkshorteningMessagingServiceInstance + + + :returns: The created LinkshorteningMessagingServiceInstance + """ + data = values.of({}) + + payload = self._version.create(method="POST", uri=self._uri, data=data) + + return LinkshorteningMessagingServiceInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + async def create_async(self) -> LinkshorteningMessagingServiceInstance: + """ + Asynchronous coroutine to create the LinkshorteningMessagingServiceInstance + + + :returns: The created LinkshorteningMessagingServiceInstance + """ + data = values.of({}) + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data + ) + + return LinkshorteningMessagingServiceInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def delete(self) -> bool: + """ + Deletes the LinkshorteningMessagingServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the LinkshorteningMessagingServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class LinkshorteningMessagingServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the LinkshorteningMessagingServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get( + self, domain_sid: str, messaging_service_sid: str + ) -> LinkshorteningMessagingServiceContext: + """ + Constructs a LinkshorteningMessagingServiceContext + + :param domain_sid: The domain SID to dissociate from a messaging service. With URL shortening enabled, links in messages sent with the associated messaging service will be shortened to the provided domain + :param messaging_service_sid: A messaging service SID to dissociate from a domain. With URL shortening enabled, links in messages sent with the provided messaging service will be shortened to the associated domain + """ + return LinkshorteningMessagingServiceContext( + self._version, + domain_sid=domain_sid, + messaging_service_sid=messaging_service_sid, + ) + + def __call__( + self, domain_sid: str, messaging_service_sid: str + ) -> LinkshorteningMessagingServiceContext: + """ + Constructs a LinkshorteningMessagingServiceContext + + :param domain_sid: The domain SID to dissociate from a messaging service. With URL shortening enabled, links in messages sent with the associated messaging service will be shortened to the provided domain + :param messaging_service_sid: A messaging service SID to dissociate from a domain. With URL shortening enabled, links in messages sent with the provided messaging service will be shortened to the associated domain + """ + return LinkshorteningMessagingServiceContext( + self._version, + domain_sid=domain_sid, + messaging_service_sid=messaging_service_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/linkshortening_messaging_service_domain_association.py b/venv/Lib/site-packages/twilio/rest/messaging/v1/linkshortening_messaging_service_domain_association.py new file mode 100644 index 00000000..4c0b52bd --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/v1/linkshortening_messaging_service_domain_association.py @@ -0,0 +1,217 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class LinkshorteningMessagingServiceDomainAssociationInstance(InstanceResource): + """ + :ivar domain_sid: The unique string that we created to identify the Domain resource. + :ivar messaging_service_sid: The unique string that identifies the messaging service + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + messaging_service_sid: Optional[str] = None, + ): + super().__init__(version) + + self.domain_sid: Optional[str] = payload.get("domain_sid") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "messaging_service_sid": messaging_service_sid + or self.messaging_service_sid, + } + self._context: Optional[ + LinkshorteningMessagingServiceDomainAssociationContext + ] = None + + @property + def _proxy(self) -> "LinkshorteningMessagingServiceDomainAssociationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: LinkshorteningMessagingServiceDomainAssociationContext for this LinkshorteningMessagingServiceDomainAssociationInstance + """ + if self._context is None: + self._context = LinkshorteningMessagingServiceDomainAssociationContext( + self._version, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return self._context + + def fetch(self) -> "LinkshorteningMessagingServiceDomainAssociationInstance": + """ + Fetch the LinkshorteningMessagingServiceDomainAssociationInstance + + + :returns: The fetched LinkshorteningMessagingServiceDomainAssociationInstance + """ + return self._proxy.fetch() + + async def fetch_async( + self, + ) -> "LinkshorteningMessagingServiceDomainAssociationInstance": + """ + Asynchronous coroutine to fetch the LinkshorteningMessagingServiceDomainAssociationInstance + + + :returns: The fetched LinkshorteningMessagingServiceDomainAssociationInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class LinkshorteningMessagingServiceDomainAssociationContext(InstanceContext): + + def __init__(self, version: Version, messaging_service_sid: str): + """ + Initialize the LinkshorteningMessagingServiceDomainAssociationContext + + :param version: Version that contains the resource + :param messaging_service_sid: Unique string used to identify the Messaging service that this domain should be associated with. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "messaging_service_sid": messaging_service_sid, + } + self._uri = ( + "/LinkShortening/MessagingServices/{messaging_service_sid}/Domain".format( + **self._solution + ) + ) + + def fetch(self) -> LinkshorteningMessagingServiceDomainAssociationInstance: + """ + Fetch the LinkshorteningMessagingServiceDomainAssociationInstance + + + :returns: The fetched LinkshorteningMessagingServiceDomainAssociationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return LinkshorteningMessagingServiceDomainAssociationInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + async def fetch_async( + self, + ) -> LinkshorteningMessagingServiceDomainAssociationInstance: + """ + Asynchronous coroutine to fetch the LinkshorteningMessagingServiceDomainAssociationInstance + + + :returns: The fetched LinkshorteningMessagingServiceDomainAssociationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return LinkshorteningMessagingServiceDomainAssociationInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class LinkshorteningMessagingServiceDomainAssociationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the LinkshorteningMessagingServiceDomainAssociationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get( + self, messaging_service_sid: str + ) -> LinkshorteningMessagingServiceDomainAssociationContext: + """ + Constructs a LinkshorteningMessagingServiceDomainAssociationContext + + :param messaging_service_sid: Unique string used to identify the Messaging service that this domain should be associated with. + """ + return LinkshorteningMessagingServiceDomainAssociationContext( + self._version, messaging_service_sid=messaging_service_sid + ) + + def __call__( + self, messaging_service_sid: str + ) -> LinkshorteningMessagingServiceDomainAssociationContext: + """ + Constructs a LinkshorteningMessagingServiceDomainAssociationContext + + :param messaging_service_sid: Unique string used to identify the Messaging service that this domain should be associated with. + """ + return LinkshorteningMessagingServiceDomainAssociationContext( + self._version, messaging_service_sid=messaging_service_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return ( + "" + ) diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/request_managed_cert.py b/venv/Lib/site-packages/twilio/rest/messaging/v1/request_managed_cert.py new file mode 100644 index 00000000..81ccf948 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/v1/request_managed_cert.py @@ -0,0 +1,213 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class RequestManagedCertInstance(InstanceResource): + """ + :ivar domain_sid: The unique string that we created to identify the Domain resource. + :ivar date_updated: Date that this Domain was last updated. + :ivar date_created: Date that this Domain was registered to the Twilio platform to create a new Domain object. + :ivar date_expires: Date that the private certificate associated with this domain expires. This is the expiration date of your existing cert. + :ivar domain_name: Full url path for this domain. + :ivar certificate_sid: The unique string that we created to identify this Certificate resource. + :ivar url: + :ivar managed: A boolean flag indicating if the certificate is managed by Twilio. + :ivar requesting: A boolean flag indicating if a managed certificate needs to be fulfilled by Twilio. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + domain_sid: Optional[str] = None, + ): + super().__init__(version) + + self.domain_sid: Optional[str] = payload.get("domain_sid") + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_expires: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_expires") + ) + self.domain_name: Optional[str] = payload.get("domain_name") + self.certificate_sid: Optional[str] = payload.get("certificate_sid") + self.url: Optional[str] = payload.get("url") + self.managed: Optional[bool] = payload.get("managed") + self.requesting: Optional[bool] = payload.get("requesting") + + self._solution = { + "domain_sid": domain_sid or self.domain_sid, + } + self._context: Optional[RequestManagedCertContext] = None + + @property + def _proxy(self) -> "RequestManagedCertContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RequestManagedCertContext for this RequestManagedCertInstance + """ + if self._context is None: + self._context = RequestManagedCertContext( + self._version, + domain_sid=self._solution["domain_sid"], + ) + return self._context + + def update(self) -> "RequestManagedCertInstance": + """ + Update the RequestManagedCertInstance + + + :returns: The updated RequestManagedCertInstance + """ + return self._proxy.update() + + async def update_async(self) -> "RequestManagedCertInstance": + """ + Asynchronous coroutine to update the RequestManagedCertInstance + + + :returns: The updated RequestManagedCertInstance + """ + return await self._proxy.update_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RequestManagedCertContext(InstanceContext): + + def __init__(self, version: Version, domain_sid: str): + """ + Initialize the RequestManagedCertContext + + :param version: Version that contains the resource + :param domain_sid: Unique string used to identify the domain that this certificate should be associated with. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "domain_sid": domain_sid, + } + self._uri = "/LinkShortening/Domains/{domain_sid}/RequestManagedCert".format( + **self._solution + ) + + def update(self) -> RequestManagedCertInstance: + """ + Update the RequestManagedCertInstance + + + :returns: The updated RequestManagedCertInstance + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RequestManagedCertInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + + async def update_async(self) -> RequestManagedCertInstance: + """ + Asynchronous coroutine to update the RequestManagedCertInstance + + + :returns: The updated RequestManagedCertInstance + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RequestManagedCertInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RequestManagedCertList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the RequestManagedCertList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, domain_sid: str) -> RequestManagedCertContext: + """ + Constructs a RequestManagedCertContext + + :param domain_sid: Unique string used to identify the domain that this certificate should be associated with. + """ + return RequestManagedCertContext(self._version, domain_sid=domain_sid) + + def __call__(self, domain_sid: str) -> RequestManagedCertContext: + """ + Constructs a RequestManagedCertContext + + :param domain_sid: Unique string used to identify the domain that this certificate should be associated with. + """ + return RequestManagedCertContext(self._version, domain_sid=domain_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__init__.py b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__init__.py new file mode 100644 index 00000000..06a53c9a --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__init__.py @@ -0,0 +1,1115 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.messaging.v1.service.alpha_sender import AlphaSenderList +from twilio.rest.messaging.v1.service.channel_sender import ChannelSenderList +from twilio.rest.messaging.v1.service.destination_alpha_sender import ( + DestinationAlphaSenderList, +) +from twilio.rest.messaging.v1.service.phone_number import PhoneNumberList +from twilio.rest.messaging.v1.service.short_code import ShortCodeList +from twilio.rest.messaging.v1.service.us_app_to_person import UsAppToPersonList +from twilio.rest.messaging.v1.service.us_app_to_person_usecase import ( + UsAppToPersonUsecaseList, +) + + +class ServiceInstance(InstanceResource): + + class ScanMessageContent(object): + INHERIT = "inherit" + ENABLE = "enable" + DISABLE = "disable" + + """ + :ivar sid: The unique string that we created to identify the Service resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :ivar inbound_method: The HTTP method we use to call `inbound_request_url`. Can be `GET` or `POST`. + :ivar fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :ivar fallback_method: The HTTP method we use to call `fallback_url`. Can be: `GET` or `POST`. + :ivar status_callback: The URL we call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :ivar sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :ivar mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :ivar smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :ivar scan_message_content: + :ivar fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :ivar area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :ivar synchronous_validation: Reserved. + :ivar validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. Default value is `14,400`. + :ivar url: The absolute URL of the Service resource. + :ivar links: The absolute URLs of related resources. + :ivar usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :ivar us_app_to_person_registered: Whether US A2P campaign is registered for this Service. + :ivar use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.inbound_request_url: Optional[str] = payload.get("inbound_request_url") + self.inbound_method: Optional[str] = payload.get("inbound_method") + self.fallback_url: Optional[str] = payload.get("fallback_url") + self.fallback_method: Optional[str] = payload.get("fallback_method") + self.status_callback: Optional[str] = payload.get("status_callback") + self.sticky_sender: Optional[bool] = payload.get("sticky_sender") + self.mms_converter: Optional[bool] = payload.get("mms_converter") + self.smart_encoding: Optional[bool] = payload.get("smart_encoding") + self.scan_message_content: Optional["ServiceInstance.ScanMessageContent"] = ( + payload.get("scan_message_content") + ) + self.fallback_to_long_code: Optional[bool] = payload.get( + "fallback_to_long_code" + ) + self.area_code_geomatch: Optional[bool] = payload.get("area_code_geomatch") + self.synchronous_validation: Optional[bool] = payload.get( + "synchronous_validation" + ) + self.validity_period: Optional[int] = deserialize.integer( + payload.get("validity_period") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.usecase: Optional[str] = payload.get("usecase") + self.us_app_to_person_registered: Optional[bool] = payload.get( + "us_app_to_person_registered" + ) + self.use_inbound_webhook_on_number: Optional[bool] = payload.get( + "use_inbound_webhook_on_number" + ) + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. Default value is `14,400`. + :param synchronous_validation: Reserved. + :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + inbound_request_url=inbound_request_url, + inbound_method=inbound_method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + sticky_sender=sticky_sender, + mms_converter=mms_converter, + smart_encoding=smart_encoding, + scan_message_content=scan_message_content, + fallback_to_long_code=fallback_to_long_code, + area_code_geomatch=area_code_geomatch, + validity_period=validity_period, + synchronous_validation=synchronous_validation, + usecase=usecase, + use_inbound_webhook_on_number=use_inbound_webhook_on_number, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. Default value is `14,400`. + :param synchronous_validation: Reserved. + :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + inbound_request_url=inbound_request_url, + inbound_method=inbound_method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + sticky_sender=sticky_sender, + mms_converter=mms_converter, + smart_encoding=smart_encoding, + scan_message_content=scan_message_content, + fallback_to_long_code=fallback_to_long_code, + area_code_geomatch=area_code_geomatch, + validity_period=validity_period, + synchronous_validation=synchronous_validation, + usecase=usecase, + use_inbound_webhook_on_number=use_inbound_webhook_on_number, + ) + + @property + def alpha_senders(self) -> AlphaSenderList: + """ + Access the alpha_senders + """ + return self._proxy.alpha_senders + + @property + def channel_senders(self) -> ChannelSenderList: + """ + Access the channel_senders + """ + return self._proxy.channel_senders + + @property + def destination_alpha_senders(self) -> DestinationAlphaSenderList: + """ + Access the destination_alpha_senders + """ + return self._proxy.destination_alpha_senders + + @property + def phone_numbers(self) -> PhoneNumberList: + """ + Access the phone_numbers + """ + return self._proxy.phone_numbers + + @property + def short_codes(self) -> ShortCodeList: + """ + Access the short_codes + """ + return self._proxy.short_codes + + @property + def us_app_to_person(self) -> UsAppToPersonList: + """ + Access the us_app_to_person + """ + return self._proxy.us_app_to_person + + @property + def us_app_to_person_usecases(self) -> UsAppToPersonUsecaseList: + """ + Access the us_app_to_person_usecases + """ + return self._proxy.us_app_to_person_usecases + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: The SID of the Service resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._alpha_senders: Optional[AlphaSenderList] = None + self._channel_senders: Optional[ChannelSenderList] = None + self._destination_alpha_senders: Optional[DestinationAlphaSenderList] = None + self._phone_numbers: Optional[PhoneNumberList] = None + self._short_codes: Optional[ShortCodeList] = None + self._us_app_to_person: Optional[UsAppToPersonList] = None + self._us_app_to_person_usecases: Optional[UsAppToPersonUsecaseList] = None + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. Default value is `14,400`. + :param synchronous_validation: Reserved. + :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "InboundRequestUrl": inbound_request_url, + "InboundMethod": inbound_method, + "FallbackUrl": fallback_url, + "FallbackMethod": fallback_method, + "StatusCallback": status_callback, + "StickySender": serialize.boolean_to_string(sticky_sender), + "MmsConverter": serialize.boolean_to_string(mms_converter), + "SmartEncoding": serialize.boolean_to_string(smart_encoding), + "ScanMessageContent": scan_message_content, + "FallbackToLongCode": serialize.boolean_to_string( + fallback_to_long_code + ), + "AreaCodeGeomatch": serialize.boolean_to_string(area_code_geomatch), + "ValidityPeriod": validity_period, + "SynchronousValidation": serialize.boolean_to_string( + synchronous_validation + ), + "Usecase": usecase, + "UseInboundWebhookOnNumber": serialize.boolean_to_string( + use_inbound_webhook_on_number + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. Default value is `14,400`. + :param synchronous_validation: Reserved. + :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "InboundRequestUrl": inbound_request_url, + "InboundMethod": inbound_method, + "FallbackUrl": fallback_url, + "FallbackMethod": fallback_method, + "StatusCallback": status_callback, + "StickySender": serialize.boolean_to_string(sticky_sender), + "MmsConverter": serialize.boolean_to_string(mms_converter), + "SmartEncoding": serialize.boolean_to_string(smart_encoding), + "ScanMessageContent": scan_message_content, + "FallbackToLongCode": serialize.boolean_to_string( + fallback_to_long_code + ), + "AreaCodeGeomatch": serialize.boolean_to_string(area_code_geomatch), + "ValidityPeriod": validity_period, + "SynchronousValidation": serialize.boolean_to_string( + synchronous_validation + ), + "Usecase": usecase, + "UseInboundWebhookOnNumber": serialize.boolean_to_string( + use_inbound_webhook_on_number + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def alpha_senders(self) -> AlphaSenderList: + """ + Access the alpha_senders + """ + if self._alpha_senders is None: + self._alpha_senders = AlphaSenderList( + self._version, + self._solution["sid"], + ) + return self._alpha_senders + + @property + def channel_senders(self) -> ChannelSenderList: + """ + Access the channel_senders + """ + if self._channel_senders is None: + self._channel_senders = ChannelSenderList( + self._version, + self._solution["sid"], + ) + return self._channel_senders + + @property + def destination_alpha_senders(self) -> DestinationAlphaSenderList: + """ + Access the destination_alpha_senders + """ + if self._destination_alpha_senders is None: + self._destination_alpha_senders = DestinationAlphaSenderList( + self._version, + self._solution["sid"], + ) + return self._destination_alpha_senders + + @property + def phone_numbers(self) -> PhoneNumberList: + """ + Access the phone_numbers + """ + if self._phone_numbers is None: + self._phone_numbers = PhoneNumberList( + self._version, + self._solution["sid"], + ) + return self._phone_numbers + + @property + def short_codes(self) -> ShortCodeList: + """ + Access the short_codes + """ + if self._short_codes is None: + self._short_codes = ShortCodeList( + self._version, + self._solution["sid"], + ) + return self._short_codes + + @property + def us_app_to_person(self) -> UsAppToPersonList: + """ + Access the us_app_to_person + """ + if self._us_app_to_person is None: + self._us_app_to_person = UsAppToPersonList( + self._version, + self._solution["sid"], + ) + return self._us_app_to_person + + @property + def us_app_to_person_usecases(self) -> UsAppToPersonUsecaseList: + """ + Access the us_app_to_person_usecases + """ + if self._us_app_to_person_usecases is None: + self._us_app_to_person_usecases = UsAppToPersonUsecaseList( + self._version, + self._solution["sid"], + ) + return self._us_app_to_person_usecases + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def create( + self, + friendly_name: str, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. Default value is `14,400`. + :param synchronous_validation: Reserved. + :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "InboundRequestUrl": inbound_request_url, + "InboundMethod": inbound_method, + "FallbackUrl": fallback_url, + "FallbackMethod": fallback_method, + "StatusCallback": status_callback, + "StickySender": serialize.boolean_to_string(sticky_sender), + "MmsConverter": serialize.boolean_to_string(mms_converter), + "SmartEncoding": serialize.boolean_to_string(smart_encoding), + "ScanMessageContent": scan_message_content, + "FallbackToLongCode": serialize.boolean_to_string( + fallback_to_long_code + ), + "AreaCodeGeomatch": serialize.boolean_to_string(area_code_geomatch), + "ValidityPeriod": validity_period, + "SynchronousValidation": serialize.boolean_to_string( + synchronous_validation + ), + "Usecase": usecase, + "UseInboundWebhookOnNumber": serialize.boolean_to_string( + use_inbound_webhook_on_number + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. Default value is `14,400`. + :param synchronous_validation: Reserved. + :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "InboundRequestUrl": inbound_request_url, + "InboundMethod": inbound_method, + "FallbackUrl": fallback_url, + "FallbackMethod": fallback_method, + "StatusCallback": status_callback, + "StickySender": serialize.boolean_to_string(sticky_sender), + "MmsConverter": serialize.boolean_to_string(mms_converter), + "SmartEncoding": serialize.boolean_to_string(smart_encoding), + "ScanMessageContent": scan_message_content, + "FallbackToLongCode": serialize.boolean_to_string( + fallback_to_long_code + ), + "AreaCodeGeomatch": serialize.boolean_to_string(area_code_geomatch), + "ValidityPeriod": validity_period, + "SynchronousValidation": serialize.boolean_to_string( + synchronous_validation + ), + "Usecase": usecase, + "UseInboundWebhookOnNumber": serialize.boolean_to_string( + use_inbound_webhook_on_number + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The SID of the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The SID of the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..03d21831 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__pycache__/alpha_sender.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__pycache__/alpha_sender.cpython-312.pyc new file mode 100644 index 00000000..7f85bbad Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__pycache__/alpha_sender.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__pycache__/channel_sender.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__pycache__/channel_sender.cpython-312.pyc new file mode 100644 index 00000000..afa81446 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__pycache__/channel_sender.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__pycache__/destination_alpha_sender.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__pycache__/destination_alpha_sender.cpython-312.pyc new file mode 100644 index 00000000..95eb5ea2 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__pycache__/destination_alpha_sender.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__pycache__/phone_number.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__pycache__/phone_number.cpython-312.pyc new file mode 100644 index 00000000..64859af1 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__pycache__/phone_number.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__pycache__/short_code.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__pycache__/short_code.cpython-312.pyc new file mode 100644 index 00000000..ddb18522 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__pycache__/short_code.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__pycache__/us_app_to_person.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__pycache__/us_app_to_person.cpython-312.pyc new file mode 100644 index 00000000..abccb6e2 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__pycache__/us_app_to_person.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__pycache__/us_app_to_person_usecase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__pycache__/us_app_to_person_usecase.cpython-312.pyc new file mode 100644 index 00000000..a5cf0d91 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/__pycache__/us_app_to_person_usecase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/service/alpha_sender.py b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/alpha_sender.py new file mode 100644 index 00000000..2ba4c2a4 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/alpha_sender.py @@ -0,0 +1,542 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AlphaSenderInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the AlphaSender resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AlphaSender resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the resource is associated with. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar alpha_sender: The Alphanumeric Sender ID string. + :ivar capabilities: An array of values that describe whether the number can receive calls or messages. Can be: `SMS`. + :ivar url: The absolute URL of the AlphaSender resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.alpha_sender: Optional[str] = payload.get("alpha_sender") + self.capabilities: Optional[List[str]] = payload.get("capabilities") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[AlphaSenderContext] = None + + @property + def _proxy(self) -> "AlphaSenderContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AlphaSenderContext for this AlphaSenderInstance + """ + if self._context is None: + self._context = AlphaSenderContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AlphaSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AlphaSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AlphaSenderInstance": + """ + Fetch the AlphaSenderInstance + + + :returns: The fetched AlphaSenderInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AlphaSenderInstance": + """ + Asynchronous coroutine to fetch the AlphaSenderInstance + + + :returns: The fetched AlphaSenderInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AlphaSenderContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the AlphaSenderContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to fetch the resource from. + :param sid: The SID of the AlphaSender resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/AlphaSenders/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the AlphaSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AlphaSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AlphaSenderInstance: + """ + Fetch the AlphaSenderInstance + + + :returns: The fetched AlphaSenderInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AlphaSenderInstance: + """ + Asynchronous coroutine to fetch the AlphaSenderInstance + + + :returns: The fetched AlphaSenderInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AlphaSenderPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AlphaSenderInstance: + """ + Build an instance of AlphaSenderInstance + + :param payload: Payload response from the API + """ + return AlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AlphaSenderList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the AlphaSenderList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/AlphaSenders".format(**self._solution) + + def create(self, alpha_sender: str) -> AlphaSenderInstance: + """ + Create the AlphaSenderInstance + + :param alpha_sender: The Alphanumeric Sender ID string. Can be up to 11 characters long. Valid characters are A-Z, a-z, 0-9, space, hyphen `-`, plus `+`, underscore `_` and ampersand `&`. This value cannot contain only numbers. + + :returns: The created AlphaSenderInstance + """ + + data = values.of( + { + "AlphaSender": alpha_sender, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async(self, alpha_sender: str) -> AlphaSenderInstance: + """ + Asynchronously create the AlphaSenderInstance + + :param alpha_sender: The Alphanumeric Sender ID string. Can be up to 11 characters long. Valid characters are A-Z, a-z, 0-9, space, hyphen `-`, plus `+`, underscore `_` and ampersand `&`. This value cannot contain only numbers. + + :returns: The created AlphaSenderInstance + """ + + data = values.of( + { + "AlphaSender": alpha_sender, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AlphaSenderInstance]: + """ + Streams AlphaSenderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AlphaSenderInstance]: + """ + Asynchronously streams AlphaSenderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AlphaSenderInstance]: + """ + Lists AlphaSenderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AlphaSenderInstance]: + """ + Asynchronously lists AlphaSenderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AlphaSenderPage: + """ + Retrieve a single page of AlphaSenderInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AlphaSenderInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AlphaSenderPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AlphaSenderPage: + """ + Asynchronously retrieve a single page of AlphaSenderInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AlphaSenderInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AlphaSenderPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AlphaSenderPage: + """ + Retrieve a specific page of AlphaSenderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AlphaSenderInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AlphaSenderPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AlphaSenderPage: + """ + Asynchronously retrieve a specific page of AlphaSenderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AlphaSenderInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AlphaSenderPage(self._version, response, self._solution) + + def get(self, sid: str) -> AlphaSenderContext: + """ + Constructs a AlphaSenderContext + + :param sid: The SID of the AlphaSender resource to fetch. + """ + return AlphaSenderContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> AlphaSenderContext: + """ + Constructs a AlphaSenderContext + + :param sid: The SID of the AlphaSender resource to fetch. + """ + return AlphaSenderContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/service/channel_sender.py b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/channel_sender.py new file mode 100644 index 00000000..9d708a2f --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/channel_sender.py @@ -0,0 +1,556 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ChannelSenderInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ChannelSender resource. + :ivar messaging_service_sid: The SID of the [Service](https://www.twilio.com/docs/messaging/services) the resource is associated with. + :ivar sid: The unique string that we created to identify the ChannelSender resource. + :ivar sender: The unique string that identifies the sender e.g whatsapp:+123456XXXX. + :ivar sender_type: A string value that identifies the sender type e.g WhatsApp, Messenger. + :ivar country_code: The 2-character [ISO Country Code](https://www.iso.org/iso-3166-country-codes.html) of the number. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the ChannelSender resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + messaging_service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.sid: Optional[str] = payload.get("sid") + self.sender: Optional[str] = payload.get("sender") + self.sender_type: Optional[str] = payload.get("sender_type") + self.country_code: Optional[str] = payload.get("country_code") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "messaging_service_sid": messaging_service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ChannelSenderContext] = None + + @property + def _proxy(self) -> "ChannelSenderContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ChannelSenderContext for this ChannelSenderInstance + """ + if self._context is None: + self._context = ChannelSenderContext( + self._version, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ChannelSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ChannelSenderInstance": + """ + Fetch the ChannelSenderInstance + + + :returns: The fetched ChannelSenderInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ChannelSenderInstance": + """ + Asynchronous coroutine to fetch the ChannelSenderInstance + + + :returns: The fetched ChannelSenderInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ChannelSenderContext(InstanceContext): + + def __init__(self, version: Version, messaging_service_sid: str, sid: str): + """ + Initialize the ChannelSenderContext + + :param version: Version that contains the resource + :param messaging_service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to fetch the resource from. + :param sid: The SID of the ChannelSender resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "messaging_service_sid": messaging_service_sid, + "sid": sid, + } + self._uri = "/Services/{messaging_service_sid}/ChannelSenders/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the ChannelSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChannelSenderInstance: + """ + Fetch the ChannelSenderInstance + + + :returns: The fetched ChannelSenderInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ChannelSenderInstance: + """ + Asynchronous coroutine to fetch the ChannelSenderInstance + + + :returns: The fetched ChannelSenderInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ChannelSenderPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ChannelSenderInstance: + """ + Build an instance of ChannelSenderInstance + + :param payload: Payload response from the API + """ + return ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ChannelSenderList(ListResource): + + def __init__(self, version: Version, messaging_service_sid: str): + """ + Initialize the ChannelSenderList + + :param version: Version that contains the resource + :param messaging_service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "messaging_service_sid": messaging_service_sid, + } + self._uri = "/Services/{messaging_service_sid}/ChannelSenders".format( + **self._solution + ) + + def create(self, sid: str) -> ChannelSenderInstance: + """ + Create the ChannelSenderInstance + + :param sid: The SID of the Channel Sender being added to the Service. + + :returns: The created ChannelSenderInstance + """ + + data = values.of( + { + "Sid": sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + async def create_async(self, sid: str) -> ChannelSenderInstance: + """ + Asynchronously create the ChannelSenderInstance + + :param sid: The SID of the Channel Sender being added to the Service. + + :returns: The created ChannelSenderInstance + """ + + data = values.of( + { + "Sid": sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChannelSenderInstance]: + """ + Streams ChannelSenderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ChannelSenderInstance]: + """ + Asynchronously streams ChannelSenderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelSenderInstance]: + """ + Lists ChannelSenderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelSenderInstance]: + """ + Asynchronously lists ChannelSenderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelSenderPage: + """ + Retrieve a single page of ChannelSenderInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelSenderInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelSenderPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelSenderPage: + """ + Asynchronously retrieve a single page of ChannelSenderInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelSenderInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelSenderPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ChannelSenderPage: + """ + Retrieve a specific page of ChannelSenderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelSenderInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ChannelSenderPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ChannelSenderPage: + """ + Asynchronously retrieve a specific page of ChannelSenderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelSenderInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelSenderPage(self._version, response, self._solution) + + def get(self, sid: str) -> ChannelSenderContext: + """ + Constructs a ChannelSenderContext + + :param sid: The SID of the ChannelSender resource to fetch. + """ + return ChannelSenderContext( + self._version, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> ChannelSenderContext: + """ + Constructs a ChannelSenderContext + + :param sid: The SID of the ChannelSender resource to fetch. + """ + return ChannelSenderContext( + self._version, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/service/destination_alpha_sender.py b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/destination_alpha_sender.py new file mode 100644 index 00000000..244d906c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/destination_alpha_sender.py @@ -0,0 +1,574 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DestinationAlphaSenderInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the AlphaSender resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AlphaSender resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the resource is associated with. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar alpha_sender: The Alphanumeric Sender ID string. + :ivar capabilities: An array of values that describe whether the number can receive calls or messages. Can be: `SMS`. + :ivar url: The absolute URL of the AlphaSender resource. + :ivar iso_country_code: The Two Character ISO Country Code the Alphanumeric Sender ID will be used for. For Default Alpha Senders that work across countries, this value will be an empty string + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.alpha_sender: Optional[str] = payload.get("alpha_sender") + self.capabilities: Optional[List[str]] = payload.get("capabilities") + self.url: Optional[str] = payload.get("url") + self.iso_country_code: Optional[str] = payload.get("iso_country_code") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[DestinationAlphaSenderContext] = None + + @property + def _proxy(self) -> "DestinationAlphaSenderContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DestinationAlphaSenderContext for this DestinationAlphaSenderInstance + """ + if self._context is None: + self._context = DestinationAlphaSenderContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the DestinationAlphaSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DestinationAlphaSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "DestinationAlphaSenderInstance": + """ + Fetch the DestinationAlphaSenderInstance + + + :returns: The fetched DestinationAlphaSenderInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DestinationAlphaSenderInstance": + """ + Asynchronous coroutine to fetch the DestinationAlphaSenderInstance + + + :returns: The fetched DestinationAlphaSenderInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DestinationAlphaSenderContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the DestinationAlphaSenderContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to fetch the resource from. + :param sid: The SID of the AlphaSender resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/DestinationAlphaSenders/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the DestinationAlphaSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DestinationAlphaSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> DestinationAlphaSenderInstance: + """ + Fetch the DestinationAlphaSenderInstance + + + :returns: The fetched DestinationAlphaSenderInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DestinationAlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> DestinationAlphaSenderInstance: + """ + Asynchronous coroutine to fetch the DestinationAlphaSenderInstance + + + :returns: The fetched DestinationAlphaSenderInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DestinationAlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DestinationAlphaSenderPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DestinationAlphaSenderInstance: + """ + Build an instance of DestinationAlphaSenderInstance + + :param payload: Payload response from the API + """ + return DestinationAlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class DestinationAlphaSenderList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the DestinationAlphaSenderList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/DestinationAlphaSenders".format( + **self._solution + ) + + def create( + self, alpha_sender: str, iso_country_code: Union[str, object] = values.unset + ) -> DestinationAlphaSenderInstance: + """ + Create the DestinationAlphaSenderInstance + + :param alpha_sender: The Alphanumeric Sender ID string. Can be up to 11 characters long. Valid characters are A-Z, a-z, 0-9, space, hyphen `-`, plus `+`, underscore `_` and ampersand `&`. This value cannot contain only numbers. + :param iso_country_code: The Optional Two Character ISO Country Code the Alphanumeric Sender ID will be used for. If the IsoCountryCode is not provided, a default Alpha Sender will be created that can be used across all countries. + + :returns: The created DestinationAlphaSenderInstance + """ + + data = values.of( + { + "AlphaSender": alpha_sender, + "IsoCountryCode": iso_country_code, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DestinationAlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, alpha_sender: str, iso_country_code: Union[str, object] = values.unset + ) -> DestinationAlphaSenderInstance: + """ + Asynchronously create the DestinationAlphaSenderInstance + + :param alpha_sender: The Alphanumeric Sender ID string. Can be up to 11 characters long. Valid characters are A-Z, a-z, 0-9, space, hyphen `-`, plus `+`, underscore `_` and ampersand `&`. This value cannot contain only numbers. + :param iso_country_code: The Optional Two Character ISO Country Code the Alphanumeric Sender ID will be used for. If the IsoCountryCode is not provided, a default Alpha Sender will be created that can be used across all countries. + + :returns: The created DestinationAlphaSenderInstance + """ + + data = values.of( + { + "AlphaSender": alpha_sender, + "IsoCountryCode": iso_country_code, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DestinationAlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + iso_country_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DestinationAlphaSenderInstance]: + """ + Streams DestinationAlphaSenderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str iso_country_code: Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + iso_country_code=iso_country_code, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + iso_country_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DestinationAlphaSenderInstance]: + """ + Asynchronously streams DestinationAlphaSenderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str iso_country_code: Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + iso_country_code=iso_country_code, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + iso_country_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DestinationAlphaSenderInstance]: + """ + Lists DestinationAlphaSenderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str iso_country_code: Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + iso_country_code=iso_country_code, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + iso_country_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DestinationAlphaSenderInstance]: + """ + Asynchronously lists DestinationAlphaSenderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str iso_country_code: Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + iso_country_code=iso_country_code, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + iso_country_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DestinationAlphaSenderPage: + """ + Retrieve a single page of DestinationAlphaSenderInstance records from the API. + Request is executed immediately + + :param iso_country_code: Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DestinationAlphaSenderInstance + """ + data = values.of( + { + "IsoCountryCode": iso_country_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DestinationAlphaSenderPage(self._version, response, self._solution) + + async def page_async( + self, + iso_country_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DestinationAlphaSenderPage: + """ + Asynchronously retrieve a single page of DestinationAlphaSenderInstance records from the API. + Request is executed immediately + + :param iso_country_code: Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DestinationAlphaSenderInstance + """ + data = values.of( + { + "IsoCountryCode": iso_country_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DestinationAlphaSenderPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DestinationAlphaSenderPage: + """ + Retrieve a specific page of DestinationAlphaSenderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DestinationAlphaSenderInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DestinationAlphaSenderPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DestinationAlphaSenderPage: + """ + Asynchronously retrieve a specific page of DestinationAlphaSenderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DestinationAlphaSenderInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DestinationAlphaSenderPage(self._version, response, self._solution) + + def get(self, sid: str) -> DestinationAlphaSenderContext: + """ + Constructs a DestinationAlphaSenderContext + + :param sid: The SID of the AlphaSender resource to fetch. + """ + return DestinationAlphaSenderContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> DestinationAlphaSenderContext: + """ + Constructs a DestinationAlphaSenderContext + + :param sid: The SID of the AlphaSender resource to fetch. + """ + return DestinationAlphaSenderContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/service/phone_number.py b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/phone_number.py new file mode 100644 index 00000000..11b80658 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/phone_number.py @@ -0,0 +1,544 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class PhoneNumberInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the PhoneNumber resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the PhoneNumber resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the resource is associated with. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar country_code: The 2-character [ISO Country Code](https://www.iso.org/iso-3166-country-codes.html) of the number. + :ivar capabilities: An array of values that describe whether the number can receive calls or messages. Can be: `Voice`, `SMS`, and `MMS`. + :ivar url: The absolute URL of the PhoneNumber resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.phone_number: Optional[str] = payload.get("phone_number") + self.country_code: Optional[str] = payload.get("country_code") + self.capabilities: Optional[List[str]] = payload.get("capabilities") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[PhoneNumberContext] = None + + @property + def _proxy(self) -> "PhoneNumberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PhoneNumberContext for this PhoneNumberInstance + """ + if self._context is None: + self._context = PhoneNumberContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the PhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "PhoneNumberInstance": + """ + Fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PhoneNumberInstance": + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PhoneNumberContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the PhoneNumberContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to fetch the resource from. + :param sid: The SID of the PhoneNumber resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/PhoneNumbers/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the PhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> PhoneNumberInstance: + """ + Fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> PhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PhoneNumberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PhoneNumberInstance: + """ + Build an instance of PhoneNumberInstance + + :param payload: Payload response from the API + """ + return PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class PhoneNumberList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the PhoneNumberList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/PhoneNumbers".format(**self._solution) + + def create(self, phone_number_sid: str) -> PhoneNumberInstance: + """ + Create the PhoneNumberInstance + + :param phone_number_sid: The SID of the Phone Number being added to the Service. + + :returns: The created PhoneNumberInstance + """ + + data = values.of( + { + "PhoneNumberSid": phone_number_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async(self, phone_number_sid: str) -> PhoneNumberInstance: + """ + Asynchronously create the PhoneNumberInstance + + :param phone_number_sid: The SID of the Phone Number being added to the Service. + + :returns: The created PhoneNumberInstance + """ + + data = values.of( + { + "PhoneNumberSid": phone_number_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PhoneNumberInstance]: + """ + Streams PhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PhoneNumberInstance]: + """ + Asynchronously streams PhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PhoneNumberInstance]: + """ + Lists PhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PhoneNumberInstance]: + """ + Asynchronously lists PhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PhoneNumberPage: + """ + Retrieve a single page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PhoneNumberInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PhoneNumberPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PhoneNumberPage: + """ + Asynchronously retrieve a single page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PhoneNumberInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PhoneNumberPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> PhoneNumberPage: + """ + Retrieve a specific page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PhoneNumberInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PhoneNumberPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> PhoneNumberPage: + """ + Asynchronously retrieve a specific page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PhoneNumberInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PhoneNumberPage(self._version, response, self._solution) + + def get(self, sid: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param sid: The SID of the PhoneNumber resource to fetch. + """ + return PhoneNumberContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param sid: The SID of the PhoneNumber resource to fetch. + """ + return PhoneNumberContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/service/short_code.py b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/short_code.py new file mode 100644 index 00000000..172c78db --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/short_code.py @@ -0,0 +1,542 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ShortCodeInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the ShortCode resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ShortCode resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the resource is associated with. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar short_code: The [E.164](https://www.twilio.com/docs/glossary/what-e164) format of the short code. + :ivar country_code: The 2-character [ISO Country Code](https://www.iso.org/iso-3166-country-codes.html) of the number. + :ivar capabilities: An array of values that describe whether the number can receive calls or messages. Can be: `SMS` and `MMS`. + :ivar url: The absolute URL of the ShortCode resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.short_code: Optional[str] = payload.get("short_code") + self.country_code: Optional[str] = payload.get("country_code") + self.capabilities: Optional[List[str]] = payload.get("capabilities") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ShortCodeContext] = None + + @property + def _proxy(self) -> "ShortCodeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ShortCodeContext for this ShortCodeInstance + """ + if self._context is None: + self._context = ShortCodeContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ShortCodeInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ShortCodeInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ShortCodeInstance": + """ + Fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ShortCodeInstance": + """ + Asynchronous coroutine to fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ShortCodeContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the ShortCodeContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to fetch the resource from. + :param sid: The SID of the ShortCode resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/ShortCodes/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the ShortCodeInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ShortCodeInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ShortCodeInstance: + """ + Fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ShortCodeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ShortCodeInstance: + """ + Asynchronous coroutine to fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ShortCodeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ShortCodePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ShortCodeInstance: + """ + Build an instance of ShortCodeInstance + + :param payload: Payload response from the API + """ + return ShortCodeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ShortCodeList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the ShortCodeList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/ShortCodes".format(**self._solution) + + def create(self, short_code_sid: str) -> ShortCodeInstance: + """ + Create the ShortCodeInstance + + :param short_code_sid: The SID of the ShortCode resource being added to the Service. + + :returns: The created ShortCodeInstance + """ + + data = values.of( + { + "ShortCodeSid": short_code_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ShortCodeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async(self, short_code_sid: str) -> ShortCodeInstance: + """ + Asynchronously create the ShortCodeInstance + + :param short_code_sid: The SID of the ShortCode resource being added to the Service. + + :returns: The created ShortCodeInstance + """ + + data = values.of( + { + "ShortCodeSid": short_code_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ShortCodeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ShortCodeInstance]: + """ + Streams ShortCodeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ShortCodeInstance]: + """ + Asynchronously streams ShortCodeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ShortCodeInstance]: + """ + Lists ShortCodeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ShortCodeInstance]: + """ + Asynchronously lists ShortCodeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ShortCodePage: + """ + Retrieve a single page of ShortCodeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ShortCodeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ShortCodePage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ShortCodePage: + """ + Asynchronously retrieve a single page of ShortCodeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ShortCodeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ShortCodePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ShortCodePage: + """ + Retrieve a specific page of ShortCodeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ShortCodeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ShortCodePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ShortCodePage: + """ + Asynchronously retrieve a specific page of ShortCodeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ShortCodeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ShortCodePage(self._version, response, self._solution) + + def get(self, sid: str) -> ShortCodeContext: + """ + Constructs a ShortCodeContext + + :param sid: The SID of the ShortCode resource to fetch. + """ + return ShortCodeContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ShortCodeContext: + """ + Constructs a ShortCodeContext + + :param sid: The SID of the ShortCode resource to fetch. + """ + return ShortCodeContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/service/us_app_to_person.py b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/us_app_to_person.py new file mode 100644 index 00000000..dd451f5c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/us_app_to_person.py @@ -0,0 +1,866 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UsAppToPersonInstance(InstanceResource): + """ + :ivar sid: The unique string that identifies a US A2P Compliance resource `QE2c6890da8086d771620e9b13fadeba0b`. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the Campaign belongs to. + :ivar brand_registration_sid: The unique string to identify the A2P brand. + :ivar messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) that the resource is associated with. + :ivar description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :ivar message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :ivar us_app_to_person_usecase: A2P Campaign Use Case. Examples: [ 2FA, EMERGENCY, MARKETING, SOLE_PROPRIETOR...]. SOLE_PROPRIETOR campaign use cases can only be created by SOLE_PROPRIETOR Brands, and there can only be one SOLE_PROPRIETOR campaign created per SOLE_PROPRIETOR Brand. + :ivar has_embedded_links: Indicate that this SMS campaign will send messages that contain links. + :ivar has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :ivar subscriber_opt_in: A boolean that specifies whether campaign has Subscriber Optin or not. + :ivar age_gated: A boolean that specifies whether campaign is age gated or not. + :ivar direct_lending: A boolean that specifies whether campaign allows direct lending or not. + :ivar campaign_status: Campaign status. Examples: IN_PROGRESS, VERIFIED, FAILED. + :ivar campaign_id: The Campaign Registry (TCR) Campaign ID. + :ivar is_externally_registered: Indicates whether the campaign was registered externally or not. + :ivar rate_limits: Rate limit and/or classification set by each carrier, Ex. AT&T or T-Mobile. + :ivar message_flow: Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :ivar opt_in_message: If end users can text in a keyword to start receiving messages from this campaign, the auto-reply messages sent to the end users must be provided. The opt-in response should include the Brand name, confirmation of opt-in enrollment to a recurring message campaign, how to get help, and clear description of how to opt-out. This field is required if end users can text in a keyword to start receiving messages from this campaign. 20 character minimum. 320 character maximum. + :ivar opt_out_message: Upon receiving the opt-out keywords from the end users, Twilio customers are expected to send back an auto-generated response, which must provide acknowledgment of the opt-out request and confirmation that no further messages will be sent. It is also recommended that these opt-out messages include the brand name. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. + :ivar help_message: When customers receive the help keywords from their end users, Twilio customers are expected to send back an auto-generated response; this may include the brand name and additional support contact information. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. + :ivar opt_in_keywords: If end users can text in a keyword to start receiving messages from this campaign, those keywords must be provided. This field is required if end users can text in a keyword to start receiving messages from this campaign. Values must be alphanumeric. 255 character maximum. + :ivar opt_out_keywords: End users should be able to text in a keyword to stop receiving messages from this campaign. Those keywords must be provided. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. + :ivar help_keywords: End users should be able to text in a keyword to receive help. Those keywords must be provided as part of the campaign registration request. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the US App to Person resource. + :ivar mock: A boolean that specifies whether campaign is a mock or not. Mock campaigns will be automatically created if using a mock brand. Mock campaigns should only be used for testing purposes. + :ivar errors: Details indicating why a campaign registration failed. These errors can indicate one or more fields that were incorrect or did not meet review requirements. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + messaging_service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.brand_registration_sid: Optional[str] = payload.get( + "brand_registration_sid" + ) + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.description: Optional[str] = payload.get("description") + self.message_samples: Optional[List[str]] = payload.get("message_samples") + self.us_app_to_person_usecase: Optional[str] = payload.get( + "us_app_to_person_usecase" + ) + self.has_embedded_links: Optional[bool] = payload.get("has_embedded_links") + self.has_embedded_phone: Optional[bool] = payload.get("has_embedded_phone") + self.subscriber_opt_in: Optional[bool] = payload.get("subscriber_opt_in") + self.age_gated: Optional[bool] = payload.get("age_gated") + self.direct_lending: Optional[bool] = payload.get("direct_lending") + self.campaign_status: Optional[str] = payload.get("campaign_status") + self.campaign_id: Optional[str] = payload.get("campaign_id") + self.is_externally_registered: Optional[bool] = payload.get( + "is_externally_registered" + ) + self.rate_limits: Optional[Dict[str, object]] = payload.get("rate_limits") + self.message_flow: Optional[str] = payload.get("message_flow") + self.opt_in_message: Optional[str] = payload.get("opt_in_message") + self.opt_out_message: Optional[str] = payload.get("opt_out_message") + self.help_message: Optional[str] = payload.get("help_message") + self.opt_in_keywords: Optional[List[str]] = payload.get("opt_in_keywords") + self.opt_out_keywords: Optional[List[str]] = payload.get("opt_out_keywords") + self.help_keywords: Optional[List[str]] = payload.get("help_keywords") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.mock: Optional[bool] = payload.get("mock") + self.errors: Optional[List[Dict[str, object]]] = payload.get("errors") + + self._solution = { + "messaging_service_sid": messaging_service_sid, + "sid": sid or self.sid, + } + self._context: Optional[UsAppToPersonContext] = None + + @property + def _proxy(self) -> "UsAppToPersonContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UsAppToPersonContext for this UsAppToPersonInstance + """ + if self._context is None: + self._context = UsAppToPersonContext( + self._version, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UsAppToPersonInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UsAppToPersonInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "UsAppToPersonInstance": + """ + Fetch the UsAppToPersonInstance + + + :returns: The fetched UsAppToPersonInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UsAppToPersonInstance": + """ + Asynchronous coroutine to fetch the UsAppToPersonInstance + + + :returns: The fetched UsAppToPersonInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + has_embedded_links: bool, + has_embedded_phone: bool, + message_samples: List[str], + message_flow: str, + description: str, + age_gated: bool, + direct_lending: bool, + ) -> "UsAppToPersonInstance": + """ + Update the UsAppToPersonInstance + + :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. + :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :param age_gated: A boolean that specifies whether campaign requires age gate for federally legal content. + :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + + :returns: The updated UsAppToPersonInstance + """ + return self._proxy.update( + has_embedded_links=has_embedded_links, + has_embedded_phone=has_embedded_phone, + message_samples=message_samples, + message_flow=message_flow, + description=description, + age_gated=age_gated, + direct_lending=direct_lending, + ) + + async def update_async( + self, + has_embedded_links: bool, + has_embedded_phone: bool, + message_samples: List[str], + message_flow: str, + description: str, + age_gated: bool, + direct_lending: bool, + ) -> "UsAppToPersonInstance": + """ + Asynchronous coroutine to update the UsAppToPersonInstance + + :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. + :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :param age_gated: A boolean that specifies whether campaign requires age gate for federally legal content. + :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + + :returns: The updated UsAppToPersonInstance + """ + return await self._proxy.update_async( + has_embedded_links=has_embedded_links, + has_embedded_phone=has_embedded_phone, + message_samples=message_samples, + message_flow=message_flow, + description=description, + age_gated=age_gated, + direct_lending=direct_lending, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UsAppToPersonContext(InstanceContext): + + def __init__(self, version: Version, messaging_service_sid: str, sid: str): + """ + Initialize the UsAppToPersonContext + + :param version: Version that contains the resource + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services/api) to update the resource from. + :param sid: The SID of the US A2P Compliance resource to update `QE2c6890da8086d771620e9b13fadeba0b`. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "messaging_service_sid": messaging_service_sid, + "sid": sid, + } + self._uri = "/Services/{messaging_service_sid}/Compliance/Usa2p/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the UsAppToPersonInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UsAppToPersonInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UsAppToPersonInstance: + """ + Fetch the UsAppToPersonInstance + + + :returns: The fetched UsAppToPersonInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> UsAppToPersonInstance: + """ + Asynchronous coroutine to fetch the UsAppToPersonInstance + + + :returns: The fetched UsAppToPersonInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + has_embedded_links: bool, + has_embedded_phone: bool, + message_samples: List[str], + message_flow: str, + description: str, + age_gated: bool, + direct_lending: bool, + ) -> UsAppToPersonInstance: + """ + Update the UsAppToPersonInstance + + :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. + :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :param age_gated: A boolean that specifies whether campaign requires age gate for federally legal content. + :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + + :returns: The updated UsAppToPersonInstance + """ + + data = values.of( + { + "HasEmbeddedLinks": serialize.boolean_to_string(has_embedded_links), + "HasEmbeddedPhone": serialize.boolean_to_string(has_embedded_phone), + "MessageSamples": serialize.map(message_samples, lambda e: e), + "MessageFlow": message_flow, + "Description": description, + "AgeGated": serialize.boolean_to_string(age_gated), + "DirectLending": serialize.boolean_to_string(direct_lending), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + has_embedded_links: bool, + has_embedded_phone: bool, + message_samples: List[str], + message_flow: str, + description: str, + age_gated: bool, + direct_lending: bool, + ) -> UsAppToPersonInstance: + """ + Asynchronous coroutine to update the UsAppToPersonInstance + + :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. + :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :param age_gated: A boolean that specifies whether campaign requires age gate for federally legal content. + :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + + :returns: The updated UsAppToPersonInstance + """ + + data = values.of( + { + "HasEmbeddedLinks": serialize.boolean_to_string(has_embedded_links), + "HasEmbeddedPhone": serialize.boolean_to_string(has_embedded_phone), + "MessageSamples": serialize.map(message_samples, lambda e: e), + "MessageFlow": message_flow, + "Description": description, + "AgeGated": serialize.boolean_to_string(age_gated), + "DirectLending": serialize.boolean_to_string(direct_lending), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UsAppToPersonPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UsAppToPersonInstance: + """ + Build an instance of UsAppToPersonInstance + + :param payload: Payload response from the API + """ + return UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class UsAppToPersonList(ListResource): + + def __init__(self, version: Version, messaging_service_sid: str): + """ + Initialize the UsAppToPersonList + + :param version: Version that contains the resource + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to fetch the resource from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "messaging_service_sid": messaging_service_sid, + } + self._uri = "/Services/{messaging_service_sid}/Compliance/Usa2p".format( + **self._solution + ) + + def create( + self, + brand_registration_sid: str, + description: str, + message_flow: str, + message_samples: List[str], + us_app_to_person_usecase: str, + has_embedded_links: bool, + has_embedded_phone: bool, + opt_in_message: Union[str, object] = values.unset, + opt_out_message: Union[str, object] = values.unset, + help_message: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + opt_out_keywords: Union[List[str], object] = values.unset, + help_keywords: Union[List[str], object] = values.unset, + subscriber_opt_in: Union[bool, object] = values.unset, + age_gated: Union[bool, object] = values.unset, + direct_lending: Union[bool, object] = values.unset, + ) -> UsAppToPersonInstance: + """ + Create the UsAppToPersonInstance + + :param brand_registration_sid: A2P Brand Registration SID + :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :param us_app_to_person_usecase: A2P Campaign Use Case. Examples: [ 2FA, EMERGENCY, MARKETING..] + :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. + :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param opt_in_message: If end users can text in a keyword to start receiving messages from this campaign, the auto-reply messages sent to the end users must be provided. The opt-in response should include the Brand name, confirmation of opt-in enrollment to a recurring message campaign, how to get help, and clear description of how to opt-out. This field is required if end users can text in a keyword to start receiving messages from this campaign. 20 character minimum. 320 character maximum. + :param opt_out_message: Upon receiving the opt-out keywords from the end users, Twilio customers are expected to send back an auto-generated response, which must provide acknowledgment of the opt-out request and confirmation that no further messages will be sent. It is also recommended that these opt-out messages include the brand name. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. + :param help_message: When customers receive the help keywords from their end users, Twilio customers are expected to send back an auto-generated response; this may include the brand name and additional support contact information. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. + :param opt_in_keywords: If end users can text in a keyword to start receiving messages from this campaign, those keywords must be provided. This field is required if end users can text in a keyword to start receiving messages from this campaign. Values must be alphanumeric. 255 character maximum. + :param opt_out_keywords: End users should be able to text in a keyword to stop receiving messages from this campaign. Those keywords must be provided. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. + :param help_keywords: End users should be able to text in a keyword to receive help. Those keywords must be provided as part of the campaign registration request. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. + :param subscriber_opt_in: A boolean that specifies whether campaign has Subscriber Optin or not. + :param age_gated: A boolean that specifies whether campaign is age gated or not. + :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + + :returns: The created UsAppToPersonInstance + """ + + data = values.of( + { + "BrandRegistrationSid": brand_registration_sid, + "Description": description, + "MessageFlow": message_flow, + "MessageSamples": serialize.map(message_samples, lambda e: e), + "UsAppToPersonUsecase": us_app_to_person_usecase, + "HasEmbeddedLinks": serialize.boolean_to_string(has_embedded_links), + "HasEmbeddedPhone": serialize.boolean_to_string(has_embedded_phone), + "OptInMessage": opt_in_message, + "OptOutMessage": opt_out_message, + "HelpMessage": help_message, + "OptInKeywords": serialize.map(opt_in_keywords, lambda e: e), + "OptOutKeywords": serialize.map(opt_out_keywords, lambda e: e), + "HelpKeywords": serialize.map(help_keywords, lambda e: e), + "SubscriberOptIn": serialize.boolean_to_string(subscriber_opt_in), + "AgeGated": serialize.boolean_to_string(age_gated), + "DirectLending": serialize.boolean_to_string(direct_lending), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + async def create_async( + self, + brand_registration_sid: str, + description: str, + message_flow: str, + message_samples: List[str], + us_app_to_person_usecase: str, + has_embedded_links: bool, + has_embedded_phone: bool, + opt_in_message: Union[str, object] = values.unset, + opt_out_message: Union[str, object] = values.unset, + help_message: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + opt_out_keywords: Union[List[str], object] = values.unset, + help_keywords: Union[List[str], object] = values.unset, + subscriber_opt_in: Union[bool, object] = values.unset, + age_gated: Union[bool, object] = values.unset, + direct_lending: Union[bool, object] = values.unset, + ) -> UsAppToPersonInstance: + """ + Asynchronously create the UsAppToPersonInstance + + :param brand_registration_sid: A2P Brand Registration SID + :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :param us_app_to_person_usecase: A2P Campaign Use Case. Examples: [ 2FA, EMERGENCY, MARKETING..] + :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. + :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param opt_in_message: If end users can text in a keyword to start receiving messages from this campaign, the auto-reply messages sent to the end users must be provided. The opt-in response should include the Brand name, confirmation of opt-in enrollment to a recurring message campaign, how to get help, and clear description of how to opt-out. This field is required if end users can text in a keyword to start receiving messages from this campaign. 20 character minimum. 320 character maximum. + :param opt_out_message: Upon receiving the opt-out keywords from the end users, Twilio customers are expected to send back an auto-generated response, which must provide acknowledgment of the opt-out request and confirmation that no further messages will be sent. It is also recommended that these opt-out messages include the brand name. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. + :param help_message: When customers receive the help keywords from their end users, Twilio customers are expected to send back an auto-generated response; this may include the brand name and additional support contact information. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. + :param opt_in_keywords: If end users can text in a keyword to start receiving messages from this campaign, those keywords must be provided. This field is required if end users can text in a keyword to start receiving messages from this campaign. Values must be alphanumeric. 255 character maximum. + :param opt_out_keywords: End users should be able to text in a keyword to stop receiving messages from this campaign. Those keywords must be provided. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. + :param help_keywords: End users should be able to text in a keyword to receive help. Those keywords must be provided as part of the campaign registration request. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. + :param subscriber_opt_in: A boolean that specifies whether campaign has Subscriber Optin or not. + :param age_gated: A boolean that specifies whether campaign is age gated or not. + :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + + :returns: The created UsAppToPersonInstance + """ + + data = values.of( + { + "BrandRegistrationSid": brand_registration_sid, + "Description": description, + "MessageFlow": message_flow, + "MessageSamples": serialize.map(message_samples, lambda e: e), + "UsAppToPersonUsecase": us_app_to_person_usecase, + "HasEmbeddedLinks": serialize.boolean_to_string(has_embedded_links), + "HasEmbeddedPhone": serialize.boolean_to_string(has_embedded_phone), + "OptInMessage": opt_in_message, + "OptOutMessage": opt_out_message, + "HelpMessage": help_message, + "OptInKeywords": serialize.map(opt_in_keywords, lambda e: e), + "OptOutKeywords": serialize.map(opt_out_keywords, lambda e: e), + "HelpKeywords": serialize.map(help_keywords, lambda e: e), + "SubscriberOptIn": serialize.boolean_to_string(subscriber_opt_in), + "AgeGated": serialize.boolean_to_string(age_gated), + "DirectLending": serialize.boolean_to_string(direct_lending), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UsAppToPersonInstance]: + """ + Streams UsAppToPersonInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UsAppToPersonInstance]: + """ + Asynchronously streams UsAppToPersonInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UsAppToPersonInstance]: + """ + Lists UsAppToPersonInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UsAppToPersonInstance]: + """ + Asynchronously lists UsAppToPersonInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UsAppToPersonPage: + """ + Retrieve a single page of UsAppToPersonInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UsAppToPersonInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsAppToPersonPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UsAppToPersonPage: + """ + Asynchronously retrieve a single page of UsAppToPersonInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UsAppToPersonInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsAppToPersonPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UsAppToPersonPage: + """ + Retrieve a specific page of UsAppToPersonInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UsAppToPersonInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UsAppToPersonPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UsAppToPersonPage: + """ + Asynchronously retrieve a specific page of UsAppToPersonInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UsAppToPersonInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UsAppToPersonPage(self._version, response, self._solution) + + def get(self, sid: str) -> UsAppToPersonContext: + """ + Constructs a UsAppToPersonContext + + :param sid: The SID of the US A2P Compliance resource to update `QE2c6890da8086d771620e9b13fadeba0b`. + """ + return UsAppToPersonContext( + self._version, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> UsAppToPersonContext: + """ + Constructs a UsAppToPersonContext + + :param sid: The SID of the US A2P Compliance resource to update `QE2c6890da8086d771620e9b13fadeba0b`. + """ + return UsAppToPersonContext( + self._version, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/service/us_app_to_person_usecase.py b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/us_app_to_person_usecase.py new file mode 100644 index 00000000..bf9e48e6 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/v1/service/us_app_to_person_usecase.py @@ -0,0 +1,137 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class UsAppToPersonUsecaseInstance(InstanceResource): + """ + :ivar us_app_to_person_usecases: Human readable name, code, description and post_approval_required (indicates whether or not post approval is required for this Use Case) of A2P Campaign Use Cases. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], messaging_service_sid: str + ): + super().__init__(version) + + self.us_app_to_person_usecases: Optional[List[Dict[str, object]]] = payload.get( + "us_app_to_person_usecases" + ) + + self._solution = { + "messaging_service_sid": messaging_service_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UsAppToPersonUsecaseList(ListResource): + + def __init__(self, version: Version, messaging_service_sid: str): + """ + Initialize the UsAppToPersonUsecaseList + + :param version: Version that contains the resource + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to fetch the resource from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "messaging_service_sid": messaging_service_sid, + } + self._uri = ( + "/Services/{messaging_service_sid}/Compliance/Usa2p/Usecases".format( + **self._solution + ) + ) + + def fetch( + self, brand_registration_sid: Union[str, object] = values.unset + ) -> UsAppToPersonUsecaseInstance: + """ + Asynchronously fetch the UsAppToPersonUsecaseInstance + + :param brand_registration_sid: The unique string to identify the A2P brand. + :returns: The fetched UsAppToPersonUsecaseInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "BrandRegistrationSid": brand_registration_sid, + } + ) + + payload = self._version.fetch( + method="GET", uri=self._uri, headers=headers, params=params + ) + + return UsAppToPersonUsecaseInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + async def fetch_async( + self, brand_registration_sid: Union[str, object] = values.unset + ) -> UsAppToPersonUsecaseInstance: + """ + Asynchronously fetch the UsAppToPersonUsecaseInstance + + :param brand_registration_sid: The unique string to identify the A2P brand. + :returns: The fetched UsAppToPersonUsecaseInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "BrandRegistrationSid": brand_registration_sid, + } + ) + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers, params=params + ) + + return UsAppToPersonUsecaseInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/tollfree_verification.py b/venv/Lib/site-packages/twilio/rest/messaging/v1/tollfree_verification.py new file mode 100644 index 00000000..00cf9c96 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/v1/tollfree_verification.py @@ -0,0 +1,1173 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TollfreeVerificationInstance(InstanceResource): + + class OptInType(object): + VERBAL = "VERBAL" + WEB_FORM = "WEB_FORM" + PAPER_FORM = "PAPER_FORM" + VIA_TEXT = "VIA_TEXT" + MOBILE_QR_CODE = "MOBILE_QR_CODE" + IMPORT = "IMPORT" + IMPORT_PLEASE_REPLACE = "IMPORT_PLEASE_REPLACE" + + class Status(object): + PENDING_REVIEW = "PENDING_REVIEW" + IN_REVIEW = "IN_REVIEW" + TWILIO_APPROVED = "TWILIO_APPROVED" + TWILIO_REJECTED = "TWILIO_REJECTED" + + """ + :ivar sid: The unique string to identify Tollfree Verification. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Tollfree Verification resource. + :ivar customer_profile_sid: Customer's Profile Bundle BundleSid. + :ivar trust_product_sid: Tollfree TrustProduct Bundle BundleSid. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar regulated_item_sid: The SID of the Regulated Item. + :ivar business_name: The name of the business or organization using the Tollfree number. + :ivar business_street_address: The address of the business or organization using the Tollfree number. + :ivar business_street_address2: The address of the business or organization using the Tollfree number. + :ivar business_city: The city of the business or organization using the Tollfree number. + :ivar business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :ivar business_postal_code: The postal code of the business or organization using the Tollfree number. + :ivar business_country: The country of the business or organization using the Tollfree number. + :ivar business_website: The website of the business or organization using the Tollfree number. + :ivar business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :ivar business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :ivar business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :ivar business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. + :ivar notification_email: The email address to receive the notification about the verification result. . + :ivar use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :ivar use_case_summary: Use this to further explain how messaging is used by the business or organization. + :ivar production_message_sample: An example of message content, i.e. a sample message. + :ivar opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :ivar opt_in_type: + :ivar message_volume: Estimate monthly volume of messages from the Tollfree Number. + :ivar additional_information: Additional information to be provided for verification. + :ivar tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :ivar status: + :ivar url: The absolute URL of the Tollfree Verification resource. + :ivar rejection_reason: The rejection reason given when a Tollfree Verification has been rejected. + :ivar error_code: The error code given when a Tollfree Verification has been rejected. + :ivar edit_expiration: The date and time when the ability to edit a rejected verification expires. + :ivar edit_allowed: If a rejected verification is allowed to be edited/resubmitted. Some rejection reasons allow editing and some do not. + :ivar rejection_reasons: A list of rejection reasons and codes describing why a Tollfree Verification has been rejected. + :ivar resource_links: The URLs of the documents associated with the Tollfree Verification resource. + :ivar external_reference_id: An optional external reference ID supplied by customer and echoed back on status retrieval. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.customer_profile_sid: Optional[str] = payload.get("customer_profile_sid") + self.trust_product_sid: Optional[str] = payload.get("trust_product_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.regulated_item_sid: Optional[str] = payload.get("regulated_item_sid") + self.business_name: Optional[str] = payload.get("business_name") + self.business_street_address: Optional[str] = payload.get( + "business_street_address" + ) + self.business_street_address2: Optional[str] = payload.get( + "business_street_address2" + ) + self.business_city: Optional[str] = payload.get("business_city") + self.business_state_province_region: Optional[str] = payload.get( + "business_state_province_region" + ) + self.business_postal_code: Optional[str] = payload.get("business_postal_code") + self.business_country: Optional[str] = payload.get("business_country") + self.business_website: Optional[str] = payload.get("business_website") + self.business_contact_first_name: Optional[str] = payload.get( + "business_contact_first_name" + ) + self.business_contact_last_name: Optional[str] = payload.get( + "business_contact_last_name" + ) + self.business_contact_email: Optional[str] = payload.get( + "business_contact_email" + ) + self.business_contact_phone: Optional[str] = payload.get( + "business_contact_phone" + ) + self.notification_email: Optional[str] = payload.get("notification_email") + self.use_case_categories: Optional[List[str]] = payload.get( + "use_case_categories" + ) + self.use_case_summary: Optional[str] = payload.get("use_case_summary") + self.production_message_sample: Optional[str] = payload.get( + "production_message_sample" + ) + self.opt_in_image_urls: Optional[List[str]] = payload.get("opt_in_image_urls") + self.opt_in_type: Optional["TollfreeVerificationInstance.OptInType"] = ( + payload.get("opt_in_type") + ) + self.message_volume: Optional[str] = payload.get("message_volume") + self.additional_information: Optional[str] = payload.get( + "additional_information" + ) + self.tollfree_phone_number_sid: Optional[str] = payload.get( + "tollfree_phone_number_sid" + ) + self.status: Optional["TollfreeVerificationInstance.Status"] = payload.get( + "status" + ) + self.url: Optional[str] = payload.get("url") + self.rejection_reason: Optional[str] = payload.get("rejection_reason") + self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) + self.edit_expiration: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("edit_expiration") + ) + self.edit_allowed: Optional[bool] = payload.get("edit_allowed") + self.rejection_reasons: Optional[List[Dict[str, object]]] = payload.get( + "rejection_reasons" + ) + self.resource_links: Optional[Dict[str, object]] = payload.get("resource_links") + self.external_reference_id: Optional[str] = payload.get("external_reference_id") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[TollfreeVerificationContext] = None + + @property + def _proxy(self) -> "TollfreeVerificationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TollfreeVerificationContext for this TollfreeVerificationInstance + """ + if self._context is None: + self._context = TollfreeVerificationContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TollfreeVerificationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TollfreeVerificationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "TollfreeVerificationInstance": + """ + Fetch the TollfreeVerificationInstance + + + :returns: The fetched TollfreeVerificationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TollfreeVerificationInstance": + """ + Asynchronous coroutine to fetch the TollfreeVerificationInstance + + + :returns: The fetched TollfreeVerificationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "TollfreeVerificationInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + edit_reason: Union[str, object] = values.unset, + ) -> "TollfreeVerificationInstance": + """ + Update the TollfreeVerificationInstance + + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param notification_email: The email address to receive the notification about the verification result. . + :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. + :param edit_reason: Describe why the verification is being edited. If the verification was rejected because of a technical issue, such as the website being down, and the issue has been resolved this parameter should be set to something similar to 'Website fixed'. + + :returns: The updated TollfreeVerificationInstance + """ + return self._proxy.update( + business_name=business_name, + business_website=business_website, + notification_email=notification_email, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + edit_reason=edit_reason, + ) + + async def update_async( + self, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "TollfreeVerificationInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + edit_reason: Union[str, object] = values.unset, + ) -> "TollfreeVerificationInstance": + """ + Asynchronous coroutine to update the TollfreeVerificationInstance + + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param notification_email: The email address to receive the notification about the verification result. . + :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. + :param edit_reason: Describe why the verification is being edited. If the verification was rejected because of a technical issue, such as the website being down, and the issue has been resolved this parameter should be set to something similar to 'Website fixed'. + + :returns: The updated TollfreeVerificationInstance + """ + return await self._proxy.update_async( + business_name=business_name, + business_website=business_website, + notification_email=notification_email, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + edit_reason=edit_reason, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TollfreeVerificationContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the TollfreeVerificationContext + + :param version: Version that contains the resource + :param sid: The unique string to identify Tollfree Verification. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Tollfree/Verifications/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the TollfreeVerificationInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TollfreeVerificationInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TollfreeVerificationInstance: + """ + Fetch the TollfreeVerificationInstance + + + :returns: The fetched TollfreeVerificationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TollfreeVerificationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TollfreeVerificationInstance: + """ + Asynchronous coroutine to fetch the TollfreeVerificationInstance + + + :returns: The fetched TollfreeVerificationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TollfreeVerificationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "TollfreeVerificationInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + edit_reason: Union[str, object] = values.unset, + ) -> TollfreeVerificationInstance: + """ + Update the TollfreeVerificationInstance + + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param notification_email: The email address to receive the notification about the verification result. . + :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. + :param edit_reason: Describe why the verification is being edited. If the verification was rejected because of a technical issue, such as the website being down, and the issue has been resolved this parameter should be set to something similar to 'Website fixed'. + + :returns: The updated TollfreeVerificationInstance + """ + + data = values.of( + { + "BusinessName": business_name, + "BusinessWebsite": business_website, + "NotificationEmail": notification_email, + "UseCaseCategories": serialize.map(use_case_categories, lambda e: e), + "UseCaseSummary": use_case_summary, + "ProductionMessageSample": production_message_sample, + "OptInImageUrls": serialize.map(opt_in_image_urls, lambda e: e), + "OptInType": opt_in_type, + "MessageVolume": message_volume, + "BusinessStreetAddress": business_street_address, + "BusinessStreetAddress2": business_street_address2, + "BusinessCity": business_city, + "BusinessStateProvinceRegion": business_state_province_region, + "BusinessPostalCode": business_postal_code, + "BusinessCountry": business_country, + "AdditionalInformation": additional_information, + "BusinessContactFirstName": business_contact_first_name, + "BusinessContactLastName": business_contact_last_name, + "BusinessContactEmail": business_contact_email, + "BusinessContactPhone": business_contact_phone, + "EditReason": edit_reason, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TollfreeVerificationInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "TollfreeVerificationInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + edit_reason: Union[str, object] = values.unset, + ) -> TollfreeVerificationInstance: + """ + Asynchronous coroutine to update the TollfreeVerificationInstance + + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param notification_email: The email address to receive the notification about the verification result. . + :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. + :param edit_reason: Describe why the verification is being edited. If the verification was rejected because of a technical issue, such as the website being down, and the issue has been resolved this parameter should be set to something similar to 'Website fixed'. + + :returns: The updated TollfreeVerificationInstance + """ + + data = values.of( + { + "BusinessName": business_name, + "BusinessWebsite": business_website, + "NotificationEmail": notification_email, + "UseCaseCategories": serialize.map(use_case_categories, lambda e: e), + "UseCaseSummary": use_case_summary, + "ProductionMessageSample": production_message_sample, + "OptInImageUrls": serialize.map(opt_in_image_urls, lambda e: e), + "OptInType": opt_in_type, + "MessageVolume": message_volume, + "BusinessStreetAddress": business_street_address, + "BusinessStreetAddress2": business_street_address2, + "BusinessCity": business_city, + "BusinessStateProvinceRegion": business_state_province_region, + "BusinessPostalCode": business_postal_code, + "BusinessCountry": business_country, + "AdditionalInformation": additional_information, + "BusinessContactFirstName": business_contact_first_name, + "BusinessContactLastName": business_contact_last_name, + "BusinessContactEmail": business_contact_email, + "BusinessContactPhone": business_contact_phone, + "EditReason": edit_reason, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TollfreeVerificationInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TollfreeVerificationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TollfreeVerificationInstance: + """ + Build an instance of TollfreeVerificationInstance + + :param payload: Payload response from the API + """ + return TollfreeVerificationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TollfreeVerificationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TollfreeVerificationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Tollfree/Verifications" + + def create( + self, + business_name: str, + business_website: str, + notification_email: str, + use_case_categories: List[str], + use_case_summary: str, + production_message_sample: str, + opt_in_image_urls: List[str], + opt_in_type: "TollfreeVerificationInstance.OptInType", + message_volume: str, + tollfree_phone_number_sid: str, + customer_profile_sid: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + ) -> TollfreeVerificationInstance: + """ + Create the TollfreeVerificationInstance + + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param notification_email: The email address to receive the notification about the verification result. . + :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param customer_profile_sid: Customer's Profile Bundle BundleSid. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. + :param external_reference_id: An optional external reference ID supplied by customer and echoed back on status retrieval. + + :returns: The created TollfreeVerificationInstance + """ + + data = values.of( + { + "BusinessName": business_name, + "BusinessWebsite": business_website, + "NotificationEmail": notification_email, + "UseCaseCategories": serialize.map(use_case_categories, lambda e: e), + "UseCaseSummary": use_case_summary, + "ProductionMessageSample": production_message_sample, + "OptInImageUrls": serialize.map(opt_in_image_urls, lambda e: e), + "OptInType": opt_in_type, + "MessageVolume": message_volume, + "TollfreePhoneNumberSid": tollfree_phone_number_sid, + "CustomerProfileSid": customer_profile_sid, + "BusinessStreetAddress": business_street_address, + "BusinessStreetAddress2": business_street_address2, + "BusinessCity": business_city, + "BusinessStateProvinceRegion": business_state_province_region, + "BusinessPostalCode": business_postal_code, + "BusinessCountry": business_country, + "AdditionalInformation": additional_information, + "BusinessContactFirstName": business_contact_first_name, + "BusinessContactLastName": business_contact_last_name, + "BusinessContactEmail": business_contact_email, + "BusinessContactPhone": business_contact_phone, + "ExternalReferenceId": external_reference_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TollfreeVerificationInstance(self._version, payload) + + async def create_async( + self, + business_name: str, + business_website: str, + notification_email: str, + use_case_categories: List[str], + use_case_summary: str, + production_message_sample: str, + opt_in_image_urls: List[str], + opt_in_type: "TollfreeVerificationInstance.OptInType", + message_volume: str, + tollfree_phone_number_sid: str, + customer_profile_sid: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + ) -> TollfreeVerificationInstance: + """ + Asynchronously create the TollfreeVerificationInstance + + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param notification_email: The email address to receive the notification about the verification result. . + :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param customer_profile_sid: Customer's Profile Bundle BundleSid. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. + :param external_reference_id: An optional external reference ID supplied by customer and echoed back on status retrieval. + + :returns: The created TollfreeVerificationInstance + """ + + data = values.of( + { + "BusinessName": business_name, + "BusinessWebsite": business_website, + "NotificationEmail": notification_email, + "UseCaseCategories": serialize.map(use_case_categories, lambda e: e), + "UseCaseSummary": use_case_summary, + "ProductionMessageSample": production_message_sample, + "OptInImageUrls": serialize.map(opt_in_image_urls, lambda e: e), + "OptInType": opt_in_type, + "MessageVolume": message_volume, + "TollfreePhoneNumberSid": tollfree_phone_number_sid, + "CustomerProfileSid": customer_profile_sid, + "BusinessStreetAddress": business_street_address, + "BusinessStreetAddress2": business_street_address2, + "BusinessCity": business_city, + "BusinessStateProvinceRegion": business_state_province_region, + "BusinessPostalCode": business_postal_code, + "BusinessCountry": business_country, + "AdditionalInformation": additional_information, + "BusinessContactFirstName": business_contact_first_name, + "BusinessContactLastName": business_contact_last_name, + "BusinessContactEmail": business_contact_email, + "BusinessContactPhone": business_contact_phone, + "ExternalReferenceId": external_reference_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TollfreeVerificationInstance(self._version, payload) + + def stream( + self, + tollfree_phone_number_sid: Union[str, object] = values.unset, + status: Union["TollfreeVerificationInstance.Status", object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + include_sub_accounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TollfreeVerificationInstance]: + """ + Streams TollfreeVerificationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param "TollfreeVerificationInstance.Status" status: The compliance status of the Tollfree Verification record. + :param str external_reference_id: Customer supplied reference id for the Tollfree Verification record. + :param bool include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + tollfree_phone_number_sid=tollfree_phone_number_sid, + status=status, + external_reference_id=external_reference_id, + include_sub_accounts=include_sub_accounts, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + tollfree_phone_number_sid: Union[str, object] = values.unset, + status: Union["TollfreeVerificationInstance.Status", object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + include_sub_accounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TollfreeVerificationInstance]: + """ + Asynchronously streams TollfreeVerificationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param "TollfreeVerificationInstance.Status" status: The compliance status of the Tollfree Verification record. + :param str external_reference_id: Customer supplied reference id for the Tollfree Verification record. + :param bool include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + tollfree_phone_number_sid=tollfree_phone_number_sid, + status=status, + external_reference_id=external_reference_id, + include_sub_accounts=include_sub_accounts, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + tollfree_phone_number_sid: Union[str, object] = values.unset, + status: Union["TollfreeVerificationInstance.Status", object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + include_sub_accounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TollfreeVerificationInstance]: + """ + Lists TollfreeVerificationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param "TollfreeVerificationInstance.Status" status: The compliance status of the Tollfree Verification record. + :param str external_reference_id: Customer supplied reference id for the Tollfree Verification record. + :param bool include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + tollfree_phone_number_sid=tollfree_phone_number_sid, + status=status, + external_reference_id=external_reference_id, + include_sub_accounts=include_sub_accounts, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + tollfree_phone_number_sid: Union[str, object] = values.unset, + status: Union["TollfreeVerificationInstance.Status", object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + include_sub_accounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TollfreeVerificationInstance]: + """ + Asynchronously lists TollfreeVerificationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param "TollfreeVerificationInstance.Status" status: The compliance status of the Tollfree Verification record. + :param str external_reference_id: Customer supplied reference id for the Tollfree Verification record. + :param bool include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + tollfree_phone_number_sid=tollfree_phone_number_sid, + status=status, + external_reference_id=external_reference_id, + include_sub_accounts=include_sub_accounts, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + tollfree_phone_number_sid: Union[str, object] = values.unset, + status: Union["TollfreeVerificationInstance.Status", object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + include_sub_accounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TollfreeVerificationPage: + """ + Retrieve a single page of TollfreeVerificationInstance records from the API. + Request is executed immediately + + :param tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param status: The compliance status of the Tollfree Verification record. + :param external_reference_id: Customer supplied reference id for the Tollfree Verification record. + :param include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TollfreeVerificationInstance + """ + data = values.of( + { + "TollfreePhoneNumberSid": tollfree_phone_number_sid, + "Status": status, + "ExternalReferenceId": external_reference_id, + "IncludeSubAccounts": serialize.boolean_to_string(include_sub_accounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TollfreeVerificationPage(self._version, response) + + async def page_async( + self, + tollfree_phone_number_sid: Union[str, object] = values.unset, + status: Union["TollfreeVerificationInstance.Status", object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + include_sub_accounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TollfreeVerificationPage: + """ + Asynchronously retrieve a single page of TollfreeVerificationInstance records from the API. + Request is executed immediately + + :param tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param status: The compliance status of the Tollfree Verification record. + :param external_reference_id: Customer supplied reference id for the Tollfree Verification record. + :param include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TollfreeVerificationInstance + """ + data = values.of( + { + "TollfreePhoneNumberSid": tollfree_phone_number_sid, + "Status": status, + "ExternalReferenceId": external_reference_id, + "IncludeSubAccounts": serialize.boolean_to_string(include_sub_accounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TollfreeVerificationPage(self._version, response) + + def get_page(self, target_url: str) -> TollfreeVerificationPage: + """ + Retrieve a specific page of TollfreeVerificationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TollfreeVerificationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TollfreeVerificationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> TollfreeVerificationPage: + """ + Asynchronously retrieve a specific page of TollfreeVerificationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TollfreeVerificationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TollfreeVerificationPage(self._version, response) + + def get(self, sid: str) -> TollfreeVerificationContext: + """ + Constructs a TollfreeVerificationContext + + :param sid: The unique string to identify Tollfree Verification. + """ + return TollfreeVerificationContext(self._version, sid=sid) + + def __call__(self, sid: str) -> TollfreeVerificationContext: + """ + Constructs a TollfreeVerificationContext + + :param sid: The unique string to identify Tollfree Verification. + """ + return TollfreeVerificationContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v1/usecase.py b/venv/Lib/site-packages/twilio/rest/messaging/v1/usecase.py new file mode 100644 index 00000000..fe811e0c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/v1/usecase.py @@ -0,0 +1,94 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class UsecaseInstance(InstanceResource): + """ + :ivar usecases: Human readable use case details (usecase, description and purpose) of Messaging Service Use Cases. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.usecases: Optional[List[Dict[str, object]]] = payload.get("usecases") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class UsecaseList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the UsecaseList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services/Usecases" + + def fetch(self) -> UsecaseInstance: + """ + Asynchronously fetch the UsecaseInstance + + + :returns: The fetched UsecaseInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UsecaseInstance(self._version, payload) + + async def fetch_async(self) -> UsecaseInstance: + """ + Asynchronously fetch the UsecaseInstance + + + :returns: The fetched UsecaseInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UsecaseInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v2/__init__.py b/venv/Lib/site-packages/twilio/rest/messaging/v2/__init__.py new file mode 100644 index 00000000..7ef89fdc --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/v2/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.messaging.v2.channels_sender import ChannelsSenderList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Messaging + + :param domain: The Twilio.messaging domain + """ + super().__init__(domain, "v2") + self._channels_senders: Optional[ChannelsSenderList] = None + + @property + def channels_senders(self) -> ChannelsSenderList: + if self._channels_senders is None: + self._channels_senders = ChannelsSenderList(self) + return self._channels_senders + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v2/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/v2/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..147f9841 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/v2/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v2/__pycache__/channels_sender.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/messaging/v2/__pycache__/channels_sender.cpython-312.pyc new file mode 100644 index 00000000..daded122 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/messaging/v2/__pycache__/channels_sender.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/messaging/v2/channels_sender.py b/venv/Lib/site-packages/twilio/rest/messaging/v2/channels_sender.py new file mode 100644 index 00000000..a6e4252d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/messaging/v2/channels_sender.py @@ -0,0 +1,1104 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ChannelsSenderInstance(InstanceResource): + + class MessagingV2ChannelsSenderConfiguration(object): + """ + :ivar waba_id: The ID of the WhatsApp Business Account to use for this sender. + :ivar verification_method: The method to use for verification. Either \"sms\" or \"voice\". + :ivar verification_code: The verification code to use for this sender. + :ivar voice_application_sid: The SID of the Twilio Voice application to use for this sender. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.waba_id: Optional[str] = payload.get("waba_id") + self.verification_method: Optional["ChannelsSenderInstance.str"] = ( + payload.get("verification_method") + ) + self.verification_code: Optional[str] = payload.get("verification_code") + self.voice_application_sid: Optional[str] = payload.get( + "voice_application_sid" + ) + + def to_dict(self): + return { + "waba_id": self.waba_id, + "verification_method": self.verification_method, + "verification_code": self.verification_code, + "voice_application_sid": self.voice_application_sid, + } + + class MessagingV2ChannelsSenderProfile(object): + """ + :ivar name: The name of the sender. + :ivar about: The about text of the sender. + :ivar address: The address of the sender. + :ivar description: The description of the sender. + :ivar emails: The emails of the sender. + :ivar logo_url: The logo URL of the sender. + :ivar vertical: The vertical of the sender. Allowed values are: - \"Automotive\" - \"Beauty, Spa and Salon\" - \"Clothing and Apparel\" - \"Education\" - \"Entertainment\" - \"Event Planning and Service\" - \"Finance and Banking\" - \"Food and Grocery\" - \"Public Service\" - \"Hotel and Lodging\" - \"Medical and Health\" - \"Non-profit\" - \"Professional Services\" - \"Shopping and Retail\" - \"Travel and Transportation\" - \"Restaurant\" - \"Other\" + :ivar websites: The websites of the sender. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.about: Optional[str] = payload.get("about") + self.address: Optional[str] = payload.get("address") + self.description: Optional[str] = payload.get("description") + self.emails: Optional[Dict[str, object]] = payload.get("emails") + self.logo_url: Optional[str] = payload.get("logo_url") + self.vertical: Optional[str] = payload.get("vertical") + self.websites: Optional[Dict[str, object]] = payload.get("websites") + + def to_dict(self): + return { + "name": self.name, + "about": self.about, + "address": self.address, + "description": self.description, + "emails": self.emails, + "logo_url": self.logo_url, + "vertical": self.vertical, + "websites": self.websites, + } + + class MessagingV2ChannelsSenderRequestsCreate(object): + """ + :ivar sender_id: The ID of this Sender prefixed with the channel, e.g., `whatsapp:E.164` + :ivar configuration: + :ivar webhook: + :ivar profile: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.sender_id: Optional[str] = payload.get("sender_id") + self.configuration: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderConfiguration + ] = payload.get("configuration") + self.webhook: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderWebhook + ] = payload.get("webhook") + self.profile: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderProfile + ] = payload.get("profile") + + def to_dict(self): + return { + "sender_id": self.sender_id, + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + "webhook": self.webhook.to_dict() if self.webhook is not None else None, + "profile": self.profile.to_dict() if self.profile is not None else None, + } + + class MessagingV2ChannelsSenderRequestsUpdate(object): + """ + :ivar configuration: + :ivar webhook: + :ivar profile: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.configuration: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderConfiguration + ] = payload.get("configuration") + self.webhook: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderWebhook + ] = payload.get("webhook") + self.profile: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderProfile + ] = payload.get("profile") + + def to_dict(self): + return { + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + "webhook": self.webhook.to_dict() if self.webhook is not None else None, + "profile": self.profile.to_dict() if self.profile is not None else None, + } + + class MessagingV2ChannelsSenderWebhook(object): + """ + :ivar callback_url: The URL to send the webhook to. + :ivar callback_method: The HTTP method to use for the webhook. Either \"POST\" or \"PUT\". + :ivar fallback_url: The URL to send the fallback webhook to. + :ivar fallback_method: The HTTP method to use for the fallback webhook. Either \"POST\" or \"PUT\". + :ivar status_callback_url: The URL to send the status callback to. + :ivar status_callback_method: The HTTP method to use for the status callback. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.callback_url: Optional[str] = payload.get("callback_url") + self.callback_method: Optional["ChannelsSenderInstance.str"] = payload.get( + "callback_method" + ) + self.fallback_url: Optional[str] = payload.get("fallback_url") + self.fallback_method: Optional["ChannelsSenderInstance.str"] = payload.get( + "fallback_method" + ) + self.status_callback_url: Optional[str] = payload.get("status_callback_url") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + + def to_dict(self): + return { + "callback_url": self.callback_url, + "callback_method": self.callback_method, + "fallback_url": self.fallback_url, + "fallback_method": self.fallback_method, + "status_callback_url": self.status_callback_url, + "status_callback_method": self.status_callback_method, + } + + class Status(object): + CREATING = "CREATING" + ONLINE = "ONLINE" + OFFLINE = "OFFLINE" + PENDING_VERIFICATION = "PENDING_VERIFICATION" + VERIFYING = "VERIFYING" + ONLINE_UPDATING = "ONLINE:UPDATING" + STUBBED = "STUBBED" + + """ + :ivar sid: A 34 character string that uniquely identifies this Sender. + :ivar status: + :ivar sender_id: The ID of this Sender prefixed with the channel, e.g., `whatsapp:E.164` + :ivar configuration: + :ivar webhook: + :ivar profile: + :ivar properties: + :ivar offline_reasons: Reasons why the sender is offline., e.g., [{\"code\": \"21211400\", \"message\": \"Whatsapp business account is banned by provider {provider_name} | Credit line is assigned to another BSP\", \"more_info\": \"https://www.twilio.com/docs/errors/21211400\"}] + :ivar url: The URL of this resource, relative to `https://messaging.twilio.com`. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.status: Optional["ChannelsSenderInstance.Status"] = payload.get("status") + self.sender_id: Optional[str] = payload.get("sender_id") + self.configuration: Optional[str] = payload.get("configuration") + self.webhook: Optional[str] = payload.get("webhook") + self.profile: Optional[str] = payload.get("profile") + self.properties: Optional[str] = payload.get("properties") + self.offline_reasons: Optional[List[str]] = payload.get("offline_reasons") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ChannelsSenderContext] = None + + @property + def _proxy(self) -> "ChannelsSenderContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ChannelsSenderContext for this ChannelsSenderInstance + """ + if self._context is None: + self._context = ChannelsSenderContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ChannelsSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelsSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ChannelsSenderInstance": + """ + Fetch the ChannelsSenderInstance + + + :returns: The fetched ChannelsSenderInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ChannelsSenderInstance": + """ + Asynchronous coroutine to fetch the ChannelsSenderInstance + + + :returns: The fetched ChannelsSenderInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + messaging_v2_channels_sender_requests_update: Union[ + MessagingV2ChannelsSenderRequestsUpdate, object + ] = values.unset, + ) -> "ChannelsSenderInstance": + """ + Update the ChannelsSenderInstance + + :param messaging_v2_channels_sender_requests_update: + + :returns: The updated ChannelsSenderInstance + """ + return self._proxy.update( + messaging_v2_channels_sender_requests_update=messaging_v2_channels_sender_requests_update, + ) + + async def update_async( + self, + messaging_v2_channels_sender_requests_update: Union[ + MessagingV2ChannelsSenderRequestsUpdate, object + ] = values.unset, + ) -> "ChannelsSenderInstance": + """ + Asynchronous coroutine to update the ChannelsSenderInstance + + :param messaging_v2_channels_sender_requests_update: + + :returns: The updated ChannelsSenderInstance + """ + return await self._proxy.update_async( + messaging_v2_channels_sender_requests_update=messaging_v2_channels_sender_requests_update, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ChannelsSenderContext(InstanceContext): + + class MessagingV2ChannelsSenderConfiguration(object): + """ + :ivar waba_id: The ID of the WhatsApp Business Account to use for this sender. + :ivar verification_method: The method to use for verification. Either \"sms\" or \"voice\". + :ivar verification_code: The verification code to use for this sender. + :ivar voice_application_sid: The SID of the Twilio Voice application to use for this sender. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.waba_id: Optional[str] = payload.get("waba_id") + self.verification_method: Optional["ChannelsSenderInstance.str"] = ( + payload.get("verification_method") + ) + self.verification_code: Optional[str] = payload.get("verification_code") + self.voice_application_sid: Optional[str] = payload.get( + "voice_application_sid" + ) + + def to_dict(self): + return { + "waba_id": self.waba_id, + "verification_method": self.verification_method, + "verification_code": self.verification_code, + "voice_application_sid": self.voice_application_sid, + } + + class MessagingV2ChannelsSenderProfile(object): + """ + :ivar name: The name of the sender. + :ivar about: The about text of the sender. + :ivar address: The address of the sender. + :ivar description: The description of the sender. + :ivar emails: The emails of the sender. + :ivar logo_url: The logo URL of the sender. + :ivar vertical: The vertical of the sender. Allowed values are: - \"Automotive\" - \"Beauty, Spa and Salon\" - \"Clothing and Apparel\" - \"Education\" - \"Entertainment\" - \"Event Planning and Service\" - \"Finance and Banking\" - \"Food and Grocery\" - \"Public Service\" - \"Hotel and Lodging\" - \"Medical and Health\" - \"Non-profit\" - \"Professional Services\" - \"Shopping and Retail\" - \"Travel and Transportation\" - \"Restaurant\" - \"Other\" + :ivar websites: The websites of the sender. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.about: Optional[str] = payload.get("about") + self.address: Optional[str] = payload.get("address") + self.description: Optional[str] = payload.get("description") + self.emails: Optional[Dict[str, object]] = payload.get("emails") + self.logo_url: Optional[str] = payload.get("logo_url") + self.vertical: Optional[str] = payload.get("vertical") + self.websites: Optional[Dict[str, object]] = payload.get("websites") + + def to_dict(self): + return { + "name": self.name, + "about": self.about, + "address": self.address, + "description": self.description, + "emails": self.emails, + "logo_url": self.logo_url, + "vertical": self.vertical, + "websites": self.websites, + } + + class MessagingV2ChannelsSenderRequestsCreate(object): + """ + :ivar sender_id: The ID of this Sender prefixed with the channel, e.g., `whatsapp:E.164` + :ivar configuration: + :ivar webhook: + :ivar profile: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.sender_id: Optional[str] = payload.get("sender_id") + self.configuration: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderConfiguration + ] = payload.get("configuration") + self.webhook: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderWebhook + ] = payload.get("webhook") + self.profile: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderProfile + ] = payload.get("profile") + + def to_dict(self): + return { + "sender_id": self.sender_id, + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + "webhook": self.webhook.to_dict() if self.webhook is not None else None, + "profile": self.profile.to_dict() if self.profile is not None else None, + } + + class MessagingV2ChannelsSenderRequestsUpdate(object): + """ + :ivar configuration: + :ivar webhook: + :ivar profile: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.configuration: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderConfiguration + ] = payload.get("configuration") + self.webhook: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderWebhook + ] = payload.get("webhook") + self.profile: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderProfile + ] = payload.get("profile") + + def to_dict(self): + return { + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + "webhook": self.webhook.to_dict() if self.webhook is not None else None, + "profile": self.profile.to_dict() if self.profile is not None else None, + } + + class MessagingV2ChannelsSenderWebhook(object): + """ + :ivar callback_url: The URL to send the webhook to. + :ivar callback_method: The HTTP method to use for the webhook. Either \"POST\" or \"PUT\". + :ivar fallback_url: The URL to send the fallback webhook to. + :ivar fallback_method: The HTTP method to use for the fallback webhook. Either \"POST\" or \"PUT\". + :ivar status_callback_url: The URL to send the status callback to. + :ivar status_callback_method: The HTTP method to use for the status callback. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.callback_url: Optional[str] = payload.get("callback_url") + self.callback_method: Optional["ChannelsSenderInstance.str"] = payload.get( + "callback_method" + ) + self.fallback_url: Optional[str] = payload.get("fallback_url") + self.fallback_method: Optional["ChannelsSenderInstance.str"] = payload.get( + "fallback_method" + ) + self.status_callback_url: Optional[str] = payload.get("status_callback_url") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + + def to_dict(self): + return { + "callback_url": self.callback_url, + "callback_method": self.callback_method, + "fallback_url": self.fallback_url, + "fallback_method": self.fallback_method, + "status_callback_url": self.status_callback_url, + "status_callback_method": self.status_callback_method, + } + + def __init__(self, version: Version, sid: str): + """ + Initialize the ChannelsSenderContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this Sender. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Channels/Senders/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the ChannelsSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelsSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChannelsSenderInstance: + """ + Fetch the ChannelsSenderInstance + + + :returns: The fetched ChannelsSenderInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ChannelsSenderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ChannelsSenderInstance: + """ + Asynchronous coroutine to fetch the ChannelsSenderInstance + + + :returns: The fetched ChannelsSenderInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ChannelsSenderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + messaging_v2_channels_sender_requests_update: Union[ + MessagingV2ChannelsSenderRequestsUpdate, object + ] = values.unset, + ) -> ChannelsSenderInstance: + """ + Update the ChannelsSenderInstance + + :param messaging_v2_channels_sender_requests_update: + + :returns: The updated ChannelsSenderInstance + """ + data = messaging_v2_channels_sender_requests_update.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelsSenderInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + messaging_v2_channels_sender_requests_update: Union[ + MessagingV2ChannelsSenderRequestsUpdate, object + ] = values.unset, + ) -> ChannelsSenderInstance: + """ + Asynchronous coroutine to update the ChannelsSenderInstance + + :param messaging_v2_channels_sender_requests_update: + + :returns: The updated ChannelsSenderInstance + """ + data = messaging_v2_channels_sender_requests_update.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelsSenderInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ChannelsSenderPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ChannelsSenderInstance: + """ + Build an instance of ChannelsSenderInstance + + :param payload: Payload response from the API + """ + return ChannelsSenderInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ChannelsSenderList(ListResource): + + class MessagingV2ChannelsSenderConfiguration(object): + """ + :ivar waba_id: The ID of the WhatsApp Business Account to use for this sender. + :ivar verification_method: The method to use for verification. Either \"sms\" or \"voice\". + :ivar verification_code: The verification code to use for this sender. + :ivar voice_application_sid: The SID of the Twilio Voice application to use for this sender. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.waba_id: Optional[str] = payload.get("waba_id") + self.verification_method: Optional["ChannelsSenderInstance.str"] = ( + payload.get("verification_method") + ) + self.verification_code: Optional[str] = payload.get("verification_code") + self.voice_application_sid: Optional[str] = payload.get( + "voice_application_sid" + ) + + def to_dict(self): + return { + "waba_id": self.waba_id, + "verification_method": self.verification_method, + "verification_code": self.verification_code, + "voice_application_sid": self.voice_application_sid, + } + + class MessagingV2ChannelsSenderProfile(object): + """ + :ivar name: The name of the sender. + :ivar about: The about text of the sender. + :ivar address: The address of the sender. + :ivar description: The description of the sender. + :ivar emails: The emails of the sender. + :ivar logo_url: The logo URL of the sender. + :ivar vertical: The vertical of the sender. Allowed values are: - \"Automotive\" - \"Beauty, Spa and Salon\" - \"Clothing and Apparel\" - \"Education\" - \"Entertainment\" - \"Event Planning and Service\" - \"Finance and Banking\" - \"Food and Grocery\" - \"Public Service\" - \"Hotel and Lodging\" - \"Medical and Health\" - \"Non-profit\" - \"Professional Services\" - \"Shopping and Retail\" - \"Travel and Transportation\" - \"Restaurant\" - \"Other\" + :ivar websites: The websites of the sender. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.about: Optional[str] = payload.get("about") + self.address: Optional[str] = payload.get("address") + self.description: Optional[str] = payload.get("description") + self.emails: Optional[Dict[str, object]] = payload.get("emails") + self.logo_url: Optional[str] = payload.get("logo_url") + self.vertical: Optional[str] = payload.get("vertical") + self.websites: Optional[Dict[str, object]] = payload.get("websites") + + def to_dict(self): + return { + "name": self.name, + "about": self.about, + "address": self.address, + "description": self.description, + "emails": self.emails, + "logo_url": self.logo_url, + "vertical": self.vertical, + "websites": self.websites, + } + + class MessagingV2ChannelsSenderRequestsCreate(object): + """ + :ivar sender_id: The ID of this Sender prefixed with the channel, e.g., `whatsapp:E.164` + :ivar configuration: + :ivar webhook: + :ivar profile: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.sender_id: Optional[str] = payload.get("sender_id") + self.configuration: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderConfiguration + ] = payload.get("configuration") + self.webhook: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderWebhook + ] = payload.get("webhook") + self.profile: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderProfile + ] = payload.get("profile") + + def to_dict(self): + return { + "sender_id": self.sender_id, + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + "webhook": self.webhook.to_dict() if self.webhook is not None else None, + "profile": self.profile.to_dict() if self.profile is not None else None, + } + + class MessagingV2ChannelsSenderRequestsUpdate(object): + """ + :ivar configuration: + :ivar webhook: + :ivar profile: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.configuration: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderConfiguration + ] = payload.get("configuration") + self.webhook: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderWebhook + ] = payload.get("webhook") + self.profile: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderProfile + ] = payload.get("profile") + + def to_dict(self): + return { + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + "webhook": self.webhook.to_dict() if self.webhook is not None else None, + "profile": self.profile.to_dict() if self.profile is not None else None, + } + + class MessagingV2ChannelsSenderWebhook(object): + """ + :ivar callback_url: The URL to send the webhook to. + :ivar callback_method: The HTTP method to use for the webhook. Either \"POST\" or \"PUT\". + :ivar fallback_url: The URL to send the fallback webhook to. + :ivar fallback_method: The HTTP method to use for the fallback webhook. Either \"POST\" or \"PUT\". + :ivar status_callback_url: The URL to send the status callback to. + :ivar status_callback_method: The HTTP method to use for the status callback. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.callback_url: Optional[str] = payload.get("callback_url") + self.callback_method: Optional["ChannelsSenderInstance.str"] = payload.get( + "callback_method" + ) + self.fallback_url: Optional[str] = payload.get("fallback_url") + self.fallback_method: Optional["ChannelsSenderInstance.str"] = payload.get( + "fallback_method" + ) + self.status_callback_url: Optional[str] = payload.get("status_callback_url") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + + def to_dict(self): + return { + "callback_url": self.callback_url, + "callback_method": self.callback_method, + "fallback_url": self.fallback_url, + "fallback_method": self.fallback_method, + "status_callback_url": self.status_callback_url, + "status_callback_method": self.status_callback_method, + } + + def __init__(self, version: Version): + """ + Initialize the ChannelsSenderList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Channels/Senders" + + def create( + self, + messaging_v2_channels_sender_requests_create: MessagingV2ChannelsSenderRequestsCreate, + ) -> ChannelsSenderInstance: + """ + Create the ChannelsSenderInstance + + :param messaging_v2_channels_sender_requests_create: + + :returns: The created ChannelsSenderInstance + """ + data = messaging_v2_channels_sender_requests_create.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelsSenderInstance(self._version, payload) + + async def create_async( + self, + messaging_v2_channels_sender_requests_create: MessagingV2ChannelsSenderRequestsCreate, + ) -> ChannelsSenderInstance: + """ + Asynchronously create the ChannelsSenderInstance + + :param messaging_v2_channels_sender_requests_create: + + :returns: The created ChannelsSenderInstance + """ + data = messaging_v2_channels_sender_requests_create.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelsSenderInstance(self._version, payload) + + def stream( + self, + channel: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChannelsSenderInstance]: + """ + Streams ChannelsSenderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str channel: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(channel=channel, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + channel: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ChannelsSenderInstance]: + """ + Asynchronously streams ChannelsSenderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str channel: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(channel=channel, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + channel: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelsSenderInstance]: + """ + Lists ChannelsSenderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str channel: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + channel=channel, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + channel: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelsSenderInstance]: + """ + Asynchronously lists ChannelsSenderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str channel: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + channel=channel, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + channel: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelsSenderPage: + """ + Retrieve a single page of ChannelsSenderInstance records from the API. + Request is executed immediately + + :param channel: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelsSenderInstance + """ + data = values.of( + { + "Channel": channel, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelsSenderPage(self._version, response) + + async def page_async( + self, + channel: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelsSenderPage: + """ + Asynchronously retrieve a single page of ChannelsSenderInstance records from the API. + Request is executed immediately + + :param channel: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelsSenderInstance + """ + data = values.of( + { + "Channel": channel, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelsSenderPage(self._version, response) + + def get_page(self, target_url: str) -> ChannelsSenderPage: + """ + Retrieve a specific page of ChannelsSenderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelsSenderInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ChannelsSenderPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ChannelsSenderPage: + """ + Asynchronously retrieve a specific page of ChannelsSenderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelsSenderInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelsSenderPage(self._version, response) + + def get(self, sid: str) -> ChannelsSenderContext: + """ + Constructs a ChannelsSenderContext + + :param sid: A 34 character string that uniquely identifies this Sender. + """ + return ChannelsSenderContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ChannelsSenderContext: + """ + Constructs a ChannelsSenderContext + + :param sid: A 34 character string that uniquely identifies this Sender. + """ + return ChannelsSenderContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/microvisor/MicrovisorBase.py b/venv/Lib/site-packages/twilio/rest/microvisor/MicrovisorBase.py new file mode 100644 index 00000000..e8c874b9 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/microvisor/MicrovisorBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.microvisor.v1 import V1 + + +class MicrovisorBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Microvisor Domain + + :returns: Domain for Microvisor + """ + super().__init__(twilio, "https://microvisor.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Microvisor + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/microvisor/__init__.py b/venv/Lib/site-packages/twilio/rest/microvisor/__init__.py new file mode 100644 index 00000000..6bf448b2 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/microvisor/__init__.py @@ -0,0 +1,43 @@ +from warnings import warn + +from twilio.rest.microvisor.MicrovisorBase import MicrovisorBase +from twilio.rest.microvisor.v1.account_config import AccountConfigList +from twilio.rest.microvisor.v1.account_secret import AccountSecretList +from twilio.rest.microvisor.v1.app import AppList +from twilio.rest.microvisor.v1.device import DeviceList + + +class Microvisor(MicrovisorBase): + @property + def account_configs(self) -> AccountConfigList: + warn( + "account_configs is deprecated. Use v1.account_configs instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.account_configs + + @property + def account_secrets(self) -> AccountSecretList: + warn( + "account_secrets is deprecated. Use v1.account_secrets instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.account_secrets + + @property + def apps(self) -> AppList: + warn( + "apps is deprecated. Use v1.apps instead.", DeprecationWarning, stacklevel=2 + ) + return self.v1.apps + + @property + def devices(self) -> DeviceList: + warn( + "devices is deprecated. Use v1.devices instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.devices diff --git a/venv/Lib/site-packages/twilio/rest/microvisor/__pycache__/MicrovisorBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/microvisor/__pycache__/MicrovisorBase.cpython-312.pyc new file mode 100644 index 00000000..e678be0c Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/microvisor/__pycache__/MicrovisorBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/microvisor/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/microvisor/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..20abb9b8 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/microvisor/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/microvisor/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/microvisor/v1/__init__.py new file mode 100644 index 00000000..22010d62 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/microvisor/v1/__init__.py @@ -0,0 +1,67 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Microvisor + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.microvisor.v1.account_config import AccountConfigList +from twilio.rest.microvisor.v1.account_secret import AccountSecretList +from twilio.rest.microvisor.v1.app import AppList +from twilio.rest.microvisor.v1.device import DeviceList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Microvisor + + :param domain: The Twilio.microvisor domain + """ + super().__init__(domain, "v1") + self._account_configs: Optional[AccountConfigList] = None + self._account_secrets: Optional[AccountSecretList] = None + self._apps: Optional[AppList] = None + self._devices: Optional[DeviceList] = None + + @property + def account_configs(self) -> AccountConfigList: + if self._account_configs is None: + self._account_configs = AccountConfigList(self) + return self._account_configs + + @property + def account_secrets(self) -> AccountSecretList: + if self._account_secrets is None: + self._account_secrets = AccountSecretList(self) + return self._account_secrets + + @property + def apps(self) -> AppList: + if self._apps is None: + self._apps = AppList(self) + return self._apps + + @property + def devices(self) -> DeviceList: + if self._devices is None: + self._devices = DeviceList(self) + return self._devices + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/microvisor/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/microvisor/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..d18a434a Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/microvisor/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/microvisor/v1/__pycache__/account_config.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/microvisor/v1/__pycache__/account_config.cpython-312.pyc new file mode 100644 index 00000000..038cdd6a Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/microvisor/v1/__pycache__/account_config.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/microvisor/v1/__pycache__/account_secret.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/microvisor/v1/__pycache__/account_secret.cpython-312.pyc new file mode 100644 index 00000000..c7b36378 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/microvisor/v1/__pycache__/account_secret.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/microvisor/v1/account_config.py b/venv/Lib/site-packages/twilio/rest/microvisor/v1/account_config.py new file mode 100644 index 00000000..7faba8ac --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/microvisor/v1/account_config.py @@ -0,0 +1,585 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Microvisor + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AccountConfigInstance(InstanceResource): + """ + :ivar key: The config key; up to 100 characters. + :ivar date_updated: + :ivar value: The config value; up to 4096 characters. + :ivar url: The absolute URL of the Config. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], key: Optional[str] = None + ): + super().__init__(version) + + self.key: Optional[str] = payload.get("key") + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.value: Optional[str] = payload.get("value") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "key": key or self.key, + } + self._context: Optional[AccountConfigContext] = None + + @property + def _proxy(self) -> "AccountConfigContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AccountConfigContext for this AccountConfigInstance + """ + if self._context is None: + self._context = AccountConfigContext( + self._version, + key=self._solution["key"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AccountConfigInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AccountConfigInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AccountConfigInstance": + """ + Fetch the AccountConfigInstance + + + :returns: The fetched AccountConfigInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AccountConfigInstance": + """ + Asynchronous coroutine to fetch the AccountConfigInstance + + + :returns: The fetched AccountConfigInstance + """ + return await self._proxy.fetch_async() + + def update(self, value: str) -> "AccountConfigInstance": + """ + Update the AccountConfigInstance + + :param value: The config value; up to 4096 characters. + + :returns: The updated AccountConfigInstance + """ + return self._proxy.update( + value=value, + ) + + async def update_async(self, value: str) -> "AccountConfigInstance": + """ + Asynchronous coroutine to update the AccountConfigInstance + + :param value: The config value; up to 4096 characters. + + :returns: The updated AccountConfigInstance + """ + return await self._proxy.update_async( + value=value, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AccountConfigContext(InstanceContext): + + def __init__(self, version: Version, key: str): + """ + Initialize the AccountConfigContext + + :param version: Version that contains the resource + :param key: The config key; up to 100 characters. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "key": key, + } + self._uri = "/Configs/{key}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the AccountConfigInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AccountConfigInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AccountConfigInstance: + """ + Fetch the AccountConfigInstance + + + :returns: The fetched AccountConfigInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AccountConfigInstance( + self._version, + payload, + key=self._solution["key"], + ) + + async def fetch_async(self) -> AccountConfigInstance: + """ + Asynchronous coroutine to fetch the AccountConfigInstance + + + :returns: The fetched AccountConfigInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AccountConfigInstance( + self._version, + payload, + key=self._solution["key"], + ) + + def update(self, value: str) -> AccountConfigInstance: + """ + Update the AccountConfigInstance + + :param value: The config value; up to 4096 characters. + + :returns: The updated AccountConfigInstance + """ + + data = values.of( + { + "Value": value, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AccountConfigInstance(self._version, payload, key=self._solution["key"]) + + async def update_async(self, value: str) -> AccountConfigInstance: + """ + Asynchronous coroutine to update the AccountConfigInstance + + :param value: The config value; up to 4096 characters. + + :returns: The updated AccountConfigInstance + """ + + data = values.of( + { + "Value": value, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AccountConfigInstance(self._version, payload, key=self._solution["key"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AccountConfigPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AccountConfigInstance: + """ + Build an instance of AccountConfigInstance + + :param payload: Payload response from the API + """ + return AccountConfigInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AccountConfigList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AccountConfigList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Configs" + + def create(self, key: str, value: str) -> AccountConfigInstance: + """ + Create the AccountConfigInstance + + :param key: The config key; up to 100 characters. + :param value: The config value; up to 4096 characters. + + :returns: The created AccountConfigInstance + """ + + data = values.of( + { + "Key": key, + "Value": value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AccountConfigInstance(self._version, payload) + + async def create_async(self, key: str, value: str) -> AccountConfigInstance: + """ + Asynchronously create the AccountConfigInstance + + :param key: The config key; up to 100 characters. + :param value: The config value; up to 4096 characters. + + :returns: The created AccountConfigInstance + """ + + data = values.of( + { + "Key": key, + "Value": value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AccountConfigInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AccountConfigInstance]: + """ + Streams AccountConfigInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AccountConfigInstance]: + """ + Asynchronously streams AccountConfigInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AccountConfigInstance]: + """ + Lists AccountConfigInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AccountConfigInstance]: + """ + Asynchronously lists AccountConfigInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AccountConfigPage: + """ + Retrieve a single page of AccountConfigInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AccountConfigInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AccountConfigPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AccountConfigPage: + """ + Asynchronously retrieve a single page of AccountConfigInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AccountConfigInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AccountConfigPage(self._version, response) + + def get_page(self, target_url: str) -> AccountConfigPage: + """ + Retrieve a specific page of AccountConfigInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AccountConfigInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AccountConfigPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AccountConfigPage: + """ + Asynchronously retrieve a specific page of AccountConfigInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AccountConfigInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AccountConfigPage(self._version, response) + + def get(self, key: str) -> AccountConfigContext: + """ + Constructs a AccountConfigContext + + :param key: The config key; up to 100 characters. + """ + return AccountConfigContext(self._version, key=key) + + def __call__(self, key: str) -> AccountConfigContext: + """ + Constructs a AccountConfigContext + + :param key: The config key; up to 100 characters. + """ + return AccountConfigContext(self._version, key=key) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/microvisor/v1/account_secret.py b/venv/Lib/site-packages/twilio/rest/microvisor/v1/account_secret.py new file mode 100644 index 00000000..13ca961e --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/microvisor/v1/account_secret.py @@ -0,0 +1,583 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Microvisor + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AccountSecretInstance(InstanceResource): + """ + :ivar key: The secret key; up to 100 characters. + :ivar date_rotated: + :ivar url: The absolute URL of the Secret. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], key: Optional[str] = None + ): + super().__init__(version) + + self.key: Optional[str] = payload.get("key") + self.date_rotated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_rotated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "key": key or self.key, + } + self._context: Optional[AccountSecretContext] = None + + @property + def _proxy(self) -> "AccountSecretContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AccountSecretContext for this AccountSecretInstance + """ + if self._context is None: + self._context = AccountSecretContext( + self._version, + key=self._solution["key"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AccountSecretInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AccountSecretInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AccountSecretInstance": + """ + Fetch the AccountSecretInstance + + + :returns: The fetched AccountSecretInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AccountSecretInstance": + """ + Asynchronous coroutine to fetch the AccountSecretInstance + + + :returns: The fetched AccountSecretInstance + """ + return await self._proxy.fetch_async() + + def update(self, value: str) -> "AccountSecretInstance": + """ + Update the AccountSecretInstance + + :param value: The secret value; up to 4096 characters. + + :returns: The updated AccountSecretInstance + """ + return self._proxy.update( + value=value, + ) + + async def update_async(self, value: str) -> "AccountSecretInstance": + """ + Asynchronous coroutine to update the AccountSecretInstance + + :param value: The secret value; up to 4096 characters. + + :returns: The updated AccountSecretInstance + """ + return await self._proxy.update_async( + value=value, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AccountSecretContext(InstanceContext): + + def __init__(self, version: Version, key: str): + """ + Initialize the AccountSecretContext + + :param version: Version that contains the resource + :param key: The secret key; up to 100 characters. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "key": key, + } + self._uri = "/Secrets/{key}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the AccountSecretInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AccountSecretInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AccountSecretInstance: + """ + Fetch the AccountSecretInstance + + + :returns: The fetched AccountSecretInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AccountSecretInstance( + self._version, + payload, + key=self._solution["key"], + ) + + async def fetch_async(self) -> AccountSecretInstance: + """ + Asynchronous coroutine to fetch the AccountSecretInstance + + + :returns: The fetched AccountSecretInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AccountSecretInstance( + self._version, + payload, + key=self._solution["key"], + ) + + def update(self, value: str) -> AccountSecretInstance: + """ + Update the AccountSecretInstance + + :param value: The secret value; up to 4096 characters. + + :returns: The updated AccountSecretInstance + """ + + data = values.of( + { + "Value": value, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AccountSecretInstance(self._version, payload, key=self._solution["key"]) + + async def update_async(self, value: str) -> AccountSecretInstance: + """ + Asynchronous coroutine to update the AccountSecretInstance + + :param value: The secret value; up to 4096 characters. + + :returns: The updated AccountSecretInstance + """ + + data = values.of( + { + "Value": value, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AccountSecretInstance(self._version, payload, key=self._solution["key"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AccountSecretPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AccountSecretInstance: + """ + Build an instance of AccountSecretInstance + + :param payload: Payload response from the API + """ + return AccountSecretInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AccountSecretList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AccountSecretList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Secrets" + + def create(self, key: str, value: str) -> AccountSecretInstance: + """ + Create the AccountSecretInstance + + :param key: The secret key; up to 100 characters. + :param value: The secret value; up to 4096 characters. + + :returns: The created AccountSecretInstance + """ + + data = values.of( + { + "Key": key, + "Value": value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AccountSecretInstance(self._version, payload) + + async def create_async(self, key: str, value: str) -> AccountSecretInstance: + """ + Asynchronously create the AccountSecretInstance + + :param key: The secret key; up to 100 characters. + :param value: The secret value; up to 4096 characters. + + :returns: The created AccountSecretInstance + """ + + data = values.of( + { + "Key": key, + "Value": value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AccountSecretInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AccountSecretInstance]: + """ + Streams AccountSecretInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AccountSecretInstance]: + """ + Asynchronously streams AccountSecretInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AccountSecretInstance]: + """ + Lists AccountSecretInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AccountSecretInstance]: + """ + Asynchronously lists AccountSecretInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AccountSecretPage: + """ + Retrieve a single page of AccountSecretInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AccountSecretInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AccountSecretPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AccountSecretPage: + """ + Asynchronously retrieve a single page of AccountSecretInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AccountSecretInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AccountSecretPage(self._version, response) + + def get_page(self, target_url: str) -> AccountSecretPage: + """ + Retrieve a specific page of AccountSecretInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AccountSecretInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AccountSecretPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AccountSecretPage: + """ + Asynchronously retrieve a specific page of AccountSecretInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AccountSecretInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AccountSecretPage(self._version, response) + + def get(self, key: str) -> AccountSecretContext: + """ + Constructs a AccountSecretContext + + :param key: The secret key; up to 100 characters. + """ + return AccountSecretContext(self._version, key=key) + + def __call__(self, key: str) -> AccountSecretContext: + """ + Constructs a AccountSecretContext + + :param key: The secret key; up to 100 characters. + """ + return AccountSecretContext(self._version, key=key) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/microvisor/v1/app/__init__.py b/venv/Lib/site-packages/twilio/rest/microvisor/v1/app/__init__.py new file mode 100644 index 00000000..8cfbbe68 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/microvisor/v1/app/__init__.py @@ -0,0 +1,485 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Microvisor + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.microvisor.v1.app.app_manifest import AppManifestList + + +class AppInstance(InstanceResource): + """ + :ivar sid: A 34-character string that uniquely identifies this App. + :ivar account_sid: The unique SID identifier of the Account. + :ivar hash: App manifest hash represented as `hash_algorithm:hash_value`. + :ivar unique_name: A developer-defined string that uniquely identifies the App. This value must be unique for all Apps on this Account. The `unique_name` value may be used as an alternative to the `sid` in the URL path to address the resource. + :ivar date_created: The date that this App was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date that this App was last updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The URL of this resource. + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.hash: Optional[str] = payload.get("hash") + self.unique_name: Optional[str] = payload.get("unique_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[AppContext] = None + + @property + def _proxy(self) -> "AppContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AppContext for this AppInstance + """ + if self._context is None: + self._context = AppContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AppInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AppInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AppInstance": + """ + Fetch the AppInstance + + + :returns: The fetched AppInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AppInstance": + """ + Asynchronous coroutine to fetch the AppInstance + + + :returns: The fetched AppInstance + """ + return await self._proxy.fetch_async() + + @property + def app_manifests(self) -> AppManifestList: + """ + Access the app_manifests + """ + return self._proxy.app_manifests + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AppContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the AppContext + + :param version: Version that contains the resource + :param sid: A 34-character string that uniquely identifies this App. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Apps/{sid}".format(**self._solution) + + self._app_manifests: Optional[AppManifestList] = None + + def delete(self) -> bool: + """ + Deletes the AppInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AppInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AppInstance: + """ + Fetch the AppInstance + + + :returns: The fetched AppInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AppInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AppInstance: + """ + Asynchronous coroutine to fetch the AppInstance + + + :returns: The fetched AppInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AppInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + @property + def app_manifests(self) -> AppManifestList: + """ + Access the app_manifests + """ + if self._app_manifests is None: + self._app_manifests = AppManifestList( + self._version, + self._solution["sid"], + ) + return self._app_manifests + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AppPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AppInstance: + """ + Build an instance of AppInstance + + :param payload: Payload response from the API + """ + return AppInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AppList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AppList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Apps" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AppInstance]: + """ + Streams AppInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AppInstance]: + """ + Asynchronously streams AppInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AppInstance]: + """ + Lists AppInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AppInstance]: + """ + Asynchronously lists AppInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AppPage: + """ + Retrieve a single page of AppInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AppInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AppPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AppPage: + """ + Asynchronously retrieve a single page of AppInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AppInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AppPage(self._version, response) + + def get_page(self, target_url: str) -> AppPage: + """ + Retrieve a specific page of AppInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AppInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AppPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AppPage: + """ + Asynchronously retrieve a specific page of AppInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AppInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AppPage(self._version, response) + + def get(self, sid: str) -> AppContext: + """ + Constructs a AppContext + + :param sid: A 34-character string that uniquely identifies this App. + """ + return AppContext(self._version, sid=sid) + + def __call__(self, sid: str) -> AppContext: + """ + Constructs a AppContext + + :param sid: A 34-character string that uniquely identifies this App. + """ + return AppContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/microvisor/v1/app/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/microvisor/v1/app/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..682eabbe Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/microvisor/v1/app/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/microvisor/v1/app/__pycache__/app_manifest.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/microvisor/v1/app/__pycache__/app_manifest.cpython-312.pyc new file mode 100644 index 00000000..14a3665a Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/microvisor/v1/app/__pycache__/app_manifest.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/microvisor/v1/app/app_manifest.py b/venv/Lib/site-packages/twilio/rest/microvisor/v1/app/app_manifest.py new file mode 100644 index 00000000..0412cadc --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/microvisor/v1/app/app_manifest.py @@ -0,0 +1,193 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Microvisor + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class AppManifestInstance(InstanceResource): + """ + :ivar app_sid: A 34-character string that uniquely identifies this App. + :ivar hash: App manifest hash represented as `hash_algorithm:hash_value`. + :ivar encoded_bytes: The base-64 encoded manifest + :ivar url: The absolute URL of this Manifest. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], app_sid: str): + super().__init__(version) + + self.app_sid: Optional[str] = payload.get("app_sid") + self.hash: Optional[str] = payload.get("hash") + self.encoded_bytes: Optional[str] = payload.get("encoded_bytes") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "app_sid": app_sid, + } + self._context: Optional[AppManifestContext] = None + + @property + def _proxy(self) -> "AppManifestContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AppManifestContext for this AppManifestInstance + """ + if self._context is None: + self._context = AppManifestContext( + self._version, + app_sid=self._solution["app_sid"], + ) + return self._context + + def fetch(self) -> "AppManifestInstance": + """ + Fetch the AppManifestInstance + + + :returns: The fetched AppManifestInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AppManifestInstance": + """ + Asynchronous coroutine to fetch the AppManifestInstance + + + :returns: The fetched AppManifestInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AppManifestContext(InstanceContext): + + def __init__(self, version: Version, app_sid: str): + """ + Initialize the AppManifestContext + + :param version: Version that contains the resource + :param app_sid: A 34-character string that uniquely identifies this App. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "app_sid": app_sid, + } + self._uri = "/Apps/{app_sid}/Manifest".format(**self._solution) + + def fetch(self) -> AppManifestInstance: + """ + Fetch the AppManifestInstance + + + :returns: The fetched AppManifestInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AppManifestInstance( + self._version, + payload, + app_sid=self._solution["app_sid"], + ) + + async def fetch_async(self) -> AppManifestInstance: + """ + Asynchronous coroutine to fetch the AppManifestInstance + + + :returns: The fetched AppManifestInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AppManifestInstance( + self._version, + payload, + app_sid=self._solution["app_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AppManifestList(ListResource): + + def __init__(self, version: Version, app_sid: str): + """ + Initialize the AppManifestList + + :param version: Version that contains the resource + :param app_sid: A 34-character string that uniquely identifies this App. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "app_sid": app_sid, + } + + def get(self) -> AppManifestContext: + """ + Constructs a AppManifestContext + + """ + return AppManifestContext(self._version, app_sid=self._solution["app_sid"]) + + def __call__(self) -> AppManifestContext: + """ + Constructs a AppManifestContext + + """ + return AppManifestContext(self._version, app_sid=self._solution["app_sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/microvisor/v1/device/__init__.py b/venv/Lib/site-packages/twilio/rest/microvisor/v1/device/__init__.py new file mode 100644 index 00000000..a3b30891 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/microvisor/v1/device/__init__.py @@ -0,0 +1,588 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Microvisor + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.microvisor.v1.device.device_config import DeviceConfigList +from twilio.rest.microvisor.v1.device.device_secret import DeviceSecretList + + +class DeviceInstance(InstanceResource): + """ + :ivar sid: A 34-character string that uniquely identifies this Device. + :ivar unique_name: A developer-defined string that uniquely identifies the Device. This value must be unique for all Devices on this Account. The `unique_name` value may be used as an alternative to the `sid` in the URL path to address the resource. + :ivar account_sid: The unique SID identifier of the Account. + :ivar app: Information about the target App and the App reported by this Device. Contains the properties `target_sid`, `date_targeted`, `update_status` (one of `up-to-date`, `pending` and `error`), `update_error_code`, `reported_sid` and `date_reported`. + :ivar logging: Object specifying whether application logging is enabled for this Device. Contains the properties `enabled` and `date_expires`. + :ivar date_created: The date that this Device was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date that this Device was last updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The URL of this resource. + :ivar links: The absolute URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.app: Optional[Dict[str, object]] = payload.get("app") + self.logging: Optional[Dict[str, object]] = payload.get("logging") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[DeviceContext] = None + + @property + def _proxy(self) -> "DeviceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DeviceContext for this DeviceInstance + """ + if self._context is None: + self._context = DeviceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "DeviceInstance": + """ + Fetch the DeviceInstance + + + :returns: The fetched DeviceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DeviceInstance": + """ + Asynchronous coroutine to fetch the DeviceInstance + + + :returns: The fetched DeviceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + unique_name: Union[str, object] = values.unset, + target_app: Union[str, object] = values.unset, + logging_enabled: Union[bool, object] = values.unset, + restart_app: Union[bool, object] = values.unset, + ) -> "DeviceInstance": + """ + Update the DeviceInstance + + :param unique_name: A unique and addressable name to be assigned to this Device by the developer. It may be used in place of the Device SID. + :param target_app: The SID or unique name of the App to be targeted to the Device. + :param logging_enabled: A Boolean flag specifying whether to enable application logging. Logs will be enabled or extended for 24 hours. + :param restart_app: Set to true to restart the App running on the Device. + + :returns: The updated DeviceInstance + """ + return self._proxy.update( + unique_name=unique_name, + target_app=target_app, + logging_enabled=logging_enabled, + restart_app=restart_app, + ) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + target_app: Union[str, object] = values.unset, + logging_enabled: Union[bool, object] = values.unset, + restart_app: Union[bool, object] = values.unset, + ) -> "DeviceInstance": + """ + Asynchronous coroutine to update the DeviceInstance + + :param unique_name: A unique and addressable name to be assigned to this Device by the developer. It may be used in place of the Device SID. + :param target_app: The SID or unique name of the App to be targeted to the Device. + :param logging_enabled: A Boolean flag specifying whether to enable application logging. Logs will be enabled or extended for 24 hours. + :param restart_app: Set to true to restart the App running on the Device. + + :returns: The updated DeviceInstance + """ + return await self._proxy.update_async( + unique_name=unique_name, + target_app=target_app, + logging_enabled=logging_enabled, + restart_app=restart_app, + ) + + @property + def device_configs(self) -> DeviceConfigList: + """ + Access the device_configs + """ + return self._proxy.device_configs + + @property + def device_secrets(self) -> DeviceSecretList: + """ + Access the device_secrets + """ + return self._proxy.device_secrets + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DeviceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the DeviceContext + + :param version: Version that contains the resource + :param sid: A 34-character string that uniquely identifies this Device. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Devices/{sid}".format(**self._solution) + + self._device_configs: Optional[DeviceConfigList] = None + self._device_secrets: Optional[DeviceSecretList] = None + + def fetch(self) -> DeviceInstance: + """ + Fetch the DeviceInstance + + + :returns: The fetched DeviceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DeviceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> DeviceInstance: + """ + Asynchronous coroutine to fetch the DeviceInstance + + + :returns: The fetched DeviceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DeviceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + unique_name: Union[str, object] = values.unset, + target_app: Union[str, object] = values.unset, + logging_enabled: Union[bool, object] = values.unset, + restart_app: Union[bool, object] = values.unset, + ) -> DeviceInstance: + """ + Update the DeviceInstance + + :param unique_name: A unique and addressable name to be assigned to this Device by the developer. It may be used in place of the Device SID. + :param target_app: The SID or unique name of the App to be targeted to the Device. + :param logging_enabled: A Boolean flag specifying whether to enable application logging. Logs will be enabled or extended for 24 hours. + :param restart_app: Set to true to restart the App running on the Device. + + :returns: The updated DeviceInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "TargetApp": target_app, + "LoggingEnabled": serialize.boolean_to_string(logging_enabled), + "RestartApp": serialize.boolean_to_string(restart_app), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DeviceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + target_app: Union[str, object] = values.unset, + logging_enabled: Union[bool, object] = values.unset, + restart_app: Union[bool, object] = values.unset, + ) -> DeviceInstance: + """ + Asynchronous coroutine to update the DeviceInstance + + :param unique_name: A unique and addressable name to be assigned to this Device by the developer. It may be used in place of the Device SID. + :param target_app: The SID or unique name of the App to be targeted to the Device. + :param logging_enabled: A Boolean flag specifying whether to enable application logging. Logs will be enabled or extended for 24 hours. + :param restart_app: Set to true to restart the App running on the Device. + + :returns: The updated DeviceInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "TargetApp": target_app, + "LoggingEnabled": serialize.boolean_to_string(logging_enabled), + "RestartApp": serialize.boolean_to_string(restart_app), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DeviceInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def device_configs(self) -> DeviceConfigList: + """ + Access the device_configs + """ + if self._device_configs is None: + self._device_configs = DeviceConfigList( + self._version, + self._solution["sid"], + ) + return self._device_configs + + @property + def device_secrets(self) -> DeviceSecretList: + """ + Access the device_secrets + """ + if self._device_secrets is None: + self._device_secrets = DeviceSecretList( + self._version, + self._solution["sid"], + ) + return self._device_secrets + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DevicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DeviceInstance: + """ + Build an instance of DeviceInstance + + :param payload: Payload response from the API + """ + return DeviceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class DeviceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the DeviceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Devices" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DeviceInstance]: + """ + Streams DeviceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DeviceInstance]: + """ + Asynchronously streams DeviceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DeviceInstance]: + """ + Lists DeviceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DeviceInstance]: + """ + Asynchronously lists DeviceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DevicePage: + """ + Retrieve a single page of DeviceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DeviceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DevicePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DevicePage: + """ + Asynchronously retrieve a single page of DeviceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DeviceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DevicePage(self._version, response) + + def get_page(self, target_url: str) -> DevicePage: + """ + Retrieve a specific page of DeviceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DeviceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DevicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> DevicePage: + """ + Asynchronously retrieve a specific page of DeviceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DeviceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DevicePage(self._version, response) + + def get(self, sid: str) -> DeviceContext: + """ + Constructs a DeviceContext + + :param sid: A 34-character string that uniquely identifies this Device. + """ + return DeviceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> DeviceContext: + """ + Constructs a DeviceContext + + :param sid: A 34-character string that uniquely identifies this Device. + """ + return DeviceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/microvisor/v1/device/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/microvisor/v1/device/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..5c110329 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/microvisor/v1/device/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/microvisor/v1/device/__pycache__/device_config.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/microvisor/v1/device/__pycache__/device_config.cpython-312.pyc new file mode 100644 index 00000000..133a2314 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/microvisor/v1/device/__pycache__/device_config.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/microvisor/v1/device/__pycache__/device_secret.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/microvisor/v1/device/__pycache__/device_secret.cpython-312.pyc new file mode 100644 index 00000000..0fd12c37 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/microvisor/v1/device/__pycache__/device_secret.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/microvisor/v1/device/device_config.py b/venv/Lib/site-packages/twilio/rest/microvisor/v1/device/device_config.py new file mode 100644 index 00000000..b87063f5 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/microvisor/v1/device/device_config.py @@ -0,0 +1,622 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Microvisor + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DeviceConfigInstance(InstanceResource): + """ + :ivar device_sid: A 34-character string that uniquely identifies the parent Device. + :ivar key: The config key; up to 100 characters. + :ivar value: The config value; up to 4096 characters. + :ivar date_updated: + :ivar url: The absolute URL of the Config. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + device_sid: str, + key: Optional[str] = None, + ): + super().__init__(version) + + self.device_sid: Optional[str] = payload.get("device_sid") + self.key: Optional[str] = payload.get("key") + self.value: Optional[str] = payload.get("value") + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "device_sid": device_sid, + "key": key or self.key, + } + self._context: Optional[DeviceConfigContext] = None + + @property + def _proxy(self) -> "DeviceConfigContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DeviceConfigContext for this DeviceConfigInstance + """ + if self._context is None: + self._context = DeviceConfigContext( + self._version, + device_sid=self._solution["device_sid"], + key=self._solution["key"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the DeviceConfigInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DeviceConfigInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "DeviceConfigInstance": + """ + Fetch the DeviceConfigInstance + + + :returns: The fetched DeviceConfigInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DeviceConfigInstance": + """ + Asynchronous coroutine to fetch the DeviceConfigInstance + + + :returns: The fetched DeviceConfigInstance + """ + return await self._proxy.fetch_async() + + def update(self, value: str) -> "DeviceConfigInstance": + """ + Update the DeviceConfigInstance + + :param value: The config value; up to 4096 characters. + + :returns: The updated DeviceConfigInstance + """ + return self._proxy.update( + value=value, + ) + + async def update_async(self, value: str) -> "DeviceConfigInstance": + """ + Asynchronous coroutine to update the DeviceConfigInstance + + :param value: The config value; up to 4096 characters. + + :returns: The updated DeviceConfigInstance + """ + return await self._proxy.update_async( + value=value, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DeviceConfigContext(InstanceContext): + + def __init__(self, version: Version, device_sid: str, key: str): + """ + Initialize the DeviceConfigContext + + :param version: Version that contains the resource + :param device_sid: A 34-character string that uniquely identifies the Device. + :param key: The config key; up to 100 characters. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "device_sid": device_sid, + "key": key, + } + self._uri = "/Devices/{device_sid}/Configs/{key}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the DeviceConfigInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DeviceConfigInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> DeviceConfigInstance: + """ + Fetch the DeviceConfigInstance + + + :returns: The fetched DeviceConfigInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DeviceConfigInstance( + self._version, + payload, + device_sid=self._solution["device_sid"], + key=self._solution["key"], + ) + + async def fetch_async(self) -> DeviceConfigInstance: + """ + Asynchronous coroutine to fetch the DeviceConfigInstance + + + :returns: The fetched DeviceConfigInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DeviceConfigInstance( + self._version, + payload, + device_sid=self._solution["device_sid"], + key=self._solution["key"], + ) + + def update(self, value: str) -> DeviceConfigInstance: + """ + Update the DeviceConfigInstance + + :param value: The config value; up to 4096 characters. + + :returns: The updated DeviceConfigInstance + """ + + data = values.of( + { + "Value": value, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DeviceConfigInstance( + self._version, + payload, + device_sid=self._solution["device_sid"], + key=self._solution["key"], + ) + + async def update_async(self, value: str) -> DeviceConfigInstance: + """ + Asynchronous coroutine to update the DeviceConfigInstance + + :param value: The config value; up to 4096 characters. + + :returns: The updated DeviceConfigInstance + """ + + data = values.of( + { + "Value": value, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DeviceConfigInstance( + self._version, + payload, + device_sid=self._solution["device_sid"], + key=self._solution["key"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DeviceConfigPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DeviceConfigInstance: + """ + Build an instance of DeviceConfigInstance + + :param payload: Payload response from the API + """ + return DeviceConfigInstance( + self._version, payload, device_sid=self._solution["device_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class DeviceConfigList(ListResource): + + def __init__(self, version: Version, device_sid: str): + """ + Initialize the DeviceConfigList + + :param version: Version that contains the resource + :param device_sid: A 34-character string that uniquely identifies the Device. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "device_sid": device_sid, + } + self._uri = "/Devices/{device_sid}/Configs".format(**self._solution) + + def create(self, key: str, value: str) -> DeviceConfigInstance: + """ + Create the DeviceConfigInstance + + :param key: The config key; up to 100 characters. + :param value: The config value; up to 4096 characters. + + :returns: The created DeviceConfigInstance + """ + + data = values.of( + { + "Key": key, + "Value": value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DeviceConfigInstance( + self._version, payload, device_sid=self._solution["device_sid"] + ) + + async def create_async(self, key: str, value: str) -> DeviceConfigInstance: + """ + Asynchronously create the DeviceConfigInstance + + :param key: The config key; up to 100 characters. + :param value: The config value; up to 4096 characters. + + :returns: The created DeviceConfigInstance + """ + + data = values.of( + { + "Key": key, + "Value": value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DeviceConfigInstance( + self._version, payload, device_sid=self._solution["device_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DeviceConfigInstance]: + """ + Streams DeviceConfigInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DeviceConfigInstance]: + """ + Asynchronously streams DeviceConfigInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DeviceConfigInstance]: + """ + Lists DeviceConfigInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DeviceConfigInstance]: + """ + Asynchronously lists DeviceConfigInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DeviceConfigPage: + """ + Retrieve a single page of DeviceConfigInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DeviceConfigInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DeviceConfigPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DeviceConfigPage: + """ + Asynchronously retrieve a single page of DeviceConfigInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DeviceConfigInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DeviceConfigPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DeviceConfigPage: + """ + Retrieve a specific page of DeviceConfigInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DeviceConfigInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DeviceConfigPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DeviceConfigPage: + """ + Asynchronously retrieve a specific page of DeviceConfigInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DeviceConfigInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DeviceConfigPage(self._version, response, self._solution) + + def get(self, key: str) -> DeviceConfigContext: + """ + Constructs a DeviceConfigContext + + :param key: The config key; up to 100 characters. + """ + return DeviceConfigContext( + self._version, device_sid=self._solution["device_sid"], key=key + ) + + def __call__(self, key: str) -> DeviceConfigContext: + """ + Constructs a DeviceConfigContext + + :param key: The config key; up to 100 characters. + """ + return DeviceConfigContext( + self._version, device_sid=self._solution["device_sid"], key=key + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/microvisor/v1/device/device_secret.py b/venv/Lib/site-packages/twilio/rest/microvisor/v1/device/device_secret.py new file mode 100644 index 00000000..30b805ea --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/microvisor/v1/device/device_secret.py @@ -0,0 +1,620 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Microvisor + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DeviceSecretInstance(InstanceResource): + """ + :ivar device_sid: A 34-character string that uniquely identifies the parent Device. + :ivar key: The secret key; up to 100 characters. + :ivar date_rotated: + :ivar url: The absolute URL of the Secret. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + device_sid: str, + key: Optional[str] = None, + ): + super().__init__(version) + + self.device_sid: Optional[str] = payload.get("device_sid") + self.key: Optional[str] = payload.get("key") + self.date_rotated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_rotated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "device_sid": device_sid, + "key": key or self.key, + } + self._context: Optional[DeviceSecretContext] = None + + @property + def _proxy(self) -> "DeviceSecretContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DeviceSecretContext for this DeviceSecretInstance + """ + if self._context is None: + self._context = DeviceSecretContext( + self._version, + device_sid=self._solution["device_sid"], + key=self._solution["key"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the DeviceSecretInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DeviceSecretInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "DeviceSecretInstance": + """ + Fetch the DeviceSecretInstance + + + :returns: The fetched DeviceSecretInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DeviceSecretInstance": + """ + Asynchronous coroutine to fetch the DeviceSecretInstance + + + :returns: The fetched DeviceSecretInstance + """ + return await self._proxy.fetch_async() + + def update(self, value: str) -> "DeviceSecretInstance": + """ + Update the DeviceSecretInstance + + :param value: The secret value; up to 4096 characters. + + :returns: The updated DeviceSecretInstance + """ + return self._proxy.update( + value=value, + ) + + async def update_async(self, value: str) -> "DeviceSecretInstance": + """ + Asynchronous coroutine to update the DeviceSecretInstance + + :param value: The secret value; up to 4096 characters. + + :returns: The updated DeviceSecretInstance + """ + return await self._proxy.update_async( + value=value, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DeviceSecretContext(InstanceContext): + + def __init__(self, version: Version, device_sid: str, key: str): + """ + Initialize the DeviceSecretContext + + :param version: Version that contains the resource + :param device_sid: A 34-character string that uniquely identifies the Device. + :param key: The secret key; up to 100 characters. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "device_sid": device_sid, + "key": key, + } + self._uri = "/Devices/{device_sid}/Secrets/{key}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the DeviceSecretInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DeviceSecretInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> DeviceSecretInstance: + """ + Fetch the DeviceSecretInstance + + + :returns: The fetched DeviceSecretInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DeviceSecretInstance( + self._version, + payload, + device_sid=self._solution["device_sid"], + key=self._solution["key"], + ) + + async def fetch_async(self) -> DeviceSecretInstance: + """ + Asynchronous coroutine to fetch the DeviceSecretInstance + + + :returns: The fetched DeviceSecretInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DeviceSecretInstance( + self._version, + payload, + device_sid=self._solution["device_sid"], + key=self._solution["key"], + ) + + def update(self, value: str) -> DeviceSecretInstance: + """ + Update the DeviceSecretInstance + + :param value: The secret value; up to 4096 characters. + + :returns: The updated DeviceSecretInstance + """ + + data = values.of( + { + "Value": value, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DeviceSecretInstance( + self._version, + payload, + device_sid=self._solution["device_sid"], + key=self._solution["key"], + ) + + async def update_async(self, value: str) -> DeviceSecretInstance: + """ + Asynchronous coroutine to update the DeviceSecretInstance + + :param value: The secret value; up to 4096 characters. + + :returns: The updated DeviceSecretInstance + """ + + data = values.of( + { + "Value": value, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DeviceSecretInstance( + self._version, + payload, + device_sid=self._solution["device_sid"], + key=self._solution["key"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DeviceSecretPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DeviceSecretInstance: + """ + Build an instance of DeviceSecretInstance + + :param payload: Payload response from the API + """ + return DeviceSecretInstance( + self._version, payload, device_sid=self._solution["device_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class DeviceSecretList(ListResource): + + def __init__(self, version: Version, device_sid: str): + """ + Initialize the DeviceSecretList + + :param version: Version that contains the resource + :param device_sid: A 34-character string that uniquely identifies the Device. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "device_sid": device_sid, + } + self._uri = "/Devices/{device_sid}/Secrets".format(**self._solution) + + def create(self, key: str, value: str) -> DeviceSecretInstance: + """ + Create the DeviceSecretInstance + + :param key: The secret key; up to 100 characters. + :param value: The secret value; up to 4096 characters. + + :returns: The created DeviceSecretInstance + """ + + data = values.of( + { + "Key": key, + "Value": value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DeviceSecretInstance( + self._version, payload, device_sid=self._solution["device_sid"] + ) + + async def create_async(self, key: str, value: str) -> DeviceSecretInstance: + """ + Asynchronously create the DeviceSecretInstance + + :param key: The secret key; up to 100 characters. + :param value: The secret value; up to 4096 characters. + + :returns: The created DeviceSecretInstance + """ + + data = values.of( + { + "Key": key, + "Value": value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DeviceSecretInstance( + self._version, payload, device_sid=self._solution["device_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DeviceSecretInstance]: + """ + Streams DeviceSecretInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DeviceSecretInstance]: + """ + Asynchronously streams DeviceSecretInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DeviceSecretInstance]: + """ + Lists DeviceSecretInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DeviceSecretInstance]: + """ + Asynchronously lists DeviceSecretInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DeviceSecretPage: + """ + Retrieve a single page of DeviceSecretInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DeviceSecretInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DeviceSecretPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DeviceSecretPage: + """ + Asynchronously retrieve a single page of DeviceSecretInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DeviceSecretInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DeviceSecretPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DeviceSecretPage: + """ + Retrieve a specific page of DeviceSecretInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DeviceSecretInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DeviceSecretPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DeviceSecretPage: + """ + Asynchronously retrieve a specific page of DeviceSecretInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DeviceSecretInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DeviceSecretPage(self._version, response, self._solution) + + def get(self, key: str) -> DeviceSecretContext: + """ + Constructs a DeviceSecretContext + + :param key: The secret key; up to 100 characters. + """ + return DeviceSecretContext( + self._version, device_sid=self._solution["device_sid"], key=key + ) + + def __call__(self, key: str) -> DeviceSecretContext: + """ + Constructs a DeviceSecretContext + + :param key: The secret key; up to 100 characters. + """ + return DeviceSecretContext( + self._version, device_sid=self._solution["device_sid"], key=key + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/monitor/MonitorBase.py b/venv/Lib/site-packages/twilio/rest/monitor/MonitorBase.py new file mode 100644 index 00000000..4c5c6ebc --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/monitor/MonitorBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.monitor.v1 import V1 + + +class MonitorBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Monitor Domain + + :returns: Domain for Monitor + """ + super().__init__(twilio, "https://monitor.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Monitor + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/monitor/__init__.py b/venv/Lib/site-packages/twilio/rest/monitor/__init__.py new file mode 100644 index 00000000..a39a5b24 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/monitor/__init__.py @@ -0,0 +1,25 @@ +from warnings import warn + +from twilio.rest.monitor.MonitorBase import MonitorBase +from twilio.rest.monitor.v1.alert import AlertList +from twilio.rest.monitor.v1.event import EventList + + +class Monitor(MonitorBase): + @property + def alerts(self) -> AlertList: + warn( + "alerts is deprecated. Use v1.alerts instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.alerts + + @property + def events(self) -> EventList: + warn( + "events is deprecated. Use v1.events instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.events diff --git a/venv/Lib/site-packages/twilio/rest/monitor/__pycache__/MonitorBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/monitor/__pycache__/MonitorBase.cpython-312.pyc new file mode 100644 index 00000000..9fed79f9 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/monitor/__pycache__/MonitorBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/monitor/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/monitor/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..ce8cf3ab Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/monitor/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/monitor/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/monitor/v1/__init__.py new file mode 100644 index 00000000..e892612b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/monitor/v1/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Monitor + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.monitor.v1.alert import AlertList +from twilio.rest.monitor.v1.event import EventList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Monitor + + :param domain: The Twilio.monitor domain + """ + super().__init__(domain, "v1") + self._alerts: Optional[AlertList] = None + self._events: Optional[EventList] = None + + @property + def alerts(self) -> AlertList: + if self._alerts is None: + self._alerts = AlertList(self) + return self._alerts + + @property + def events(self) -> EventList: + if self._events is None: + self._events = EventList(self) + return self._events + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/monitor/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/monitor/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..96d896da Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/monitor/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/monitor/v1/__pycache__/alert.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/monitor/v1/__pycache__/alert.cpython-312.pyc new file mode 100644 index 00000000..30d08db5 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/monitor/v1/__pycache__/alert.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/monitor/v1/__pycache__/event.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/monitor/v1/__pycache__/event.cpython-312.pyc new file mode 100644 index 00000000..4b45f63a Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/monitor/v1/__pycache__/event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/monitor/v1/alert.py b/venv/Lib/site-packages/twilio/rest/monitor/v1/alert.py new file mode 100644 index 00000000..829e6336 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/monitor/v1/alert.py @@ -0,0 +1,501 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Monitor + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AlertInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Alert resource. + :ivar alert_text: The text of the alert. + :ivar api_version: The API version used when the alert was generated. Can be empty for events that don't have a specific API version. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_generated: The date and time in GMT when the alert was generated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. Due to buffering, this can be different than `date_created`. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar error_code: The error code for the condition that generated the alert. See the [Error Dictionary](https://www.twilio.com/docs/api/errors) for possible causes and solutions to the error. + :ivar log_level: The log level. Can be: `error`, `warning`, `notice`, or `debug`. + :ivar more_info: The URL of the page in our [Error Dictionary](https://www.twilio.com/docs/api/errors) with more information about the error condition. + :ivar request_method: The method used by the request that generated the alert. If the alert was generated by a request we made to your server, this is the method we used. If the alert was generated by a request from your application to our API, this is the method your application used. + :ivar request_url: The URL of the request that generated the alert. If the alert was generated by a request we made to your server, this is the URL on your server that generated the alert. If the alert was generated by a request from your application to our API, this is the URL of the resource requested. + :ivar request_variables: The variables passed in the request that generated the alert. This value is only returned when a single Alert resource is fetched. + :ivar resource_sid: The SID of the resource for which the alert was generated. For instance, if your server failed to respond to an HTTP request during the flow of a particular call, this value would be the SID of the server. This value is empty if the alert was not generated for a particular resource. + :ivar response_body: The response body of the request that generated the alert. This value is only returned when a single Alert resource is fetched. + :ivar response_headers: The response headers of the request that generated the alert. This value is only returned when a single Alert resource is fetched. + :ivar sid: The unique string that we created to identify the Alert resource. + :ivar url: The absolute URL of the Alert resource. + :ivar request_headers: The request headers of the request that generated the alert. This value is only returned when a single Alert resource is fetched. + :ivar service_sid: The SID of the service or resource that generated the alert. Can be `null`. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.alert_text: Optional[str] = payload.get("alert_text") + self.api_version: Optional[str] = payload.get("api_version") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_generated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_generated") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.error_code: Optional[str] = payload.get("error_code") + self.log_level: Optional[str] = payload.get("log_level") + self.more_info: Optional[str] = payload.get("more_info") + self.request_method: Optional[str] = payload.get("request_method") + self.request_url: Optional[str] = payload.get("request_url") + self.request_variables: Optional[str] = payload.get("request_variables") + self.resource_sid: Optional[str] = payload.get("resource_sid") + self.response_body: Optional[str] = payload.get("response_body") + self.response_headers: Optional[str] = payload.get("response_headers") + self.sid: Optional[str] = payload.get("sid") + self.url: Optional[str] = payload.get("url") + self.request_headers: Optional[str] = payload.get("request_headers") + self.service_sid: Optional[str] = payload.get("service_sid") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[AlertContext] = None + + @property + def _proxy(self) -> "AlertContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AlertContext for this AlertInstance + """ + if self._context is None: + self._context = AlertContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "AlertInstance": + """ + Fetch the AlertInstance + + + :returns: The fetched AlertInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AlertInstance": + """ + Asynchronous coroutine to fetch the AlertInstance + + + :returns: The fetched AlertInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AlertContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the AlertContext + + :param version: Version that contains the resource + :param sid: The SID of the Alert resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Alerts/{sid}".format(**self._solution) + + def fetch(self) -> AlertInstance: + """ + Fetch the AlertInstance + + + :returns: The fetched AlertInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AlertInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AlertInstance: + """ + Asynchronous coroutine to fetch the AlertInstance + + + :returns: The fetched AlertInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AlertInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AlertPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AlertInstance: + """ + Build an instance of AlertInstance + + :param payload: Payload response from the API + """ + return AlertInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AlertList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AlertList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Alerts" + + def stream( + self, + log_level: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AlertInstance]: + """ + Streams AlertInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param datetime start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param datetime end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + log_level=log_level, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + log_level: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AlertInstance]: + """ + Asynchronously streams AlertInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param datetime start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param datetime end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + log_level=log_level, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + log_level: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AlertInstance]: + """ + Lists AlertInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param datetime start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param datetime end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + log_level=log_level, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + log_level: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AlertInstance]: + """ + Asynchronously lists AlertInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param datetime start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param datetime end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + log_level=log_level, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + log_level: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AlertPage: + """ + Retrieve a single page of AlertInstance records from the API. + Request is executed immediately + + :param log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AlertInstance + """ + data = values.of( + { + "LogLevel": log_level, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AlertPage(self._version, response) + + async def page_async( + self, + log_level: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AlertPage: + """ + Asynchronously retrieve a single page of AlertInstance records from the API. + Request is executed immediately + + :param log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AlertInstance + """ + data = values.of( + { + "LogLevel": log_level, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AlertPage(self._version, response) + + def get_page(self, target_url: str) -> AlertPage: + """ + Retrieve a specific page of AlertInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AlertInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AlertPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AlertPage: + """ + Asynchronously retrieve a specific page of AlertInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AlertInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AlertPage(self._version, response) + + def get(self, sid: str) -> AlertContext: + """ + Constructs a AlertContext + + :param sid: The SID of the Alert resource to fetch. + """ + return AlertContext(self._version, sid=sid) + + def __call__(self, sid: str) -> AlertContext: + """ + Constructs a AlertContext + + :param sid: The SID of the Alert resource to fetch. + """ + return AlertContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/monitor/v1/event.py b/venv/Lib/site-packages/twilio/rest/monitor/v1/event.py new file mode 100644 index 00000000..61450c87 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/monitor/v1/event.py @@ -0,0 +1,541 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Monitor + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class EventInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Event resource. + :ivar actor_sid: The SID of the actor that caused the event, if available. This can be either a User ID (matching the pattern `^US[0-9a-fA-F]{32}$`) or an Account SID (matching the pattern `^AC[0-9a-fA-F]{32}$`). If the actor's SID isn't available, this field will be `null`. + :ivar actor_type: The type of actor that caused the event. Can be: `user` for a change made by a logged-in user in the Twilio Console, `account` for an event caused by an API request by an authenticating Account, `twilio-admin` for an event caused by a Twilio employee, and so on. + :ivar description: A description of the event. Can be `null`. + :ivar event_data: An object with additional data about the event. The contents depend on `event_type`. For example, event-types of the form `RESOURCE.updated`, this value contains a `resource_properties` dictionary that describes the previous and updated properties of the resource. + :ivar event_date: The date and time in GMT when the event was recorded specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar event_type: The event's type. Event-types are typically in the form: `RESOURCE_TYPE.ACTION`, where `RESOURCE_TYPE` is the type of resource that was affected and `ACTION` is what happened to it. For example, `phone-number.created`. For a full list of all event-types, see the [Monitor Event Types](https://www.twilio.com/docs/usage/monitor-events#event-types). + :ivar resource_sid: The SID of the resource that was affected. + :ivar resource_type: The type of resource that was affected. For a full list of all resource-types, see the [Monitor Event Types](https://www.twilio.com/docs/usage/monitor-events#event-types). + :ivar sid: The unique string that we created to identify the Event resource. + :ivar source: The originating system or interface that caused the event. Can be: `web` for events caused by user action in the Twilio Console, `api` for events caused by a request to our API, or `twilio` for events caused by an automated or internal Twilio system. + :ivar source_ip_address: The IP address of the source, if the source is outside the Twilio cloud. This value is `null` for events with `source` of `twilio` + :ivar url: The absolute URL of the resource that was affected. Can be `null`. + :ivar links: The absolute URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.actor_sid: Optional[str] = payload.get("actor_sid") + self.actor_type: Optional[str] = payload.get("actor_type") + self.description: Optional[str] = payload.get("description") + self.event_data: Optional[Dict[str, object]] = payload.get("event_data") + self.event_date: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("event_date") + ) + self.event_type: Optional[str] = payload.get("event_type") + self.resource_sid: Optional[str] = payload.get("resource_sid") + self.resource_type: Optional[str] = payload.get("resource_type") + self.sid: Optional[str] = payload.get("sid") + self.source: Optional[str] = payload.get("source") + self.source_ip_address: Optional[str] = payload.get("source_ip_address") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[EventContext] = None + + @property + def _proxy(self) -> "EventContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EventContext for this EventInstance + """ + if self._context is None: + self._context = EventContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "EventInstance": + """ + Fetch the EventInstance + + + :returns: The fetched EventInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EventInstance": + """ + Asynchronous coroutine to fetch the EventInstance + + + :returns: The fetched EventInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EventContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the EventContext + + :param version: Version that contains the resource + :param sid: The SID of the Event resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Events/{sid}".format(**self._solution) + + def fetch(self) -> EventInstance: + """ + Fetch the EventInstance + + + :returns: The fetched EventInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EventInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> EventInstance: + """ + Asynchronous coroutine to fetch the EventInstance + + + :returns: The fetched EventInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EventInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EventPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EventInstance: + """ + Build an instance of EventInstance + + :param payload: Payload response from the API + """ + return EventInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class EventList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the EventList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Events" + + def stream( + self, + actor_sid: Union[str, object] = values.unset, + event_type: Union[str, object] = values.unset, + resource_sid: Union[str, object] = values.unset, + source_ip_address: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EventInstance]: + """ + Streams EventInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str actor_sid: Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. + :param str event_type: Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). + :param str resource_sid: Only include events that refer to this resource. Useful for discovering the history of a specific resource. + :param str source_ip_address: Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. + :param datetime start_date: Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param datetime end_date: Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + actor_sid=actor_sid, + event_type=event_type, + resource_sid=resource_sid, + source_ip_address=source_ip_address, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + actor_sid: Union[str, object] = values.unset, + event_type: Union[str, object] = values.unset, + resource_sid: Union[str, object] = values.unset, + source_ip_address: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EventInstance]: + """ + Asynchronously streams EventInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str actor_sid: Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. + :param str event_type: Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). + :param str resource_sid: Only include events that refer to this resource. Useful for discovering the history of a specific resource. + :param str source_ip_address: Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. + :param datetime start_date: Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param datetime end_date: Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + actor_sid=actor_sid, + event_type=event_type, + resource_sid=resource_sid, + source_ip_address=source_ip_address, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + actor_sid: Union[str, object] = values.unset, + event_type: Union[str, object] = values.unset, + resource_sid: Union[str, object] = values.unset, + source_ip_address: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventInstance]: + """ + Lists EventInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str actor_sid: Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. + :param str event_type: Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). + :param str resource_sid: Only include events that refer to this resource. Useful for discovering the history of a specific resource. + :param str source_ip_address: Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. + :param datetime start_date: Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param datetime end_date: Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + actor_sid=actor_sid, + event_type=event_type, + resource_sid=resource_sid, + source_ip_address=source_ip_address, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + actor_sid: Union[str, object] = values.unset, + event_type: Union[str, object] = values.unset, + resource_sid: Union[str, object] = values.unset, + source_ip_address: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventInstance]: + """ + Asynchronously lists EventInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str actor_sid: Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. + :param str event_type: Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). + :param str resource_sid: Only include events that refer to this resource. Useful for discovering the history of a specific resource. + :param str source_ip_address: Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. + :param datetime start_date: Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param datetime end_date: Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + actor_sid=actor_sid, + event_type=event_type, + resource_sid=resource_sid, + source_ip_address=source_ip_address, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + actor_sid: Union[str, object] = values.unset, + event_type: Union[str, object] = values.unset, + resource_sid: Union[str, object] = values.unset, + source_ip_address: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EventPage: + """ + Retrieve a single page of EventInstance records from the API. + Request is executed immediately + + :param actor_sid: Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. + :param event_type: Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). + :param resource_sid: Only include events that refer to this resource. Useful for discovering the history of a specific resource. + :param source_ip_address: Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. + :param start_date: Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EventInstance + """ + data = values.of( + { + "ActorSid": actor_sid, + "EventType": event_type, + "ResourceSid": resource_sid, + "SourceIpAddress": source_ip_address, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response) + + async def page_async( + self, + actor_sid: Union[str, object] = values.unset, + event_type: Union[str, object] = values.unset, + resource_sid: Union[str, object] = values.unset, + source_ip_address: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EventPage: + """ + Asynchronously retrieve a single page of EventInstance records from the API. + Request is executed immediately + + :param actor_sid: Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. + :param event_type: Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). + :param resource_sid: Only include events that refer to this resource. Useful for discovering the history of a specific resource. + :param source_ip_address: Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. + :param start_date: Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EventInstance + """ + data = values.of( + { + "ActorSid": actor_sid, + "EventType": event_type, + "ResourceSid": resource_sid, + "SourceIpAddress": source_ip_address, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response) + + def get_page(self, target_url: str) -> EventPage: + """ + Retrieve a specific page of EventInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EventInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EventPage(self._version, response) + + async def get_page_async(self, target_url: str) -> EventPage: + """ + Asynchronously retrieve a specific page of EventInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EventInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EventPage(self._version, response) + + def get(self, sid: str) -> EventContext: + """ + Constructs a EventContext + + :param sid: The SID of the Event resource to fetch. + """ + return EventContext(self._version, sid=sid) + + def __call__(self, sid: str) -> EventContext: + """ + Constructs a EventContext + + :param sid: The SID of the Event resource to fetch. + """ + return EventContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/notify/NotifyBase.py b/venv/Lib/site-packages/twilio/rest/notify/NotifyBase.py new file mode 100644 index 00000000..2772ed09 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/notify/NotifyBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.notify.v1 import V1 + + +class NotifyBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Notify Domain + + :returns: Domain for Notify + """ + super().__init__(twilio, "https://notify.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Notify + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/notify/__init__.py b/venv/Lib/site-packages/twilio/rest/notify/__init__.py new file mode 100644 index 00000000..61f8fafb --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/notify/__init__.py @@ -0,0 +1,25 @@ +from warnings import warn + +from twilio.rest.notify.NotifyBase import NotifyBase +from twilio.rest.notify.v1.credential import CredentialList +from twilio.rest.notify.v1.service import ServiceList + + +class Notify(NotifyBase): + @property + def credentials(self) -> CredentialList: + warn( + "credentials is deprecated. Use v1.credentials instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.credentials + + @property + def services(self) -> ServiceList: + warn( + "services is deprecated. Use v1.services instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.services diff --git a/venv/Lib/site-packages/twilio/rest/notify/__pycache__/NotifyBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/notify/__pycache__/NotifyBase.cpython-312.pyc new file mode 100644 index 00000000..69546054 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/notify/__pycache__/NotifyBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/notify/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/notify/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..ea13ec0c Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/notify/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/notify/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/notify/v1/__init__.py new file mode 100644 index 00000000..90cab950 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/notify/v1/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Notify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.notify.v1.credential import CredentialList +from twilio.rest.notify.v1.service import ServiceList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Notify + + :param domain: The Twilio.notify domain + """ + super().__init__(domain, "v1") + self._credentials: Optional[CredentialList] = None + self._services: Optional[ServiceList] = None + + @property + def credentials(self) -> CredentialList: + if self._credentials is None: + self._credentials = CredentialList(self) + return self._credentials + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/notify/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/notify/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..eb1c64b7 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/notify/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/notify/v1/__pycache__/credential.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/notify/v1/__pycache__/credential.cpython-312.pyc new file mode 100644 index 00000000..8f40360e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/notify/v1/__pycache__/credential.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/notify/v1/credential.py b/venv/Lib/site-packages/twilio/rest/notify/v1/credential.py new file mode 100644 index 00000000..9ca59927 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/notify/v1/credential.py @@ -0,0 +1,711 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Notify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CredentialInstance(InstanceResource): + + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: The unique string that we created to identify the Credential resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Credential resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the Credential resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["CredentialInstance.PushService"] = payload.get("type") + self.sandbox: Optional[str] = payload.get("sandbox") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CredentialContext] = None + + @property + def _proxy(self) -> "CredentialContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CredentialInstance": + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CredentialInstance": + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CredentialContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialInstance: + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: + """ + Build an instance of CredentialInstance + + :param payload: Payload response from the API + """ + return CredentialInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CredentialList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CredentialList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Credentials" + + def create( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Create the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload) + + async def create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialInstance]: + """ + Streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialInstance]: + """ + Asynchronously streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Asynchronously lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Asynchronously retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response) + + def get_page(self, target_url: str) -> CredentialPage: + """ + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CredentialPage: + """ + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response) + + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. + """ + return CredentialContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. + """ + return CredentialContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/notify/v1/service/__init__.py b/venv/Lib/site-packages/twilio/rest/notify/v1/service/__init__.py new file mode 100644 index 00000000..e097e69a --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/notify/v1/service/__init__.py @@ -0,0 +1,948 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Notify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.notify.v1.service.binding import BindingList +from twilio.rest.notify.v1.service.notification import NotificationList + + +class ServiceInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Service resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :ivar gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :ivar fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :ivar messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. In order to send SMS notifications this parameter has to be set. + :ivar facebook_messenger_page_id: Deprecated. + :ivar default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :ivar default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :ivar default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :ivar log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :ivar url: The absolute URL of the Service resource. + :ivar links: The URLs of the Binding, Notification, Segment, and User resources related to the service. + :ivar alexa_skill_id: Deprecated. + :ivar default_alexa_notification_protocol_version: Deprecated. + :ivar delivery_callback_url: URL to send delivery status callback. + :ivar delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.apn_credential_sid: Optional[str] = payload.get("apn_credential_sid") + self.gcm_credential_sid: Optional[str] = payload.get("gcm_credential_sid") + self.fcm_credential_sid: Optional[str] = payload.get("fcm_credential_sid") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.facebook_messenger_page_id: Optional[str] = payload.get( + "facebook_messenger_page_id" + ) + self.default_apn_notification_protocol_version: Optional[str] = payload.get( + "default_apn_notification_protocol_version" + ) + self.default_gcm_notification_protocol_version: Optional[str] = payload.get( + "default_gcm_notification_protocol_version" + ) + self.default_fcm_notification_protocol_version: Optional[str] = payload.get( + "default_fcm_notification_protocol_version" + ) + self.log_enabled: Optional[bool] = payload.get("log_enabled") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.alexa_skill_id: Optional[str] = payload.get("alexa_skill_id") + self.default_alexa_notification_protocol_version: Optional[str] = payload.get( + "default_alexa_notification_protocol_version" + ) + self.delivery_callback_url: Optional[str] = payload.get("delivery_callback_url") + self.delivery_callback_enabled: Optional[bool] = payload.get( + "delivery_callback_enabled" + ) + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + apn_credential_sid=apn_credential_sid, + gcm_credential_sid=gcm_credential_sid, + messaging_service_sid=messaging_service_sid, + facebook_messenger_page_id=facebook_messenger_page_id, + default_apn_notification_protocol_version=default_apn_notification_protocol_version, + default_gcm_notification_protocol_version=default_gcm_notification_protocol_version, + fcm_credential_sid=fcm_credential_sid, + default_fcm_notification_protocol_version=default_fcm_notification_protocol_version, + log_enabled=log_enabled, + alexa_skill_id=alexa_skill_id, + default_alexa_notification_protocol_version=default_alexa_notification_protocol_version, + delivery_callback_url=delivery_callback_url, + delivery_callback_enabled=delivery_callback_enabled, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + apn_credential_sid=apn_credential_sid, + gcm_credential_sid=gcm_credential_sid, + messaging_service_sid=messaging_service_sid, + facebook_messenger_page_id=facebook_messenger_page_id, + default_apn_notification_protocol_version=default_apn_notification_protocol_version, + default_gcm_notification_protocol_version=default_gcm_notification_protocol_version, + fcm_credential_sid=fcm_credential_sid, + default_fcm_notification_protocol_version=default_fcm_notification_protocol_version, + log_enabled=log_enabled, + alexa_skill_id=alexa_skill_id, + default_alexa_notification_protocol_version=default_alexa_notification_protocol_version, + delivery_callback_url=delivery_callback_url, + delivery_callback_enabled=delivery_callback_enabled, + ) + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + return self._proxy.bindings + + @property + def notifications(self) -> NotificationList: + """ + Access the notifications + """ + return self._proxy.notifications + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._bindings: Optional[BindingList] = None + self._notifications: Optional[NotificationList] = None + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ApnCredentialSid": apn_credential_sid, + "GcmCredentialSid": gcm_credential_sid, + "MessagingServiceSid": messaging_service_sid, + "FacebookMessengerPageId": facebook_messenger_page_id, + "DefaultApnNotificationProtocolVersion": default_apn_notification_protocol_version, + "DefaultGcmNotificationProtocolVersion": default_gcm_notification_protocol_version, + "FcmCredentialSid": fcm_credential_sid, + "DefaultFcmNotificationProtocolVersion": default_fcm_notification_protocol_version, + "LogEnabled": serialize.boolean_to_string(log_enabled), + "AlexaSkillId": alexa_skill_id, + "DefaultAlexaNotificationProtocolVersion": default_alexa_notification_protocol_version, + "DeliveryCallbackUrl": delivery_callback_url, + "DeliveryCallbackEnabled": serialize.boolean_to_string( + delivery_callback_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ApnCredentialSid": apn_credential_sid, + "GcmCredentialSid": gcm_credential_sid, + "MessagingServiceSid": messaging_service_sid, + "FacebookMessengerPageId": facebook_messenger_page_id, + "DefaultApnNotificationProtocolVersion": default_apn_notification_protocol_version, + "DefaultGcmNotificationProtocolVersion": default_gcm_notification_protocol_version, + "FcmCredentialSid": fcm_credential_sid, + "DefaultFcmNotificationProtocolVersion": default_fcm_notification_protocol_version, + "LogEnabled": serialize.boolean_to_string(log_enabled), + "AlexaSkillId": alexa_skill_id, + "DefaultAlexaNotificationProtocolVersion": default_alexa_notification_protocol_version, + "DeliveryCallbackUrl": delivery_callback_url, + "DeliveryCallbackEnabled": serialize.boolean_to_string( + delivery_callback_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + if self._bindings is None: + self._bindings = BindingList( + self._version, + self._solution["sid"], + ) + return self._bindings + + @property + def notifications(self) -> NotificationList: + """ + Access the notifications + """ + if self._notifications is None: + self._notifications = NotificationList( + self._version, + self._solution["sid"], + ) + return self._notifications + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def create( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ApnCredentialSid": apn_credential_sid, + "GcmCredentialSid": gcm_credential_sid, + "MessagingServiceSid": messaging_service_sid, + "FacebookMessengerPageId": facebook_messenger_page_id, + "DefaultApnNotificationProtocolVersion": default_apn_notification_protocol_version, + "DefaultGcmNotificationProtocolVersion": default_gcm_notification_protocol_version, + "FcmCredentialSid": fcm_credential_sid, + "DefaultFcmNotificationProtocolVersion": default_fcm_notification_protocol_version, + "LogEnabled": serialize.boolean_to_string(log_enabled), + "AlexaSkillId": alexa_skill_id, + "DefaultAlexaNotificationProtocolVersion": default_alexa_notification_protocol_version, + "DeliveryCallbackUrl": delivery_callback_url, + "DeliveryCallbackEnabled": serialize.boolean_to_string( + delivery_callback_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ApnCredentialSid": apn_credential_sid, + "GcmCredentialSid": gcm_credential_sid, + "MessagingServiceSid": messaging_service_sid, + "FacebookMessengerPageId": facebook_messenger_page_id, + "DefaultApnNotificationProtocolVersion": default_apn_notification_protocol_version, + "DefaultGcmNotificationProtocolVersion": default_gcm_notification_protocol_version, + "FcmCredentialSid": fcm_credential_sid, + "DefaultFcmNotificationProtocolVersion": default_fcm_notification_protocol_version, + "LogEnabled": serialize.boolean_to_string(log_enabled), + "AlexaSkillId": alexa_skill_id, + "DefaultAlexaNotificationProtocolVersion": default_alexa_notification_protocol_version, + "DeliveryCallbackUrl": delivery_callback_url, + "DeliveryCallbackEnabled": serialize.boolean_to_string( + delivery_callback_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The string that identifies the Service resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(friendly_name=friendly_name, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The string that identifies the Service resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The string that identifies the Service resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The string that identifies the Service resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param friendly_name: The string that identifies the Service resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param friendly_name: The string that identifies the Service resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/notify/v1/service/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/notify/v1/service/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..eedd43e0 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/notify/v1/service/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/notify/v1/service/__pycache__/binding.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/notify/v1/service/__pycache__/binding.cpython-312.pyc new file mode 100644 index 00000000..db753210 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/notify/v1/service/__pycache__/binding.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/notify/v1/service/__pycache__/notification.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/notify/v1/service/__pycache__/notification.cpython-312.pyc new file mode 100644 index 00000000..975d3b94 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/notify/v1/service/__pycache__/notification.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/notify/v1/service/binding.py b/venv/Lib/site-packages/twilio/rest/notify/v1/service/binding.py new file mode 100644 index 00000000..33b1a4aa --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/notify/v1/service/binding.py @@ -0,0 +1,681 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Notify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class BindingInstance(InstanceResource): + + class BindingType(object): + APN = "apn" + GCM = "gcm" + SMS = "sms" + FCM = "fcm" + FACEBOOK_MESSENGER = "facebook-messenger" + ALEXA = "alexa" + + """ + :ivar sid: The unique string that we created to identify the Binding resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Binding resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/notify/api/service-resource) the resource is associated with. + :ivar credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) resource to be used to send notifications to this Binding. If present, this overrides the Credential specified in the Service resource. Applicable only to `apn`, `fcm`, and `gcm` type Bindings. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar notification_protocol_version: The protocol version to use to send the notification. This defaults to the value of `default_xxxx_notification_protocol_version` in the [Service](https://www.twilio.com/docs/notify/api/service-resource) for the protocol. The current version is `\"3\"` for `apn`, `fcm`, and `gcm` type Bindings. The parameter is not applicable to `sms` and `facebook-messenger` type Bindings as the data format is fixed. + :ivar endpoint: Deprecated. + :ivar identity: The `identity` value that uniquely identifies the resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Up to 20 Bindings can be created for the same Identity in a given Service. + :ivar binding_type: The transport technology to use for the Binding. Can be: `apn`, `fcm`, `gcm`, `sms`, or `facebook-messenger`. + :ivar address: The channel-specific address. For APNS, the device token. For FCM and GCM, the registration token. For SMS, a phone number in E.164 format. For Facebook Messenger, the Messenger ID of the user or a phone number in E.164 format. + :ivar tags: The list of tags associated with this Binding. Tags can be used to select the Bindings to use when sending a notification. Maximum 20 tags are allowed. + :ivar url: The absolute URL of the Binding resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.credential_sid: Optional[str] = payload.get("credential_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.notification_protocol_version: Optional[str] = payload.get( + "notification_protocol_version" + ) + self.endpoint: Optional[str] = payload.get("endpoint") + self.identity: Optional[str] = payload.get("identity") + self.binding_type: Optional[str] = payload.get("binding_type") + self.address: Optional[str] = payload.get("address") + self.tags: Optional[List[str]] = payload.get("tags") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[BindingContext] = None + + @property + def _proxy(self) -> "BindingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BindingContext for this BindingInstance + """ + if self._context is None: + self._context = BindingContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "BindingInstance": + """ + Fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BindingInstance": + """ + Asynchronous coroutine to fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BindingContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the BindingContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/notify/api/service-resource) to fetch the resource from. + :param sid: The Twilio-provided string that uniquely identifies the Binding resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Bindings/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> BindingInstance: + """ + Fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> BindingInstance: + """ + Asynchronous coroutine to fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BindingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> BindingInstance: + """ + Build an instance of BindingInstance + + :param payload: Payload response from the API + """ + return BindingInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class BindingList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the BindingList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/notify/api/service-resource) to read the resource from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Bindings".format(**self._solution) + + def create( + self, + identity: str, + binding_type: "BindingInstance.BindingType", + address: str, + tag: Union[List[str], object] = values.unset, + notification_protocol_version: Union[str, object] = values.unset, + credential_sid: Union[str, object] = values.unset, + endpoint: Union[str, object] = values.unset, + ) -> BindingInstance: + """ + Create the BindingInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Up to 20 Bindings can be created for the same Identity in a given Service. + :param binding_type: + :param address: The channel-specific address. For APNS, the device token. For FCM and GCM, the registration token. For SMS, a phone number in E.164 format. For Facebook Messenger, the Messenger ID of the user or a phone number in E.164 format. + :param tag: A tag that can be used to select the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 20 tags. + :param notification_protocol_version: The protocol version to use to send the notification. This defaults to the value of `default_xxxx_notification_protocol_version` for the protocol in the [Service](https://www.twilio.com/docs/notify/api/service-resource). The current version is `\\\"3\\\"` for `apn`, `fcm`, and `gcm` type Bindings. The parameter is not applicable to `sms` and `facebook-messenger` type Bindings as the data format is fixed. + :param credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) resource to be used to send notifications to this Binding. If present, this overrides the Credential specified in the Service resource. Applies to only `apn`, `fcm`, and `gcm` type Bindings. + :param endpoint: Deprecated. + + :returns: The created BindingInstance + """ + + data = values.of( + { + "Identity": identity, + "BindingType": binding_type, + "Address": address, + "Tag": serialize.map(tag, lambda e: e), + "NotificationProtocolVersion": notification_protocol_version, + "CredentialSid": credential_sid, + "Endpoint": endpoint, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BindingInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + identity: str, + binding_type: "BindingInstance.BindingType", + address: str, + tag: Union[List[str], object] = values.unset, + notification_protocol_version: Union[str, object] = values.unset, + credential_sid: Union[str, object] = values.unset, + endpoint: Union[str, object] = values.unset, + ) -> BindingInstance: + """ + Asynchronously create the BindingInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Up to 20 Bindings can be created for the same Identity in a given Service. + :param binding_type: + :param address: The channel-specific address. For APNS, the device token. For FCM and GCM, the registration token. For SMS, a phone number in E.164 format. For Facebook Messenger, the Messenger ID of the user or a phone number in E.164 format. + :param tag: A tag that can be used to select the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 20 tags. + :param notification_protocol_version: The protocol version to use to send the notification. This defaults to the value of `default_xxxx_notification_protocol_version` for the protocol in the [Service](https://www.twilio.com/docs/notify/api/service-resource). The current version is `\\\"3\\\"` for `apn`, `fcm`, and `gcm` type Bindings. The parameter is not applicable to `sms` and `facebook-messenger` type Bindings as the data format is fixed. + :param credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) resource to be used to send notifications to this Binding. If present, this overrides the Credential specified in the Service resource. Applies to only `apn`, `fcm`, and `gcm` type Bindings. + :param endpoint: Deprecated. + + :returns: The created BindingInstance + """ + + data = values.of( + { + "Identity": identity, + "BindingType": binding_type, + "Address": address, + "Tag": serialize.map(tag, lambda e: e), + "NotificationProtocolVersion": notification_protocol_version, + "CredentialSid": credential_sid, + "Endpoint": endpoint, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BindingInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BindingInstance]: + """ + Streams BindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param List[str] tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + start_date=start_date, + end_date=end_date, + identity=identity, + tag=tag, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BindingInstance]: + """ + Asynchronously streams BindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param List[str] tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + start_date=start_date, + end_date=end_date, + identity=identity, + tag=tag, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BindingInstance]: + """ + Lists BindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param List[str] tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + start_date=start_date, + end_date=end_date, + identity=identity, + tag=tag, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BindingInstance]: + """ + Asynchronously lists BindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param List[str] tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + start_date=start_date, + end_date=end_date, + identity=identity, + tag=tag, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BindingPage: + """ + Retrieve a single page of BindingInstance records from the API. + Request is executed immediately + + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BindingInstance + """ + data = values.of( + { + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "Identity": serialize.map(identity, lambda e: e), + "Tag": serialize.map(tag, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BindingPage(self._version, response, self._solution) + + async def page_async( + self, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BindingPage: + """ + Asynchronously retrieve a single page of BindingInstance records from the API. + Request is executed immediately + + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BindingInstance + """ + data = values.of( + { + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "Identity": serialize.map(identity, lambda e: e), + "Tag": serialize.map(tag, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BindingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> BindingPage: + """ + Retrieve a specific page of BindingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BindingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return BindingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> BindingPage: + """ + Asynchronously retrieve a specific page of BindingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BindingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return BindingPage(self._version, response, self._solution) + + def get(self, sid: str) -> BindingContext: + """ + Constructs a BindingContext + + :param sid: The Twilio-provided string that uniquely identifies the Binding resource to fetch. + """ + return BindingContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> BindingContext: + """ + Constructs a BindingContext + + :param sid: The Twilio-provided string that uniquely identifies the Binding resource to fetch. + """ + return BindingContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/notify/v1/service/notification.py b/venv/Lib/site-packages/twilio/rest/notify/v1/service/notification.py new file mode 100644 index 00000000..4d228e86 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/notify/v1/service/notification.py @@ -0,0 +1,285 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Notify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NotificationInstance(InstanceResource): + + class Priority(object): + HIGH = "high" + LOW = "low" + + """ + :ivar sid: The unique string that we created to identify the Notification resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Notification resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/notify/api/service-resource) the resource is associated with. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar identities: The list of `identity` values of the Users to notify. We will attempt to deliver notifications only to Bindings with an identity in this list. + :ivar tags: The tags that select the Bindings to notify. Notifications will be attempted only to Bindings that have all of the tags listed in this property. + :ivar segments: The list of Segments to notify. The [Segment](https://www.twilio.com/docs/notify/api/segment-resource) resource is deprecated. Use the `tags` property, instead. + :ivar priority: + :ivar ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 2,419,200, which is 4 weeks, the default and the maximum supported time to live (TTL). Delivery should be attempted if the device is offline until the TTL elapses. Zero means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. SMS does not support this property. + :ivar title: The notification title. For FCM and GCM, this translates to the `data.twi_title` value. For APNS, this translates to the `aps.alert.title` value. SMS does not support this property. This field is not visible on iOS phones and tablets but appears on Apple Watch and Android devices. + :ivar body: The notification text. For FCM and GCM, translates to `data.twi_body`. For APNS, translates to `aps.alert.body`. For SMS, translates to `body`. SMS requires either this `body` value, or `media_urls` attribute defined in the `sms` parameter of the notification. + :ivar sound: The name of the sound to be played for the notification. For FCM and GCM, this Translates to `data.twi_sound`. For APNS, this translates to `aps.sound`. SMS does not support this property. + :ivar action: The actions to display for the notification. For APNS, translates to the `aps.category` value. For GCM, translates to the `data.twi_action` value. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :ivar data: The custom key-value pairs of the notification's payload. For FCM and GCM, this value translates to `data` in the FCM and GCM payloads. FCM and GCM [reserve certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref) that cannot be used in those channels. For APNS, attributes of `data` are inserted into the APNS payload as custom properties outside of the `aps` dictionary. In all channels, we reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed and are rejected as 400 Bad request with no delivery attempted. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :ivar apn: The APNS-specific payload that overrides corresponding attributes in the generic payload for APNS Bindings. This property maps to the APNS `Payload` item, therefore the `aps` key must be used to change standard attributes. Adds custom key-value pairs to the root of the dictionary. See the [APNS documentation](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html) for more details. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. + :ivar gcm: The GCM-specific payload that overrides corresponding attributes in the generic payload for GCM Bindings. This property maps to the root JSON dictionary. Target parameters `to`, `registration_ids`, and `notification_key` are not allowed. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. + :ivar fcm: The FCM-specific payload that overrides corresponding attributes in the generic payload for FCM Bindings. This property maps to the root JSON dictionary. See the [FCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream) for more details. Target parameters `to`, `registration_ids`, `condition`, and `notification_key` are not allowed in this parameter. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. FCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref), which cannot be used in that channel. + :ivar sms: The SMS-specific payload that overrides corresponding attributes in the generic payload for SMS Bindings. Each attribute in this value maps to the corresponding `form` parameter of the Twilio [Message](https://www.twilio.com/docs/sms/api/message-resource) resource. These parameters of the Message resource are supported in snake case format: `body`, `media_urls`, `status_callback`, and `max_price`. The `status_callback` parameter overrides the corresponding parameter in the messaging service, if configured. The `media_urls` property expects a JSON array. + :ivar facebook_messenger: Deprecated. + :ivar alexa: Deprecated. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], service_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.identities: Optional[List[str]] = payload.get("identities") + self.tags: Optional[List[str]] = payload.get("tags") + self.segments: Optional[List[str]] = payload.get("segments") + self.priority: Optional["NotificationInstance.Priority"] = payload.get( + "priority" + ) + self.ttl: Optional[int] = deserialize.integer(payload.get("ttl")) + self.title: Optional[str] = payload.get("title") + self.body: Optional[str] = payload.get("body") + self.sound: Optional[str] = payload.get("sound") + self.action: Optional[str] = payload.get("action") + self.data: Optional[Dict[str, object]] = payload.get("data") + self.apn: Optional[Dict[str, object]] = payload.get("apn") + self.gcm: Optional[Dict[str, object]] = payload.get("gcm") + self.fcm: Optional[Dict[str, object]] = payload.get("fcm") + self.sms: Optional[Dict[str, object]] = payload.get("sms") + self.facebook_messenger: Optional[Dict[str, object]] = payload.get( + "facebook_messenger" + ) + self.alexa: Optional[Dict[str, object]] = payload.get("alexa") + + self._solution = { + "service_sid": service_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NotificationList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the NotificationList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/notify/api/service-resource) to create the resource under. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Notifications".format(**self._solution) + + def create( + self, + body: Union[str, object] = values.unset, + priority: Union["NotificationInstance.Priority", object] = values.unset, + ttl: Union[int, object] = values.unset, + title: Union[str, object] = values.unset, + sound: Union[str, object] = values.unset, + action: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + apn: Union[object, object] = values.unset, + gcm: Union[object, object] = values.unset, + sms: Union[object, object] = values.unset, + facebook_messenger: Union[object, object] = values.unset, + fcm: Union[object, object] = values.unset, + segment: Union[List[str], object] = values.unset, + alexa: Union[object, object] = values.unset, + to_binding: Union[List[str], object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + ) -> NotificationInstance: + """ + Create the NotificationInstance + + :param body: The notification text. For FCM and GCM, translates to `data.twi_body`. For APNS, translates to `aps.alert.body`. For SMS, translates to `body`. SMS requires either this `body` value, or `media_urls` attribute defined in the `sms` parameter of the notification. + :param priority: + :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 2,419,200, which is 4 weeks, the default and the maximum supported time to live (TTL). Delivery should be attempted if the device is offline until the TTL elapses. Zero means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. SMS does not support this property. + :param title: The notification title. For FCM and GCM, this translates to the `data.twi_title` value. For APNS, this translates to the `aps.alert.title` value. SMS does not support this property. This field is not visible on iOS phones and tablets but appears on Apple Watch and Android devices. + :param sound: The name of the sound to be played for the notification. For FCM and GCM, this Translates to `data.twi_sound`. For APNS, this translates to `aps.sound`. SMS does not support this property. + :param action: The actions to display for the notification. For APNS, translates to the `aps.category` value. For GCM, translates to the `data.twi_action` value. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param data: The custom key-value pairs of the notification's payload. For FCM and GCM, this value translates to `data` in the FCM and GCM payloads. FCM and GCM [reserve certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref) that cannot be used in those channels. For APNS, attributes of `data` are inserted into the APNS payload as custom properties outside of the `aps` dictionary. In all channels, we reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed and are rejected as 400 Bad request with no delivery attempted. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param apn: The APNS-specific payload that overrides corresponding attributes in the generic payload for APNS Bindings. This property maps to the APNS `Payload` item, therefore the `aps` key must be used to change standard attributes. Adds custom key-value pairs to the root of the dictionary. See the [APNS documentation](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html) for more details. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. + :param gcm: The GCM-specific payload that overrides corresponding attributes in the generic payload for GCM Bindings. This property maps to the root JSON dictionary. See the [GCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref) for more details. Target parameters `to`, `registration_ids`, and `notification_key` are not allowed. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. GCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref). + :param sms: The SMS-specific payload that overrides corresponding attributes in the generic payload for SMS Bindings. Each attribute in this value maps to the corresponding `form` parameter of the Twilio [Message](https://www.twilio.com/docs/sms/quickstart) resource. These parameters of the Message resource are supported in snake case format: `body`, `media_urls`, `status_callback`, and `max_price`. The `status_callback` parameter overrides the corresponding parameter in the messaging service, if configured. The `media_urls` property expects a JSON array. + :param facebook_messenger: Deprecated. + :param fcm: The FCM-specific payload that overrides corresponding attributes in the generic payload for FCM Bindings. This property maps to the root JSON dictionary. See the [FCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream) for more details. Target parameters `to`, `registration_ids`, `condition`, and `notification_key` are not allowed in this parameter. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. FCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref), which cannot be used in that channel. + :param segment: The Segment resource is deprecated. Use the `tag` parameter, instead. + :param alexa: Deprecated. + :param to_binding: The destination address specified as a JSON string. Multiple `to_binding` parameters can be included but the total size of the request entity should not exceed 1MB. This is typically sufficient for 10,000 phone numbers. + :param delivery_callback_url: URL to send webhooks. + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Delivery will be attempted only to Bindings with an Identity in this list. No more than 20 items are allowed in this list. + :param tag: A tag that selects the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 5 tags. The implicit tag `all` is available to notify all Bindings in a Service instance. Similarly, the implicit tags `apn`, `fcm`, `gcm`, `sms` and `facebook-messenger` are available to notify all Bindings in a specific channel. + + :returns: The created NotificationInstance + """ + + data = values.of( + { + "Body": body, + "Priority": priority, + "Ttl": ttl, + "Title": title, + "Sound": sound, + "Action": action, + "Data": serialize.object(data), + "Apn": serialize.object(apn), + "Gcm": serialize.object(gcm), + "Sms": serialize.object(sms), + "FacebookMessenger": serialize.object(facebook_messenger), + "Fcm": serialize.object(fcm), + "Segment": serialize.map(segment, lambda e: e), + "Alexa": serialize.object(alexa), + "ToBinding": serialize.map(to_binding, lambda e: e), + "DeliveryCallbackUrl": delivery_callback_url, + "Identity": serialize.map(identity, lambda e: e), + "Tag": serialize.map(tag, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NotificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + body: Union[str, object] = values.unset, + priority: Union["NotificationInstance.Priority", object] = values.unset, + ttl: Union[int, object] = values.unset, + title: Union[str, object] = values.unset, + sound: Union[str, object] = values.unset, + action: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + apn: Union[object, object] = values.unset, + gcm: Union[object, object] = values.unset, + sms: Union[object, object] = values.unset, + facebook_messenger: Union[object, object] = values.unset, + fcm: Union[object, object] = values.unset, + segment: Union[List[str], object] = values.unset, + alexa: Union[object, object] = values.unset, + to_binding: Union[List[str], object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + ) -> NotificationInstance: + """ + Asynchronously create the NotificationInstance + + :param body: The notification text. For FCM and GCM, translates to `data.twi_body`. For APNS, translates to `aps.alert.body`. For SMS, translates to `body`. SMS requires either this `body` value, or `media_urls` attribute defined in the `sms` parameter of the notification. + :param priority: + :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 2,419,200, which is 4 weeks, the default and the maximum supported time to live (TTL). Delivery should be attempted if the device is offline until the TTL elapses. Zero means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. SMS does not support this property. + :param title: The notification title. For FCM and GCM, this translates to the `data.twi_title` value. For APNS, this translates to the `aps.alert.title` value. SMS does not support this property. This field is not visible on iOS phones and tablets but appears on Apple Watch and Android devices. + :param sound: The name of the sound to be played for the notification. For FCM and GCM, this Translates to `data.twi_sound`. For APNS, this translates to `aps.sound`. SMS does not support this property. + :param action: The actions to display for the notification. For APNS, translates to the `aps.category` value. For GCM, translates to the `data.twi_action` value. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param data: The custom key-value pairs of the notification's payload. For FCM and GCM, this value translates to `data` in the FCM and GCM payloads. FCM and GCM [reserve certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref) that cannot be used in those channels. For APNS, attributes of `data` are inserted into the APNS payload as custom properties outside of the `aps` dictionary. In all channels, we reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed and are rejected as 400 Bad request with no delivery attempted. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param apn: The APNS-specific payload that overrides corresponding attributes in the generic payload for APNS Bindings. This property maps to the APNS `Payload` item, therefore the `aps` key must be used to change standard attributes. Adds custom key-value pairs to the root of the dictionary. See the [APNS documentation](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html) for more details. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. + :param gcm: The GCM-specific payload that overrides corresponding attributes in the generic payload for GCM Bindings. This property maps to the root JSON dictionary. See the [GCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref) for more details. Target parameters `to`, `registration_ids`, and `notification_key` are not allowed. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. GCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref). + :param sms: The SMS-specific payload that overrides corresponding attributes in the generic payload for SMS Bindings. Each attribute in this value maps to the corresponding `form` parameter of the Twilio [Message](https://www.twilio.com/docs/sms/quickstart) resource. These parameters of the Message resource are supported in snake case format: `body`, `media_urls`, `status_callback`, and `max_price`. The `status_callback` parameter overrides the corresponding parameter in the messaging service, if configured. The `media_urls` property expects a JSON array. + :param facebook_messenger: Deprecated. + :param fcm: The FCM-specific payload that overrides corresponding attributes in the generic payload for FCM Bindings. This property maps to the root JSON dictionary. See the [FCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream) for more details. Target parameters `to`, `registration_ids`, `condition`, and `notification_key` are not allowed in this parameter. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. FCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref), which cannot be used in that channel. + :param segment: The Segment resource is deprecated. Use the `tag` parameter, instead. + :param alexa: Deprecated. + :param to_binding: The destination address specified as a JSON string. Multiple `to_binding` parameters can be included but the total size of the request entity should not exceed 1MB. This is typically sufficient for 10,000 phone numbers. + :param delivery_callback_url: URL to send webhooks. + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Delivery will be attempted only to Bindings with an Identity in this list. No more than 20 items are allowed in this list. + :param tag: A tag that selects the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 5 tags. The implicit tag `all` is available to notify all Bindings in a Service instance. Similarly, the implicit tags `apn`, `fcm`, `gcm`, `sms` and `facebook-messenger` are available to notify all Bindings in a specific channel. + + :returns: The created NotificationInstance + """ + + data = values.of( + { + "Body": body, + "Priority": priority, + "Ttl": ttl, + "Title": title, + "Sound": sound, + "Action": action, + "Data": serialize.object(data), + "Apn": serialize.object(apn), + "Gcm": serialize.object(gcm), + "Sms": serialize.object(sms), + "FacebookMessenger": serialize.object(facebook_messenger), + "Fcm": serialize.object(fcm), + "Segment": serialize.map(segment, lambda e: e), + "Alexa": serialize.object(alexa), + "ToBinding": serialize.map(to_binding, lambda e: e), + "DeliveryCallbackUrl": delivery_callback_url, + "Identity": serialize.map(identity, lambda e: e), + "Tag": serialize.map(tag, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NotificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/NumbersBase.py b/venv/Lib/site-packages/twilio/rest/numbers/NumbersBase.py new file mode 100644 index 00000000..7b9e0863 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/NumbersBase.py @@ -0,0 +1,55 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.numbers.v1 import V1 +from twilio.rest.numbers.v2 import V2 + + +class NumbersBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Numbers Domain + + :returns: Domain for Numbers + """ + super().__init__(twilio, "https://numbers.twilio.com") + self._v1: Optional[V1] = None + self._v2: Optional[V2] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Numbers + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Numbers + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/__init__.py b/venv/Lib/site-packages/twilio/rest/numbers/__init__.py new file mode 100644 index 00000000..abe9985d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/__init__.py @@ -0,0 +1,15 @@ +from warnings import warn + +from twilio.rest.numbers.NumbersBase import NumbersBase +from twilio.rest.numbers.v2.regulatory_compliance import RegulatoryComplianceList + + +class Numbers(NumbersBase): + @property + def regulatory_compliance(self) -> RegulatoryComplianceList: + warn( + "regulatory_compliance is deprecated. Use v2.regulatory_compliance instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.regulatory_compliance diff --git a/venv/Lib/site-packages/twilio/rest/numbers/__pycache__/NumbersBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/__pycache__/NumbersBase.cpython-312.pyc new file mode 100644 index 00000000..04bc53b5 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/__pycache__/NumbersBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..50693526 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/numbers/v1/__init__.py new file mode 100644 index 00000000..043364c3 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v1/__init__.py @@ -0,0 +1,135 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.numbers.v1.bulk_eligibility import BulkEligibilityList +from twilio.rest.numbers.v1.eligibility import EligibilityList +from twilio.rest.numbers.v1.porting_port_in import PortingPortInList +from twilio.rest.numbers.v1.porting_port_in_phone_number import ( + PortingPortInPhoneNumberList, +) +from twilio.rest.numbers.v1.porting_portability import PortingPortabilityList +from twilio.rest.numbers.v1.porting_webhook_configuration import ( + PortingWebhookConfigurationList, +) +from twilio.rest.numbers.v1.porting_webhook_configuration_delete import ( + PortingWebhookConfigurationDeleteList, +) +from twilio.rest.numbers.v1.porting_webhook_configuration_fetch import ( + PortingWebhookConfigurationFetchList, +) +from twilio.rest.numbers.v1.signing_request_configuration import ( + SigningRequestConfigurationList, +) + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Numbers + + :param domain: The Twilio.numbers domain + """ + super().__init__(domain, "v1") + self._bulk_eligibilities: Optional[BulkEligibilityList] = None + self._eligibilities: Optional[EligibilityList] = None + self._porting_port_ins: Optional[PortingPortInList] = None + self._porting_port_in_phone_number: Optional[PortingPortInPhoneNumberList] = ( + None + ) + self._porting_portabilities: Optional[PortingPortabilityList] = None + self._porting_webhook_configurations: Optional[ + PortingWebhookConfigurationList + ] = None + self._porting_webhook_configurations_delete: Optional[ + PortingWebhookConfigurationDeleteList + ] = None + self._porting_webhook_configuration_fetch: Optional[ + PortingWebhookConfigurationFetchList + ] = None + self._signing_request_configurations: Optional[ + SigningRequestConfigurationList + ] = None + + @property + def bulk_eligibilities(self) -> BulkEligibilityList: + if self._bulk_eligibilities is None: + self._bulk_eligibilities = BulkEligibilityList(self) + return self._bulk_eligibilities + + @property + def eligibilities(self) -> EligibilityList: + if self._eligibilities is None: + self._eligibilities = EligibilityList(self) + return self._eligibilities + + @property + def porting_port_ins(self) -> PortingPortInList: + if self._porting_port_ins is None: + self._porting_port_ins = PortingPortInList(self) + return self._porting_port_ins + + @property + def porting_port_in_phone_number(self) -> PortingPortInPhoneNumberList: + if self._porting_port_in_phone_number is None: + self._porting_port_in_phone_number = PortingPortInPhoneNumberList(self) + return self._porting_port_in_phone_number + + @property + def porting_portabilities(self) -> PortingPortabilityList: + if self._porting_portabilities is None: + self._porting_portabilities = PortingPortabilityList(self) + return self._porting_portabilities + + @property + def porting_webhook_configurations(self) -> PortingWebhookConfigurationList: + if self._porting_webhook_configurations is None: + self._porting_webhook_configurations = PortingWebhookConfigurationList(self) + return self._porting_webhook_configurations + + @property + def porting_webhook_configurations_delete( + self, + ) -> PortingWebhookConfigurationDeleteList: + if self._porting_webhook_configurations_delete is None: + self._porting_webhook_configurations_delete = ( + PortingWebhookConfigurationDeleteList(self) + ) + return self._porting_webhook_configurations_delete + + @property + def porting_webhook_configuration_fetch( + self, + ) -> PortingWebhookConfigurationFetchList: + if self._porting_webhook_configuration_fetch is None: + self._porting_webhook_configuration_fetch = ( + PortingWebhookConfigurationFetchList(self) + ) + return self._porting_webhook_configuration_fetch + + @property + def signing_request_configurations(self) -> SigningRequestConfigurationList: + if self._signing_request_configurations is None: + self._signing_request_configurations = SigningRequestConfigurationList(self) + return self._signing_request_configurations + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..3ef16dac Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/bulk_eligibility.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/bulk_eligibility.cpython-312.pyc new file mode 100644 index 00000000..14f49447 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/bulk_eligibility.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/eligibility.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/eligibility.cpython-312.pyc new file mode 100644 index 00000000..78e8050b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/eligibility.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/porting_port_in.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/porting_port_in.cpython-312.pyc new file mode 100644 index 00000000..df9b837b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/porting_port_in.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/porting_port_in_phone_number.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/porting_port_in_phone_number.cpython-312.pyc new file mode 100644 index 00000000..1719b843 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/porting_port_in_phone_number.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/porting_portability.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/porting_portability.cpython-312.pyc new file mode 100644 index 00000000..9dd4daf4 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/porting_portability.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/porting_webhook_configuration.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/porting_webhook_configuration.cpython-312.pyc new file mode 100644 index 00000000..f271adc2 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/porting_webhook_configuration.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/porting_webhook_configuration_delete.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/porting_webhook_configuration_delete.cpython-312.pyc new file mode 100644 index 00000000..d3751784 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/porting_webhook_configuration_delete.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/porting_webhook_configuration_fetch.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/porting_webhook_configuration_fetch.cpython-312.pyc new file mode 100644 index 00000000..93458a39 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/porting_webhook_configuration_fetch.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/signing_request_configuration.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/signing_request_configuration.cpython-312.pyc new file mode 100644 index 00000000..d09efb73 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v1/__pycache__/signing_request_configuration.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v1/bulk_eligibility.py b/venv/Lib/site-packages/twilio/rest/numbers/v1/bulk_eligibility.py new file mode 100644 index 00000000..766032f7 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v1/bulk_eligibility.py @@ -0,0 +1,257 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class BulkEligibilityInstance(InstanceResource): + """ + :ivar request_id: The SID of the bulk eligibility check that you want to know about. + :ivar url: This is the url of the request that you're trying to reach out to locate the resource. + :ivar results: The result set that contains the eligibility check response for each requested number, each result has at least the following attributes: phone_number: The requested phone number ,hosting_account_sid: The account sid where the phone number will be hosted, country: Phone number’s country, eligibility_status: Indicates the eligibility status of the PN (Eligible/Ineligible), eligibility_sub_status: Indicates the sub status of the eligibility , ineligibility_reason: Reason for number's ineligibility (if applicable), next_step: Suggested next step in the hosting process based on the eligibility status. + :ivar friendly_name: This is the string that you assigned as a friendly name for describing the eligibility check request. + :ivar status: This is the status of the bulk eligibility check request. (Example: COMPLETE, IN_PROGRESS) + :ivar date_created: + :ivar date_completed: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + request_id: Optional[str] = None, + ): + super().__init__(version) + + self.request_id: Optional[str] = payload.get("request_id") + self.url: Optional[str] = payload.get("url") + self.results: Optional[List[Dict[str, object]]] = payload.get("results") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional[str] = payload.get("status") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_completed: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_completed") + ) + + self._solution = { + "request_id": request_id or self.request_id, + } + self._context: Optional[BulkEligibilityContext] = None + + @property + def _proxy(self) -> "BulkEligibilityContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BulkEligibilityContext for this BulkEligibilityInstance + """ + if self._context is None: + self._context = BulkEligibilityContext( + self._version, + request_id=self._solution["request_id"], + ) + return self._context + + def fetch(self) -> "BulkEligibilityInstance": + """ + Fetch the BulkEligibilityInstance + + + :returns: The fetched BulkEligibilityInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BulkEligibilityInstance": + """ + Asynchronous coroutine to fetch the BulkEligibilityInstance + + + :returns: The fetched BulkEligibilityInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BulkEligibilityContext(InstanceContext): + + def __init__(self, version: Version, request_id: str): + """ + Initialize the BulkEligibilityContext + + :param version: Version that contains the resource + :param request_id: The SID of the bulk eligibility check that you want to know about. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "request_id": request_id, + } + self._uri = "/HostedNumber/Eligibility/Bulk/{request_id}".format( + **self._solution + ) + + def fetch(self) -> BulkEligibilityInstance: + """ + Fetch the BulkEligibilityInstance + + + :returns: The fetched BulkEligibilityInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return BulkEligibilityInstance( + self._version, + payload, + request_id=self._solution["request_id"], + ) + + async def fetch_async(self) -> BulkEligibilityInstance: + """ + Asynchronous coroutine to fetch the BulkEligibilityInstance + + + :returns: The fetched BulkEligibilityInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return BulkEligibilityInstance( + self._version, + payload, + request_id=self._solution["request_id"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BulkEligibilityList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the BulkEligibilityList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/HostedNumber/Eligibility/Bulk" + + def create( + self, body: Union[object, object] = values.unset + ) -> BulkEligibilityInstance: + """ + Create the BulkEligibilityInstance + + :param body: + + :returns: The created BulkEligibilityInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BulkEligibilityInstance(self._version, payload) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> BulkEligibilityInstance: + """ + Asynchronously create the BulkEligibilityInstance + + :param body: + + :returns: The created BulkEligibilityInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BulkEligibilityInstance(self._version, payload) + + def get(self, request_id: str) -> BulkEligibilityContext: + """ + Constructs a BulkEligibilityContext + + :param request_id: The SID of the bulk eligibility check that you want to know about. + """ + return BulkEligibilityContext(self._version, request_id=request_id) + + def __call__(self, request_id: str) -> BulkEligibilityContext: + """ + Constructs a BulkEligibilityContext + + :param request_id: The SID of the bulk eligibility check that you want to know about. + """ + return BulkEligibilityContext(self._version, request_id=request_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v1/eligibility.py b/venv/Lib/site-packages/twilio/rest/numbers/v1/eligibility.py new file mode 100644 index 00000000..8c5af0ac --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v1/eligibility.py @@ -0,0 +1,108 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class EligibilityInstance(InstanceResource): + """ + :ivar results: The result set that contains the eligibility check response for the requested number, each result has at least the following attributes: phone_number: The requested phone number ,hosting_account_sid: The account sid where the phone number will be hosted, date_last_checked: Datetime (ISO 8601) when the PN was last checked for eligibility, country: Phone number’s country, eligibility_status: Indicates the eligibility status of the PN (Eligible/Ineligible), eligibility_sub_status: Indicates the sub status of the eligibility , ineligibility_reason: Reason for number's ineligibility (if applicable), next_step: Suggested next step in the hosting process based on the eligibility status. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.results: Optional[List[Dict[str, object]]] = payload.get("results") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class EligibilityList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the EligibilityList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/HostedNumber/Eligibility" + + def create(self, body: Union[object, object] = values.unset) -> EligibilityInstance: + """ + Create the EligibilityInstance + + :param body: + + :returns: The created EligibilityInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EligibilityInstance(self._version, payload) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> EligibilityInstance: + """ + Asynchronously create the EligibilityInstance + + :param body: + + :returns: The created EligibilityInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EligibilityInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v1/porting_port_in.py b/venv/Lib/site-packages/twilio/rest/numbers/v1/porting_port_in.py new file mode 100644 index 00000000..3df2c154 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v1/porting_port_in.py @@ -0,0 +1,325 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date, datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PortingPortInInstance(InstanceResource): + """ + :ivar port_in_request_sid: The SID of the Port In request. This is a unique identifier of the port in request. + :ivar url: The URL of this Port In request + :ivar account_sid: Account Sid or subaccount where the phone number(s) will be Ported + :ivar notification_emails: Additional emails to send a copy of the signed LOA to. + :ivar target_port_in_date: Target date to port the number. We cannot guarantee that this date will be honored by the other carriers, please work with Ops to get a confirmation of the firm order commitment (FOC) date. Expected format is ISO Local Date, example: ‘2011-12-03`. This date must be at least 7 days in the future for US ports and 10 days in the future for Japanese ports. We can't guarantee the exact date and time, as this depends on the losing carrier + :ivar target_port_in_time_range_start: The earliest time that the port should occur on the target port in date. Expected format is ISO Offset Time, example: ‘10:15:00-08:00'. We can't guarantee the exact date and time, as this depends on the losing carrier + :ivar target_port_in_time_range_end: The latest time that the port should occur on the target port in date. Expected format is ISO Offset Time, example: ‘10:15:00-08:00'. We can't guarantee the exact date and time, as this depends on the losing carrier + :ivar port_in_request_status: The status of the port in request. The possible values are: In progress, Completed, Expired, In review, Waiting for Signature, Action Required, and Canceled. + :ivar losing_carrier_information: Details regarding the customer’s information with the losing carrier. These values will be used to generate the letter of authorization and should match the losing carrier’s data as closely as possible to ensure the port is accepted. + :ivar phone_numbers: + :ivar documents: List of document SIDs for all phone numbers included in the port in request. At least one document SID referring to a document of the type Utility Bill is required. + :ivar date_created: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + port_in_request_sid: Optional[str] = None, + ): + super().__init__(version) + + self.port_in_request_sid: Optional[str] = payload.get("port_in_request_sid") + self.url: Optional[str] = payload.get("url") + self.account_sid: Optional[str] = payload.get("account_sid") + self.notification_emails: Optional[List[str]] = payload.get( + "notification_emails" + ) + self.target_port_in_date: Optional[date] = deserialize.iso8601_date( + payload.get("target_port_in_date") + ) + self.target_port_in_time_range_start: Optional[str] = payload.get( + "target_port_in_time_range_start" + ) + self.target_port_in_time_range_end: Optional[str] = payload.get( + "target_port_in_time_range_end" + ) + self.port_in_request_status: Optional[str] = payload.get( + "port_in_request_status" + ) + self.losing_carrier_information: Optional[Dict[str, object]] = payload.get( + "losing_carrier_information" + ) + self.phone_numbers: Optional[List[Dict[str, object]]] = payload.get( + "phone_numbers" + ) + self.documents: Optional[List[str]] = payload.get("documents") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + + self._solution = { + "port_in_request_sid": port_in_request_sid or self.port_in_request_sid, + } + self._context: Optional[PortingPortInContext] = None + + @property + def _proxy(self) -> "PortingPortInContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PortingPortInContext for this PortingPortInInstance + """ + if self._context is None: + self._context = PortingPortInContext( + self._version, + port_in_request_sid=self._solution["port_in_request_sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the PortingPortInInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PortingPortInInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "PortingPortInInstance": + """ + Fetch the PortingPortInInstance + + + :returns: The fetched PortingPortInInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PortingPortInInstance": + """ + Asynchronous coroutine to fetch the PortingPortInInstance + + + :returns: The fetched PortingPortInInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PortingPortInContext(InstanceContext): + + def __init__(self, version: Version, port_in_request_sid: str): + """ + Initialize the PortingPortInContext + + :param version: Version that contains the resource + :param port_in_request_sid: The SID of the Port In request. This is a unique identifier of the port in request. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "port_in_request_sid": port_in_request_sid, + } + self._uri = "/Porting/PortIn/{port_in_request_sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the PortingPortInInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PortingPortInInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> PortingPortInInstance: + """ + Fetch the PortingPortInInstance + + + :returns: The fetched PortingPortInInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PortingPortInInstance( + self._version, + payload, + port_in_request_sid=self._solution["port_in_request_sid"], + ) + + async def fetch_async(self) -> PortingPortInInstance: + """ + Asynchronous coroutine to fetch the PortingPortInInstance + + + :returns: The fetched PortingPortInInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PortingPortInInstance( + self._version, + payload, + port_in_request_sid=self._solution["port_in_request_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PortingPortInList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PortingPortInList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Porting/PortIn" + + def create( + self, body: Union[object, object] = values.unset + ) -> PortingPortInInstance: + """ + Create the PortingPortInInstance + + :param body: + + :returns: The created PortingPortInInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PortingPortInInstance(self._version, payload) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> PortingPortInInstance: + """ + Asynchronously create the PortingPortInInstance + + :param body: + + :returns: The created PortingPortInInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PortingPortInInstance(self._version, payload) + + def get(self, port_in_request_sid: str) -> PortingPortInContext: + """ + Constructs a PortingPortInContext + + :param port_in_request_sid: The SID of the Port In request. This is a unique identifier of the port in request. + """ + return PortingPortInContext( + self._version, port_in_request_sid=port_in_request_sid + ) + + def __call__(self, port_in_request_sid: str) -> PortingPortInContext: + """ + Constructs a PortingPortInContext + + :param port_in_request_sid: The SID of the Port In request. This is a unique identifier of the port in request. + """ + return PortingPortInContext( + self._version, port_in_request_sid=port_in_request_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v1/porting_port_in_phone_number.py b/venv/Lib/site-packages/twilio/rest/numbers/v1/porting_port_in_phone_number.py new file mode 100644 index 00000000..cc8120f7 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v1/porting_port_in_phone_number.py @@ -0,0 +1,310 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PortingPortInPhoneNumberInstance(InstanceResource): + """ + :ivar port_in_request_sid: The unique identifier for the port in request that this phone number is associated with. + :ivar phone_number_sid: The unique identifier for this phone number associated with this port in request. + :ivar url: URL reference for this resource. + :ivar account_sid: Account Sid or subaccount where the phone number(s) will be Ported. + :ivar phone_number_type: The number type of the phone number. This can be: toll-free, local, mobile or unknown. This field may be null if the number is not portable or if the portability for a number has not yet been evaluated. + :ivar date_created: The timestamp for when this port in phone number was created. + :ivar country: The ISO country code that this number is associated with. This field may be null if the number is not portable or if the portability for a number has not yet been evaluated. + :ivar missing_required_fields: Indicates if the phone number is missing required fields such as a PIN or account number. This field may be null if the number is not portable or if the portability for a number has not yet been evaluated. + :ivar last_updated: Timestamp indicating when the Port In Phone Number resource was last modified. + :ivar phone_number: Phone number to be ported. This will be in the E164 Format. + :ivar portable: If the number is portable by Twilio or not. This field may be null if the number portability has not yet been evaluated. If a number is not portable reference the `not_portability_reason_code` and `not_portability_reason` fields for more details + :ivar not_portability_reason: The not portability reason code description. This field may be null if the number is portable or if the portability for a number has not yet been evaluated. + :ivar not_portability_reason_code: The not portability reason code. This field may be null if the number is portable or if the portability for a number has not yet been evaluated. + :ivar port_in_phone_number_status: The status of the port in phone number. + :ivar port_out_pin: The pin required by the losing carrier to do the port out. + :ivar rejection_reason: The description of the rejection reason provided by the losing carrier. This field may be null if the number has not been rejected by the losing carrier. + :ivar rejection_reason_code: The code for the rejection reason provided by the losing carrier. This field may be null if the number has not been rejected by the losing carrier. + :ivar port_date: The timestamp the phone number will be ported. This will only be set once a port date has been confirmed. Not all carriers can guarantee a specific time on the port date. Twilio will try its best to get the port completed by this time on the port date. Please subscribe to webhooks for confirmation on when a port has actually been completed. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + port_in_request_sid: Optional[str] = None, + phone_number_sid: Optional[str] = None, + ): + super().__init__(version) + + self.port_in_request_sid: Optional[str] = payload.get("port_in_request_sid") + self.phone_number_sid: Optional[str] = payload.get("phone_number_sid") + self.url: Optional[str] = payload.get("url") + self.account_sid: Optional[str] = payload.get("account_sid") + self.phone_number_type: Optional[str] = payload.get("phone_number_type") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.country: Optional[str] = payload.get("country") + self.missing_required_fields: Optional[bool] = payload.get( + "missing_required_fields" + ) + self.last_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("last_updated") + ) + self.phone_number: Optional[str] = payload.get("phone_number") + self.portable: Optional[bool] = payload.get("portable") + self.not_portability_reason: Optional[str] = payload.get( + "not_portability_reason" + ) + self.not_portability_reason_code: Optional[int] = deserialize.integer( + payload.get("not_portability_reason_code") + ) + self.port_in_phone_number_status: Optional[str] = payload.get( + "port_in_phone_number_status" + ) + self.port_out_pin: Optional[int] = deserialize.integer( + payload.get("port_out_pin") + ) + self.rejection_reason: Optional[str] = payload.get("rejection_reason") + self.rejection_reason_code: Optional[int] = deserialize.integer( + payload.get("rejection_reason_code") + ) + self.port_date: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("port_date") + ) + + self._solution = { + "port_in_request_sid": port_in_request_sid or self.port_in_request_sid, + "phone_number_sid": phone_number_sid or self.phone_number_sid, + } + self._context: Optional[PortingPortInPhoneNumberContext] = None + + @property + def _proxy(self) -> "PortingPortInPhoneNumberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PortingPortInPhoneNumberContext for this PortingPortInPhoneNumberInstance + """ + if self._context is None: + self._context = PortingPortInPhoneNumberContext( + self._version, + port_in_request_sid=self._solution["port_in_request_sid"], + phone_number_sid=self._solution["phone_number_sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the PortingPortInPhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PortingPortInPhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "PortingPortInPhoneNumberInstance": + """ + Fetch the PortingPortInPhoneNumberInstance + + + :returns: The fetched PortingPortInPhoneNumberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PortingPortInPhoneNumberInstance": + """ + Asynchronous coroutine to fetch the PortingPortInPhoneNumberInstance + + + :returns: The fetched PortingPortInPhoneNumberInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PortingPortInPhoneNumberContext(InstanceContext): + + def __init__( + self, version: Version, port_in_request_sid: str, phone_number_sid: str + ): + """ + Initialize the PortingPortInPhoneNumberContext + + :param version: Version that contains the resource + :param port_in_request_sid: The SID of the Port In request. This is a unique identifier of the port in request. + :param phone_number_sid: The SID of the Phone number. This is a unique identifier of the phone number. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "port_in_request_sid": port_in_request_sid, + "phone_number_sid": phone_number_sid, + } + self._uri = "/Porting/PortIn/{port_in_request_sid}/PhoneNumber/{phone_number_sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the PortingPortInPhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PortingPortInPhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> PortingPortInPhoneNumberInstance: + """ + Fetch the PortingPortInPhoneNumberInstance + + + :returns: The fetched PortingPortInPhoneNumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PortingPortInPhoneNumberInstance( + self._version, + payload, + port_in_request_sid=self._solution["port_in_request_sid"], + phone_number_sid=self._solution["phone_number_sid"], + ) + + async def fetch_async(self) -> PortingPortInPhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PortingPortInPhoneNumberInstance + + + :returns: The fetched PortingPortInPhoneNumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PortingPortInPhoneNumberInstance( + self._version, + payload, + port_in_request_sid=self._solution["port_in_request_sid"], + phone_number_sid=self._solution["phone_number_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PortingPortInPhoneNumberList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PortingPortInPhoneNumberList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get( + self, port_in_request_sid: str, phone_number_sid: str + ) -> PortingPortInPhoneNumberContext: + """ + Constructs a PortingPortInPhoneNumberContext + + :param port_in_request_sid: The SID of the Port In request. This is a unique identifier of the port in request. + :param phone_number_sid: The SID of the Phone number. This is a unique identifier of the phone number. + """ + return PortingPortInPhoneNumberContext( + self._version, + port_in_request_sid=port_in_request_sid, + phone_number_sid=phone_number_sid, + ) + + def __call__( + self, port_in_request_sid: str, phone_number_sid: str + ) -> PortingPortInPhoneNumberContext: + """ + Constructs a PortingPortInPhoneNumberContext + + :param port_in_request_sid: The SID of the Port In request. This is a unique identifier of the port in request. + :param phone_number_sid: The SID of the Phone number. This is a unique identifier of the phone number. + """ + return PortingPortInPhoneNumberContext( + self._version, + port_in_request_sid=port_in_request_sid, + phone_number_sid=phone_number_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v1/porting_portability.py b/venv/Lib/site-packages/twilio/rest/numbers/v1/porting_portability.py new file mode 100644 index 00000000..351cd541 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v1/porting_portability.py @@ -0,0 +1,265 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PortingPortabilityInstance(InstanceResource): + + class NumberType(object): + LOCAL = "LOCAL" + UNKNOWN = "UNKNOWN" + MOBILE = "MOBILE" + TOLL_FREE = "TOLL-FREE" + + """ + :ivar phone_number: The phone number which portability is to be checked. Phone numbers are in E.164 format (e.g. +16175551212). + :ivar account_sid: Account Sid that the phone number belongs to in Twilio. This is only returned for phone numbers that already exist in Twilio’s inventory and belong to your account or sub account. + :ivar portable: Boolean flag indicates if the phone number can be ported into Twilio through the Porting API or not. + :ivar pin_and_account_number_required: Indicates if the port in process will require a personal identification number (PIN) and an account number for this phone number. If this is true you will be required to submit both a PIN and account number from the losing carrier for this number when opening a port in request. These fields will be required in order to complete the port in process to Twilio. + :ivar not_portable_reason: Reason why the phone number cannot be ported into Twilio, `null` otherwise. + :ivar not_portable_reason_code: The Portability Reason Code for the phone number if it cannot be ported into Twilio, `null` otherwise. + :ivar number_type: + :ivar country: Country the phone number belongs to. + :ivar url: This is the url of the request that you're trying to reach out to locate the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + phone_number: Optional[str] = None, + ): + super().__init__(version) + + self.phone_number: Optional[str] = payload.get("phone_number") + self.account_sid: Optional[str] = payload.get("account_sid") + self.portable: Optional[bool] = payload.get("portable") + self.pin_and_account_number_required: Optional[bool] = payload.get( + "pin_and_account_number_required" + ) + self.not_portable_reason: Optional[str] = payload.get("not_portable_reason") + self.not_portable_reason_code: Optional[int] = deserialize.integer( + payload.get("not_portable_reason_code") + ) + self.number_type: Optional["PortingPortabilityInstance.NumberType"] = ( + payload.get("number_type") + ) + self.country: Optional[str] = payload.get("country") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "phone_number": phone_number or self.phone_number, + } + self._context: Optional[PortingPortabilityContext] = None + + @property + def _proxy(self) -> "PortingPortabilityContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PortingPortabilityContext for this PortingPortabilityInstance + """ + if self._context is None: + self._context = PortingPortabilityContext( + self._version, + phone_number=self._solution["phone_number"], + ) + return self._context + + def fetch( + self, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + ) -> "PortingPortabilityInstance": + """ + Fetch the PortingPortabilityInstance + + :param target_account_sid: Account Sid to which the number will be ported. This can be used to determine if a sub account already has the number in its inventory or a different sub account. If this is not provided, the authenticated account will be assumed to be the target account. + :param address_sid: Address Sid of customer to which the number will be ported. + + :returns: The fetched PortingPortabilityInstance + """ + return self._proxy.fetch( + target_account_sid=target_account_sid, + address_sid=address_sid, + ) + + async def fetch_async( + self, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + ) -> "PortingPortabilityInstance": + """ + Asynchronous coroutine to fetch the PortingPortabilityInstance + + :param target_account_sid: Account Sid to which the number will be ported. This can be used to determine if a sub account already has the number in its inventory or a different sub account. If this is not provided, the authenticated account will be assumed to be the target account. + :param address_sid: Address Sid of customer to which the number will be ported. + + :returns: The fetched PortingPortabilityInstance + """ + return await self._proxy.fetch_async( + target_account_sid=target_account_sid, + address_sid=address_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PortingPortabilityContext(InstanceContext): + + def __init__(self, version: Version, phone_number: str): + """ + Initialize the PortingPortabilityContext + + :param version: Version that contains the resource + :param phone_number: Phone number to check portability in e164 format. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "phone_number": phone_number, + } + self._uri = "/Porting/Portability/PhoneNumber/{phone_number}".format( + **self._solution + ) + + def fetch( + self, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + ) -> PortingPortabilityInstance: + """ + Fetch the PortingPortabilityInstance + + :param target_account_sid: Account Sid to which the number will be ported. This can be used to determine if a sub account already has the number in its inventory or a different sub account. If this is not provided, the authenticated account will be assumed to be the target account. + :param address_sid: Address Sid of customer to which the number will be ported. + + :returns: The fetched PortingPortabilityInstance + """ + + data = values.of( + { + "TargetAccountSid": target_account_sid, + "AddressSid": address_sid, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PortingPortabilityInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + async def fetch_async( + self, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + ) -> PortingPortabilityInstance: + """ + Asynchronous coroutine to fetch the PortingPortabilityInstance + + :param target_account_sid: Account Sid to which the number will be ported. This can be used to determine if a sub account already has the number in its inventory or a different sub account. If this is not provided, the authenticated account will be assumed to be the target account. + :param address_sid: Address Sid of customer to which the number will be ported. + + :returns: The fetched PortingPortabilityInstance + """ + + data = values.of( + { + "TargetAccountSid": target_account_sid, + "AddressSid": address_sid, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PortingPortabilityInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PortingPortabilityList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PortingPortabilityList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, phone_number: str) -> PortingPortabilityContext: + """ + Constructs a PortingPortabilityContext + + :param phone_number: Phone number to check portability in e164 format. + """ + return PortingPortabilityContext(self._version, phone_number=phone_number) + + def __call__(self, phone_number: str) -> PortingPortabilityContext: + """ + Constructs a PortingPortabilityContext + + :param phone_number: Phone number to check portability in e164 format. + """ + return PortingPortabilityContext(self._version, phone_number=phone_number) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v1/porting_webhook_configuration.py b/venv/Lib/site-packages/twilio/rest/numbers/v1/porting_webhook_configuration.py new file mode 100644 index 00000000..cfd9e1d0 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v1/porting_webhook_configuration.py @@ -0,0 +1,116 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PortingWebhookConfigurationInstance(InstanceResource): + """ + :ivar url: The URL of the webhook configuration request + :ivar port_in_target_url: The complete webhook url that will be called when a notification event for port in request or port in phone number happens + :ivar port_out_target_url: The complete webhook url that will be called when a notification event for a port out phone number happens. + :ivar notifications_of: A list to filter what notification events to receive for this account and its sub accounts. If it is an empty list, then it means that there are no filters for the notifications events to send in each webhook and all events will get sent. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.url: Optional[str] = payload.get("url") + self.port_in_target_url: Optional[str] = payload.get("port_in_target_url") + self.port_out_target_url: Optional[str] = payload.get("port_out_target_url") + self.notifications_of: Optional[List[str]] = payload.get("notifications_of") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class PortingWebhookConfigurationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PortingWebhookConfigurationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Porting/Configuration/Webhook" + + def create( + self, body: Union[object, object] = values.unset + ) -> PortingWebhookConfigurationInstance: + """ + Create the PortingWebhookConfigurationInstance + + :param body: + + :returns: The created PortingWebhookConfigurationInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PortingWebhookConfigurationInstance(self._version, payload) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> PortingWebhookConfigurationInstance: + """ + Asynchronously create the PortingWebhookConfigurationInstance + + :param body: + + :returns: The created PortingWebhookConfigurationInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PortingWebhookConfigurationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v1/porting_webhook_configuration_delete.py b/venv/Lib/site-packages/twilio/rest/numbers/v1/porting_webhook_configuration_delete.py new file mode 100644 index 00000000..11572f18 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v1/porting_webhook_configuration_delete.py @@ -0,0 +1,124 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from twilio.base import values +from twilio.base.instance_context import InstanceContext + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PortingWebhookConfigurationDeleteContext(InstanceContext): + + def __init__( + self, + version: Version, + webhook_type: "PortingWebhookConfigurationDeleteInstance.WebhookType", + ): + """ + Initialize the PortingWebhookConfigurationDeleteContext + + :param version: Version that contains the resource + :param webhook_type: The webhook type for the configuration to be delete. `PORT_IN`, `PORT_OUT` + """ + super().__init__(version) + + # Path Solution + self._solution = { + "webhook_type": webhook_type, + } + self._uri = "/Porting/Configuration/Webhook/{webhook_type}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the PortingWebhookConfigurationDeleteInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PortingWebhookConfigurationDeleteInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class PortingWebhookConfigurationDeleteList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PortingWebhookConfigurationDeleteList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get( + self, webhook_type: "PortingWebhookConfigurationDeleteInstance.WebhookType" + ) -> PortingWebhookConfigurationDeleteContext: + """ + Constructs a PortingWebhookConfigurationDeleteContext + + :param webhook_type: The webhook type for the configuration to be delete. `PORT_IN`, `PORT_OUT` + """ + return PortingWebhookConfigurationDeleteContext( + self._version, webhook_type=webhook_type + ) + + def __call__( + self, webhook_type: "PortingWebhookConfigurationDeleteInstance.WebhookType" + ) -> PortingWebhookConfigurationDeleteContext: + """ + Constructs a PortingWebhookConfigurationDeleteContext + + :param webhook_type: The webhook type for the configuration to be delete. `PORT_IN`, `PORT_OUT` + """ + return PortingWebhookConfigurationDeleteContext( + self._version, webhook_type=webhook_type + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v1/porting_webhook_configuration_fetch.py b/venv/Lib/site-packages/twilio/rest/numbers/v1/porting_webhook_configuration_fetch.py new file mode 100644 index 00000000..5d381768 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v1/porting_webhook_configuration_fetch.py @@ -0,0 +1,109 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PortingWebhookConfigurationFetchInstance(InstanceResource): + """ + :ivar url: The URL of the webhook configuration request + :ivar port_in_target_url: The complete webhook url that will be called when a notification event for port in request or port in phone number happens + :ivar port_out_target_url: The complete webhook url that will be called when a notification event for a port out phone number happens. + :ivar notifications_of: A list to filter what notification events to receive for this account and its sub accounts. If it is an empty list, then it means that there are no filters for the notifications events to send in each webhook and all events will get sent. + :ivar port_in_target_date_created: Creation date for the port in webhook configuration + :ivar port_out_target_date_created: Creation date for the port out webhook configuration + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.url: Optional[str] = payload.get("url") + self.port_in_target_url: Optional[str] = payload.get("port_in_target_url") + self.port_out_target_url: Optional[str] = payload.get("port_out_target_url") + self.notifications_of: Optional[List[str]] = payload.get("notifications_of") + self.port_in_target_date_created: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("port_in_target_date_created")) + ) + self.port_out_target_date_created: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("port_out_target_date_created")) + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class PortingWebhookConfigurationFetchList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PortingWebhookConfigurationFetchList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Porting/Configuration/Webhook" + + def fetch(self) -> PortingWebhookConfigurationFetchInstance: + """ + Asynchronously fetch the PortingWebhookConfigurationFetchInstance + + + :returns: The fetched PortingWebhookConfigurationFetchInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PortingWebhookConfigurationFetchInstance(self._version, payload) + + async def fetch_async(self) -> PortingWebhookConfigurationFetchInstance: + """ + Asynchronously fetch the PortingWebhookConfigurationFetchInstance + + + :returns: The fetched PortingWebhookConfigurationFetchInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PortingWebhookConfigurationFetchInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v1/signing_request_configuration.py b/venv/Lib/site-packages/twilio/rest/numbers/v1/signing_request_configuration.py new file mode 100644 index 00000000..fcfcd777 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v1/signing_request_configuration.py @@ -0,0 +1,375 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SigningRequestConfigurationInstance(InstanceResource): + """ + :ivar logo_sid: The SID of the document that includes the logo that will appear in the LOA. To upload documents follow the following guide: https://www.twilio.com/docs/phone-numbers/regulatory/getting-started/create-new-bundle-public-rest-apis#supporting-document-create + :ivar friendly_name: This is the string that you assigned as a friendly name for describing the creation of the configuration. + :ivar product: The product or service for which is requesting the signature. + :ivar country: The country ISO code to apply the configuration. + :ivar email_subject: Subject of the email that the end client will receive ex: “Twilio Hosting Request”, maximum length of 255 characters. + :ivar email_message: Content of the email that the end client will receive ex: “This is a Hosting request from Twilio, please check the document and sign it”, maximum length of 5,000 characters. + :ivar url_redirection: Url the end client will be redirected after signing a document. + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.logo_sid: Optional[str] = payload.get("logo_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.product: Optional[str] = payload.get("product") + self.country: Optional[str] = payload.get("country") + self.email_subject: Optional[str] = payload.get("email_subject") + self.email_message: Optional[str] = payload.get("email_message") + self.url_redirection: Optional[str] = payload.get("url_redirection") + self.url: Optional[str] = payload.get("url") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class SigningRequestConfigurationPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> SigningRequestConfigurationInstance: + """ + Build an instance of SigningRequestConfigurationInstance + + :param payload: Payload response from the API + """ + return SigningRequestConfigurationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SigningRequestConfigurationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SigningRequestConfigurationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/SigningRequest/Configuration" + + def create( + self, body: Union[object, object] = values.unset + ) -> SigningRequestConfigurationInstance: + """ + Create the SigningRequestConfigurationInstance + + :param body: + + :returns: The created SigningRequestConfigurationInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SigningRequestConfigurationInstance(self._version, payload) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> SigningRequestConfigurationInstance: + """ + Asynchronously create the SigningRequestConfigurationInstance + + :param body: + + :returns: The created SigningRequestConfigurationInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SigningRequestConfigurationInstance(self._version, payload) + + def stream( + self, + country: Union[str, object] = values.unset, + product: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SigningRequestConfigurationInstance]: + """ + Streams SigningRequestConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str country: The country ISO code to apply this configuration, this is an optional field, Example: US, MX + :param str product: The product or service for which is requesting the signature, this is an optional field, Example: Porting, Hosting + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + country=country, product=product, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + country: Union[str, object] = values.unset, + product: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SigningRequestConfigurationInstance]: + """ + Asynchronously streams SigningRequestConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str country: The country ISO code to apply this configuration, this is an optional field, Example: US, MX + :param str product: The product or service for which is requesting the signature, this is an optional field, Example: Porting, Hosting + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + country=country, product=product, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + country: Union[str, object] = values.unset, + product: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SigningRequestConfigurationInstance]: + """ + Lists SigningRequestConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str country: The country ISO code to apply this configuration, this is an optional field, Example: US, MX + :param str product: The product or service for which is requesting the signature, this is an optional field, Example: Porting, Hosting + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + country=country, + product=product, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + country: Union[str, object] = values.unset, + product: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SigningRequestConfigurationInstance]: + """ + Asynchronously lists SigningRequestConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str country: The country ISO code to apply this configuration, this is an optional field, Example: US, MX + :param str product: The product or service for which is requesting the signature, this is an optional field, Example: Porting, Hosting + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + country=country, + product=product, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + country: Union[str, object] = values.unset, + product: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SigningRequestConfigurationPage: + """ + Retrieve a single page of SigningRequestConfigurationInstance records from the API. + Request is executed immediately + + :param country: The country ISO code to apply this configuration, this is an optional field, Example: US, MX + :param product: The product or service for which is requesting the signature, this is an optional field, Example: Porting, Hosting + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SigningRequestConfigurationInstance + """ + data = values.of( + { + "Country": country, + "Product": product, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SigningRequestConfigurationPage(self._version, response) + + async def page_async( + self, + country: Union[str, object] = values.unset, + product: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SigningRequestConfigurationPage: + """ + Asynchronously retrieve a single page of SigningRequestConfigurationInstance records from the API. + Request is executed immediately + + :param country: The country ISO code to apply this configuration, this is an optional field, Example: US, MX + :param product: The product or service for which is requesting the signature, this is an optional field, Example: Porting, Hosting + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SigningRequestConfigurationInstance + """ + data = values.of( + { + "Country": country, + "Product": product, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SigningRequestConfigurationPage(self._version, response) + + def get_page(self, target_url: str) -> SigningRequestConfigurationPage: + """ + Retrieve a specific page of SigningRequestConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SigningRequestConfigurationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SigningRequestConfigurationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SigningRequestConfigurationPage: + """ + Asynchronously retrieve a specific page of SigningRequestConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SigningRequestConfigurationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SigningRequestConfigurationPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/__init__.py b/venv/Lib/site-packages/twilio/rest/numbers/v2/__init__.py new file mode 100644 index 00000000..04b30348 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v2/__init__.py @@ -0,0 +1,75 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.numbers.v2.authorization_document import AuthorizationDocumentList +from twilio.rest.numbers.v2.bulk_hosted_number_order import BulkHostedNumberOrderList +from twilio.rest.numbers.v2.bundle_clone import BundleCloneList +from twilio.rest.numbers.v2.hosted_number_order import HostedNumberOrderList +from twilio.rest.numbers.v2.regulatory_compliance import RegulatoryComplianceList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Numbers + + :param domain: The Twilio.numbers domain + """ + super().__init__(domain, "v2") + self._authorization_documents: Optional[AuthorizationDocumentList] = None + self._bulk_hosted_number_orders: Optional[BulkHostedNumberOrderList] = None + self._bundle_clone: Optional[BundleCloneList] = None + self._hosted_number_orders: Optional[HostedNumberOrderList] = None + self._regulatory_compliance: Optional[RegulatoryComplianceList] = None + + @property + def authorization_documents(self) -> AuthorizationDocumentList: + if self._authorization_documents is None: + self._authorization_documents = AuthorizationDocumentList(self) + return self._authorization_documents + + @property + def bulk_hosted_number_orders(self) -> BulkHostedNumberOrderList: + if self._bulk_hosted_number_orders is None: + self._bulk_hosted_number_orders = BulkHostedNumberOrderList(self) + return self._bulk_hosted_number_orders + + @property + def bundle_clone(self) -> BundleCloneList: + if self._bundle_clone is None: + self._bundle_clone = BundleCloneList(self) + return self._bundle_clone + + @property + def hosted_number_orders(self) -> HostedNumberOrderList: + if self._hosted_number_orders is None: + self._hosted_number_orders = HostedNumberOrderList(self) + return self._hosted_number_orders + + @property + def regulatory_compliance(self) -> RegulatoryComplianceList: + if self._regulatory_compliance is None: + self._regulatory_compliance = RegulatoryComplianceList(self) + return self._regulatory_compliance + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v2/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..acc47fa1 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v2/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/__pycache__/bulk_hosted_number_order.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v2/__pycache__/bulk_hosted_number_order.cpython-312.pyc new file mode 100644 index 00000000..f317392e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v2/__pycache__/bulk_hosted_number_order.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/__pycache__/bundle_clone.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v2/__pycache__/bundle_clone.cpython-312.pyc new file mode 100644 index 00000000..af6d2609 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v2/__pycache__/bundle_clone.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/__pycache__/hosted_number_order.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v2/__pycache__/hosted_number_order.cpython-312.pyc new file mode 100644 index 00000000..c947fcdc Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v2/__pycache__/hosted_number_order.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/authorization_document/__init__.py b/venv/Lib/site-packages/twilio/rest/numbers/v2/authorization_document/__init__.py new file mode 100644 index 00000000..033a32cf --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v2/authorization_document/__init__.py @@ -0,0 +1,629 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.numbers.v2.authorization_document.dependent_hosted_number_order import ( + DependentHostedNumberOrderList, +) + + +class AuthorizationDocumentInstance(InstanceResource): + + class Status(object): + OPENED = "opened" + SIGNING = "signing" + SIGNED = "signed" + CANCELED = "canceled" + FAILED = "failed" + + """ + :ivar sid: A 34 character string that uniquely identifies this AuthorizationDocument. + :ivar address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :ivar status: + :ivar email: Email that this AuthorizationDocument will be sent to for signing. + :ivar cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. + :ivar date_created: The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date that this resource was updated, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.address_sid: Optional[str] = payload.get("address_sid") + self.status: Optional["AuthorizationDocumentInstance.Status"] = payload.get( + "status" + ) + self.email: Optional[str] = payload.get("email") + self.cc_emails: Optional[List[str]] = payload.get("cc_emails") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[AuthorizationDocumentContext] = None + + @property + def _proxy(self) -> "AuthorizationDocumentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AuthorizationDocumentContext for this AuthorizationDocumentInstance + """ + if self._context is None: + self._context = AuthorizationDocumentContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AuthorizationDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AuthorizationDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AuthorizationDocumentInstance": + """ + Fetch the AuthorizationDocumentInstance + + + :returns: The fetched AuthorizationDocumentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AuthorizationDocumentInstance": + """ + Asynchronous coroutine to fetch the AuthorizationDocumentInstance + + + :returns: The fetched AuthorizationDocumentInstance + """ + return await self._proxy.fetch_async() + + @property + def dependent_hosted_number_orders(self) -> DependentHostedNumberOrderList: + """ + Access the dependent_hosted_number_orders + """ + return self._proxy.dependent_hosted_number_orders + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AuthorizationDocumentContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the AuthorizationDocumentContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this AuthorizationDocument. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/HostedNumber/AuthorizationDocuments/{sid}".format( + **self._solution + ) + + self._dependent_hosted_number_orders: Optional[ + DependentHostedNumberOrderList + ] = None + + def delete(self) -> bool: + """ + Deletes the AuthorizationDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AuthorizationDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AuthorizationDocumentInstance: + """ + Fetch the AuthorizationDocumentInstance + + + :returns: The fetched AuthorizationDocumentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AuthorizationDocumentInstance: + """ + Asynchronous coroutine to fetch the AuthorizationDocumentInstance + + + :returns: The fetched AuthorizationDocumentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + @property + def dependent_hosted_number_orders(self) -> DependentHostedNumberOrderList: + """ + Access the dependent_hosted_number_orders + """ + if self._dependent_hosted_number_orders is None: + self._dependent_hosted_number_orders = DependentHostedNumberOrderList( + self._version, + self._solution["sid"], + ) + return self._dependent_hosted_number_orders + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AuthorizationDocumentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AuthorizationDocumentInstance: + """ + Build an instance of AuthorizationDocumentInstance + + :param payload: Payload response from the API + """ + return AuthorizationDocumentInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AuthorizationDocumentList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AuthorizationDocumentList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/HostedNumber/AuthorizationDocuments" + + def create( + self, + address_sid: str, + email: str, + contact_phone_number: str, + hosted_number_order_sids: List[str], + contact_title: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + ) -> AuthorizationDocumentInstance: + """ + Create the AuthorizationDocumentInstance + + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. + + :returns: The created AuthorizationDocumentInstance + """ + + data = values.of( + { + "AddressSid": address_sid, + "Email": email, + "ContactPhoneNumber": contact_phone_number, + "HostedNumberOrderSids": serialize.map( + hosted_number_order_sids, lambda e: e + ), + "ContactTitle": contact_title, + "CcEmails": serialize.map(cc_emails, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthorizationDocumentInstance(self._version, payload) + + async def create_async( + self, + address_sid: str, + email: str, + contact_phone_number: str, + hosted_number_order_sids: List[str], + contact_title: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + ) -> AuthorizationDocumentInstance: + """ + Asynchronously create the AuthorizationDocumentInstance + + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. + + :returns: The created AuthorizationDocumentInstance + """ + + data = values.of( + { + "AddressSid": address_sid, + "Email": email, + "ContactPhoneNumber": contact_phone_number, + "HostedNumberOrderSids": serialize.map( + hosted_number_order_sids, lambda e: e + ), + "ContactTitle": contact_title, + "CcEmails": serialize.map(cc_emails, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthorizationDocumentInstance(self._version, payload) + + def stream( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AuthorizationDocumentInstance]: + """ + Streams AuthorizationDocumentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(email=email, status=status, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AuthorizationDocumentInstance]: + """ + Asynchronously streams AuthorizationDocumentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + email=email, status=status, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthorizationDocumentInstance]: + """ + Lists AuthorizationDocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + email=email, + status=status, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthorizationDocumentInstance]: + """ + Asynchronously lists AuthorizationDocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + email=email, + status=status, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AuthorizationDocumentPage: + """ + Retrieve a single page of AuthorizationDocumentInstance records from the API. + Request is executed immediately + + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AuthorizationDocumentInstance + """ + data = values.of( + { + "Email": email, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthorizationDocumentPage(self._version, response) + + async def page_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AuthorizationDocumentPage: + """ + Asynchronously retrieve a single page of AuthorizationDocumentInstance records from the API. + Request is executed immediately + + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AuthorizationDocumentInstance + """ + data = values.of( + { + "Email": email, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthorizationDocumentPage(self._version, response) + + def get_page(self, target_url: str) -> AuthorizationDocumentPage: + """ + Retrieve a specific page of AuthorizationDocumentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthorizationDocumentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AuthorizationDocumentPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AuthorizationDocumentPage: + """ + Asynchronously retrieve a specific page of AuthorizationDocumentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthorizationDocumentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AuthorizationDocumentPage(self._version, response) + + def get(self, sid: str) -> AuthorizationDocumentContext: + """ + Constructs a AuthorizationDocumentContext + + :param sid: A 34 character string that uniquely identifies this AuthorizationDocument. + """ + return AuthorizationDocumentContext(self._version, sid=sid) + + def __call__(self, sid: str) -> AuthorizationDocumentContext: + """ + Constructs a AuthorizationDocumentContext + + :param sid: A 34 character string that uniquely identifies this AuthorizationDocument. + """ + return AuthorizationDocumentContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/authorization_document/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v2/authorization_document/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..a1172387 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v2/authorization_document/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/authorization_document/__pycache__/dependent_hosted_number_order.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v2/authorization_document/__pycache__/dependent_hosted_number_order.cpython-312.pyc new file mode 100644 index 00000000..9e1fe63d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v2/authorization_document/__pycache__/dependent_hosted_number_order.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/authorization_document/dependent_hosted_number_order.py b/venv/Lib/site-packages/twilio/rest/numbers/v2/authorization_document/dependent_hosted_number_order.py new file mode 100644 index 00000000..36f961f5 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v2/authorization_document/dependent_hosted_number_order.py @@ -0,0 +1,439 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DependentHostedNumberOrderInstance(InstanceResource): + + class Status(object): + RECEIVED = "received" + VERIFIED = "verified" + PENDING_LOA = "pending-loa" + CARRIER_PROCESSING = "carrier-processing" + COMPLETED = "completed" + FAILED = "failed" + ACTION_REQUIRED = "action-required" + + """ + :ivar sid: A 34 character string that uniquely identifies this Authorization Document + :ivar bulk_hosting_request_sid: A 34 character string that uniquely identifies the bulk hosting request associated with this HostedNumberOrder. + :ivar next_step: The next step you need to take to complete the hosted number order and request it successfully. + :ivar account_sid: The unique SID identifier of the Account. + :ivar incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :ivar address_sid: A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :ivar signing_document_sid: A 34 character string that uniquely identifies the LOA document associated with this HostedNumberOrder. + :ivar phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :ivar capabilities: + :ivar friendly_name: A human readable description of this resource, up to 128 characters. + :ivar status: + :ivar failure_reason: A message that explains why a hosted_number_order went to status \"action-required\" + :ivar date_created: The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date that this resource was updated, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar email: Email of the owner of this phone number that is being hosted. + :ivar cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed + :ivar contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :ivar contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], signing_document_sid: str + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.bulk_hosting_request_sid: Optional[str] = payload.get( + "bulk_hosting_request_sid" + ) + self.next_step: Optional[str] = payload.get("next_step") + self.account_sid: Optional[str] = payload.get("account_sid") + self.incoming_phone_number_sid: Optional[str] = payload.get( + "incoming_phone_number_sid" + ) + self.address_sid: Optional[str] = payload.get("address_sid") + self.signing_document_sid: Optional[str] = payload.get("signing_document_sid") + self.phone_number: Optional[str] = payload.get("phone_number") + self.capabilities: Optional[str] = payload.get("capabilities") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["DependentHostedNumberOrderInstance.Status"] = ( + payload.get("status") + ) + self.failure_reason: Optional[str] = payload.get("failure_reason") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.email: Optional[str] = payload.get("email") + self.cc_emails: Optional[List[str]] = payload.get("cc_emails") + self.contact_title: Optional[str] = payload.get("contact_title") + self.contact_phone_number: Optional[str] = payload.get("contact_phone_number") + + self._solution = { + "signing_document_sid": signing_document_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class DependentHostedNumberOrderPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> DependentHostedNumberOrderInstance: + """ + Build an instance of DependentHostedNumberOrderInstance + + :param payload: Payload response from the API + """ + return DependentHostedNumberOrderInstance( + self._version, + payload, + signing_document_sid=self._solution["signing_document_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class DependentHostedNumberOrderList(ListResource): + + def __init__(self, version: Version, signing_document_sid: str): + """ + Initialize the DependentHostedNumberOrderList + + :param version: Version that contains the resource + :param signing_document_sid: A 34 character string that uniquely identifies the LOA document associated with this HostedNumberOrder. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "signing_document_sid": signing_document_sid, + } + self._uri = "/HostedNumber/AuthorizationDocuments/{signing_document_sid}/DependentHostedNumberOrders".format( + **self._solution + ) + + def stream( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DependentHostedNumberOrderInstance]: + """ + Streams DependentHostedNumberOrderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DependentHostedNumberOrderInstance]: + """ + Asynchronously streams DependentHostedNumberOrderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DependentHostedNumberOrderInstance]: + """ + Lists DependentHostedNumberOrderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DependentHostedNumberOrderInstance]: + """ + Asynchronously lists DependentHostedNumberOrderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DependentHostedNumberOrderPage: + """ + Retrieve a single page of DependentHostedNumberOrderInstance records from the API. + Request is executed immediately + + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 128 characters. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DependentHostedNumberOrderInstance + """ + data = values.of( + { + "Status": status, + "PhoneNumber": phone_number, + "IncomingPhoneNumberSid": incoming_phone_number_sid, + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DependentHostedNumberOrderPage(self._version, response, self._solution) + + async def page_async( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DependentHostedNumberOrderPage: + """ + Asynchronously retrieve a single page of DependentHostedNumberOrderInstance records from the API. + Request is executed immediately + + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 128 characters. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DependentHostedNumberOrderInstance + """ + data = values.of( + { + "Status": status, + "PhoneNumber": phone_number, + "IncomingPhoneNumberSid": incoming_phone_number_sid, + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DependentHostedNumberOrderPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DependentHostedNumberOrderPage: + """ + Retrieve a specific page of DependentHostedNumberOrderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DependentHostedNumberOrderInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DependentHostedNumberOrderPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DependentHostedNumberOrderPage: + """ + Asynchronously retrieve a specific page of DependentHostedNumberOrderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DependentHostedNumberOrderInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DependentHostedNumberOrderPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/bulk_hosted_number_order.py b/venv/Lib/site-packages/twilio/rest/numbers/v2/bulk_hosted_number_order.py new file mode 100644 index 00000000..7259c801 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v2/bulk_hosted_number_order.py @@ -0,0 +1,305 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class BulkHostedNumberOrderInstance(InstanceResource): + + class RequestStatus(object): + QUEUED = "QUEUED" + IN_PROGRESS = "IN_PROGRESS" + PROCESSED = "PROCESSED" + + """ + :ivar bulk_hosting_sid: A 34 character string that uniquely identifies this BulkHostedNumberOrder. + :ivar request_status: + :ivar friendly_name: A 128 character string that is a human-readable text that describes this resource. + :ivar notification_email: Email address used for send notifications about this Bulk hosted number request. + :ivar date_created: The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_completed: The date that this resource was completed, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The URL of this BulkHostedNumberOrder resource. + :ivar total_count: The total count of phone numbers in this Bulk hosting request. + :ivar results: Contains a list of all the individual hosting orders and their information, for this Bulk request. Each result object is grouped by its order status. To see a complete list of order status, please check 'https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/hosted-number-order-resource#status-values'. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + bulk_hosting_sid: Optional[str] = None, + ): + super().__init__(version) + + self.bulk_hosting_sid: Optional[str] = payload.get("bulk_hosting_sid") + self.request_status: Optional["BulkHostedNumberOrderInstance.RequestStatus"] = ( + payload.get("request_status") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.notification_email: Optional[str] = payload.get("notification_email") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_completed: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_completed") + ) + self.url: Optional[str] = payload.get("url") + self.total_count: Optional[int] = deserialize.integer( + payload.get("total_count") + ) + self.results: Optional[List[Dict[str, object]]] = payload.get("results") + + self._solution = { + "bulk_hosting_sid": bulk_hosting_sid or self.bulk_hosting_sid, + } + self._context: Optional[BulkHostedNumberOrderContext] = None + + @property + def _proxy(self) -> "BulkHostedNumberOrderContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BulkHostedNumberOrderContext for this BulkHostedNumberOrderInstance + """ + if self._context is None: + self._context = BulkHostedNumberOrderContext( + self._version, + bulk_hosting_sid=self._solution["bulk_hosting_sid"], + ) + return self._context + + def fetch( + self, order_status: Union[str, object] = values.unset + ) -> "BulkHostedNumberOrderInstance": + """ + Fetch the BulkHostedNumberOrderInstance + + :param order_status: Order status can be used for filtering on Hosted Number Order status values. To see a complete list of order statuses, please check 'https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/hosted-number-order-resource#status-values'. + + :returns: The fetched BulkHostedNumberOrderInstance + """ + return self._proxy.fetch( + order_status=order_status, + ) + + async def fetch_async( + self, order_status: Union[str, object] = values.unset + ) -> "BulkHostedNumberOrderInstance": + """ + Asynchronous coroutine to fetch the BulkHostedNumberOrderInstance + + :param order_status: Order status can be used for filtering on Hosted Number Order status values. To see a complete list of order statuses, please check 'https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/hosted-number-order-resource#status-values'. + + :returns: The fetched BulkHostedNumberOrderInstance + """ + return await self._proxy.fetch_async( + order_status=order_status, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BulkHostedNumberOrderContext(InstanceContext): + + def __init__(self, version: Version, bulk_hosting_sid: str): + """ + Initialize the BulkHostedNumberOrderContext + + :param version: Version that contains the resource + :param bulk_hosting_sid: A 34 character string that uniquely identifies this BulkHostedNumberOrder. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "bulk_hosting_sid": bulk_hosting_sid, + } + self._uri = "/HostedNumber/Orders/Bulk/{bulk_hosting_sid}".format( + **self._solution + ) + + def fetch( + self, order_status: Union[str, object] = values.unset + ) -> BulkHostedNumberOrderInstance: + """ + Fetch the BulkHostedNumberOrderInstance + + :param order_status: Order status can be used for filtering on Hosted Number Order status values. To see a complete list of order statuses, please check 'https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/hosted-number-order-resource#status-values'. + + :returns: The fetched BulkHostedNumberOrderInstance + """ + + data = values.of( + { + "OrderStatus": order_status, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return BulkHostedNumberOrderInstance( + self._version, + payload, + bulk_hosting_sid=self._solution["bulk_hosting_sid"], + ) + + async def fetch_async( + self, order_status: Union[str, object] = values.unset + ) -> BulkHostedNumberOrderInstance: + """ + Asynchronous coroutine to fetch the BulkHostedNumberOrderInstance + + :param order_status: Order status can be used for filtering on Hosted Number Order status values. To see a complete list of order statuses, please check 'https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/hosted-number-order-resource#status-values'. + + :returns: The fetched BulkHostedNumberOrderInstance + """ + + data = values.of( + { + "OrderStatus": order_status, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return BulkHostedNumberOrderInstance( + self._version, + payload, + bulk_hosting_sid=self._solution["bulk_hosting_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BulkHostedNumberOrderList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the BulkHostedNumberOrderList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/HostedNumber/Orders/Bulk" + + def create( + self, body: Union[object, object] = values.unset + ) -> BulkHostedNumberOrderInstance: + """ + Create the BulkHostedNumberOrderInstance + + :param body: + + :returns: The created BulkHostedNumberOrderInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BulkHostedNumberOrderInstance(self._version, payload) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> BulkHostedNumberOrderInstance: + """ + Asynchronously create the BulkHostedNumberOrderInstance + + :param body: + + :returns: The created BulkHostedNumberOrderInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BulkHostedNumberOrderInstance(self._version, payload) + + def get(self, bulk_hosting_sid: str) -> BulkHostedNumberOrderContext: + """ + Constructs a BulkHostedNumberOrderContext + + :param bulk_hosting_sid: A 34 character string that uniquely identifies this BulkHostedNumberOrder. + """ + return BulkHostedNumberOrderContext( + self._version, bulk_hosting_sid=bulk_hosting_sid + ) + + def __call__(self, bulk_hosting_sid: str) -> BulkHostedNumberOrderContext: + """ + Constructs a BulkHostedNumberOrderContext + + :param bulk_hosting_sid: A 34 character string that uniquely identifies this BulkHostedNumberOrder. + """ + return BulkHostedNumberOrderContext( + self._version, bulk_hosting_sid=bulk_hosting_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/bundle_clone.py b/venv/Lib/site-packages/twilio/rest/numbers/v2/bundle_clone.py new file mode 100644 index 00000000..820fbc9d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v2/bundle_clone.py @@ -0,0 +1,268 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class BundleCloneInstance(InstanceResource): + + class Status(object): + DRAFT = "draft" + PENDING_REVIEW = "pending-review" + IN_REVIEW = "in-review" + TWILIO_REJECTED = "twilio-rejected" + TWILIO_APPROVED = "twilio-approved" + PROVISIONALLY_APPROVED = "provisionally-approved" + + """ + :ivar bundle_sid: The unique string that we created to identify the Bundle resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Bundle resource. + :ivar regulation_sid: The unique string of a regulation that is associated to the Bundle resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar status: + :ivar valid_until: The date and time in GMT in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format when the resource will be valid until. + :ivar email: The email address that will receive updates when the Bundle resource changes status. + :ivar status_callback: The URL we call to inform your application of status changes. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + bundle_sid: Optional[str] = None, + ): + super().__init__(version) + + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.regulation_sid: Optional[str] = payload.get("regulation_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["BundleCloneInstance.Status"] = payload.get("status") + self.valid_until: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("valid_until") + ) + self.email: Optional[str] = payload.get("email") + self.status_callback: Optional[str] = payload.get("status_callback") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "bundle_sid": bundle_sid or self.bundle_sid, + } + self._context: Optional[BundleCloneContext] = None + + @property + def _proxy(self) -> "BundleCloneContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BundleCloneContext for this BundleCloneInstance + """ + if self._context is None: + self._context = BundleCloneContext( + self._version, + bundle_sid=self._solution["bundle_sid"], + ) + return self._context + + def create( + self, + target_account_sid: str, + move_to_draft: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "BundleCloneInstance": + """ + Create the BundleCloneInstance + + :param target_account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) where the bundle needs to be cloned. + :param move_to_draft: If set to true, the cloned bundle will be in the DRAFT state, else it will be twilio-approved + :param friendly_name: The string that you assigned to describe the cloned bundle. + + :returns: The created BundleCloneInstance + """ + return self._proxy.create( + target_account_sid, + move_to_draft=move_to_draft, + friendly_name=friendly_name, + ) + + async def create_async( + self, + target_account_sid: str, + move_to_draft: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "BundleCloneInstance": + """ + Asynchronous coroutine to create the BundleCloneInstance + + :param target_account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) where the bundle needs to be cloned. + :param move_to_draft: If set to true, the cloned bundle will be in the DRAFT state, else it will be twilio-approved + :param friendly_name: The string that you assigned to describe the cloned bundle. + + :returns: The created BundleCloneInstance + """ + return await self._proxy.create_async( + target_account_sid, + move_to_draft=move_to_draft, + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BundleCloneContext(InstanceContext): + + def __init__(self, version: Version, bundle_sid: str): + """ + Initialize the BundleCloneContext + + :param version: Version that contains the resource + :param bundle_sid: The unique string that identifies the Bundle to be cloned. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "bundle_sid": bundle_sid, + } + self._uri = "/RegulatoryCompliance/Bundles/{bundle_sid}/Clones".format( + **self._solution + ) + + def create( + self, + target_account_sid: str, + move_to_draft: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> BundleCloneInstance: + """ + Create the BundleCloneInstance + + :param target_account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) where the bundle needs to be cloned. + :param move_to_draft: If set to true, the cloned bundle will be in the DRAFT state, else it will be twilio-approved + :param friendly_name: The string that you assigned to describe the cloned bundle. + + :returns: The created BundleCloneInstance + """ + data = values.of( + { + "TargetAccountSid": target_account_sid, + "MoveToDraft": serialize.boolean_to_string(move_to_draft), + "FriendlyName": friendly_name, + } + ) + + payload = self._version.create(method="POST", uri=self._uri, data=data) + + return BundleCloneInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + async def create_async( + self, + target_account_sid: str, + move_to_draft: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> BundleCloneInstance: + """ + Asynchronous coroutine to create the BundleCloneInstance + + :param target_account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) where the bundle needs to be cloned. + :param move_to_draft: If set to true, the cloned bundle will be in the DRAFT state, else it will be twilio-approved + :param friendly_name: The string that you assigned to describe the cloned bundle. + + :returns: The created BundleCloneInstance + """ + data = values.of( + { + "TargetAccountSid": target_account_sid, + "MoveToDraft": serialize.boolean_to_string(move_to_draft), + "FriendlyName": friendly_name, + } + ) + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data + ) + + return BundleCloneInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BundleCloneList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the BundleCloneList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, bundle_sid: str) -> BundleCloneContext: + """ + Constructs a BundleCloneContext + + :param bundle_sid: The unique string that identifies the Bundle to be cloned. + """ + return BundleCloneContext(self._version, bundle_sid=bundle_sid) + + def __call__(self, bundle_sid: str) -> BundleCloneContext: + """ + Constructs a BundleCloneContext + + :param bundle_sid: The unique string that identifies the Bundle to be cloned. + """ + return BundleCloneContext(self._version, bundle_sid=bundle_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/hosted_number_order.py b/venv/Lib/site-packages/twilio/rest/numbers/v2/hosted_number_order.py new file mode 100644 index 00000000..6afa755b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v2/hosted_number_order.py @@ -0,0 +1,887 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class HostedNumberOrderInstance(InstanceResource): + + class Status(object): + TWILIO_PROCESSING = "twilio-processing" + RECEIVED = "received" + PENDING_VERIFICATION = "pending-verification" + VERIFIED = "verified" + PENDING_LOA = "pending-loa" + CARRIER_PROCESSING = "carrier-processing" + TESTING = "testing" + COMPLETED = "completed" + FAILED = "failed" + ACTION_REQUIRED = "action-required" + + class VerificationType(object): + PHONE_CALL = "phone-call" + + """ + :ivar sid: A 34 character string that uniquely identifies this HostedNumberOrder. + :ivar account_sid: A 34 character string that uniquely identifies the account. + :ivar incoming_phone_number_sid: A 34 character string that uniquely identifies the [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the phone number being hosted. + :ivar address_sid: A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :ivar signing_document_sid: A 34 character string that uniquely identifies the [Authorization Document](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource) the user needs to sign. + :ivar phone_number: Phone number to be hosted. This must be in [E.164](https://en.wikipedia.org/wiki/E.164) format, e.g., +16175551212 + :ivar capabilities: + :ivar friendly_name: A 128 character string that is a human-readable text that describes this resource. + :ivar status: + :ivar failure_reason: A message that explains why a hosted_number_order went to status \"action-required\" + :ivar date_created: The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date that this resource was updated, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar email: Email of the owner of this phone number that is being hosted. + :ivar cc_emails: A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + :ivar url: The URL of this HostedNumberOrder. + :ivar contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :ivar contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :ivar bulk_hosting_request_sid: A 34 character string that uniquely identifies the bulk hosting request associated with this HostedNumberOrder. + :ivar next_step: The next step you need to take to complete the hosted number order and request it successfully. + :ivar verification_attempts: The number of attempts made to verify ownership via a call for the hosted phone number. + :ivar verification_call_sids: The Call SIDs that identify the calls placed to verify ownership. + :ivar verification_call_delay: The number of seconds to wait before initiating the ownership verification call. Can be a value between 0 and 60, inclusive. + :ivar verification_call_extension: The numerical extension to dial when making the ownership verification call. + :ivar verification_code: The digits the user must pass in the ownership verification call. + :ivar verification_type: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.incoming_phone_number_sid: Optional[str] = payload.get( + "incoming_phone_number_sid" + ) + self.address_sid: Optional[str] = payload.get("address_sid") + self.signing_document_sid: Optional[str] = payload.get("signing_document_sid") + self.phone_number: Optional[str] = payload.get("phone_number") + self.capabilities: Optional[str] = payload.get("capabilities") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["HostedNumberOrderInstance.Status"] = payload.get( + "status" + ) + self.failure_reason: Optional[str] = payload.get("failure_reason") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.email: Optional[str] = payload.get("email") + self.cc_emails: Optional[List[str]] = payload.get("cc_emails") + self.url: Optional[str] = payload.get("url") + self.contact_title: Optional[str] = payload.get("contact_title") + self.contact_phone_number: Optional[str] = payload.get("contact_phone_number") + self.bulk_hosting_request_sid: Optional[str] = payload.get( + "bulk_hosting_request_sid" + ) + self.next_step: Optional[str] = payload.get("next_step") + self.verification_attempts: Optional[int] = deserialize.integer( + payload.get("verification_attempts") + ) + self.verification_call_sids: Optional[List[str]] = payload.get( + "verification_call_sids" + ) + self.verification_call_delay: Optional[int] = deserialize.integer( + payload.get("verification_call_delay") + ) + self.verification_call_extension: Optional[str] = payload.get( + "verification_call_extension" + ) + self.verification_code: Optional[str] = payload.get("verification_code") + self.verification_type: Optional[ + "HostedNumberOrderInstance.VerificationType" + ] = payload.get("verification_type") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[HostedNumberOrderContext] = None + + @property + def _proxy(self) -> "HostedNumberOrderContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: HostedNumberOrderContext for this HostedNumberOrderInstance + """ + if self._context is None: + self._context = HostedNumberOrderContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the HostedNumberOrderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the HostedNumberOrderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "HostedNumberOrderInstance": + """ + Fetch the HostedNumberOrderInstance + + + :returns: The fetched HostedNumberOrderInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "HostedNumberOrderInstance": + """ + Asynchronous coroutine to fetch the HostedNumberOrderInstance + + + :returns: The fetched HostedNumberOrderInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + status: "HostedNumberOrderInstance.Status", + verification_call_delay: Union[int, object] = values.unset, + verification_call_extension: Union[str, object] = values.unset, + ) -> "HostedNumberOrderInstance": + """ + Update the HostedNumberOrderInstance + + :param status: + :param verification_call_delay: The number of seconds to wait before initiating the ownership verification call. Can be a value between 0 and 60, inclusive. + :param verification_call_extension: The numerical extension to dial when making the ownership verification call. + + :returns: The updated HostedNumberOrderInstance + """ + return self._proxy.update( + status=status, + verification_call_delay=verification_call_delay, + verification_call_extension=verification_call_extension, + ) + + async def update_async( + self, + status: "HostedNumberOrderInstance.Status", + verification_call_delay: Union[int, object] = values.unset, + verification_call_extension: Union[str, object] = values.unset, + ) -> "HostedNumberOrderInstance": + """ + Asynchronous coroutine to update the HostedNumberOrderInstance + + :param status: + :param verification_call_delay: The number of seconds to wait before initiating the ownership verification call. Can be a value between 0 and 60, inclusive. + :param verification_call_extension: The numerical extension to dial when making the ownership verification call. + + :returns: The updated HostedNumberOrderInstance + """ + return await self._proxy.update_async( + status=status, + verification_call_delay=verification_call_delay, + verification_call_extension=verification_call_extension, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class HostedNumberOrderContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the HostedNumberOrderContext + + :param version: Version that contains the resource + :param sid: The SID of the HostedNumberOrder resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/HostedNumber/Orders/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the HostedNumberOrderInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the HostedNumberOrderInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> HostedNumberOrderInstance: + """ + Fetch the HostedNumberOrderInstance + + + :returns: The fetched HostedNumberOrderInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> HostedNumberOrderInstance: + """ + Asynchronous coroutine to fetch the HostedNumberOrderInstance + + + :returns: The fetched HostedNumberOrderInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + status: "HostedNumberOrderInstance.Status", + verification_call_delay: Union[int, object] = values.unset, + verification_call_extension: Union[str, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Update the HostedNumberOrderInstance + + :param status: + :param verification_call_delay: The number of seconds to wait before initiating the ownership verification call. Can be a value between 0 and 60, inclusive. + :param verification_call_extension: The numerical extension to dial when making the ownership verification call. + + :returns: The updated HostedNumberOrderInstance + """ + + data = values.of( + { + "Status": status, + "VerificationCallDelay": verification_call_delay, + "VerificationCallExtension": verification_call_extension, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, + status: "HostedNumberOrderInstance.Status", + verification_call_delay: Union[int, object] = values.unset, + verification_call_extension: Union[str, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Asynchronous coroutine to update the HostedNumberOrderInstance + + :param status: + :param verification_call_delay: The number of seconds to wait before initiating the ownership verification call. Can be a value between 0 and 60, inclusive. + :param verification_call_extension: The numerical extension to dial when making the ownership verification call. + + :returns: The updated HostedNumberOrderInstance + """ + + data = values.of( + { + "Status": status, + "VerificationCallDelay": verification_call_delay, + "VerificationCallExtension": verification_call_extension, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class HostedNumberOrderPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> HostedNumberOrderInstance: + """ + Build an instance of HostedNumberOrderInstance + + :param payload: Payload response from the API + """ + return HostedNumberOrderInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class HostedNumberOrderList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the HostedNumberOrderList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/HostedNumber/Orders" + + def create( + self, + phone_number: str, + contact_phone_number: str, + address_sid: str, + email: str, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + contact_title: Union[str, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Create the HostedNumberOrderInstance + + :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :param address_sid: Optional. A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :param email: Optional. Email of the owner of this phone number that is being hosted. + :param account_sid: This defaults to the AccountSid of the authorization the user is using. This can be provided to specify a subaccount to add the HostedNumberOrder to. + :param friendly_name: A 128 character string that is a human readable text that describes this resource. + :param cc_emails: Optional. A list of emails that the LOA document for this HostedNumberOrder will be carbon copied to. + :param sms_url: The URL that Twilio should request when somebody sends an SMS to the phone number. This will be copied onto the IncomingPhoneNumber resource. + :param sms_method: The HTTP method that should be used to request the SmsUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_url: A URL that Twilio will request if an error occurs requesting or executing the TwiML defined by SmsUrl. This will be copied onto the IncomingPhoneNumber resource. + :param sms_capability: Used to specify that the SMS capability will be hosted on Twilio's platform. + :param sms_fallback_method: The HTTP method that should be used to request the SmsFallbackUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param status_callback_url: Optional. The Status Callback URL attached to the IncomingPhoneNumber resource. + :param status_callback_method: Optional. The Status Callback Method attached to the IncomingPhoneNumber resource. + :param sms_application_sid: Optional. The 34 character sid of the application Twilio should use to handle SMS messages sent to this number. If a `SmsApplicationSid` is present, Twilio will ignore all of the SMS urls above and use those set on the application. + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + + :returns: The created HostedNumberOrderInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "ContactPhoneNumber": contact_phone_number, + "AddressSid": address_sid, + "Email": email, + "AccountSid": account_sid, + "FriendlyName": friendly_name, + "CcEmails": serialize.map(cc_emails, lambda e: e), + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsCapability": serialize.boolean_to_string(sms_capability), + "SmsFallbackMethod": sms_fallback_method, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "SmsApplicationSid": sms_application_sid, + "ContactTitle": contact_title, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return HostedNumberOrderInstance(self._version, payload) + + async def create_async( + self, + phone_number: str, + contact_phone_number: str, + address_sid: str, + email: str, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + contact_title: Union[str, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Asynchronously create the HostedNumberOrderInstance + + :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :param address_sid: Optional. A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :param email: Optional. Email of the owner of this phone number that is being hosted. + :param account_sid: This defaults to the AccountSid of the authorization the user is using. This can be provided to specify a subaccount to add the HostedNumberOrder to. + :param friendly_name: A 128 character string that is a human readable text that describes this resource. + :param cc_emails: Optional. A list of emails that the LOA document for this HostedNumberOrder will be carbon copied to. + :param sms_url: The URL that Twilio should request when somebody sends an SMS to the phone number. This will be copied onto the IncomingPhoneNumber resource. + :param sms_method: The HTTP method that should be used to request the SmsUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_url: A URL that Twilio will request if an error occurs requesting or executing the TwiML defined by SmsUrl. This will be copied onto the IncomingPhoneNumber resource. + :param sms_capability: Used to specify that the SMS capability will be hosted on Twilio's platform. + :param sms_fallback_method: The HTTP method that should be used to request the SmsFallbackUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param status_callback_url: Optional. The Status Callback URL attached to the IncomingPhoneNumber resource. + :param status_callback_method: Optional. The Status Callback Method attached to the IncomingPhoneNumber resource. + :param sms_application_sid: Optional. The 34 character sid of the application Twilio should use to handle SMS messages sent to this number. If a `SmsApplicationSid` is present, Twilio will ignore all of the SMS urls above and use those set on the application. + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + + :returns: The created HostedNumberOrderInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "ContactPhoneNumber": contact_phone_number, + "AddressSid": address_sid, + "Email": email, + "AccountSid": account_sid, + "FriendlyName": friendly_name, + "CcEmails": serialize.map(cc_emails, lambda e: e), + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsCapability": serialize.boolean_to_string(sms_capability), + "SmsFallbackMethod": sms_fallback_method, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "SmsApplicationSid": sms_application_sid, + "ContactTitle": contact_title, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return HostedNumberOrderInstance(self._version, payload) + + def stream( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[HostedNumberOrderInstance]: + """ + Streams HostedNumberOrderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param bool sms_capability: Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + sms_capability=sms_capability, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[HostedNumberOrderInstance]: + """ + Asynchronously streams HostedNumberOrderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param bool sms_capability: Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + sms_capability=sms_capability, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[HostedNumberOrderInstance]: + """ + Lists HostedNumberOrderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param bool sms_capability: Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + sms_capability=sms_capability, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[HostedNumberOrderInstance]: + """ + Asynchronously lists HostedNumberOrderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param bool sms_capability: Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + sms_capability=sms_capability, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> HostedNumberOrderPage: + """ + Retrieve a single page of HostedNumberOrderInstance records from the API. + Request is executed immediately + + :param status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param sms_capability: Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 128 characters. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of HostedNumberOrderInstance + """ + data = values.of( + { + "Status": status, + "SmsCapability": serialize.boolean_to_string(sms_capability), + "PhoneNumber": phone_number, + "IncomingPhoneNumberSid": incoming_phone_number_sid, + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return HostedNumberOrderPage(self._version, response) + + async def page_async( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> HostedNumberOrderPage: + """ + Asynchronously retrieve a single page of HostedNumberOrderInstance records from the API. + Request is executed immediately + + :param status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param sms_capability: Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 128 characters. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of HostedNumberOrderInstance + """ + data = values.of( + { + "Status": status, + "SmsCapability": serialize.boolean_to_string(sms_capability), + "PhoneNumber": phone_number, + "IncomingPhoneNumberSid": incoming_phone_number_sid, + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return HostedNumberOrderPage(self._version, response) + + def get_page(self, target_url: str) -> HostedNumberOrderPage: + """ + Retrieve a specific page of HostedNumberOrderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of HostedNumberOrderInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return HostedNumberOrderPage(self._version, response) + + async def get_page_async(self, target_url: str) -> HostedNumberOrderPage: + """ + Asynchronously retrieve a specific page of HostedNumberOrderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of HostedNumberOrderInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return HostedNumberOrderPage(self._version, response) + + def get(self, sid: str) -> HostedNumberOrderContext: + """ + Constructs a HostedNumberOrderContext + + :param sid: The SID of the HostedNumberOrder resource to update. + """ + return HostedNumberOrderContext(self._version, sid=sid) + + def __call__(self, sid: str) -> HostedNumberOrderContext: + """ + Constructs a HostedNumberOrderContext + + :param sid: The SID of the HostedNumberOrder resource to update. + """ + return HostedNumberOrderContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/__init__.py b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/__init__.py new file mode 100644 index 00000000..189117d8 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/__init__.py @@ -0,0 +1,113 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.numbers.v2.regulatory_compliance.bundle import BundleList +from twilio.rest.numbers.v2.regulatory_compliance.end_user import EndUserList +from twilio.rest.numbers.v2.regulatory_compliance.end_user_type import EndUserTypeList +from twilio.rest.numbers.v2.regulatory_compliance.regulation import RegulationList +from twilio.rest.numbers.v2.regulatory_compliance.supporting_document import ( + SupportingDocumentList, +) +from twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type import ( + SupportingDocumentTypeList, +) + + +class RegulatoryComplianceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the RegulatoryComplianceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/RegulatoryCompliance" + + self._bundles: Optional[BundleList] = None + self._end_users: Optional[EndUserList] = None + self._end_user_types: Optional[EndUserTypeList] = None + self._regulations: Optional[RegulationList] = None + self._supporting_documents: Optional[SupportingDocumentList] = None + self._supporting_document_types: Optional[SupportingDocumentTypeList] = None + + @property + def bundles(self) -> BundleList: + """ + Access the bundles + """ + if self._bundles is None: + self._bundles = BundleList(self._version) + return self._bundles + + @property + def end_users(self) -> EndUserList: + """ + Access the end_users + """ + if self._end_users is None: + self._end_users = EndUserList(self._version) + return self._end_users + + @property + def end_user_types(self) -> EndUserTypeList: + """ + Access the end_user_types + """ + if self._end_user_types is None: + self._end_user_types = EndUserTypeList(self._version) + return self._end_user_types + + @property + def regulations(self) -> RegulationList: + """ + Access the regulations + """ + if self._regulations is None: + self._regulations = RegulationList(self._version) + return self._regulations + + @property + def supporting_documents(self) -> SupportingDocumentList: + """ + Access the supporting_documents + """ + if self._supporting_documents is None: + self._supporting_documents = SupportingDocumentList(self._version) + return self._supporting_documents + + @property + def supporting_document_types(self) -> SupportingDocumentTypeList: + """ + Access the supporting_document_types + """ + if self._supporting_document_types is None: + self._supporting_document_types = SupportingDocumentTypeList(self._version) + return self._supporting_document_types + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..4d9785d2 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/__pycache__/end_user.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/__pycache__/end_user.cpython-312.pyc new file mode 100644 index 00000000..66d6b799 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/__pycache__/end_user.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/__pycache__/end_user_type.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/__pycache__/end_user_type.cpython-312.pyc new file mode 100644 index 00000000..1a93c678 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/__pycache__/end_user_type.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/__pycache__/regulation.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/__pycache__/regulation.cpython-312.pyc new file mode 100644 index 00000000..13c9a883 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/__pycache__/regulation.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/__pycache__/supporting_document.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/__pycache__/supporting_document.cpython-312.pyc new file mode 100644 index 00000000..78717c91 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/__pycache__/supporting_document.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/__pycache__/supporting_document_type.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/__pycache__/supporting_document_type.cpython-312.pyc new file mode 100644 index 00000000..84809135 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/__pycache__/supporting_document_type.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/__init__.py b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/__init__.py new file mode 100644 index 00000000..079540d8 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/__init__.py @@ -0,0 +1,1013 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.numbers.v2.regulatory_compliance.bundle.bundle_copy import ( + BundleCopyList, +) +from twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation import ( + EvaluationList, +) +from twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment import ( + ItemAssignmentList, +) +from twilio.rest.numbers.v2.regulatory_compliance.bundle.replace_items import ( + ReplaceItemsList, +) + + +class BundleInstance(InstanceResource): + + class EndUserType(object): + INDIVIDUAL = "individual" + BUSINESS = "business" + + class SortBy(object): + VALID_UNTIL = "valid-until" + DATE_UPDATED = "date-updated" + + class SortDirection(object): + ASC = "ASC" + DESC = "DESC" + + class Status(object): + DRAFT = "draft" + PENDING_REVIEW = "pending-review" + IN_REVIEW = "in-review" + TWILIO_REJECTED = "twilio-rejected" + TWILIO_APPROVED = "twilio-approved" + PROVISIONALLY_APPROVED = "provisionally-approved" + + """ + :ivar sid: The unique string that we created to identify the Bundle resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Bundle resource. + :ivar regulation_sid: The unique string of a regulation that is associated to the Bundle resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar status: + :ivar valid_until: The date and time in GMT in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format when the resource will be valid until. + :ivar email: The email address that will receive updates when the Bundle resource changes status. + :ivar status_callback: The URL we call to inform your application of status changes. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Bundle resource. + :ivar links: The URLs of the Assigned Items of the Bundle resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.regulation_sid: Optional[str] = payload.get("regulation_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["BundleInstance.Status"] = payload.get("status") + self.valid_until: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("valid_until") + ) + self.email: Optional[str] = payload.get("email") + self.status_callback: Optional[str] = payload.get("status_callback") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[BundleContext] = None + + @property + def _proxy(self) -> "BundleContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BundleContext for this BundleInstance + """ + if self._context is None: + self._context = BundleContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the BundleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BundleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "BundleInstance": + """ + Fetch the BundleInstance + + + :returns: The fetched BundleInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BundleInstance": + """ + Asynchronous coroutine to fetch the BundleInstance + + + :returns: The fetched BundleInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + status: Union["BundleInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> "BundleInstance": + """ + Update the BundleInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Bundle resource changes status. + + :returns: The updated BundleInstance + """ + return self._proxy.update( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + + async def update_async( + self, + status: Union["BundleInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> "BundleInstance": + """ + Asynchronous coroutine to update the BundleInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Bundle resource changes status. + + :returns: The updated BundleInstance + """ + return await self._proxy.update_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + + @property + def bundle_copies(self) -> BundleCopyList: + """ + Access the bundle_copies + """ + return self._proxy.bundle_copies + + @property + def evaluations(self) -> EvaluationList: + """ + Access the evaluations + """ + return self._proxy.evaluations + + @property + def item_assignments(self) -> ItemAssignmentList: + """ + Access the item_assignments + """ + return self._proxy.item_assignments + + @property + def replace_items(self) -> ReplaceItemsList: + """ + Access the replace_items + """ + return self._proxy.replace_items + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BundleContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the BundleContext + + :param version: Version that contains the resource + :param sid: The unique string that we created to identify the Bundle resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/RegulatoryCompliance/Bundles/{sid}".format(**self._solution) + + self._bundle_copies: Optional[BundleCopyList] = None + self._evaluations: Optional[EvaluationList] = None + self._item_assignments: Optional[ItemAssignmentList] = None + self._replace_items: Optional[ReplaceItemsList] = None + + def delete(self) -> bool: + """ + Deletes the BundleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BundleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> BundleInstance: + """ + Fetch the BundleInstance + + + :returns: The fetched BundleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return BundleInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> BundleInstance: + """ + Asynchronous coroutine to fetch the BundleInstance + + + :returns: The fetched BundleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return BundleInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + status: Union["BundleInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> BundleInstance: + """ + Update the BundleInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Bundle resource changes status. + + :returns: The updated BundleInstance + """ + + data = values.of( + { + "Status": status, + "StatusCallback": status_callback, + "FriendlyName": friendly_name, + "Email": email, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BundleInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + status: Union["BundleInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> BundleInstance: + """ + Asynchronous coroutine to update the BundleInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Bundle resource changes status. + + :returns: The updated BundleInstance + """ + + data = values.of( + { + "Status": status, + "StatusCallback": status_callback, + "FriendlyName": friendly_name, + "Email": email, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BundleInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def bundle_copies(self) -> BundleCopyList: + """ + Access the bundle_copies + """ + if self._bundle_copies is None: + self._bundle_copies = BundleCopyList( + self._version, + self._solution["sid"], + ) + return self._bundle_copies + + @property + def evaluations(self) -> EvaluationList: + """ + Access the evaluations + """ + if self._evaluations is None: + self._evaluations = EvaluationList( + self._version, + self._solution["sid"], + ) + return self._evaluations + + @property + def item_assignments(self) -> ItemAssignmentList: + """ + Access the item_assignments + """ + if self._item_assignments is None: + self._item_assignments = ItemAssignmentList( + self._version, + self._solution["sid"], + ) + return self._item_assignments + + @property + def replace_items(self) -> ReplaceItemsList: + """ + Access the replace_items + """ + if self._replace_items is None: + self._replace_items = ReplaceItemsList( + self._version, + self._solution["sid"], + ) + return self._replace_items + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BundlePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> BundleInstance: + """ + Build an instance of BundleInstance + + :param payload: Payload response from the API + """ + return BundleInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class BundleList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the BundleList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/RegulatoryCompliance/Bundles" + + def create( + self, + friendly_name: str, + email: str, + status_callback: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + end_user_type: Union["BundleInstance.EndUserType", object] = values.unset, + number_type: Union[str, object] = values.unset, + is_test: Union[bool, object] = values.unset, + ) -> BundleInstance: + """ + Create the BundleInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Bundle resource changes status. + :param status_callback: The URL we call to inform your application of status changes. + :param regulation_sid: The unique string of a regulation that is associated to the Bundle resource. + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param end_user_type: + :param number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param is_test: Indicates that Bundle is a Test Bundle and will be Auto-Rejected + + :returns: The created BundleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Email": email, + "StatusCallback": status_callback, + "RegulationSid": regulation_sid, + "IsoCountry": iso_country, + "EndUserType": end_user_type, + "NumberType": number_type, + "IsTest": serialize.boolean_to_string(is_test), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BundleInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + email: str, + status_callback: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + end_user_type: Union["BundleInstance.EndUserType", object] = values.unset, + number_type: Union[str, object] = values.unset, + is_test: Union[bool, object] = values.unset, + ) -> BundleInstance: + """ + Asynchronously create the BundleInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Bundle resource changes status. + :param status_callback: The URL we call to inform your application of status changes. + :param regulation_sid: The unique string of a regulation that is associated to the Bundle resource. + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param end_user_type: + :param number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param is_test: Indicates that Bundle is a Test Bundle and will be Auto-Rejected + + :returns: The created BundleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Email": email, + "StatusCallback": status_callback, + "RegulationSid": regulation_sid, + "IsoCountry": iso_country, + "EndUserType": end_user_type, + "NumberType": number_type, + "IsTest": serialize.boolean_to_string(is_test), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BundleInstance(self._version, payload) + + def stream( + self, + status: Union["BundleInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + has_valid_until_date: Union[bool, object] = values.unset, + sort_by: Union["BundleInstance.SortBy", object] = values.unset, + sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, + valid_until_date: Union[datetime, object] = values.unset, + valid_until_date_before: Union[datetime, object] = values.unset, + valid_until_date_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BundleInstance]: + """ + Streams BundleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "BundleInstance.Status" status: The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. + :param str friendly_name: The string that you assigned to describe the resource. The column can contain 255 variable characters. + :param str regulation_sid: The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. + :param str iso_country: The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param str number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param bool has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. + :param "BundleInstance.SortBy" sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. + :param "BundleInstance.SortDirection" sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. + :param datetime valid_until_date: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param datetime valid_until_date_before: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param datetime valid_until_date_after: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + friendly_name=friendly_name, + regulation_sid=regulation_sid, + iso_country=iso_country, + number_type=number_type, + has_valid_until_date=has_valid_until_date, + sort_by=sort_by, + sort_direction=sort_direction, + valid_until_date=valid_until_date, + valid_until_date_before=valid_until_date_before, + valid_until_date_after=valid_until_date_after, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["BundleInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + has_valid_until_date: Union[bool, object] = values.unset, + sort_by: Union["BundleInstance.SortBy", object] = values.unset, + sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, + valid_until_date: Union[datetime, object] = values.unset, + valid_until_date_before: Union[datetime, object] = values.unset, + valid_until_date_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BundleInstance]: + """ + Asynchronously streams BundleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "BundleInstance.Status" status: The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. + :param str friendly_name: The string that you assigned to describe the resource. The column can contain 255 variable characters. + :param str regulation_sid: The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. + :param str iso_country: The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param str number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param bool has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. + :param "BundleInstance.SortBy" sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. + :param "BundleInstance.SortDirection" sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. + :param datetime valid_until_date: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param datetime valid_until_date_before: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param datetime valid_until_date_after: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + friendly_name=friendly_name, + regulation_sid=regulation_sid, + iso_country=iso_country, + number_type=number_type, + has_valid_until_date=has_valid_until_date, + sort_by=sort_by, + sort_direction=sort_direction, + valid_until_date=valid_until_date, + valid_until_date_before=valid_until_date_before, + valid_until_date_after=valid_until_date_after, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["BundleInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + has_valid_until_date: Union[bool, object] = values.unset, + sort_by: Union["BundleInstance.SortBy", object] = values.unset, + sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, + valid_until_date: Union[datetime, object] = values.unset, + valid_until_date_before: Union[datetime, object] = values.unset, + valid_until_date_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BundleInstance]: + """ + Lists BundleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "BundleInstance.Status" status: The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. + :param str friendly_name: The string that you assigned to describe the resource. The column can contain 255 variable characters. + :param str regulation_sid: The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. + :param str iso_country: The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param str number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param bool has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. + :param "BundleInstance.SortBy" sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. + :param "BundleInstance.SortDirection" sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. + :param datetime valid_until_date: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param datetime valid_until_date_before: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param datetime valid_until_date_after: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + friendly_name=friendly_name, + regulation_sid=regulation_sid, + iso_country=iso_country, + number_type=number_type, + has_valid_until_date=has_valid_until_date, + sort_by=sort_by, + sort_direction=sort_direction, + valid_until_date=valid_until_date, + valid_until_date_before=valid_until_date_before, + valid_until_date_after=valid_until_date_after, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["BundleInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + has_valid_until_date: Union[bool, object] = values.unset, + sort_by: Union["BundleInstance.SortBy", object] = values.unset, + sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, + valid_until_date: Union[datetime, object] = values.unset, + valid_until_date_before: Union[datetime, object] = values.unset, + valid_until_date_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BundleInstance]: + """ + Asynchronously lists BundleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "BundleInstance.Status" status: The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. + :param str friendly_name: The string that you assigned to describe the resource. The column can contain 255 variable characters. + :param str regulation_sid: The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. + :param str iso_country: The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param str number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param bool has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. + :param "BundleInstance.SortBy" sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. + :param "BundleInstance.SortDirection" sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. + :param datetime valid_until_date: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param datetime valid_until_date_before: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param datetime valid_until_date_after: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + friendly_name=friendly_name, + regulation_sid=regulation_sid, + iso_country=iso_country, + number_type=number_type, + has_valid_until_date=has_valid_until_date, + sort_by=sort_by, + sort_direction=sort_direction, + valid_until_date=valid_until_date, + valid_until_date_before=valid_until_date_before, + valid_until_date_after=valid_until_date_after, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["BundleInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + has_valid_until_date: Union[bool, object] = values.unset, + sort_by: Union["BundleInstance.SortBy", object] = values.unset, + sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, + valid_until_date: Union[datetime, object] = values.unset, + valid_until_date_before: Union[datetime, object] = values.unset, + valid_until_date_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BundlePage: + """ + Retrieve a single page of BundleInstance records from the API. + Request is executed immediately + + :param status: The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. + :param friendly_name: The string that you assigned to describe the resource. The column can contain 255 variable characters. + :param regulation_sid: The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. + :param iso_country: The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. + :param sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. + :param sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. + :param valid_until_date: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param valid_until_date_before: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param valid_until_date_after: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BundleInstance + """ + data = values.of( + { + "Status": status, + "FriendlyName": friendly_name, + "RegulationSid": regulation_sid, + "IsoCountry": iso_country, + "NumberType": number_type, + "HasValidUntilDate": serialize.boolean_to_string(has_valid_until_date), + "SortBy": sort_by, + "SortDirection": sort_direction, + "ValidUntilDate": serialize.iso8601_datetime(valid_until_date), + "ValidUntilDate<": serialize.iso8601_datetime(valid_until_date_before), + "ValidUntilDate>": serialize.iso8601_datetime(valid_until_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BundlePage(self._version, response) + + async def page_async( + self, + status: Union["BundleInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + has_valid_until_date: Union[bool, object] = values.unset, + sort_by: Union["BundleInstance.SortBy", object] = values.unset, + sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, + valid_until_date: Union[datetime, object] = values.unset, + valid_until_date_before: Union[datetime, object] = values.unset, + valid_until_date_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BundlePage: + """ + Asynchronously retrieve a single page of BundleInstance records from the API. + Request is executed immediately + + :param status: The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. + :param friendly_name: The string that you assigned to describe the resource. The column can contain 255 variable characters. + :param regulation_sid: The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. + :param iso_country: The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. + :param sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. + :param sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. + :param valid_until_date: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param valid_until_date_before: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param valid_until_date_after: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BundleInstance + """ + data = values.of( + { + "Status": status, + "FriendlyName": friendly_name, + "RegulationSid": regulation_sid, + "IsoCountry": iso_country, + "NumberType": number_type, + "HasValidUntilDate": serialize.boolean_to_string(has_valid_until_date), + "SortBy": sort_by, + "SortDirection": sort_direction, + "ValidUntilDate": serialize.iso8601_datetime(valid_until_date), + "ValidUntilDate<": serialize.iso8601_datetime(valid_until_date_before), + "ValidUntilDate>": serialize.iso8601_datetime(valid_until_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BundlePage(self._version, response) + + def get_page(self, target_url: str) -> BundlePage: + """ + Retrieve a specific page of BundleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BundleInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return BundlePage(self._version, response) + + async def get_page_async(self, target_url: str) -> BundlePage: + """ + Asynchronously retrieve a specific page of BundleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BundleInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return BundlePage(self._version, response) + + def get(self, sid: str) -> BundleContext: + """ + Constructs a BundleContext + + :param sid: The unique string that we created to identify the Bundle resource. + """ + return BundleContext(self._version, sid=sid) + + def __call__(self, sid: str) -> BundleContext: + """ + Constructs a BundleContext + + :param sid: The unique string that we created to identify the Bundle resource. + """ + return BundleContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..4e5275c2 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/__pycache__/bundle_copy.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/__pycache__/bundle_copy.cpython-312.pyc new file mode 100644 index 00000000..9e96678f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/__pycache__/bundle_copy.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/__pycache__/evaluation.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/__pycache__/evaluation.cpython-312.pyc new file mode 100644 index 00000000..0236e87c Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/__pycache__/evaluation.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/__pycache__/item_assignment.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/__pycache__/item_assignment.cpython-312.pyc new file mode 100644 index 00000000..757d6cd4 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/__pycache__/item_assignment.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/__pycache__/replace_items.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/__pycache__/replace_items.cpython-312.pyc new file mode 100644 index 00000000..8d83894e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/__pycache__/replace_items.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/bundle_copy.py b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/bundle_copy.py new file mode 100644 index 00000000..d20a5696 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/bundle_copy.py @@ -0,0 +1,382 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class BundleCopyInstance(InstanceResource): + + class Status(object): + DRAFT = "draft" + PENDING_REVIEW = "pending-review" + IN_REVIEW = "in-review" + TWILIO_REJECTED = "twilio-rejected" + TWILIO_APPROVED = "twilio-approved" + PROVISIONALLY_APPROVED = "provisionally-approved" + + """ + :ivar sid: The unique string that we created to identify the Bundle resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Bundle resource. + :ivar regulation_sid: The unique string of a regulation that is associated to the Bundle resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar status: + :ivar valid_until: The date and time in GMT in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format when the resource will be valid until. + :ivar email: The email address that will receive updates when the Bundle resource changes status. + :ivar status_callback: The URL we call to inform your application of status changes. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], bundle_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.regulation_sid: Optional[str] = payload.get("regulation_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["BundleCopyInstance.Status"] = payload.get("status") + self.valid_until: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("valid_until") + ) + self.email: Optional[str] = payload.get("email") + self.status_callback: Optional[str] = payload.get("status_callback") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "bundle_sid": bundle_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BundleCopyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> BundleCopyInstance: + """ + Build an instance of BundleCopyInstance + + :param payload: Payload response from the API + """ + return BundleCopyInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class BundleCopyList(ListResource): + + def __init__(self, version: Version, bundle_sid: str): + """ + Initialize the BundleCopyList + + :param version: Version that contains the resource + :param bundle_sid: The unique string that we created to identify the Bundle resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "bundle_sid": bundle_sid, + } + self._uri = "/RegulatoryCompliance/Bundles/{bundle_sid}/Copies".format( + **self._solution + ) + + def create( + self, friendly_name: Union[str, object] = values.unset + ) -> BundleCopyInstance: + """ + Create the BundleCopyInstance + + :param friendly_name: The string that you assigned to describe the copied bundle. + + :returns: The created BundleCopyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BundleCopyInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + async def create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> BundleCopyInstance: + """ + Asynchronously create the BundleCopyInstance + + :param friendly_name: The string that you assigned to describe the copied bundle. + + :returns: The created BundleCopyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BundleCopyInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BundleCopyInstance]: + """ + Streams BundleCopyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BundleCopyInstance]: + """ + Asynchronously streams BundleCopyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BundleCopyInstance]: + """ + Lists BundleCopyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BundleCopyInstance]: + """ + Asynchronously lists BundleCopyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BundleCopyPage: + """ + Retrieve a single page of BundleCopyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BundleCopyInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BundleCopyPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BundleCopyPage: + """ + Asynchronously retrieve a single page of BundleCopyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BundleCopyInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BundleCopyPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> BundleCopyPage: + """ + Retrieve a specific page of BundleCopyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BundleCopyInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return BundleCopyPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> BundleCopyPage: + """ + Asynchronously retrieve a specific page of BundleCopyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BundleCopyInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return BundleCopyPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/evaluation.py b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/evaluation.py new file mode 100644 index 00000000..fd450648 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/evaluation.py @@ -0,0 +1,487 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class EvaluationInstance(InstanceResource): + + class Status(object): + COMPLIANT = "compliant" + NONCOMPLIANT = "noncompliant" + + """ + :ivar sid: The unique string that identifies the Evaluation resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Bundle resource. + :ivar regulation_sid: The unique string of a regulation that is associated to the Bundle resource. + :ivar bundle_sid: The unique string that we created to identify the Bundle resource. + :ivar status: + :ivar results: The results of the Evaluation which includes the valid and invalid attributes. + :ivar date_created: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + bundle_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.regulation_sid: Optional[str] = payload.get("regulation_sid") + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.status: Optional["EvaluationInstance.Status"] = payload.get("status") + self.results: Optional[List[Dict[str, object]]] = payload.get("results") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "bundle_sid": bundle_sid, + "sid": sid or self.sid, + } + self._context: Optional[EvaluationContext] = None + + @property + def _proxy(self) -> "EvaluationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EvaluationContext for this EvaluationInstance + """ + if self._context is None: + self._context = EvaluationContext( + self._version, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "EvaluationInstance": + """ + Fetch the EvaluationInstance + + + :returns: The fetched EvaluationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EvaluationInstance": + """ + Asynchronous coroutine to fetch the EvaluationInstance + + + :returns: The fetched EvaluationInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EvaluationContext(InstanceContext): + + def __init__(self, version: Version, bundle_sid: str, sid: str): + """ + Initialize the EvaluationContext + + :param version: Version that contains the resource + :param bundle_sid: The unique string that we created to identify the Bundle resource. + :param sid: The unique string that identifies the Evaluation resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "bundle_sid": bundle_sid, + "sid": sid, + } + self._uri = ( + "/RegulatoryCompliance/Bundles/{bundle_sid}/Evaluations/{sid}".format( + **self._solution + ) + ) + + def fetch(self) -> EvaluationInstance: + """ + Fetch the EvaluationInstance + + + :returns: The fetched EvaluationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EvaluationInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> EvaluationInstance: + """ + Asynchronous coroutine to fetch the EvaluationInstance + + + :returns: The fetched EvaluationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EvaluationInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EvaluationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EvaluationInstance: + """ + Build an instance of EvaluationInstance + + :param payload: Payload response from the API + """ + return EvaluationInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class EvaluationList(ListResource): + + def __init__(self, version: Version, bundle_sid: str): + """ + Initialize the EvaluationList + + :param version: Version that contains the resource + :param bundle_sid: The unique string that identifies the Bundle resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "bundle_sid": bundle_sid, + } + self._uri = "/RegulatoryCompliance/Bundles/{bundle_sid}/Evaluations".format( + **self._solution + ) + + def create(self) -> EvaluationInstance: + """ + Create the EvaluationInstance + + + :returns: The created EvaluationInstance + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = self._version.create(method="POST", uri=self._uri, headers=headers) + + return EvaluationInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + async def create_async(self) -> EvaluationInstance: + """ + Asynchronously create the EvaluationInstance + + + :returns: The created EvaluationInstance + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, headers=headers + ) + + return EvaluationInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EvaluationInstance]: + """ + Streams EvaluationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EvaluationInstance]: + """ + Asynchronously streams EvaluationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EvaluationInstance]: + """ + Lists EvaluationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EvaluationInstance]: + """ + Asynchronously lists EvaluationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EvaluationPage: + """ + Retrieve a single page of EvaluationInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EvaluationInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EvaluationPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EvaluationPage: + """ + Asynchronously retrieve a single page of EvaluationInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EvaluationInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EvaluationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> EvaluationPage: + """ + Retrieve a specific page of EvaluationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EvaluationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EvaluationPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> EvaluationPage: + """ + Asynchronously retrieve a specific page of EvaluationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EvaluationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EvaluationPage(self._version, response, self._solution) + + def get(self, sid: str) -> EvaluationContext: + """ + Constructs a EvaluationContext + + :param sid: The unique string that identifies the Evaluation resource. + """ + return EvaluationContext( + self._version, bundle_sid=self._solution["bundle_sid"], sid=sid + ) + + def __call__(self, sid: str) -> EvaluationContext: + """ + Constructs a EvaluationContext + + :param sid: The unique string that identifies the Evaluation resource. + """ + return EvaluationContext( + self._version, bundle_sid=self._solution["bundle_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/item_assignment.py b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/item_assignment.py new file mode 100644 index 00000000..4eb1fe2b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/item_assignment.py @@ -0,0 +1,540 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ItemAssignmentInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Item Assignment resource. + :ivar bundle_sid: The unique string that we created to identify the Bundle resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Item Assignment resource. + :ivar object_sid: The SID of an object bag that holds information of the different items. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Identity resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + bundle_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.object_sid: Optional[str] = payload.get("object_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "bundle_sid": bundle_sid, + "sid": sid or self.sid, + } + self._context: Optional[ItemAssignmentContext] = None + + @property + def _proxy(self) -> "ItemAssignmentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ItemAssignmentContext for this ItemAssignmentInstance + """ + if self._context is None: + self._context = ItemAssignmentContext( + self._version, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ItemAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ItemAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ItemAssignmentInstance": + """ + Fetch the ItemAssignmentInstance + + + :returns: The fetched ItemAssignmentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ItemAssignmentInstance": + """ + Asynchronous coroutine to fetch the ItemAssignmentInstance + + + :returns: The fetched ItemAssignmentInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ItemAssignmentContext(InstanceContext): + + def __init__(self, version: Version, bundle_sid: str, sid: str): + """ + Initialize the ItemAssignmentContext + + :param version: Version that contains the resource + :param bundle_sid: The unique string that we created to identify the Bundle resource. + :param sid: The unique string that we created to identify the Identity resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "bundle_sid": bundle_sid, + "sid": sid, + } + self._uri = ( + "/RegulatoryCompliance/Bundles/{bundle_sid}/ItemAssignments/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the ItemAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ItemAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ItemAssignmentInstance: + """ + Fetch the ItemAssignmentInstance + + + :returns: The fetched ItemAssignmentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ItemAssignmentInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ItemAssignmentInstance: + """ + Asynchronous coroutine to fetch the ItemAssignmentInstance + + + :returns: The fetched ItemAssignmentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ItemAssignmentInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ItemAssignmentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ItemAssignmentInstance: + """ + Build an instance of ItemAssignmentInstance + + :param payload: Payload response from the API + """ + return ItemAssignmentInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ItemAssignmentList(ListResource): + + def __init__(self, version: Version, bundle_sid: str): + """ + Initialize the ItemAssignmentList + + :param version: Version that contains the resource + :param bundle_sid: The unique string that we created to identify the Bundle resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "bundle_sid": bundle_sid, + } + self._uri = "/RegulatoryCompliance/Bundles/{bundle_sid}/ItemAssignments".format( + **self._solution + ) + + def create(self, object_sid: str) -> ItemAssignmentInstance: + """ + Create the ItemAssignmentInstance + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: The created ItemAssignmentInstance + """ + + data = values.of( + { + "ObjectSid": object_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ItemAssignmentInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + async def create_async(self, object_sid: str) -> ItemAssignmentInstance: + """ + Asynchronously create the ItemAssignmentInstance + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: The created ItemAssignmentInstance + """ + + data = values.of( + { + "ObjectSid": object_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ItemAssignmentInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ItemAssignmentInstance]: + """ + Streams ItemAssignmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ItemAssignmentInstance]: + """ + Asynchronously streams ItemAssignmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ItemAssignmentInstance]: + """ + Lists ItemAssignmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ItemAssignmentInstance]: + """ + Asynchronously lists ItemAssignmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ItemAssignmentPage: + """ + Retrieve a single page of ItemAssignmentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ItemAssignmentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ItemAssignmentPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ItemAssignmentPage: + """ + Asynchronously retrieve a single page of ItemAssignmentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ItemAssignmentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ItemAssignmentPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ItemAssignmentPage: + """ + Retrieve a specific page of ItemAssignmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ItemAssignmentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ItemAssignmentPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ItemAssignmentPage: + """ + Asynchronously retrieve a specific page of ItemAssignmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ItemAssignmentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ItemAssignmentPage(self._version, response, self._solution) + + def get(self, sid: str) -> ItemAssignmentContext: + """ + Constructs a ItemAssignmentContext + + :param sid: The unique string that we created to identify the Identity resource. + """ + return ItemAssignmentContext( + self._version, bundle_sid=self._solution["bundle_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ItemAssignmentContext: + """ + Constructs a ItemAssignmentContext + + :param sid: The unique string that we created to identify the Identity resource. + """ + return ItemAssignmentContext( + self._version, bundle_sid=self._solution["bundle_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/replace_items.py b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/replace_items.py new file mode 100644 index 00000000..a6a1de02 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/bundle/replace_items.py @@ -0,0 +1,163 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ReplaceItemsInstance(InstanceResource): + + class Status(object): + DRAFT = "draft" + PENDING_REVIEW = "pending-review" + IN_REVIEW = "in-review" + TWILIO_REJECTED = "twilio-rejected" + TWILIO_APPROVED = "twilio-approved" + PROVISIONALLY_APPROVED = "provisionally-approved" + + """ + :ivar sid: The unique string that we created to identify the Bundle resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Bundle resource. + :ivar regulation_sid: The unique string of a regulation that is associated to the Bundle resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar status: + :ivar valid_until: The date and time in GMT in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format when the resource will be valid until. + :ivar email: The email address that will receive updates when the Bundle resource changes status. + :ivar status_callback: The URL we call to inform your application of status changes. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], bundle_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.regulation_sid: Optional[str] = payload.get("regulation_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["ReplaceItemsInstance.Status"] = payload.get("status") + self.valid_until: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("valid_until") + ) + self.email: Optional[str] = payload.get("email") + self.status_callback: Optional[str] = payload.get("status_callback") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "bundle_sid": bundle_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ReplaceItemsList(ListResource): + + def __init__(self, version: Version, bundle_sid: str): + """ + Initialize the ReplaceItemsList + + :param version: Version that contains the resource + :param bundle_sid: The unique string that identifies the Bundle where the item assignments are going to be replaced. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "bundle_sid": bundle_sid, + } + self._uri = "/RegulatoryCompliance/Bundles/{bundle_sid}/ReplaceItems".format( + **self._solution + ) + + def create(self, from_bundle_sid: str) -> ReplaceItemsInstance: + """ + Create the ReplaceItemsInstance + + :param from_bundle_sid: The source bundle sid to copy the item assignments from. + + :returns: The created ReplaceItemsInstance + """ + + data = values.of( + { + "FromBundleSid": from_bundle_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ReplaceItemsInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + async def create_async(self, from_bundle_sid: str) -> ReplaceItemsInstance: + """ + Asynchronously create the ReplaceItemsInstance + + :param from_bundle_sid: The source bundle sid to copy the item assignments from. + + :returns: The created ReplaceItemsInstance + """ + + data = values.of( + { + "FromBundleSid": from_bundle_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ReplaceItemsInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/end_user.py b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/end_user.py new file mode 100644 index 00000000..ab180337 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/end_user.py @@ -0,0 +1,638 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class EndUserInstance(InstanceResource): + + class Type(object): + INDIVIDUAL = "individual" + BUSINESS = "business" + + """ + :ivar sid: The unique string created by Twilio to identify the End User resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the End User resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar attributes: The set of parameters that are the attributes of the End Users resource which are listed in the End User Types. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the End User resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["EndUserInstance.Type"] = payload.get("type") + self.attributes: Optional[Dict[str, object]] = payload.get("attributes") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[EndUserContext] = None + + @property + def _proxy(self) -> "EndUserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EndUserContext for this EndUserInstance + """ + if self._context is None: + self._context = EndUserContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the EndUserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the EndUserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "EndUserInstance": + """ + Fetch the EndUserInstance + + + :returns: The fetched EndUserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EndUserInstance": + """ + Asynchronous coroutine to fetch the EndUserInstance + + + :returns: The fetched EndUserInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> "EndUserInstance": + """ + Update the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The updated EndUserInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + attributes=attributes, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> "EndUserInstance": + """ + Asynchronous coroutine to update the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The updated EndUserInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + attributes=attributes, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EndUserContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the EndUserContext + + :param version: Version that contains the resource + :param sid: The unique string created by Twilio to identify the End User resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/RegulatoryCompliance/EndUsers/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the EndUserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the EndUserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> EndUserInstance: + """ + Fetch the EndUserInstance + + + :returns: The fetched EndUserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> EndUserInstance: + """ + Asynchronous coroutine to fetch the EndUserInstance + + + :returns: The fetched EndUserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: + """ + Update the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The updated EndUserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EndUserInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: + """ + Asynchronous coroutine to update the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The updated EndUserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EndUserInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EndUserPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EndUserInstance: + """ + Build an instance of EndUserInstance + + :param payload: Payload response from the API + """ + return EndUserInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class EndUserList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the EndUserList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/RegulatoryCompliance/EndUsers" + + def create( + self, + friendly_name: str, + type: "EndUserInstance.Type", + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: + """ + Create the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param type: + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The created EndUserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EndUserInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + type: "EndUserInstance.Type", + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: + """ + Asynchronously create the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param type: + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The created EndUserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EndUserInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EndUserInstance]: + """ + Streams EndUserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EndUserInstance]: + """ + Asynchronously streams EndUserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EndUserInstance]: + """ + Lists EndUserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EndUserInstance]: + """ + Asynchronously lists EndUserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EndUserPage: + """ + Retrieve a single page of EndUserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EndUserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EndUserPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EndUserPage: + """ + Asynchronously retrieve a single page of EndUserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EndUserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EndUserPage(self._version, response) + + def get_page(self, target_url: str) -> EndUserPage: + """ + Retrieve a specific page of EndUserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EndUserInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EndUserPage(self._version, response) + + async def get_page_async(self, target_url: str) -> EndUserPage: + """ + Asynchronously retrieve a specific page of EndUserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EndUserInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EndUserPage(self._version, response) + + def get(self, sid: str) -> EndUserContext: + """ + Constructs a EndUserContext + + :param sid: The unique string created by Twilio to identify the End User resource. + """ + return EndUserContext(self._version, sid=sid) + + def __call__(self, sid: str) -> EndUserContext: + """ + Constructs a EndUserContext + + :param sid: The unique string created by Twilio to identify the End User resource. + """ + return EndUserContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/end_user_type.py b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/end_user_type.py new file mode 100644 index 00000000..f14c8905 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/end_user_type.py @@ -0,0 +1,408 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class EndUserTypeInstance(InstanceResource): + """ + :ivar sid: The unique string that identifies the End-User Type resource. + :ivar friendly_name: A human-readable description that is assigned to describe the End-User Type resource. Examples can include first name, last name, email, business name, etc + :ivar machine_name: A machine-readable description of the End-User Type resource. Examples can include first_name, last_name, email, business_name, etc. + :ivar fields: The required information for creating an End-User. The required fields will change as regulatory needs change and will differ for businesses and individuals. + :ivar url: The absolute URL of the End-User Type resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.machine_name: Optional[str] = payload.get("machine_name") + self.fields: Optional[List[Dict[str, object]]] = payload.get("fields") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[EndUserTypeContext] = None + + @property + def _proxy(self) -> "EndUserTypeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EndUserTypeContext for this EndUserTypeInstance + """ + if self._context is None: + self._context = EndUserTypeContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "EndUserTypeInstance": + """ + Fetch the EndUserTypeInstance + + + :returns: The fetched EndUserTypeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EndUserTypeInstance": + """ + Asynchronous coroutine to fetch the EndUserTypeInstance + + + :returns: The fetched EndUserTypeInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EndUserTypeContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the EndUserTypeContext + + :param version: Version that contains the resource + :param sid: The unique string that identifies the End-User Type resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/RegulatoryCompliance/EndUserTypes/{sid}".format(**self._solution) + + def fetch(self) -> EndUserTypeInstance: + """ + Fetch the EndUserTypeInstance + + + :returns: The fetched EndUserTypeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> EndUserTypeInstance: + """ + Asynchronous coroutine to fetch the EndUserTypeInstance + + + :returns: The fetched EndUserTypeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EndUserTypePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EndUserTypeInstance: + """ + Build an instance of EndUserTypeInstance + + :param payload: Payload response from the API + """ + return EndUserTypeInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class EndUserTypeList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the EndUserTypeList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/RegulatoryCompliance/EndUserTypes" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EndUserTypeInstance]: + """ + Streams EndUserTypeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EndUserTypeInstance]: + """ + Asynchronously streams EndUserTypeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EndUserTypeInstance]: + """ + Lists EndUserTypeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EndUserTypeInstance]: + """ + Asynchronously lists EndUserTypeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EndUserTypePage: + """ + Retrieve a single page of EndUserTypeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EndUserTypeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EndUserTypePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EndUserTypePage: + """ + Asynchronously retrieve a single page of EndUserTypeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EndUserTypeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EndUserTypePage(self._version, response) + + def get_page(self, target_url: str) -> EndUserTypePage: + """ + Retrieve a specific page of EndUserTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EndUserTypeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EndUserTypePage(self._version, response) + + async def get_page_async(self, target_url: str) -> EndUserTypePage: + """ + Asynchronously retrieve a specific page of EndUserTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EndUserTypeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EndUserTypePage(self._version, response) + + def get(self, sid: str) -> EndUserTypeContext: + """ + Constructs a EndUserTypeContext + + :param sid: The unique string that identifies the End-User Type resource. + """ + return EndUserTypeContext(self._version, sid=sid) + + def __call__(self, sid: str) -> EndUserTypeContext: + """ + Constructs a EndUserTypeContext + + :param sid: The unique string that identifies the End-User Type resource. + """ + return EndUserTypeContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/regulation.py b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/regulation.py new file mode 100644 index 00000000..9c122790 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/regulation.py @@ -0,0 +1,525 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RegulationInstance(InstanceResource): + + class EndUserType(object): + INDIVIDUAL = "individual" + BUSINESS = "business" + + """ + :ivar sid: The unique string that identifies the Regulation resource. + :ivar friendly_name: A human-readable description that is assigned to describe the Regulation resource. Examples can include Germany: Mobile - Business. + :ivar iso_country: The ISO country code of the phone number's country. + :ivar number_type: The type of phone number restricted by the regulatory requirement. For example, Germany mobile phone numbers provisioned by businesses require a business name with commercial register proof from the Handelsregisterauszug and a proof of address from Handelsregisterauszug or a trade license by Gewerbeanmeldung. + :ivar end_user_type: + :ivar requirements: The SID of an object that holds the regulatory information of the phone number country, phone number type, and end user type. + :ivar url: The absolute URL of the Regulation resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.iso_country: Optional[str] = payload.get("iso_country") + self.number_type: Optional[str] = payload.get("number_type") + self.end_user_type: Optional["RegulationInstance.EndUserType"] = payload.get( + "end_user_type" + ) + self.requirements: Optional[Dict[str, object]] = payload.get("requirements") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[RegulationContext] = None + + @property + def _proxy(self) -> "RegulationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RegulationContext for this RegulationInstance + """ + if self._context is None: + self._context = RegulationContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch( + self, include_constraints: Union[bool, object] = values.unset + ) -> "RegulationInstance": + """ + Fetch the RegulationInstance + + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + + :returns: The fetched RegulationInstance + """ + return self._proxy.fetch( + include_constraints=include_constraints, + ) + + async def fetch_async( + self, include_constraints: Union[bool, object] = values.unset + ) -> "RegulationInstance": + """ + Asynchronous coroutine to fetch the RegulationInstance + + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + + :returns: The fetched RegulationInstance + """ + return await self._proxy.fetch_async( + include_constraints=include_constraints, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RegulationContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the RegulationContext + + :param version: Version that contains the resource + :param sid: The unique string that identifies the Regulation resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/RegulatoryCompliance/Regulations/{sid}".format(**self._solution) + + def fetch( + self, include_constraints: Union[bool, object] = values.unset + ) -> RegulationInstance: + """ + Fetch the RegulationInstance + + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + + :returns: The fetched RegulationInstance + """ + + data = values.of( + { + "IncludeConstraints": serialize.boolean_to_string(include_constraints), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return RegulationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async( + self, include_constraints: Union[bool, object] = values.unset + ) -> RegulationInstance: + """ + Asynchronous coroutine to fetch the RegulationInstance + + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + + :returns: The fetched RegulationInstance + """ + + data = values.of( + { + "IncludeConstraints": serialize.boolean_to_string(include_constraints), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return RegulationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RegulationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RegulationInstance: + """ + Build an instance of RegulationInstance + + :param payload: Payload response from the API + """ + return RegulationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RegulationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the RegulationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/RegulatoryCompliance/Regulations" + + def stream( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RegulationInstance]: + """ + Streams RegulationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "RegulationInstance.EndUserType" end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param str iso_country: The ISO country code of the phone number's country. + :param str number_type: The type of phone number that the regulatory requiremnt is restricting. + :param bool include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + end_user_type=end_user_type, + iso_country=iso_country, + number_type=number_type, + include_constraints=include_constraints, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RegulationInstance]: + """ + Asynchronously streams RegulationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "RegulationInstance.EndUserType" end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param str iso_country: The ISO country code of the phone number's country. + :param str number_type: The type of phone number that the regulatory requiremnt is restricting. + :param bool include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + end_user_type=end_user_type, + iso_country=iso_country, + number_type=number_type, + include_constraints=include_constraints, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RegulationInstance]: + """ + Lists RegulationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "RegulationInstance.EndUserType" end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param str iso_country: The ISO country code of the phone number's country. + :param str number_type: The type of phone number that the regulatory requiremnt is restricting. + :param bool include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + end_user_type=end_user_type, + iso_country=iso_country, + number_type=number_type, + include_constraints=include_constraints, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RegulationInstance]: + """ + Asynchronously lists RegulationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "RegulationInstance.EndUserType" end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param str iso_country: The ISO country code of the phone number's country. + :param str number_type: The type of phone number that the regulatory requiremnt is restricting. + :param bool include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + end_user_type=end_user_type, + iso_country=iso_country, + number_type=number_type, + include_constraints=include_constraints, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RegulationPage: + """ + Retrieve a single page of RegulationInstance records from the API. + Request is executed immediately + + :param end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param iso_country: The ISO country code of the phone number's country. + :param number_type: The type of phone number that the regulatory requiremnt is restricting. + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RegulationInstance + """ + data = values.of( + { + "EndUserType": end_user_type, + "IsoCountry": iso_country, + "NumberType": number_type, + "IncludeConstraints": serialize.boolean_to_string(include_constraints), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RegulationPage(self._version, response) + + async def page_async( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RegulationPage: + """ + Asynchronously retrieve a single page of RegulationInstance records from the API. + Request is executed immediately + + :param end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param iso_country: The ISO country code of the phone number's country. + :param number_type: The type of phone number that the regulatory requiremnt is restricting. + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RegulationInstance + """ + data = values.of( + { + "EndUserType": end_user_type, + "IsoCountry": iso_country, + "NumberType": number_type, + "IncludeConstraints": serialize.boolean_to_string(include_constraints), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RegulationPage(self._version, response) + + def get_page(self, target_url: str) -> RegulationPage: + """ + Retrieve a specific page of RegulationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RegulationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RegulationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> RegulationPage: + """ + Asynchronously retrieve a specific page of RegulationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RegulationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RegulationPage(self._version, response) + + def get(self, sid: str) -> RegulationContext: + """ + Constructs a RegulationContext + + :param sid: The unique string that identifies the Regulation resource. + """ + return RegulationContext(self._version, sid=sid) + + def __call__(self, sid: str) -> RegulationContext: + """ + Constructs a RegulationContext + + :param sid: The unique string that identifies the Regulation resource. + """ + return RegulationContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/supporting_document.py b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/supporting_document.py new file mode 100644 index 00000000..b72f9938 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/supporting_document.py @@ -0,0 +1,658 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SupportingDocumentInstance(InstanceResource): + + class Status(object): + DRAFT = "draft" + PENDING_REVIEW = "pending-review" + REJECTED = "rejected" + APPROVED = "approved" + EXPIRED = "expired" + PROVISIONALLY_APPROVED = "provisionally-approved" + + """ + :ivar sid: The unique string created by Twilio to identify the Supporting Document resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Document resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar mime_type: The image type uploaded in the Supporting Document container. + :ivar status: + :ivar failure_reason: The failure reason of the Supporting Document Resource. + :ivar errors: A list of errors that occurred during the registering RC Bundle + :ivar type: The type of the Supporting Document. + :ivar attributes: The set of parameters that are the attributes of the Supporting Documents resource which are listed in the Supporting Document Types. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Supporting Document resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.mime_type: Optional[str] = payload.get("mime_type") + self.status: Optional["SupportingDocumentInstance.Status"] = payload.get( + "status" + ) + self.failure_reason: Optional[str] = payload.get("failure_reason") + self.errors: Optional[List[Dict[str, object]]] = payload.get("errors") + self.type: Optional[str] = payload.get("type") + self.attributes: Optional[Dict[str, object]] = payload.get("attributes") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SupportingDocumentContext] = None + + @property + def _proxy(self) -> "SupportingDocumentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SupportingDocumentContext for this SupportingDocumentInstance + """ + if self._context is None: + self._context = SupportingDocumentContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SupportingDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SupportingDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SupportingDocumentInstance": + """ + Fetch the SupportingDocumentInstance + + + :returns: The fetched SupportingDocumentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SupportingDocumentInstance": + """ + Asynchronous coroutine to fetch the SupportingDocumentInstance + + + :returns: The fetched SupportingDocumentInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> "SupportingDocumentInstance": + """ + Update the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: The updated SupportingDocumentInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + attributes=attributes, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> "SupportingDocumentInstance": + """ + Asynchronous coroutine to update the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: The updated SupportingDocumentInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + attributes=attributes, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SupportingDocumentContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SupportingDocumentContext + + :param version: Version that contains the resource + :param sid: The unique string created by Twilio to identify the Supporting Document resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/RegulatoryCompliance/SupportingDocuments/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the SupportingDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SupportingDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SupportingDocumentInstance: + """ + Fetch the SupportingDocumentInstance + + + :returns: The fetched SupportingDocumentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SupportingDocumentInstance: + """ + Asynchronous coroutine to fetch the SupportingDocumentInstance + + + :returns: The fetched SupportingDocumentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: + """ + Update the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: The updated SupportingDocumentInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SupportingDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: + """ + Asynchronous coroutine to update the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: The updated SupportingDocumentInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SupportingDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SupportingDocumentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SupportingDocumentInstance: + """ + Build an instance of SupportingDocumentInstance + + :param payload: Payload response from the API + """ + return SupportingDocumentInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SupportingDocumentList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SupportingDocumentList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/RegulatoryCompliance/SupportingDocuments" + + def create( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: + """ + Create the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of the Supporting Document. + :param attributes: The set of parameters that are the attributes of the Supporting Documents resource which are derived Supporting Document Types. + + :returns: The created SupportingDocumentInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SupportingDocumentInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: + """ + Asynchronously create the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of the Supporting Document. + :param attributes: The set of parameters that are the attributes of the Supporting Documents resource which are derived Supporting Document Types. + + :returns: The created SupportingDocumentInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SupportingDocumentInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SupportingDocumentInstance]: + """ + Streams SupportingDocumentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SupportingDocumentInstance]: + """ + Asynchronously streams SupportingDocumentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SupportingDocumentInstance]: + """ + Lists SupportingDocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SupportingDocumentInstance]: + """ + Asynchronously lists SupportingDocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SupportingDocumentPage: + """ + Retrieve a single page of SupportingDocumentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SupportingDocumentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SupportingDocumentPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SupportingDocumentPage: + """ + Asynchronously retrieve a single page of SupportingDocumentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SupportingDocumentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SupportingDocumentPage(self._version, response) + + def get_page(self, target_url: str) -> SupportingDocumentPage: + """ + Retrieve a specific page of SupportingDocumentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SupportingDocumentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SupportingDocumentPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SupportingDocumentPage: + """ + Asynchronously retrieve a specific page of SupportingDocumentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SupportingDocumentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SupportingDocumentPage(self._version, response) + + def get(self, sid: str) -> SupportingDocumentContext: + """ + Constructs a SupportingDocumentContext + + :param sid: The unique string created by Twilio to identify the Supporting Document resource. + """ + return SupportingDocumentContext(self._version, sid=sid) + + def __call__(self, sid: str) -> SupportingDocumentContext: + """ + Constructs a SupportingDocumentContext + + :param sid: The unique string created by Twilio to identify the Supporting Document resource. + """ + return SupportingDocumentContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/supporting_document_type.py b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/supporting_document_type.py new file mode 100644 index 00000000..692248cb --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/numbers/v2/regulatory_compliance/supporting_document_type.py @@ -0,0 +1,410 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SupportingDocumentTypeInstance(InstanceResource): + """ + :ivar sid: The unique string that identifies the Supporting Document Type resource. + :ivar friendly_name: A human-readable description of the Supporting Document Type resource. + :ivar machine_name: The machine-readable description of the Supporting Document Type resource. + :ivar fields: The required information for creating a Supporting Document. The required fields will change as regulatory needs change and will differ for businesses and individuals. + :ivar url: The absolute URL of the Supporting Document Type resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.machine_name: Optional[str] = payload.get("machine_name") + self.fields: Optional[List[Dict[str, object]]] = payload.get("fields") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SupportingDocumentTypeContext] = None + + @property + def _proxy(self) -> "SupportingDocumentTypeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SupportingDocumentTypeContext for this SupportingDocumentTypeInstance + """ + if self._context is None: + self._context = SupportingDocumentTypeContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "SupportingDocumentTypeInstance": + """ + Fetch the SupportingDocumentTypeInstance + + + :returns: The fetched SupportingDocumentTypeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SupportingDocumentTypeInstance": + """ + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance + + + :returns: The fetched SupportingDocumentTypeInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SupportingDocumentTypeContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SupportingDocumentTypeContext + + :param version: Version that contains the resource + :param sid: The unique string that identifies the Supporting Document Type resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/RegulatoryCompliance/SupportingDocumentTypes/{sid}".format( + **self._solution + ) + + def fetch(self) -> SupportingDocumentTypeInstance: + """ + Fetch the SupportingDocumentTypeInstance + + + :returns: The fetched SupportingDocumentTypeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SupportingDocumentTypeInstance: + """ + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance + + + :returns: The fetched SupportingDocumentTypeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SupportingDocumentTypePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SupportingDocumentTypeInstance: + """ + Build an instance of SupportingDocumentTypeInstance + + :param payload: Payload response from the API + """ + return SupportingDocumentTypeInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SupportingDocumentTypeList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SupportingDocumentTypeList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/RegulatoryCompliance/SupportingDocumentTypes" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SupportingDocumentTypeInstance]: + """ + Streams SupportingDocumentTypeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SupportingDocumentTypeInstance]: + """ + Asynchronously streams SupportingDocumentTypeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SupportingDocumentTypeInstance]: + """ + Lists SupportingDocumentTypeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SupportingDocumentTypeInstance]: + """ + Asynchronously lists SupportingDocumentTypeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SupportingDocumentTypePage: + """ + Retrieve a single page of SupportingDocumentTypeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SupportingDocumentTypeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SupportingDocumentTypePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SupportingDocumentTypePage: + """ + Asynchronously retrieve a single page of SupportingDocumentTypeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SupportingDocumentTypeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SupportingDocumentTypePage(self._version, response) + + def get_page(self, target_url: str) -> SupportingDocumentTypePage: + """ + Retrieve a specific page of SupportingDocumentTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SupportingDocumentTypeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SupportingDocumentTypePage(self._version, response) + + async def get_page_async(self, target_url: str) -> SupportingDocumentTypePage: + """ + Asynchronously retrieve a specific page of SupportingDocumentTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SupportingDocumentTypeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SupportingDocumentTypePage(self._version, response) + + def get(self, sid: str) -> SupportingDocumentTypeContext: + """ + Constructs a SupportingDocumentTypeContext + + :param sid: The unique string that identifies the Supporting Document Type resource. + """ + return SupportingDocumentTypeContext(self._version, sid=sid) + + def __call__(self, sid: str) -> SupportingDocumentTypeContext: + """ + Constructs a SupportingDocumentTypeContext + + :param sid: The unique string that identifies the Supporting Document Type resource. + """ + return SupportingDocumentTypeContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/oauth/OauthBase.py b/venv/Lib/site-packages/twilio/rest/oauth/OauthBase.py new file mode 100644 index 00000000..87cbbac2 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/oauth/OauthBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.oauth.v1 import V1 + + +class OauthBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Oauth Domain + + :returns: Domain for Oauth + """ + super().__init__(twilio, "https://oauth.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Oauth + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/oauth/__init__.py b/venv/Lib/site-packages/twilio/rest/oauth/__init__.py new file mode 100644 index 00000000..586cf6b4 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/oauth/__init__.py @@ -0,0 +1,16 @@ +from warnings import warn + +from twilio.rest.oauth.OauthBase import OauthBase +from twilio.rest.oauth.v1.token import TokenList + + +class Oauth(OauthBase): + + @property + def token(self) -> TokenList: + warn( + "token is deprecated. Use v1.token instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.token diff --git a/venv/Lib/site-packages/twilio/rest/oauth/__pycache__/OauthBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/oauth/__pycache__/OauthBase.cpython-312.pyc new file mode 100644 index 00000000..17981a75 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/oauth/__pycache__/OauthBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/oauth/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/oauth/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..15edae68 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/oauth/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/oauth/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/oauth/v1/__init__.py new file mode 100644 index 00000000..e05c7de5 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/oauth/v1/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Oauth + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.oauth.v1.authorize import AuthorizeList +from twilio.rest.oauth.v1.token import TokenList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Oauth + + :param domain: The Twilio.oauth domain + """ + super().__init__(domain, "v1") + self._authorize: Optional[AuthorizeList] = None + self._token: Optional[TokenList] = None + + @property + def authorize(self) -> AuthorizeList: + if self._authorize is None: + self._authorize = AuthorizeList(self) + return self._authorize + + @property + def token(self) -> TokenList: + if self._token is None: + self._token = TokenList(self) + return self._token + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/oauth/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/oauth/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..acec8fb6 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/oauth/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/oauth/v1/__pycache__/authorize.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/oauth/v1/__pycache__/authorize.cpython-312.pyc new file mode 100644 index 00000000..a68dd01e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/oauth/v1/__pycache__/authorize.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/oauth/v1/__pycache__/token.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/oauth/v1/__pycache__/token.cpython-312.pyc new file mode 100644 index 00000000..c7f70046 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/oauth/v1/__pycache__/token.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/oauth/v1/authorize.py b/venv/Lib/site-packages/twilio/rest/oauth/v1/authorize.py new file mode 100644 index 00000000..a353c4b8 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/oauth/v1/authorize.py @@ -0,0 +1,130 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Oauth + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class AuthorizeInstance(InstanceResource): + """ + :ivar redirect_to: The callback URL + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.redirect_to: Optional[str] = payload.get("redirect_to") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class AuthorizeList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AuthorizeList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/authorize" + + def fetch( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + ) -> AuthorizeInstance: + """ + Asynchronously fetch the AuthorizeInstance + + :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback + :returns: The fetched AuthorizeInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "ResponseType": response_type, + "ClientId": client_id, + "RedirectUri": redirect_uri, + "Scope": scope, + "State": state, + } + ) + + payload = self._version.fetch( + method="GET", uri=self._uri, headers=headers, params=params + ) + + return AuthorizeInstance(self._version, payload) + + async def fetch_async( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + ) -> AuthorizeInstance: + """ + Asynchronously fetch the AuthorizeInstance + + :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback + :returns: The fetched AuthorizeInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "ResponseType": response_type, + "ClientId": client_id, + "RedirectUri": redirect_uri, + "Scope": scope, + "State": state, + } + ) + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers, params=params + ) + + return AuthorizeInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/oauth/v1/token.py b/venv/Lib/site-packages/twilio/rest/oauth/v1/token.py new file mode 100644 index 00000000..18de1008 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/oauth/v1/token.py @@ -0,0 +1,170 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Oauth + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TokenInstance(InstanceResource): + """ + :ivar access_token: Token which carries the necessary information to access a Twilio resource directly. + :ivar refresh_token: Token which carries the information necessary to get a new access token. + :ivar id_token: Token which carries the information necessary of user profile. + :ivar token_type: Token type + :ivar expires_in: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.access_token: Optional[str] = payload.get("access_token") + self.refresh_token: Optional[str] = payload.get("refresh_token") + self.id_token: Optional[str] = payload.get("id_token") + self.token_type: Optional[str] = payload.get("token_type") + self.expires_in: Optional[int] = payload.get("expires_in") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class TokenList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TokenList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/token" + + def create( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> TokenInstance: + """ + Create the TokenInstance + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: The created TokenInstance + """ + + data = values.of( + { + "GrantType": grant_type, + "ClientId": client_id, + "ClientSecret": client_secret, + "Code": code, + "RedirectUri": redirect_uri, + "Audience": audience, + "RefreshToken": refresh_token, + "Scope": scope, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TokenInstance(self._version, payload) + + async def create_async( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> TokenInstance: + """ + Asynchronously create the TokenInstance + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: The created TokenInstance + """ + + data = values.of( + { + "GrantType": grant_type, + "ClientId": client_id, + "ClientSecret": client_secret, + "Code": code, + "RedirectUri": redirect_uri, + "Audience": audience, + "RefreshToken": refresh_token, + "Scope": scope, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TokenInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/preview/PreviewBase.py b/venv/Lib/site-packages/twilio/rest/preview/PreviewBase.py new file mode 100644 index 00000000..dd8317b4 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview/PreviewBase.py @@ -0,0 +1,66 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.preview.hosted_numbers import HostedNumbers +from twilio.rest.preview.marketplace import Marketplace +from twilio.rest.preview.wireless import Wireless + + +class PreviewBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Preview Domain + + :returns: Domain for Preview + """ + super().__init__(twilio, "https://preview.twilio.com") + self._hosted_numbers: Optional[HostedNumbers] = None + self._marketplace: Optional[Marketplace] = None + self._wireless: Optional[Wireless] = None + + @property + def hosted_numbers(self) -> HostedNumbers: + """ + :returns: Versions hosted_numbers of Preview + """ + if self._hosted_numbers is None: + self._hosted_numbers = HostedNumbers(self) + return self._hosted_numbers + + @property + def marketplace(self) -> Marketplace: + """ + :returns: Versions marketplace of Preview + """ + if self._marketplace is None: + self._marketplace = Marketplace(self) + return self._marketplace + + @property + def wireless(self) -> Wireless: + """ + :returns: Versions wireless of Preview + """ + if self._wireless is None: + self._wireless = Wireless(self) + return self._wireless + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/preview/__init__.py b/venv/Lib/site-packages/twilio/rest/preview/__init__.py new file mode 100644 index 00000000..501ae417 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview/__init__.py @@ -0,0 +1,88 @@ +from warnings import warn + +from twilio.rest.preview.PreviewBase import PreviewBase +from twilio.rest.preview.hosted_numbers.authorization_document import ( + AuthorizationDocumentList, +) +from twilio.rest.preview.hosted_numbers.hosted_number_order import HostedNumberOrderList +from twilio.rest.preview.marketplace.available_add_on import AvailableAddOnList +from twilio.rest.preview.marketplace.installed_add_on import InstalledAddOnList +from twilio.rest.preview.sync.service import ServiceList +from twilio.rest.preview.wireless.command import CommandList +from twilio.rest.preview.wireless.rate_plan import RatePlanList +from twilio.rest.preview.wireless.sim import SimList + + +class Preview(PreviewBase): + + @property + def authorization_documents(self) -> AuthorizationDocumentList: + warn( + "authorization_documents is deprecated. Use hosted_numbers.authorization_documents instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.hosted_numbers.authorization_documents + + @property + def hosted_number_orders(self) -> HostedNumberOrderList: + warn( + "hosted_number_orders is deprecated. Use hosted_numbers.hosted_number_orders instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.hosted_numbers.hosted_number_orders + + @property + def available_add_ons(self) -> AvailableAddOnList: + warn( + "available_add_ons is deprecated. Use marketplace.available_add_ons instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.marketplace.available_add_ons + + @property + def installed_add_ons(self) -> InstalledAddOnList: + warn( + "installed_add_ons is deprecated. Use marketplace.installed_add_ons instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.marketplace.installed_add_ons + + @property + def services(self) -> ServiceList: + warn( + "services is deprecated. Use sync.services instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.sync.services + + @property + def commands(self) -> CommandList: + warn( + "commands is deprecated. Use wireless.commands instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.wireless.commands + + @property + def rate_plans(self) -> RatePlanList: + warn( + "rate_plans is deprecated. Use wireless.rate_plans instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.wireless.rate_plans + + @property + def sims(self) -> SimList: + warn( + "sims is deprecated. Use wireless.sims instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.wireless.sims diff --git a/venv/Lib/site-packages/twilio/rest/preview/__pycache__/PreviewBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview/__pycache__/PreviewBase.cpython-312.pyc new file mode 100644 index 00000000..5b964fd6 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview/__pycache__/PreviewBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..6e7ba000 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview/hosted_numbers/__init__.py b/venv/Lib/site-packages/twilio/rest/preview/hosted_numbers/__init__.py new file mode 100644 index 00000000..7b3a767e --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview/hosted_numbers/__init__.py @@ -0,0 +1,53 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.preview.hosted_numbers.authorization_document import ( + AuthorizationDocumentList, +) +from twilio.rest.preview.hosted_numbers.hosted_number_order import HostedNumberOrderList + + +class HostedNumbers(Version): + + def __init__(self, domain: Domain): + """ + Initialize the HostedNumbers version of Preview + + :param domain: The Twilio.preview domain + """ + super().__init__(domain, "HostedNumbers") + self._authorization_documents: Optional[AuthorizationDocumentList] = None + self._hosted_number_orders: Optional[HostedNumberOrderList] = None + + @property + def authorization_documents(self) -> AuthorizationDocumentList: + if self._authorization_documents is None: + self._authorization_documents = AuthorizationDocumentList(self) + return self._authorization_documents + + @property + def hosted_number_orders(self) -> HostedNumberOrderList: + if self._hosted_number_orders is None: + self._hosted_number_orders = HostedNumberOrderList(self) + return self._hosted_number_orders + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/preview/hosted_numbers/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview/hosted_numbers/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..cd14093f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview/hosted_numbers/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview/hosted_numbers/__pycache__/hosted_number_order.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview/hosted_numbers/__pycache__/hosted_number_order.cpython-312.pyc new file mode 100644 index 00000000..40922006 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview/hosted_numbers/__pycache__/hosted_number_order.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py b/venv/Lib/site-packages/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py new file mode 100644 index 00000000..49d3d40d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py @@ -0,0 +1,755 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order import ( + DependentHostedNumberOrderList, +) + + +class AuthorizationDocumentInstance(InstanceResource): + + class Status(object): + OPENED = "opened" + SIGNING = "signing" + SIGNED = "signed" + CANCELED = "canceled" + FAILED = "failed" + + """ + :ivar sid: A 34 character string that uniquely identifies this AuthorizationDocument. + :ivar address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :ivar status: + :ivar email: Email that this AuthorizationDocument will be sent to for signing. + :ivar cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. + :ivar date_created: The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date that this resource was updated, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.address_sid: Optional[str] = payload.get("address_sid") + self.status: Optional["AuthorizationDocumentInstance.Status"] = payload.get( + "status" + ) + self.email: Optional[str] = payload.get("email") + self.cc_emails: Optional[List[str]] = payload.get("cc_emails") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[AuthorizationDocumentContext] = None + + @property + def _proxy(self) -> "AuthorizationDocumentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AuthorizationDocumentContext for this AuthorizationDocumentInstance + """ + if self._context is None: + self._context = AuthorizationDocumentContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "AuthorizationDocumentInstance": + """ + Fetch the AuthorizationDocumentInstance + + + :returns: The fetched AuthorizationDocumentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AuthorizationDocumentInstance": + """ + Asynchronous coroutine to fetch the AuthorizationDocumentInstance + + + :returns: The fetched AuthorizationDocumentInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + hosted_number_order_sids: Union[List[str], object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + contact_title: Union[str, object] = values.unset, + contact_phone_number: Union[str, object] = values.unset, + ) -> "AuthorizationDocumentInstance": + """ + Update the AuthorizationDocumentInstance + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed + :param status: + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + + :returns: The updated AuthorizationDocumentInstance + """ + return self._proxy.update( + hosted_number_order_sids=hosted_number_order_sids, + address_sid=address_sid, + email=email, + cc_emails=cc_emails, + status=status, + contact_title=contact_title, + contact_phone_number=contact_phone_number, + ) + + async def update_async( + self, + hosted_number_order_sids: Union[List[str], object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + contact_title: Union[str, object] = values.unset, + contact_phone_number: Union[str, object] = values.unset, + ) -> "AuthorizationDocumentInstance": + """ + Asynchronous coroutine to update the AuthorizationDocumentInstance + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed + :param status: + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + + :returns: The updated AuthorizationDocumentInstance + """ + return await self._proxy.update_async( + hosted_number_order_sids=hosted_number_order_sids, + address_sid=address_sid, + email=email, + cc_emails=cc_emails, + status=status, + contact_title=contact_title, + contact_phone_number=contact_phone_number, + ) + + @property + def dependent_hosted_number_orders(self) -> DependentHostedNumberOrderList: + """ + Access the dependent_hosted_number_orders + """ + return self._proxy.dependent_hosted_number_orders + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class AuthorizationDocumentContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the AuthorizationDocumentContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this AuthorizationDocument. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/AuthorizationDocuments/{sid}".format(**self._solution) + + self._dependent_hosted_number_orders: Optional[ + DependentHostedNumberOrderList + ] = None + + def fetch(self) -> AuthorizationDocumentInstance: + """ + Fetch the AuthorizationDocumentInstance + + + :returns: The fetched AuthorizationDocumentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AuthorizationDocumentInstance: + """ + Asynchronous coroutine to fetch the AuthorizationDocumentInstance + + + :returns: The fetched AuthorizationDocumentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + hosted_number_order_sids: Union[List[str], object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + contact_title: Union[str, object] = values.unset, + contact_phone_number: Union[str, object] = values.unset, + ) -> AuthorizationDocumentInstance: + """ + Update the AuthorizationDocumentInstance + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed + :param status: + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + + :returns: The updated AuthorizationDocumentInstance + """ + + data = values.of( + { + "HostedNumberOrderSids": serialize.map( + hosted_number_order_sids, lambda e: e + ), + "AddressSid": address_sid, + "Email": email, + "CcEmails": serialize.map(cc_emails, lambda e: e), + "Status": status, + "ContactTitle": contact_title, + "ContactPhoneNumber": contact_phone_number, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthorizationDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, + hosted_number_order_sids: Union[List[str], object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + contact_title: Union[str, object] = values.unset, + contact_phone_number: Union[str, object] = values.unset, + ) -> AuthorizationDocumentInstance: + """ + Asynchronous coroutine to update the AuthorizationDocumentInstance + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed + :param status: + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + + :returns: The updated AuthorizationDocumentInstance + """ + + data = values.of( + { + "HostedNumberOrderSids": serialize.map( + hosted_number_order_sids, lambda e: e + ), + "AddressSid": address_sid, + "Email": email, + "CcEmails": serialize.map(cc_emails, lambda e: e), + "Status": status, + "ContactTitle": contact_title, + "ContactPhoneNumber": contact_phone_number, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthorizationDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + + @property + def dependent_hosted_number_orders(self) -> DependentHostedNumberOrderList: + """ + Access the dependent_hosted_number_orders + """ + if self._dependent_hosted_number_orders is None: + self._dependent_hosted_number_orders = DependentHostedNumberOrderList( + self._version, + self._solution["sid"], + ) + return self._dependent_hosted_number_orders + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class AuthorizationDocumentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AuthorizationDocumentInstance: + """ + Build an instance of AuthorizationDocumentInstance + + :param payload: Payload response from the API + """ + return AuthorizationDocumentInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AuthorizationDocumentList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AuthorizationDocumentList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/AuthorizationDocuments" + + def create( + self, + hosted_number_order_sids: List[str], + address_sid: str, + email: str, + contact_title: str, + contact_phone_number: str, + cc_emails: Union[List[str], object] = values.unset, + ) -> AuthorizationDocumentInstance: + """ + Create the AuthorizationDocumentInstance + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. + + :returns: The created AuthorizationDocumentInstance + """ + + data = values.of( + { + "HostedNumberOrderSids": serialize.map( + hosted_number_order_sids, lambda e: e + ), + "AddressSid": address_sid, + "Email": email, + "ContactTitle": contact_title, + "ContactPhoneNumber": contact_phone_number, + "CcEmails": serialize.map(cc_emails, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthorizationDocumentInstance(self._version, payload) + + async def create_async( + self, + hosted_number_order_sids: List[str], + address_sid: str, + email: str, + contact_title: str, + contact_phone_number: str, + cc_emails: Union[List[str], object] = values.unset, + ) -> AuthorizationDocumentInstance: + """ + Asynchronously create the AuthorizationDocumentInstance + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. + + :returns: The created AuthorizationDocumentInstance + """ + + data = values.of( + { + "HostedNumberOrderSids": serialize.map( + hosted_number_order_sids, lambda e: e + ), + "AddressSid": address_sid, + "Email": email, + "ContactTitle": contact_title, + "ContactPhoneNumber": contact_phone_number, + "CcEmails": serialize.map(cc_emails, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthorizationDocumentInstance(self._version, payload) + + def stream( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AuthorizationDocumentInstance]: + """ + Streams AuthorizationDocumentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(email=email, status=status, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AuthorizationDocumentInstance]: + """ + Asynchronously streams AuthorizationDocumentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + email=email, status=status, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthorizationDocumentInstance]: + """ + Lists AuthorizationDocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + email=email, + status=status, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthorizationDocumentInstance]: + """ + Asynchronously lists AuthorizationDocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + email=email, + status=status, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AuthorizationDocumentPage: + """ + Retrieve a single page of AuthorizationDocumentInstance records from the API. + Request is executed immediately + + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AuthorizationDocumentInstance + """ + data = values.of( + { + "Email": email, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthorizationDocumentPage(self._version, response) + + async def page_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AuthorizationDocumentPage: + """ + Asynchronously retrieve a single page of AuthorizationDocumentInstance records from the API. + Request is executed immediately + + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AuthorizationDocumentInstance + """ + data = values.of( + { + "Email": email, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthorizationDocumentPage(self._version, response) + + def get_page(self, target_url: str) -> AuthorizationDocumentPage: + """ + Retrieve a specific page of AuthorizationDocumentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthorizationDocumentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AuthorizationDocumentPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AuthorizationDocumentPage: + """ + Asynchronously retrieve a specific page of AuthorizationDocumentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthorizationDocumentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AuthorizationDocumentPage(self._version, response) + + def get(self, sid: str) -> AuthorizationDocumentContext: + """ + Constructs a AuthorizationDocumentContext + + :param sid: A 34 character string that uniquely identifies this AuthorizationDocument. + """ + return AuthorizationDocumentContext(self._version, sid=sid) + + def __call__(self, sid: str) -> AuthorizationDocumentContext: + """ + Constructs a AuthorizationDocumentContext + + :param sid: A 34 character string that uniquely identifies this AuthorizationDocument. + """ + return AuthorizationDocumentContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/preview/hosted_numbers/authorization_document/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview/hosted_numbers/authorization_document/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..aa6cd140 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview/hosted_numbers/authorization_document/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview/hosted_numbers/authorization_document/__pycache__/dependent_hosted_number_order.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview/hosted_numbers/authorization_document/__pycache__/dependent_hosted_number_order.cpython-312.pyc new file mode 100644 index 00000000..8805aa30 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview/hosted_numbers/authorization_document/__pycache__/dependent_hosted_number_order.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview/hosted_numbers/authorization_document/dependent_hosted_number_order.py b/venv/Lib/site-packages/twilio/rest/preview/hosted_numbers/authorization_document/dependent_hosted_number_order.py new file mode 100644 index 00000000..0ec58f87 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview/hosted_numbers/authorization_document/dependent_hosted_number_order.py @@ -0,0 +1,477 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DependentHostedNumberOrderInstance(InstanceResource): + + class Status(object): + RECEIVED = "received" + PENDING_VERIFICATION = "pending-verification" + VERIFIED = "verified" + PENDING_LOA = "pending-loa" + CARRIER_PROCESSING = "carrier-processing" + TESTING = "testing" + COMPLETED = "completed" + FAILED = "failed" + ACTION_REQUIRED = "action-required" + + class VerificationType(object): + PHONE_CALL = "phone-call" + PHONE_BILL = "phone-bill" + + """ + :ivar sid: A 34 character string that uniquely identifies this Authorization Document + :ivar account_sid: The unique SID identifier of the Account. + :ivar incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :ivar address_sid: A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :ivar signing_document_sid: A 34 character string that uniquely identifies the LOA document associated with this HostedNumberOrder. + :ivar phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :ivar capabilities: + :ivar friendly_name: A human readable description of this resource, up to 64 characters. + :ivar unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :ivar status: + :ivar failure_reason: A message that explains why a hosted_number_order went to status \"action-required\" + :ivar date_created: The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date that this resource was updated, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar verification_attempts: The number of attempts made to verify ownership of the phone number that is being hosted. + :ivar email: Email of the owner of this phone number that is being hosted. + :ivar cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed + :ivar verification_type: + :ivar verification_document_sid: A 34 character string that uniquely identifies the Identity Document resource that represents the document for verifying ownership of the number to be hosted. + :ivar extension: A numerical extension to be used when making the ownership verification call. + :ivar call_delay: A value between 0-30 specifying the number of seconds to delay initiating the ownership verification call. + :ivar verification_code: The digits passed during the ownership verification call. + :ivar verification_call_sids: A list of 34 character strings that are unique identifiers for the calls placed as part of ownership verification. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], signing_document_sid: str + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.incoming_phone_number_sid: Optional[str] = payload.get( + "incoming_phone_number_sid" + ) + self.address_sid: Optional[str] = payload.get("address_sid") + self.signing_document_sid: Optional[str] = payload.get("signing_document_sid") + self.phone_number: Optional[str] = payload.get("phone_number") + self.capabilities: Optional[str] = payload.get("capabilities") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.status: Optional["DependentHostedNumberOrderInstance.Status"] = ( + payload.get("status") + ) + self.failure_reason: Optional[str] = payload.get("failure_reason") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.verification_attempts: Optional[int] = deserialize.integer( + payload.get("verification_attempts") + ) + self.email: Optional[str] = payload.get("email") + self.cc_emails: Optional[List[str]] = payload.get("cc_emails") + self.verification_type: Optional[ + "DependentHostedNumberOrderInstance.VerificationType" + ] = payload.get("verification_type") + self.verification_document_sid: Optional[str] = payload.get( + "verification_document_sid" + ) + self.extension: Optional[str] = payload.get("extension") + self.call_delay: Optional[int] = deserialize.integer(payload.get("call_delay")) + self.verification_code: Optional[str] = payload.get("verification_code") + self.verification_call_sids: Optional[List[str]] = payload.get( + "verification_call_sids" + ) + + self._solution = { + "signing_document_sid": signing_document_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class DependentHostedNumberOrderPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> DependentHostedNumberOrderInstance: + """ + Build an instance of DependentHostedNumberOrderInstance + + :param payload: Payload response from the API + """ + return DependentHostedNumberOrderInstance( + self._version, + payload, + signing_document_sid=self._solution["signing_document_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class DependentHostedNumberOrderList(ListResource): + + def __init__(self, version: Version, signing_document_sid: str): + """ + Initialize the DependentHostedNumberOrderList + + :param version: Version that contains the resource + :param signing_document_sid: A 34 character string that uniquely identifies the LOA document associated with this HostedNumberOrder. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "signing_document_sid": signing_document_sid, + } + self._uri = "/AuthorizationDocuments/{signing_document_sid}/DependentHostedNumberOrders".format( + **self._solution + ) + + def stream( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DependentHostedNumberOrderInstance]: + """ + Streams DependentHostedNumberOrderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DependentHostedNumberOrderInstance]: + """ + Asynchronously streams DependentHostedNumberOrderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DependentHostedNumberOrderInstance]: + """ + Lists DependentHostedNumberOrderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DependentHostedNumberOrderInstance]: + """ + Asynchronously lists DependentHostedNumberOrderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DependentHostedNumberOrderPage: + """ + Retrieve a single page of DependentHostedNumberOrderInstance records from the API. + Request is executed immediately + + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DependentHostedNumberOrderInstance + """ + data = values.of( + { + "Status": status, + "PhoneNumber": phone_number, + "IncomingPhoneNumberSid": incoming_phone_number_sid, + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DependentHostedNumberOrderPage(self._version, response, self._solution) + + async def page_async( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DependentHostedNumberOrderPage: + """ + Asynchronously retrieve a single page of DependentHostedNumberOrderInstance records from the API. + Request is executed immediately + + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DependentHostedNumberOrderInstance + """ + data = values.of( + { + "Status": status, + "PhoneNumber": phone_number, + "IncomingPhoneNumberSid": incoming_phone_number_sid, + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DependentHostedNumberOrderPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DependentHostedNumberOrderPage: + """ + Retrieve a specific page of DependentHostedNumberOrderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DependentHostedNumberOrderInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DependentHostedNumberOrderPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DependentHostedNumberOrderPage: + """ + Asynchronously retrieve a specific page of DependentHostedNumberOrderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DependentHostedNumberOrderInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DependentHostedNumberOrderPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/preview/hosted_numbers/hosted_number_order.py b/venv/Lib/site-packages/twilio/rest/preview/hosted_numbers/hosted_number_order.py new file mode 100644 index 00000000..0c20af87 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview/hosted_numbers/hosted_number_order.py @@ -0,0 +1,985 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class HostedNumberOrderInstance(InstanceResource): + + class Status(object): + RECEIVED = "received" + PENDING_VERIFICATION = "pending-verification" + VERIFIED = "verified" + PENDING_LOA = "pending-loa" + CARRIER_PROCESSING = "carrier-processing" + TESTING = "testing" + COMPLETED = "completed" + FAILED = "failed" + ACTION_REQUIRED = "action-required" + + class VerificationType(object): + PHONE_CALL = "phone-call" + PHONE_BILL = "phone-bill" + + """ + :ivar sid: A 34 character string that uniquely identifies this HostedNumberOrder. + :ivar account_sid: A 34 character string that uniquely identifies the account. + :ivar incoming_phone_number_sid: A 34 character string that uniquely identifies the [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the phone number being hosted. + :ivar address_sid: A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :ivar signing_document_sid: A 34 character string that uniquely identifies the [Authorization Document](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource) the user needs to sign. + :ivar phone_number: Phone number to be hosted. This must be in [E.164](https://en.wikipedia.org/wiki/E.164) format, e.g., +16175551212 + :ivar capabilities: + :ivar friendly_name: A 64 character string that is a human-readable text that describes this resource. + :ivar unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :ivar status: + :ivar failure_reason: A message that explains why a hosted_number_order went to status \"action-required\" + :ivar date_created: The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date that this resource was updated, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar verification_attempts: The number of attempts made to verify ownership of the phone number that is being hosted. + :ivar email: Email of the owner of this phone number that is being hosted. + :ivar cc_emails: A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + :ivar url: The URL of this HostedNumberOrder. + :ivar verification_type: + :ivar verification_document_sid: A 34 character string that uniquely identifies the Identity Document resource that represents the document for verifying ownership of the number to be hosted. + :ivar extension: A numerical extension to be used when making the ownership verification call. + :ivar call_delay: A value between 0-30 specifying the number of seconds to delay initiating the ownership verification call. + :ivar verification_code: A verification code provided in the response for a user to enter when they pick up the phone call. + :ivar verification_call_sids: A list of 34 character strings that are unique identifiers for the calls placed as part of ownership verification. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.incoming_phone_number_sid: Optional[str] = payload.get( + "incoming_phone_number_sid" + ) + self.address_sid: Optional[str] = payload.get("address_sid") + self.signing_document_sid: Optional[str] = payload.get("signing_document_sid") + self.phone_number: Optional[str] = payload.get("phone_number") + self.capabilities: Optional[str] = payload.get("capabilities") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.status: Optional["HostedNumberOrderInstance.Status"] = payload.get( + "status" + ) + self.failure_reason: Optional[str] = payload.get("failure_reason") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.verification_attempts: Optional[int] = deserialize.integer( + payload.get("verification_attempts") + ) + self.email: Optional[str] = payload.get("email") + self.cc_emails: Optional[List[str]] = payload.get("cc_emails") + self.url: Optional[str] = payload.get("url") + self.verification_type: Optional[ + "HostedNumberOrderInstance.VerificationType" + ] = payload.get("verification_type") + self.verification_document_sid: Optional[str] = payload.get( + "verification_document_sid" + ) + self.extension: Optional[str] = payload.get("extension") + self.call_delay: Optional[int] = deserialize.integer(payload.get("call_delay")) + self.verification_code: Optional[str] = payload.get("verification_code") + self.verification_call_sids: Optional[List[str]] = payload.get( + "verification_call_sids" + ) + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[HostedNumberOrderContext] = None + + @property + def _proxy(self) -> "HostedNumberOrderContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: HostedNumberOrderContext for this HostedNumberOrderInstance + """ + if self._context is None: + self._context = HostedNumberOrderContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the HostedNumberOrderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the HostedNumberOrderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "HostedNumberOrderInstance": + """ + Fetch the HostedNumberOrderInstance + + + :returns: The fetched HostedNumberOrderInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "HostedNumberOrderInstance": + """ + Asynchronous coroutine to fetch the HostedNumberOrderInstance + + + :returns: The fetched HostedNumberOrderInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + verification_code: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + extension: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + ) -> "HostedNumberOrderInstance": + """ + Update the HostedNumberOrderInstance + + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param email: Email of the owner of this phone number that is being hosted. + :param cc_emails: Optional. A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + :param status: + :param verification_code: A verification code that is given to the user via a phone call to the phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + :param extension: Digits to dial after connecting the verification call. + :param call_delay: The number of seconds, between 0 and 60, to delay before initiating the verification call. Defaults to 0. + + :returns: The updated HostedNumberOrderInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + unique_name=unique_name, + email=email, + cc_emails=cc_emails, + status=status, + verification_code=verification_code, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + extension=extension, + call_delay=call_delay, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + verification_code: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + extension: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + ) -> "HostedNumberOrderInstance": + """ + Asynchronous coroutine to update the HostedNumberOrderInstance + + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param email: Email of the owner of this phone number that is being hosted. + :param cc_emails: Optional. A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + :param status: + :param verification_code: A verification code that is given to the user via a phone call to the phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + :param extension: Digits to dial after connecting the verification call. + :param call_delay: The number of seconds, between 0 and 60, to delay before initiating the verification call. Defaults to 0. + + :returns: The updated HostedNumberOrderInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + unique_name=unique_name, + email=email, + cc_emails=cc_emails, + status=status, + verification_code=verification_code, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + extension=extension, + call_delay=call_delay, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class HostedNumberOrderContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the HostedNumberOrderContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this HostedNumberOrder. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/HostedNumberOrders/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the HostedNumberOrderInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the HostedNumberOrderInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> HostedNumberOrderInstance: + """ + Fetch the HostedNumberOrderInstance + + + :returns: The fetched HostedNumberOrderInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> HostedNumberOrderInstance: + """ + Asynchronous coroutine to fetch the HostedNumberOrderInstance + + + :returns: The fetched HostedNumberOrderInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + verification_code: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + extension: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Update the HostedNumberOrderInstance + + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param email: Email of the owner of this phone number that is being hosted. + :param cc_emails: Optional. A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + :param status: + :param verification_code: A verification code that is given to the user via a phone call to the phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + :param extension: Digits to dial after connecting the verification call. + :param call_delay: The number of seconds, between 0 and 60, to delay before initiating the verification call. Defaults to 0. + + :returns: The updated HostedNumberOrderInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Email": email, + "CcEmails": serialize.map(cc_emails, lambda e: e), + "Status": status, + "VerificationCode": verification_code, + "VerificationType": verification_type, + "VerificationDocumentSid": verification_document_sid, + "Extension": extension, + "CallDelay": call_delay, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + verification_code: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + extension: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Asynchronous coroutine to update the HostedNumberOrderInstance + + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param email: Email of the owner of this phone number that is being hosted. + :param cc_emails: Optional. A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + :param status: + :param verification_code: A verification code that is given to the user via a phone call to the phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + :param extension: Digits to dial after connecting the verification call. + :param call_delay: The number of seconds, between 0 and 60, to delay before initiating the verification call. Defaults to 0. + + :returns: The updated HostedNumberOrderInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Email": email, + "CcEmails": serialize.map(cc_emails, lambda e: e), + "Status": status, + "VerificationCode": verification_code, + "VerificationType": verification_type, + "VerificationDocumentSid": verification_document_sid, + "Extension": extension, + "CallDelay": call_delay, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class HostedNumberOrderPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> HostedNumberOrderInstance: + """ + Build an instance of HostedNumberOrderInstance + + :param payload: Payload response from the API + """ + return HostedNumberOrderInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class HostedNumberOrderList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the HostedNumberOrderList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/HostedNumberOrders" + + def create( + self, + phone_number: str, + sms_capability: bool, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Create the HostedNumberOrderInstance + + :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format + :param sms_capability: Used to specify that the SMS capability will be hosted on Twilio's platform. + :param account_sid: This defaults to the AccountSid of the authorization the user is using. This can be provided to specify a subaccount to add the HostedNumberOrder to. + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Optional. Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param cc_emails: Optional. A list of emails that the LOA document for this HostedNumberOrder will be carbon copied to. + :param sms_url: The URL that Twilio should request when somebody sends an SMS to the phone number. This will be copied onto the IncomingPhoneNumber resource. + :param sms_method: The HTTP method that should be used to request the SmsUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_url: A URL that Twilio will request if an error occurs requesting or executing the TwiML defined by SmsUrl. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_method: The HTTP method that should be used to request the SmsFallbackUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param status_callback_url: Optional. The Status Callback URL attached to the IncomingPhoneNumber resource. + :param status_callback_method: Optional. The Status Callback Method attached to the IncomingPhoneNumber resource. + :param sms_application_sid: Optional. The 34 character sid of the application Twilio should use to handle SMS messages sent to this number. If a `SmsApplicationSid` is present, Twilio will ignore all of the SMS urls above and use those set on the application. + :param address_sid: Optional. A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :param email: Optional. Email of the owner of this phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + + :returns: The created HostedNumberOrderInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "SmsCapability": serialize.boolean_to_string(sms_capability), + "AccountSid": account_sid, + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "CcEmails": serialize.map(cc_emails, lambda e: e), + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsFallbackMethod": sms_fallback_method, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "SmsApplicationSid": sms_application_sid, + "AddressSid": address_sid, + "Email": email, + "VerificationType": verification_type, + "VerificationDocumentSid": verification_document_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return HostedNumberOrderInstance(self._version, payload) + + async def create_async( + self, + phone_number: str, + sms_capability: bool, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Asynchronously create the HostedNumberOrderInstance + + :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format + :param sms_capability: Used to specify that the SMS capability will be hosted on Twilio's platform. + :param account_sid: This defaults to the AccountSid of the authorization the user is using. This can be provided to specify a subaccount to add the HostedNumberOrder to. + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Optional. Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param cc_emails: Optional. A list of emails that the LOA document for this HostedNumberOrder will be carbon copied to. + :param sms_url: The URL that Twilio should request when somebody sends an SMS to the phone number. This will be copied onto the IncomingPhoneNumber resource. + :param sms_method: The HTTP method that should be used to request the SmsUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_url: A URL that Twilio will request if an error occurs requesting or executing the TwiML defined by SmsUrl. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_method: The HTTP method that should be used to request the SmsFallbackUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param status_callback_url: Optional. The Status Callback URL attached to the IncomingPhoneNumber resource. + :param status_callback_method: Optional. The Status Callback Method attached to the IncomingPhoneNumber resource. + :param sms_application_sid: Optional. The 34 character sid of the application Twilio should use to handle SMS messages sent to this number. If a `SmsApplicationSid` is present, Twilio will ignore all of the SMS urls above and use those set on the application. + :param address_sid: Optional. A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :param email: Optional. Email of the owner of this phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + + :returns: The created HostedNumberOrderInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "SmsCapability": serialize.boolean_to_string(sms_capability), + "AccountSid": account_sid, + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "CcEmails": serialize.map(cc_emails, lambda e: e), + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsFallbackMethod": sms_fallback_method, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "SmsApplicationSid": sms_application_sid, + "AddressSid": address_sid, + "Email": email, + "VerificationType": verification_type, + "VerificationDocumentSid": verification_document_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return HostedNumberOrderInstance(self._version, payload) + + def stream( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[HostedNumberOrderInstance]: + """ + Streams HostedNumberOrderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[HostedNumberOrderInstance]: + """ + Asynchronously streams HostedNumberOrderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[HostedNumberOrderInstance]: + """ + Lists HostedNumberOrderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[HostedNumberOrderInstance]: + """ + Asynchronously lists HostedNumberOrderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> HostedNumberOrderPage: + """ + Retrieve a single page of HostedNumberOrderInstance records from the API. + Request is executed immediately + + :param status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of HostedNumberOrderInstance + """ + data = values.of( + { + "Status": status, + "PhoneNumber": phone_number, + "IncomingPhoneNumberSid": incoming_phone_number_sid, + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return HostedNumberOrderPage(self._version, response) + + async def page_async( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> HostedNumberOrderPage: + """ + Asynchronously retrieve a single page of HostedNumberOrderInstance records from the API. + Request is executed immediately + + :param status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of HostedNumberOrderInstance + """ + data = values.of( + { + "Status": status, + "PhoneNumber": phone_number, + "IncomingPhoneNumberSid": incoming_phone_number_sid, + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return HostedNumberOrderPage(self._version, response) + + def get_page(self, target_url: str) -> HostedNumberOrderPage: + """ + Retrieve a specific page of HostedNumberOrderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of HostedNumberOrderInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return HostedNumberOrderPage(self._version, response) + + async def get_page_async(self, target_url: str) -> HostedNumberOrderPage: + """ + Asynchronously retrieve a specific page of HostedNumberOrderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of HostedNumberOrderInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return HostedNumberOrderPage(self._version, response) + + def get(self, sid: str) -> HostedNumberOrderContext: + """ + Constructs a HostedNumberOrderContext + + :param sid: A 34 character string that uniquely identifies this HostedNumberOrder. + """ + return HostedNumberOrderContext(self._version, sid=sid) + + def __call__(self, sid: str) -> HostedNumberOrderContext: + """ + Constructs a HostedNumberOrderContext + + :param sid: A 34 character string that uniquely identifies this HostedNumberOrder. + """ + return HostedNumberOrderContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/preview/marketplace/__init__.py b/venv/Lib/site-packages/twilio/rest/preview/marketplace/__init__.py new file mode 100644 index 00000000..fcc99a41 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview/marketplace/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.preview.marketplace.available_add_on import AvailableAddOnList +from twilio.rest.preview.marketplace.installed_add_on import InstalledAddOnList + + +class Marketplace(Version): + + def __init__(self, domain: Domain): + """ + Initialize the Marketplace version of Preview + + :param domain: The Twilio.preview domain + """ + super().__init__(domain, "marketplace") + self._available_add_ons: Optional[AvailableAddOnList] = None + self._installed_add_ons: Optional[InstalledAddOnList] = None + + @property + def available_add_ons(self) -> AvailableAddOnList: + if self._available_add_ons is None: + self._available_add_ons = AvailableAddOnList(self) + return self._available_add_ons + + @property + def installed_add_ons(self) -> InstalledAddOnList: + if self._installed_add_ons is None: + self._installed_add_ons = InstalledAddOnList(self) + return self._installed_add_ons + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/preview/marketplace/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview/marketplace/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..06308f3d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview/marketplace/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview/marketplace/available_add_on/__init__.py b/venv/Lib/site-packages/twilio/rest/preview/marketplace/available_add_on/__init__.py new file mode 100644 index 00000000..e81ec649 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview/marketplace/available_add_on/__init__.py @@ -0,0 +1,438 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.preview.marketplace.available_add_on.available_add_on_extension import ( + AvailableAddOnExtensionList, +) + + +class AvailableAddOnInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the AvailableAddOn resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar description: A short description of the Add-on's functionality. + :ivar pricing_type: How customers are charged for using this Add-on. + :ivar configuration_schema: The JSON object with the configuration that must be provided when installing a given Add-on. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.pricing_type: Optional[str] = payload.get("pricing_type") + self.configuration_schema: Optional[Dict[str, object]] = payload.get( + "configuration_schema" + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[AvailableAddOnContext] = None + + @property + def _proxy(self) -> "AvailableAddOnContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AvailableAddOnContext for this AvailableAddOnInstance + """ + if self._context is None: + self._context = AvailableAddOnContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "AvailableAddOnInstance": + """ + Fetch the AvailableAddOnInstance + + + :returns: The fetched AvailableAddOnInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AvailableAddOnInstance": + """ + Asynchronous coroutine to fetch the AvailableAddOnInstance + + + :returns: The fetched AvailableAddOnInstance + """ + return await self._proxy.fetch_async() + + @property + def extensions(self) -> AvailableAddOnExtensionList: + """ + Access the extensions + """ + return self._proxy.extensions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AvailableAddOnContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the AvailableAddOnContext + + :param version: Version that contains the resource + :param sid: The SID of the AvailableAddOn resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/AvailableAddOns/{sid}".format(**self._solution) + + self._extensions: Optional[AvailableAddOnExtensionList] = None + + def fetch(self) -> AvailableAddOnInstance: + """ + Fetch the AvailableAddOnInstance + + + :returns: The fetched AvailableAddOnInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AvailableAddOnInstance: + """ + Asynchronous coroutine to fetch the AvailableAddOnInstance + + + :returns: The fetched AvailableAddOnInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + @property + def extensions(self) -> AvailableAddOnExtensionList: + """ + Access the extensions + """ + if self._extensions is None: + self._extensions = AvailableAddOnExtensionList( + self._version, + self._solution["sid"], + ) + return self._extensions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AvailableAddOnPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AvailableAddOnInstance: + """ + Build an instance of AvailableAddOnInstance + + :param payload: Payload response from the API + """ + return AvailableAddOnInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AvailableAddOnList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AvailableAddOnList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/AvailableAddOns" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AvailableAddOnInstance]: + """ + Streams AvailableAddOnInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AvailableAddOnInstance]: + """ + Asynchronously streams AvailableAddOnInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnInstance]: + """ + Lists AvailableAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnInstance]: + """ + Asynchronously lists AvailableAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AvailableAddOnPage: + """ + Retrieve a single page of AvailableAddOnInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AvailableAddOnInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailableAddOnPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AvailableAddOnPage: + """ + Asynchronously retrieve a single page of AvailableAddOnInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AvailableAddOnInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailableAddOnPage(self._version, response) + + def get_page(self, target_url: str) -> AvailableAddOnPage: + """ + Retrieve a specific page of AvailableAddOnInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailableAddOnInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AvailableAddOnPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AvailableAddOnPage: + """ + Asynchronously retrieve a specific page of AvailableAddOnInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailableAddOnInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AvailableAddOnPage(self._version, response) + + def get(self, sid: str) -> AvailableAddOnContext: + """ + Constructs a AvailableAddOnContext + + :param sid: The SID of the AvailableAddOn resource to fetch. + """ + return AvailableAddOnContext(self._version, sid=sid) + + def __call__(self, sid: str) -> AvailableAddOnContext: + """ + Constructs a AvailableAddOnContext + + :param sid: The SID of the AvailableAddOn resource to fetch. + """ + return AvailableAddOnContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/preview/marketplace/available_add_on/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview/marketplace/available_add_on/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..077766ce Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview/marketplace/available_add_on/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview/marketplace/available_add_on/__pycache__/available_add_on_extension.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview/marketplace/available_add_on/__pycache__/available_add_on_extension.cpython-312.pyc new file mode 100644 index 00000000..3d9d8676 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview/marketplace/available_add_on/__pycache__/available_add_on_extension.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview/marketplace/available_add_on/available_add_on_extension.py b/venv/Lib/site-packages/twilio/rest/preview/marketplace/available_add_on/available_add_on_extension.py new file mode 100644 index 00000000..4c05f424 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview/marketplace/available_add_on/available_add_on_extension.py @@ -0,0 +1,445 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AvailableAddOnExtensionInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the AvailableAddOnExtension resource. + :ivar available_add_on_sid: The SID of the AvailableAddOn resource to which this extension applies. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar product_name: The name of the Product this Extension is used within. + :ivar unique_name: An application-defined string that uniquely identifies the resource. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + available_add_on_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.available_add_on_sid: Optional[str] = payload.get("available_add_on_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.product_name: Optional[str] = payload.get("product_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "available_add_on_sid": available_add_on_sid, + "sid": sid or self.sid, + } + self._context: Optional[AvailableAddOnExtensionContext] = None + + @property + def _proxy(self) -> "AvailableAddOnExtensionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AvailableAddOnExtensionContext for this AvailableAddOnExtensionInstance + """ + if self._context is None: + self._context = AvailableAddOnExtensionContext( + self._version, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "AvailableAddOnExtensionInstance": + """ + Fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AvailableAddOnExtensionInstance": + """ + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class AvailableAddOnExtensionContext(InstanceContext): + + def __init__(self, version: Version, available_add_on_sid: str, sid: str): + """ + Initialize the AvailableAddOnExtensionContext + + :param version: Version that contains the resource + :param available_add_on_sid: The SID of the AvailableAddOn resource with the extension to fetch. + :param sid: The SID of the AvailableAddOn Extension resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "available_add_on_sid": available_add_on_sid, + "sid": sid, + } + self._uri = "/AvailableAddOns/{available_add_on_sid}/Extensions/{sid}".format( + **self._solution + ) + + def fetch(self) -> AvailableAddOnExtensionInstance: + """ + Fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AvailableAddOnExtensionInstance: + """ + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class AvailableAddOnExtensionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AvailableAddOnExtensionInstance: + """ + Build an instance of AvailableAddOnExtensionInstance + + :param payload: Payload response from the API + """ + return AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AvailableAddOnExtensionList(ListResource): + + def __init__(self, version: Version, available_add_on_sid: str): + """ + Initialize the AvailableAddOnExtensionList + + :param version: Version that contains the resource + :param available_add_on_sid: The SID of the AvailableAddOn resource with the extensions to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "available_add_on_sid": available_add_on_sid, + } + self._uri = "/AvailableAddOns/{available_add_on_sid}/Extensions".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AvailableAddOnExtensionInstance]: + """ + Streams AvailableAddOnExtensionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AvailableAddOnExtensionInstance]: + """ + Asynchronously streams AvailableAddOnExtensionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnExtensionInstance]: + """ + Lists AvailableAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnExtensionInstance]: + """ + Asynchronously lists AvailableAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AvailableAddOnExtensionPage: + """ + Retrieve a single page of AvailableAddOnExtensionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AvailableAddOnExtensionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailableAddOnExtensionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AvailableAddOnExtensionPage: + """ + Asynchronously retrieve a single page of AvailableAddOnExtensionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AvailableAddOnExtensionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailableAddOnExtensionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AvailableAddOnExtensionPage: + """ + Retrieve a specific page of AvailableAddOnExtensionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailableAddOnExtensionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AvailableAddOnExtensionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AvailableAddOnExtensionPage: + """ + Asynchronously retrieve a specific page of AvailableAddOnExtensionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailableAddOnExtensionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AvailableAddOnExtensionPage(self._version, response, self._solution) + + def get(self, sid: str) -> AvailableAddOnExtensionContext: + """ + Constructs a AvailableAddOnExtensionContext + + :param sid: The SID of the AvailableAddOn Extension resource to fetch. + """ + return AvailableAddOnExtensionContext( + self._version, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> AvailableAddOnExtensionContext: + """ + Constructs a AvailableAddOnExtensionContext + + :param sid: The SID of the AvailableAddOn Extension resource to fetch. + """ + return AvailableAddOnExtensionContext( + self._version, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/preview/marketplace/installed_add_on/__init__.py b/venv/Lib/site-packages/twilio/rest/preview/marketplace/installed_add_on/__init__.py new file mode 100644 index 00000000..7f1fadc5 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview/marketplace/installed_add_on/__init__.py @@ -0,0 +1,671 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension import ( + InstalledAddOnExtensionList, +) + + +class InstalledAddOnInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the InstalledAddOn resource. This Sid can also be found in the Console on that specific Add-ons page as the 'Available Add-on Sid'. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the InstalledAddOn resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar description: A short description of the Add-on's functionality. + :ivar configuration: The JSON object that represents the current configuration of installed Add-on. + :ivar unique_name: An application-defined string that uniquely identifies the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + self.unique_name: Optional[str] = payload.get("unique_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[InstalledAddOnContext] = None + + @property + def _proxy(self) -> "InstalledAddOnContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InstalledAddOnContext for this InstalledAddOnInstance + """ + if self._context is None: + self._context = InstalledAddOnContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the InstalledAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InstalledAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "InstalledAddOnInstance": + """ + Fetch the InstalledAddOnInstance + + + :returns: The fetched InstalledAddOnInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InstalledAddOnInstance": + """ + Asynchronous coroutine to fetch the InstalledAddOnInstance + + + :returns: The fetched InstalledAddOnInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> "InstalledAddOnInstance": + """ + Update the InstalledAddOnInstance + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The updated InstalledAddOnInstance + """ + return self._proxy.update( + configuration=configuration, + unique_name=unique_name, + ) + + async def update_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> "InstalledAddOnInstance": + """ + Asynchronous coroutine to update the InstalledAddOnInstance + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The updated InstalledAddOnInstance + """ + return await self._proxy.update_async( + configuration=configuration, + unique_name=unique_name, + ) + + @property + def extensions(self) -> InstalledAddOnExtensionList: + """ + Access the extensions + """ + return self._proxy.extensions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InstalledAddOnContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the InstalledAddOnContext + + :param version: Version that contains the resource + :param sid: The SID of the InstalledAddOn resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/InstalledAddOns/{sid}".format(**self._solution) + + self._extensions: Optional[InstalledAddOnExtensionList] = None + + def delete(self) -> bool: + """ + Deletes the InstalledAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InstalledAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> InstalledAddOnInstance: + """ + Fetch the InstalledAddOnInstance + + + :returns: The fetched InstalledAddOnInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> InstalledAddOnInstance: + """ + Asynchronous coroutine to fetch the InstalledAddOnInstance + + + :returns: The fetched InstalledAddOnInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> InstalledAddOnInstance: + """ + Update the InstalledAddOnInstance + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The updated InstalledAddOnInstance + """ + + data = values.of( + { + "Configuration": serialize.object(configuration), + "UniqueName": unique_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> InstalledAddOnInstance: + """ + Asynchronous coroutine to update the InstalledAddOnInstance + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The updated InstalledAddOnInstance + """ + + data = values.of( + { + "Configuration": serialize.object(configuration), + "UniqueName": unique_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def extensions(self) -> InstalledAddOnExtensionList: + """ + Access the extensions + """ + if self._extensions is None: + self._extensions = InstalledAddOnExtensionList( + self._version, + self._solution["sid"], + ) + return self._extensions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InstalledAddOnPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InstalledAddOnInstance: + """ + Build an instance of InstalledAddOnInstance + + :param payload: Payload response from the API + """ + return InstalledAddOnInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class InstalledAddOnList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InstalledAddOnList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/InstalledAddOns" + + def create( + self, + available_add_on_sid: str, + accept_terms_of_service: bool, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> InstalledAddOnInstance: + """ + Create the InstalledAddOnInstance + + :param available_add_on_sid: The SID of the AvaliableAddOn to install. + :param accept_terms_of_service: Whether the Terms of Service were accepted. + :param configuration: The JSON object that represents the configuration of the new Add-on being installed. + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The created InstalledAddOnInstance + """ + + data = values.of( + { + "AvailableAddOnSid": available_add_on_sid, + "AcceptTermsOfService": serialize.boolean_to_string( + accept_terms_of_service + ), + "Configuration": serialize.object(configuration), + "UniqueName": unique_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnInstance(self._version, payload) + + async def create_async( + self, + available_add_on_sid: str, + accept_terms_of_service: bool, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> InstalledAddOnInstance: + """ + Asynchronously create the InstalledAddOnInstance + + :param available_add_on_sid: The SID of the AvaliableAddOn to install. + :param accept_terms_of_service: Whether the Terms of Service were accepted. + :param configuration: The JSON object that represents the configuration of the new Add-on being installed. + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The created InstalledAddOnInstance + """ + + data = values.of( + { + "AvailableAddOnSid": available_add_on_sid, + "AcceptTermsOfService": serialize.boolean_to_string( + accept_terms_of_service + ), + "Configuration": serialize.object(configuration), + "UniqueName": unique_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InstalledAddOnInstance]: + """ + Streams InstalledAddOnInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InstalledAddOnInstance]: + """ + Asynchronously streams InstalledAddOnInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InstalledAddOnInstance]: + """ + Lists InstalledAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InstalledAddOnInstance]: + """ + Asynchronously lists InstalledAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InstalledAddOnPage: + """ + Retrieve a single page of InstalledAddOnInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InstalledAddOnInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InstalledAddOnPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InstalledAddOnPage: + """ + Asynchronously retrieve a single page of InstalledAddOnInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InstalledAddOnInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InstalledAddOnPage(self._version, response) + + def get_page(self, target_url: str) -> InstalledAddOnPage: + """ + Retrieve a specific page of InstalledAddOnInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InstalledAddOnInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InstalledAddOnPage(self._version, response) + + async def get_page_async(self, target_url: str) -> InstalledAddOnPage: + """ + Asynchronously retrieve a specific page of InstalledAddOnInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InstalledAddOnInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InstalledAddOnPage(self._version, response) + + def get(self, sid: str) -> InstalledAddOnContext: + """ + Constructs a InstalledAddOnContext + + :param sid: The SID of the InstalledAddOn resource to update. + """ + return InstalledAddOnContext(self._version, sid=sid) + + def __call__(self, sid: str) -> InstalledAddOnContext: + """ + Constructs a InstalledAddOnContext + + :param sid: The SID of the InstalledAddOn resource to update. + """ + return InstalledAddOnContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/preview/marketplace/installed_add_on/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview/marketplace/installed_add_on/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..b02f332b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview/marketplace/installed_add_on/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview/marketplace/installed_add_on/__pycache__/installed_add_on_extension.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview/marketplace/installed_add_on/__pycache__/installed_add_on_extension.cpython-312.pyc new file mode 100644 index 00000000..60f26b32 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview/marketplace/installed_add_on/__pycache__/installed_add_on_extension.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview/marketplace/installed_add_on/installed_add_on_extension.py b/venv/Lib/site-packages/twilio/rest/preview/marketplace/installed_add_on/installed_add_on_extension.py new file mode 100644 index 00000000..e0574ee2 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview/marketplace/installed_add_on/installed_add_on_extension.py @@ -0,0 +1,533 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InstalledAddOnExtensionInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the InstalledAddOn Extension resource. + :ivar installed_add_on_sid: The SID of the InstalledAddOn resource to which this extension applies. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar product_name: The name of the Product this Extension is used within. + :ivar unique_name: An application-defined string that uniquely identifies the resource. + :ivar enabled: Whether the Extension will be invoked. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + installed_add_on_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.installed_add_on_sid: Optional[str] = payload.get("installed_add_on_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.product_name: Optional[str] = payload.get("product_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.enabled: Optional[bool] = payload.get("enabled") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "installed_add_on_sid": installed_add_on_sid, + "sid": sid or self.sid, + } + self._context: Optional[InstalledAddOnExtensionContext] = None + + @property + def _proxy(self) -> "InstalledAddOnExtensionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InstalledAddOnExtensionContext for this InstalledAddOnExtensionInstance + """ + if self._context is None: + self._context = InstalledAddOnExtensionContext( + self._version, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "InstalledAddOnExtensionInstance": + """ + Fetch the InstalledAddOnExtensionInstance + + + :returns: The fetched InstalledAddOnExtensionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InstalledAddOnExtensionInstance": + """ + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance + + + :returns: The fetched InstalledAddOnExtensionInstance + """ + return await self._proxy.fetch_async() + + def update(self, enabled: bool) -> "InstalledAddOnExtensionInstance": + """ + Update the InstalledAddOnExtensionInstance + + :param enabled: Whether the Extension should be invoked. + + :returns: The updated InstalledAddOnExtensionInstance + """ + return self._proxy.update( + enabled=enabled, + ) + + async def update_async(self, enabled: bool) -> "InstalledAddOnExtensionInstance": + """ + Asynchronous coroutine to update the InstalledAddOnExtensionInstance + + :param enabled: Whether the Extension should be invoked. + + :returns: The updated InstalledAddOnExtensionInstance + """ + return await self._proxy.update_async( + enabled=enabled, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class InstalledAddOnExtensionContext(InstanceContext): + + def __init__(self, version: Version, installed_add_on_sid: str, sid: str): + """ + Initialize the InstalledAddOnExtensionContext + + :param version: Version that contains the resource + :param installed_add_on_sid: The SID of the InstalledAddOn resource with the extension to update. + :param sid: The SID of the InstalledAddOn Extension resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "installed_add_on_sid": installed_add_on_sid, + "sid": sid, + } + self._uri = "/InstalledAddOns/{installed_add_on_sid}/Extensions/{sid}".format( + **self._solution + ) + + def fetch(self) -> InstalledAddOnExtensionInstance: + """ + Fetch the InstalledAddOnExtensionInstance + + + :returns: The fetched InstalledAddOnExtensionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> InstalledAddOnExtensionInstance: + """ + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance + + + :returns: The fetched InstalledAddOnExtensionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + + def update(self, enabled: bool) -> InstalledAddOnExtensionInstance: + """ + Update the InstalledAddOnExtensionInstance + + :param enabled: Whether the Extension should be invoked. + + :returns: The updated InstalledAddOnExtensionInstance + """ + + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, enabled: bool) -> InstalledAddOnExtensionInstance: + """ + Asynchronous coroutine to update the InstalledAddOnExtensionInstance + + :param enabled: Whether the Extension should be invoked. + + :returns: The updated InstalledAddOnExtensionInstance + """ + + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class InstalledAddOnExtensionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InstalledAddOnExtensionInstance: + """ + Build an instance of InstalledAddOnExtensionInstance + + :param payload: Payload response from the API + """ + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class InstalledAddOnExtensionList(ListResource): + + def __init__(self, version: Version, installed_add_on_sid: str): + """ + Initialize the InstalledAddOnExtensionList + + :param version: Version that contains the resource + :param installed_add_on_sid: The SID of the InstalledAddOn resource with the extensions to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "installed_add_on_sid": installed_add_on_sid, + } + self._uri = "/InstalledAddOns/{installed_add_on_sid}/Extensions".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InstalledAddOnExtensionInstance]: + """ + Streams InstalledAddOnExtensionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InstalledAddOnExtensionInstance]: + """ + Asynchronously streams InstalledAddOnExtensionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InstalledAddOnExtensionInstance]: + """ + Lists InstalledAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InstalledAddOnExtensionInstance]: + """ + Asynchronously lists InstalledAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InstalledAddOnExtensionPage: + """ + Retrieve a single page of InstalledAddOnExtensionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InstalledAddOnExtensionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InstalledAddOnExtensionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InstalledAddOnExtensionPage: + """ + Asynchronously retrieve a single page of InstalledAddOnExtensionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InstalledAddOnExtensionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InstalledAddOnExtensionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> InstalledAddOnExtensionPage: + """ + Retrieve a specific page of InstalledAddOnExtensionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InstalledAddOnExtensionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InstalledAddOnExtensionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> InstalledAddOnExtensionPage: + """ + Asynchronously retrieve a specific page of InstalledAddOnExtensionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InstalledAddOnExtensionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InstalledAddOnExtensionPage(self._version, response, self._solution) + + def get(self, sid: str) -> InstalledAddOnExtensionContext: + """ + Constructs a InstalledAddOnExtensionContext + + :param sid: The SID of the InstalledAddOn Extension resource to update. + """ + return InstalledAddOnExtensionContext( + self._version, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InstalledAddOnExtensionContext: + """ + Constructs a InstalledAddOnExtensionContext + + :param sid: The SID of the InstalledAddOn Extension resource to update. + """ + return InstalledAddOnExtensionContext( + self._version, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/preview/wireless/__init__.py b/venv/Lib/site-packages/twilio/rest/preview/wireless/__init__.py new file mode 100644 index 00000000..85ed4fb5 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview/wireless/__init__.py @@ -0,0 +1,59 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.preview.wireless.command import CommandList +from twilio.rest.preview.wireless.rate_plan import RatePlanList +from twilio.rest.preview.wireless.sim import SimList + + +class Wireless(Version): + + def __init__(self, domain: Domain): + """ + Initialize the Wireless version of Preview + + :param domain: The Twilio.preview domain + """ + super().__init__(domain, "wireless") + self._commands: Optional[CommandList] = None + self._rate_plans: Optional[RatePlanList] = None + self._sims: Optional[SimList] = None + + @property + def commands(self) -> CommandList: + if self._commands is None: + self._commands = CommandList(self) + return self._commands + + @property + def rate_plans(self) -> RatePlanList: + if self._rate_plans is None: + self._rate_plans = RatePlanList(self) + return self._rate_plans + + @property + def sims(self) -> SimList: + if self._sims is None: + self._sims = SimList(self) + return self._sims + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/preview/wireless/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview/wireless/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..76497420 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview/wireless/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview/wireless/__pycache__/command.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview/wireless/__pycache__/command.cpython-312.pyc new file mode 100644 index 00000000..b52f454d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview/wireless/__pycache__/command.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview/wireless/__pycache__/rate_plan.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview/wireless/__pycache__/rate_plan.cpython-312.pyc new file mode 100644 index 00000000..faa46e07 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview/wireless/__pycache__/rate_plan.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview/wireless/command.py b/venv/Lib/site-packages/twilio/rest/preview/wireless/command.py new file mode 100644 index 00000000..8e715e09 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview/wireless/command.py @@ -0,0 +1,595 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CommandInstance(InstanceResource): + """ + :ivar sid: + :ivar account_sid: + :ivar device_sid: + :ivar sim_sid: + :ivar command: + :ivar command_mode: + :ivar status: + :ivar direction: + :ivar date_created: + :ivar date_updated: + :ivar url: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.device_sid: Optional[str] = payload.get("device_sid") + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.command: Optional[str] = payload.get("command") + self.command_mode: Optional[str] = payload.get("command_mode") + self.status: Optional[str] = payload.get("status") + self.direction: Optional[str] = payload.get("direction") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CommandContext] = None + + @property + def _proxy(self) -> "CommandContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CommandContext for this CommandInstance + """ + if self._context is None: + self._context = CommandContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "CommandInstance": + """ + Fetch the CommandInstance + + + :returns: The fetched CommandInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CommandInstance": + """ + Asynchronous coroutine to fetch the CommandInstance + + + :returns: The fetched CommandInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CommandContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CommandContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Commands/{sid}".format(**self._solution) + + def fetch(self) -> CommandInstance: + """ + Fetch the CommandInstance + + + :returns: The fetched CommandInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CommandInstance: + """ + Asynchronous coroutine to fetch the CommandInstance + + + :returns: The fetched CommandInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CommandPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CommandInstance: + """ + Build an instance of CommandInstance + + :param payload: Payload response from the API + """ + return CommandInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CommandList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CommandList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Commands" + + def create( + self, + command: str, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union[str, object] = values.unset, + include_sid: Union[str, object] = values.unset, + ) -> CommandInstance: + """ + Create the CommandInstance + + :param command: + :param device: + :param sim: + :param callback_method: + :param callback_url: + :param command_mode: + :param include_sid: + + :returns: The created CommandInstance + """ + + data = values.of( + { + "Command": command, + "Device": device, + "Sim": sim, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "CommandMode": command_mode, + "IncludeSid": include_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CommandInstance(self._version, payload) + + async def create_async( + self, + command: str, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union[str, object] = values.unset, + include_sid: Union[str, object] = values.unset, + ) -> CommandInstance: + """ + Asynchronously create the CommandInstance + + :param command: + :param device: + :param sim: + :param callback_method: + :param callback_url: + :param command_mode: + :param include_sid: + + :returns: The created CommandInstance + """ + + data = values.of( + { + "Command": command, + "Device": device, + "Sim": sim, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "CommandMode": command_mode, + "IncludeSid": include_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CommandInstance(self._version, payload) + + def stream( + self, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CommandInstance]: + """ + Streams CommandInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str device: + :param str sim: + :param str status: + :param str direction: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + device=device, + sim=sim, + status=status, + direction=direction, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CommandInstance]: + """ + Asynchronously streams CommandInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str device: + :param str sim: + :param str status: + :param str direction: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + device=device, + sim=sim, + status=status, + direction=direction, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CommandInstance]: + """ + Lists CommandInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str device: + :param str sim: + :param str status: + :param str direction: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + device=device, + sim=sim, + status=status, + direction=direction, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CommandInstance]: + """ + Asynchronously lists CommandInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str device: + :param str sim: + :param str status: + :param str direction: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + device=device, + sim=sim, + status=status, + direction=direction, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CommandPage: + """ + Retrieve a single page of CommandInstance records from the API. + Request is executed immediately + + :param device: + :param sim: + :param status: + :param direction: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CommandInstance + """ + data = values.of( + { + "Device": device, + "Sim": sim, + "Status": status, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CommandPage(self._version, response) + + async def page_async( + self, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CommandPage: + """ + Asynchronously retrieve a single page of CommandInstance records from the API. + Request is executed immediately + + :param device: + :param sim: + :param status: + :param direction: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CommandInstance + """ + data = values.of( + { + "Device": device, + "Sim": sim, + "Status": status, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CommandPage(self._version, response) + + def get_page(self, target_url: str) -> CommandPage: + """ + Retrieve a specific page of CommandInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CommandInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CommandPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CommandPage: + """ + Asynchronously retrieve a specific page of CommandInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CommandInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CommandPage(self._version, response) + + def get(self, sid: str) -> CommandContext: + """ + Constructs a CommandContext + + :param sid: + """ + return CommandContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CommandContext: + """ + Constructs a CommandContext + + :param sid: + """ + return CommandContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/preview/wireless/rate_plan.py b/venv/Lib/site-packages/twilio/rest/preview/wireless/rate_plan.py new file mode 100644 index 00000000..95e45f1e --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview/wireless/rate_plan.py @@ -0,0 +1,699 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RatePlanInstance(InstanceResource): + """ + :ivar sid: + :ivar unique_name: + :ivar account_sid: + :ivar friendly_name: + :ivar data_enabled: + :ivar data_metering: + :ivar data_limit: + :ivar messaging_enabled: + :ivar voice_enabled: + :ivar national_roaming_enabled: + :ivar international_roaming: + :ivar date_created: + :ivar date_updated: + :ivar url: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.data_enabled: Optional[bool] = payload.get("data_enabled") + self.data_metering: Optional[str] = payload.get("data_metering") + self.data_limit: Optional[int] = deserialize.integer(payload.get("data_limit")) + self.messaging_enabled: Optional[bool] = payload.get("messaging_enabled") + self.voice_enabled: Optional[bool] = payload.get("voice_enabled") + self.national_roaming_enabled: Optional[bool] = payload.get( + "national_roaming_enabled" + ) + self.international_roaming: Optional[List[str]] = payload.get( + "international_roaming" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[RatePlanContext] = None + + @property + def _proxy(self) -> "RatePlanContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RatePlanContext for this RatePlanInstance + """ + if self._context is None: + self._context = RatePlanContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RatePlanInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RatePlanInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RatePlanInstance": + """ + Fetch the RatePlanInstance + + + :returns: The fetched RatePlanInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RatePlanInstance": + """ + Asynchronous coroutine to fetch the RatePlanInstance + + + :returns: The fetched RatePlanInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "RatePlanInstance": + """ + Update the RatePlanInstance + + :param unique_name: + :param friendly_name: + + :returns: The updated RatePlanInstance + """ + return self._proxy.update( + unique_name=unique_name, + friendly_name=friendly_name, + ) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "RatePlanInstance": + """ + Asynchronous coroutine to update the RatePlanInstance + + :param unique_name: + :param friendly_name: + + :returns: The updated RatePlanInstance + """ + return await self._proxy.update_async( + unique_name=unique_name, + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RatePlanContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the RatePlanContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/RatePlans/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the RatePlanInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RatePlanInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RatePlanInstance: + """ + Fetch the RatePlanInstance + + + :returns: The fetched RatePlanInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RatePlanInstance: + """ + Asynchronous coroutine to fetch the RatePlanInstance + + + :returns: The fetched RatePlanInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> RatePlanInstance: + """ + Update the RatePlanInstance + + :param unique_name: + :param friendly_name: + + :returns: The updated RatePlanInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> RatePlanInstance: + """ + Asynchronous coroutine to update the RatePlanInstance + + :param unique_name: + :param friendly_name: + + :returns: The updated RatePlanInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RatePlanPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RatePlanInstance: + """ + Build an instance of RatePlanInstance + + :param payload: Payload response from the API + """ + return RatePlanInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RatePlanList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the RatePlanList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/RatePlans" + + def create( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + commands_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + ) -> RatePlanInstance: + """ + Create the RatePlanInstance + + :param unique_name: + :param friendly_name: + :param data_enabled: + :param data_limit: + :param data_metering: + :param messaging_enabled: + :param voice_enabled: + :param commands_enabled: + :param national_roaming_enabled: + :param international_roaming: + + :returns: The created RatePlanInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + "DataEnabled": serialize.boolean_to_string(data_enabled), + "DataLimit": data_limit, + "DataMetering": data_metering, + "MessagingEnabled": serialize.boolean_to_string(messaging_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "CommandsEnabled": serialize.boolean_to_string(commands_enabled), + "NationalRoamingEnabled": serialize.boolean_to_string( + national_roaming_enabled + ), + "InternationalRoaming": serialize.map( + international_roaming, lambda e: e + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RatePlanInstance(self._version, payload) + + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + commands_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + ) -> RatePlanInstance: + """ + Asynchronously create the RatePlanInstance + + :param unique_name: + :param friendly_name: + :param data_enabled: + :param data_limit: + :param data_metering: + :param messaging_enabled: + :param voice_enabled: + :param commands_enabled: + :param national_roaming_enabled: + :param international_roaming: + + :returns: The created RatePlanInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + "DataEnabled": serialize.boolean_to_string(data_enabled), + "DataLimit": data_limit, + "DataMetering": data_metering, + "MessagingEnabled": serialize.boolean_to_string(messaging_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "CommandsEnabled": serialize.boolean_to_string(commands_enabled), + "NationalRoamingEnabled": serialize.boolean_to_string( + national_roaming_enabled + ), + "InternationalRoaming": serialize.map( + international_roaming, lambda e: e + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RatePlanInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RatePlanInstance]: + """ + Streams RatePlanInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RatePlanInstance]: + """ + Asynchronously streams RatePlanInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RatePlanInstance]: + """ + Lists RatePlanInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RatePlanInstance]: + """ + Asynchronously lists RatePlanInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RatePlanPage: + """ + Retrieve a single page of RatePlanInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RatePlanInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RatePlanPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RatePlanPage: + """ + Asynchronously retrieve a single page of RatePlanInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RatePlanInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RatePlanPage(self._version, response) + + def get_page(self, target_url: str) -> RatePlanPage: + """ + Retrieve a specific page of RatePlanInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RatePlanInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RatePlanPage(self._version, response) + + async def get_page_async(self, target_url: str) -> RatePlanPage: + """ + Asynchronously retrieve a specific page of RatePlanInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RatePlanInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RatePlanPage(self._version, response) + + def get(self, sid: str) -> RatePlanContext: + """ + Constructs a RatePlanContext + + :param sid: + """ + return RatePlanContext(self._version, sid=sid) + + def __call__(self, sid: str) -> RatePlanContext: + """ + Constructs a RatePlanContext + + :param sid: + """ + return RatePlanContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/preview/wireless/sim/__init__.py b/venv/Lib/site-packages/twilio/rest/preview/wireless/sim/__init__.py new file mode 100644 index 00000000..07a9e74d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview/wireless/sim/__init__.py @@ -0,0 +1,833 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.preview.wireless.sim.usage import UsageList + + +class SimInstance(InstanceResource): + """ + :ivar sid: + :ivar unique_name: + :ivar account_sid: + :ivar rate_plan_sid: + :ivar friendly_name: + :ivar iccid: + :ivar e_id: + :ivar status: + :ivar commands_callback_url: + :ivar commands_callback_method: + :ivar sms_fallback_method: + :ivar sms_fallback_url: + :ivar sms_method: + :ivar sms_url: + :ivar voice_fallback_method: + :ivar voice_fallback_url: + :ivar voice_method: + :ivar voice_url: + :ivar date_created: + :ivar date_updated: + :ivar url: + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.rate_plan_sid: Optional[str] = payload.get("rate_plan_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.iccid: Optional[str] = payload.get("iccid") + self.e_id: Optional[str] = payload.get("e_id") + self.status: Optional[str] = payload.get("status") + self.commands_callback_url: Optional[str] = payload.get("commands_callback_url") + self.commands_callback_method: Optional[str] = payload.get( + "commands_callback_method" + ) + self.sms_fallback_method: Optional[str] = payload.get("sms_fallback_method") + self.sms_fallback_url: Optional[str] = payload.get("sms_fallback_url") + self.sms_method: Optional[str] = payload.get("sms_method") + self.sms_url: Optional[str] = payload.get("sms_url") + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_url: Optional[str] = payload.get("voice_url") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SimContext] = None + + @property + def _proxy(self) -> "SimContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SimContext for this SimInstance + """ + if self._context is None: + self._context = SimContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "SimInstance": + """ + Fetch the SimInstance + + + :returns: The fetched SimInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SimInstance": + """ + Asynchronous coroutine to fetch the SimInstance + + + :returns: The fetched SimInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + ) -> "SimInstance": + """ + Update the SimInstance + + :param unique_name: + :param callback_method: + :param callback_url: + :param friendly_name: + :param rate_plan: + :param status: + :param commands_callback_method: + :param commands_callback_url: + :param sms_fallback_method: + :param sms_fallback_url: + :param sms_method: + :param sms_url: + :param voice_fallback_method: + :param voice_fallback_url: + :param voice_method: + :param voice_url: + + :returns: The updated SimInstance + """ + return self._proxy.update( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + ) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + ) -> "SimInstance": + """ + Asynchronous coroutine to update the SimInstance + + :param unique_name: + :param callback_method: + :param callback_url: + :param friendly_name: + :param rate_plan: + :param status: + :param commands_callback_method: + :param commands_callback_url: + :param sms_fallback_method: + :param sms_fallback_url: + :param sms_method: + :param sms_url: + :param voice_fallback_method: + :param voice_fallback_url: + :param voice_method: + :param voice_url: + + :returns: The updated SimInstance + """ + return await self._proxy.update_async( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + ) + + @property + def usage(self) -> UsageList: + """ + Access the usage + """ + return self._proxy.usage + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SimContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SimContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Sims/{sid}".format(**self._solution) + + self._usage: Optional[UsageList] = None + + def fetch(self) -> SimInstance: + """ + Fetch the SimInstance + + + :returns: The fetched SimInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SimInstance: + """ + Asynchronous coroutine to fetch the SimInstance + + + :returns: The fetched SimInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + ) -> SimInstance: + """ + Update the SimInstance + + :param unique_name: + :param callback_method: + :param callback_url: + :param friendly_name: + :param rate_plan: + :param status: + :param commands_callback_method: + :param commands_callback_url: + :param sms_fallback_method: + :param sms_fallback_url: + :param sms_method: + :param sms_url: + :param voice_fallback_method: + :param voice_fallback_url: + :param voice_method: + :param voice_url: + + :returns: The updated SimInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "FriendlyName": friendly_name, + "RatePlan": rate_plan, + "Status": status, + "CommandsCallbackMethod": commands_callback_method, + "CommandsCallbackUrl": commands_callback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SimInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + ) -> SimInstance: + """ + Asynchronous coroutine to update the SimInstance + + :param unique_name: + :param callback_method: + :param callback_url: + :param friendly_name: + :param rate_plan: + :param status: + :param commands_callback_method: + :param commands_callback_url: + :param sms_fallback_method: + :param sms_fallback_url: + :param sms_method: + :param sms_url: + :param voice_fallback_method: + :param voice_fallback_url: + :param voice_method: + :param voice_url: + + :returns: The updated SimInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "FriendlyName": friendly_name, + "RatePlan": rate_plan, + "Status": status, + "CommandsCallbackMethod": commands_callback_method, + "CommandsCallbackUrl": commands_callback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SimInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def usage(self) -> UsageList: + """ + Access the usage + """ + if self._usage is None: + self._usage = UsageList( + self._version, + self._solution["sid"], + ) + return self._usage + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SimPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SimInstance: + """ + Build an instance of SimInstance + + :param payload: Payload response from the API + """ + return SimInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SimList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SimList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Sims" + + def stream( + self, + status: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SimInstance]: + """ + Streams SimInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str status: + :param str iccid: + :param str rate_plan: + :param str e_id: + :param str sim_registration_code: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SimInstance]: + """ + Asynchronously streams SimInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str status: + :param str iccid: + :param str rate_plan: + :param str e_id: + :param str sim_registration_code: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SimInstance]: + """ + Lists SimInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str status: + :param str iccid: + :param str rate_plan: + :param str e_id: + :param str sim_registration_code: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SimInstance]: + """ + Asynchronously lists SimInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str status: + :param str iccid: + :param str rate_plan: + :param str e_id: + :param str sim_registration_code: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SimPage: + """ + Retrieve a single page of SimInstance records from the API. + Request is executed immediately + + :param status: + :param iccid: + :param rate_plan: + :param e_id: + :param sim_registration_code: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SimInstance + """ + data = values.of( + { + "Status": status, + "Iccid": iccid, + "RatePlan": rate_plan, + "EId": e_id, + "SimRegistrationCode": sim_registration_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SimPage(self._version, response) + + async def page_async( + self, + status: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SimPage: + """ + Asynchronously retrieve a single page of SimInstance records from the API. + Request is executed immediately + + :param status: + :param iccid: + :param rate_plan: + :param e_id: + :param sim_registration_code: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SimInstance + """ + data = values.of( + { + "Status": status, + "Iccid": iccid, + "RatePlan": rate_plan, + "EId": e_id, + "SimRegistrationCode": sim_registration_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SimPage(self._version, response) + + def get_page(self, target_url: str) -> SimPage: + """ + Retrieve a specific page of SimInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SimInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SimPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SimPage: + """ + Asynchronously retrieve a specific page of SimInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SimInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SimPage(self._version, response) + + def get(self, sid: str) -> SimContext: + """ + Constructs a SimContext + + :param sid: + """ + return SimContext(self._version, sid=sid) + + def __call__(self, sid: str) -> SimContext: + """ + Constructs a SimContext + + :param sid: + """ + return SimContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/preview/wireless/sim/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview/wireless/sim/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..9cea5ccc Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview/wireless/sim/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview/wireless/sim/__pycache__/usage.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview/wireless/sim/__pycache__/usage.cpython-312.pyc new file mode 100644 index 00000000..558b006e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview/wireless/sim/__pycache__/usage.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview/wireless/sim/usage.py b/venv/Lib/site-packages/twilio/rest/preview/wireless/sim/usage.py new file mode 100644 index 00000000..aff3731b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview/wireless/sim/usage.py @@ -0,0 +1,249 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class UsageInstance(InstanceResource): + """ + :ivar sim_sid: + :ivar sim_unique_name: + :ivar account_sid: + :ivar period: + :ivar commands_usage: + :ivar commands_costs: + :ivar data_usage: + :ivar data_costs: + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], sim_sid: str): + super().__init__(version) + + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.sim_unique_name: Optional[str] = payload.get("sim_unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.period: Optional[Dict[str, object]] = payload.get("period") + self.commands_usage: Optional[Dict[str, object]] = payload.get("commands_usage") + self.commands_costs: Optional[Dict[str, object]] = payload.get("commands_costs") + self.data_usage: Optional[Dict[str, object]] = payload.get("data_usage") + self.data_costs: Optional[Dict[str, object]] = payload.get("data_costs") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sim_sid": sim_sid, + } + self._context: Optional[UsageContext] = None + + @property + def _proxy(self) -> "UsageContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UsageContext for this UsageInstance + """ + if self._context is None: + self._context = UsageContext( + self._version, + sim_sid=self._solution["sim_sid"], + ) + return self._context + + def fetch( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> "UsageInstance": + """ + Fetch the UsageInstance + + :param end: + :param start: + + :returns: The fetched UsageInstance + """ + return self._proxy.fetch( + end=end, + start=start, + ) + + async def fetch_async( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> "UsageInstance": + """ + Asynchronous coroutine to fetch the UsageInstance + + :param end: + :param start: + + :returns: The fetched UsageInstance + """ + return await self._proxy.fetch_async( + end=end, + start=start, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UsageContext(InstanceContext): + + def __init__(self, version: Version, sim_sid: str): + """ + Initialize the UsageContext + + :param version: Version that contains the resource + :param sim_sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sim_sid": sim_sid, + } + self._uri = "/Sims/{sim_sid}/Usage".format(**self._solution) + + def fetch( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> UsageInstance: + """ + Fetch the UsageInstance + + :param end: + :param start: + + :returns: The fetched UsageInstance + """ + + data = values.of( + { + "End": end, + "Start": start, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return UsageInstance( + self._version, + payload, + sim_sid=self._solution["sim_sid"], + ) + + async def fetch_async( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> UsageInstance: + """ + Asynchronous coroutine to fetch the UsageInstance + + :param end: + :param start: + + :returns: The fetched UsageInstance + """ + + data = values.of( + { + "End": end, + "Start": start, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return UsageInstance( + self._version, + payload, + sim_sid=self._solution["sim_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UsageList(ListResource): + + def __init__(self, version: Version, sim_sid: str): + """ + Initialize the UsageList + + :param version: Version that contains the resource + :param sim_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sim_sid": sim_sid, + } + + def get(self) -> UsageContext: + """ + Constructs a UsageContext + + """ + return UsageContext(self._version, sim_sid=self._solution["sim_sid"]) + + def __call__(self) -> UsageContext: + """ + Constructs a UsageContext + + """ + return UsageContext(self._version, sim_sid=self._solution["sim_sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/preview_iam/PreviewIamBase.py b/venv/Lib/site-packages/twilio/rest/preview_iam/PreviewIamBase.py new file mode 100644 index 00000000..22fcbe70 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview_iam/PreviewIamBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.preview_iam.v1 import V1 + + +class PreviewIamBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the PreviewIam Domain + + :returns: Domain for PreviewIam + """ + super().__init__(twilio, "https://preview-iam.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of PreviewIam + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/preview_iam/__init__.py b/venv/Lib/site-packages/twilio/rest/preview_iam/__init__.py new file mode 100644 index 00000000..9a5bf85b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview_iam/__init__.py @@ -0,0 +1,26 @@ +from twilio.rest.preview_iam.PreviewIamBase import PreviewIamBase + +from twilio.rest.preview_iam.v1.authorize import ( + AuthorizeList, +) +from twilio.rest.preview_iam.v1.token import ( + TokenList, +) +from twilio.rest.preview_iam.versionless.organization import ( + OrganizationList, +) +from twilio.rest.preview_iam.versionless import Versionless + + +class PreviewIam(PreviewIamBase): + @property + def organization(self) -> OrganizationList: + return Versionless(self).organization + + @property + def authorize(self) -> AuthorizeList: + return self.v1.authorize + + @property + def token(self) -> TokenList: + return self.v1.token diff --git a/venv/Lib/site-packages/twilio/rest/preview_iam/__pycache__/PreviewIamBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview_iam/__pycache__/PreviewIamBase.cpython-312.pyc new file mode 100644 index 00000000..c96e8d29 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview_iam/__pycache__/PreviewIamBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview_iam/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview_iam/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..f0019344 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview_iam/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview_iam/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/preview_iam/v1/__init__.py new file mode 100644 index 00000000..22432777 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview_iam/v1/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.preview_iam.v1.authorize import AuthorizeList +from twilio.rest.preview_iam.v1.token import TokenList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of PreviewIam + + :param domain: The Twilio.preview_iam domain + """ + super().__init__(domain, "v1") + self._authorize: Optional[AuthorizeList] = None + self._token: Optional[TokenList] = None + + @property + def authorize(self) -> AuthorizeList: + if self._authorize is None: + self._authorize = AuthorizeList(self) + return self._authorize + + @property + def token(self) -> TokenList: + if self._token is None: + self._token = TokenList(self) + return self._token + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/preview_iam/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview_iam/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..45b1fa9f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview_iam/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview_iam/v1/__pycache__/authorize.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview_iam/v1/__pycache__/authorize.cpython-312.pyc new file mode 100644 index 00000000..8365fd3e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview_iam/v1/__pycache__/authorize.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview_iam/v1/__pycache__/token.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview_iam/v1/__pycache__/token.cpython-312.pyc new file mode 100644 index 00000000..aa32f1b9 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview_iam/v1/__pycache__/token.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview_iam/v1/authorize.py b/venv/Lib/site-packages/twilio/rest/preview_iam/v1/authorize.py new file mode 100644 index 00000000..4166b4ae --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview_iam/v1/authorize.py @@ -0,0 +1,130 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class AuthorizeInstance(InstanceResource): + """ + :ivar redirect_to: The callback URL + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.redirect_to: Optional[str] = payload.get("redirect_to") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class AuthorizeList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AuthorizeList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/authorize" + + def fetch( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + ) -> AuthorizeInstance: + """ + Asynchronously fetch the AuthorizeInstance + + :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback + :returns: The fetched AuthorizeInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "response_type": response_type, + "client_id": client_id, + "redirect_uri": redirect_uri, + "scope": scope, + "state": state, + } + ) + + payload = self._version.fetch( + method="GET", uri=self._uri, headers=headers, params=params + ) + + return AuthorizeInstance(self._version, payload) + + async def fetch_async( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + ) -> AuthorizeInstance: + """ + Asynchronously fetch the AuthorizeInstance + + :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback + :returns: The fetched AuthorizeInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "response_type": response_type, + "client_id": client_id, + "redirect_uri": redirect_uri, + "scope": scope, + "state": state, + } + ) + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers, params=params + ) + + return AuthorizeInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/preview_iam/v1/token.py b/venv/Lib/site-packages/twilio/rest/preview_iam/v1/token.py new file mode 100644 index 00000000..34d9f300 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview_iam/v1/token.py @@ -0,0 +1,170 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TokenInstance(InstanceResource): + """ + :ivar access_token: Token which carries the necessary information to access a Twilio resource directly. + :ivar refresh_token: Token which carries the information necessary to get a new access token. + :ivar id_token: Token which carries the information necessary of user profile. + :ivar token_type: Token type + :ivar expires_in: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.access_token: Optional[str] = payload.get("access_token") + self.refresh_token: Optional[str] = payload.get("refresh_token") + self.id_token: Optional[str] = payload.get("id_token") + self.token_type: Optional[str] = payload.get("token_type") + self.expires_in: Optional[int] = payload.get("expires_in") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class TokenList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TokenList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/token" + + def create( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> TokenInstance: + """ + Create the TokenInstance + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: The created TokenInstance + """ + + data = values.of( + { + "grant_type": grant_type, + "client_id": client_id, + "client_secret": client_secret, + "code": code, + "redirect_uri": redirect_uri, + "audience": audience, + "refresh_token": refresh_token, + "scope": scope, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TokenInstance(self._version, payload) + + async def create_async( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> TokenInstance: + """ + Asynchronously create the TokenInstance + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: The created TokenInstance + """ + + data = values.of( + { + "grant_type": grant_type, + "client_id": client_id, + "client_secret": client_secret, + "code": code, + "redirect_uri": redirect_uri, + "audience": audience, + "refresh_token": refresh_token, + "scope": scope, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TokenInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/__init__.py b/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/__init__.py new file mode 100644 index 00000000..7d6d210f --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.preview_iam.versionless.organization import OrganizationList + + +class Versionless(Version): + + def __init__(self, domain: Domain): + """ + Initialize the Versionless version of PreviewIam + + :param domain: The Twilio.preview_iam domain + """ + super().__init__(domain, "Organizations") + self._organization: Optional[OrganizationList] = None + + @property + def organization(self) -> OrganizationList: + if self._organization is None: + self._organization = OrganizationList(self) + return self._organization + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..b3769421 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/organization/__init__.py b/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/organization/__init__.py new file mode 100644 index 00000000..ce6e70e9 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/organization/__init__.py @@ -0,0 +1,128 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.instance_context import InstanceContext + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.preview_iam.versionless.organization.account import AccountList +from twilio.rest.preview_iam.versionless.organization.role_assignment import ( + RoleAssignmentList, +) +from twilio.rest.preview_iam.versionless.organization.user import UserList + + +class OrganizationContext(InstanceContext): + + def __init__(self, version: Version, organization_sid: str): + """ + Initialize the OrganizationContext + + :param version: Version that contains the resource + :param organization_sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + } + self._uri = "/{organization_sid}".format(**self._solution) + + self._accounts: Optional[AccountList] = None + self._role_assignments: Optional[RoleAssignmentList] = None + self._users: Optional[UserList] = None + + @property + def accounts(self) -> AccountList: + """ + Access the accounts + """ + if self._accounts is None: + self._accounts = AccountList( + self._version, + self._solution["organization_sid"], + ) + return self._accounts + + @property + def role_assignments(self) -> RoleAssignmentList: + """ + Access the role_assignments + """ + if self._role_assignments is None: + self._role_assignments = RoleAssignmentList( + self._version, + self._solution["organization_sid"], + ) + return self._role_assignments + + @property + def users(self) -> UserList: + """ + Access the users + """ + if self._users is None: + self._users = UserList( + self._version, + self._solution["organization_sid"], + ) + return self._users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OrganizationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OrganizationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, organization_sid: str) -> OrganizationContext: + """ + Constructs a OrganizationContext + + :param organization_sid: + """ + return OrganizationContext(self._version, organization_sid=organization_sid) + + def __call__(self, organization_sid: str) -> OrganizationContext: + """ + Constructs a OrganizationContext + + :param organization_sid: + """ + return OrganizationContext(self._version, organization_sid=organization_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/organization/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/organization/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..3f7c5cb5 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/organization/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/organization/__pycache__/account.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/organization/__pycache__/account.cpython-312.pyc new file mode 100644 index 00000000..dfa0858d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/organization/__pycache__/account.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/organization/__pycache__/role_assignment.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/organization/__pycache__/role_assignment.cpython-312.pyc new file mode 100644 index 00000000..173b486b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/organization/__pycache__/role_assignment.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/organization/__pycache__/user.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/organization/__pycache__/user.cpython-312.pyc new file mode 100644 index 00000000..6716535a Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/organization/__pycache__/user.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/organization/account.py b/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/organization/account.py new file mode 100644 index 00000000..f1c80198 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/organization/account.py @@ -0,0 +1,438 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AccountInstance(InstanceResource): + """ + :ivar account_sid: Twilio account sid + :ivar friendly_name: Account friendly name + :ivar status: Account status + :ivar owner_sid: Twilio account sid + :ivar date_created: The date and time when the account was created in the system + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + organization_sid: str, + account_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional[str] = payload.get("status") + self.owner_sid: Optional[str] = payload.get("owner_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + + self._solution = { + "organization_sid": organization_sid, + "account_sid": account_sid or self.account_sid, + } + self._context: Optional[AccountContext] = None + + @property + def _proxy(self) -> "AccountContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AccountContext for this AccountInstance + """ + if self._context is None: + self._context = AccountContext( + self._version, + organization_sid=self._solution["organization_sid"], + account_sid=self._solution["account_sid"], + ) + return self._context + + def fetch(self) -> "AccountInstance": + """ + Fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AccountInstance": + """ + Asynchronous coroutine to fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AccountContext(InstanceContext): + + def __init__(self, version: Version, organization_sid: str, account_sid: str): + """ + Initialize the AccountContext + + :param version: Version that contains the resource + :param organization_sid: + :param account_sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + "account_sid": account_sid, + } + self._uri = "/{organization_sid}/Accounts/{account_sid}".format( + **self._solution + ) + + def fetch(self) -> AccountInstance: + """ + Fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AccountInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + account_sid=self._solution["account_sid"], + ) + + async def fetch_async(self) -> AccountInstance: + """ + Asynchronous coroutine to fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AccountInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + account_sid=self._solution["account_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AccountPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AccountInstance: + """ + Build an instance of AccountInstance + + :param payload: Payload response from the API + """ + return AccountInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AccountList(ListResource): + + def __init__(self, version: Version, organization_sid: str): + """ + Initialize the AccountList + + :param version: Version that contains the resource + :param organization_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + } + self._uri = "/{organization_sid}/Accounts".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AccountInstance]: + """ + Streams AccountInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AccountInstance]: + """ + Asynchronously streams AccountInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AccountInstance]: + """ + Lists AccountInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AccountInstance]: + """ + Asynchronously lists AccountInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AccountPage: + """ + Retrieve a single page of AccountInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AccountInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AccountPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AccountPage: + """ + Asynchronously retrieve a single page of AccountInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AccountInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AccountPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AccountPage: + """ + Retrieve a specific page of AccountInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AccountInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AccountPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AccountPage: + """ + Asynchronously retrieve a specific page of AccountInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AccountInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AccountPage(self._version, response, self._solution) + + def get(self, account_sid: str) -> AccountContext: + """ + Constructs a AccountContext + + :param account_sid: + """ + return AccountContext( + self._version, + organization_sid=self._solution["organization_sid"], + account_sid=account_sid, + ) + + def __call__(self, account_sid: str) -> AccountContext: + """ + Constructs a AccountContext + + :param account_sid: + """ + return AccountContext( + self._version, + organization_sid=self._solution["organization_sid"], + account_sid=account_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/organization/role_assignment.py b/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/organization/role_assignment.py new file mode 100644 index 00000000..9d356f2c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/organization/role_assignment.py @@ -0,0 +1,574 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RoleAssignmentInstance(InstanceResource): + + class PublicApiCreateRoleAssignmentRequest(object): + """ + :ivar role_sid: Twilio Role Sid representing assigned role + :ivar scope: Twilio Sid representing scope of this assignment + :ivar identity: Twilio Sid representing identity of this assignment + """ + + def __init__(self, payload: Dict[str, Any]): + + self.role_sid: Optional[str] = payload.get("role_sid") + self.scope: Optional[str] = payload.get("scope") + self.identity: Optional[str] = payload.get("identity") + + def to_dict(self): + return { + "role_sid": self.role_sid, + "scope": self.scope, + "identity": self.identity, + } + + """ + :ivar sid: Twilio Role Assignment Sid representing this role assignment + :ivar role_sid: Twilio Role Sid representing assigned role + :ivar scope: Twilio Sid representing identity of this assignment + :ivar identity: Twilio Sid representing scope of this assignment + :ivar code: Twilio-specific error code + :ivar message: Error message + :ivar more_info: Link to Error Code References + :ivar status: HTTP response status code + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + organization_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.role_sid: Optional[str] = payload.get("role_sid") + self.scope: Optional[str] = payload.get("scope") + self.identity: Optional[str] = payload.get("identity") + self.code: Optional[int] = payload.get("code") + self.message: Optional[str] = payload.get("message") + self.more_info: Optional[str] = payload.get("moreInfo") + self.status: Optional[int] = payload.get("status") + + self._solution = { + "organization_sid": organization_sid, + "sid": sid or self.sid, + } + self._context: Optional[RoleAssignmentContext] = None + + @property + def _proxy(self) -> "RoleAssignmentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RoleAssignmentContext for this RoleAssignmentInstance + """ + if self._context is None: + self._context = RoleAssignmentContext( + self._version, + organization_sid=self._solution["organization_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RoleAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class RoleAssignmentContext(InstanceContext): + + class PublicApiCreateRoleAssignmentRequest(object): + """ + :ivar role_sid: Twilio Role Sid representing assigned role + :ivar scope: Twilio Sid representing scope of this assignment + :ivar identity: Twilio Sid representing identity of this assignment + """ + + def __init__(self, payload: Dict[str, Any]): + + self.role_sid: Optional[str] = payload.get("role_sid") + self.scope: Optional[str] = payload.get("scope") + self.identity: Optional[str] = payload.get("identity") + + def to_dict(self): + return { + "role_sid": self.role_sid, + "scope": self.scope, + "identity": self.identity, + } + + def __init__(self, version: Version, organization_sid: str, sid: str): + """ + Initialize the RoleAssignmentContext + + :param version: Version that contains the resource + :param organization_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + "sid": sid, + } + self._uri = "/{organization_sid}/RoleAssignments/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the RoleAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class RoleAssignmentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RoleAssignmentInstance: + """ + Build an instance of RoleAssignmentInstance + + :param payload: Payload response from the API + """ + return RoleAssignmentInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RoleAssignmentList(ListResource): + + class PublicApiCreateRoleAssignmentRequest(object): + """ + :ivar role_sid: Twilio Role Sid representing assigned role + :ivar scope: Twilio Sid representing scope of this assignment + :ivar identity: Twilio Sid representing identity of this assignment + """ + + def __init__(self, payload: Dict[str, Any]): + + self.role_sid: Optional[str] = payload.get("role_sid") + self.scope: Optional[str] = payload.get("scope") + self.identity: Optional[str] = payload.get("identity") + + def to_dict(self): + return { + "role_sid": self.role_sid, + "scope": self.scope, + "identity": self.identity, + } + + def __init__(self, version: Version, organization_sid: str): + """ + Initialize the RoleAssignmentList + + :param version: Version that contains the resource + :param organization_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + } + self._uri = "/{organization_sid}/RoleAssignments".format(**self._solution) + + def create( + self, + public_api_create_role_assignment_request: PublicApiCreateRoleAssignmentRequest, + ) -> RoleAssignmentInstance: + """ + Create the RoleAssignmentInstance + + :param public_api_create_role_assignment_request: + + :returns: The created RoleAssignmentInstance + """ + data = public_api_create_role_assignment_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleAssignmentInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + async def create_async( + self, + public_api_create_role_assignment_request: PublicApiCreateRoleAssignmentRequest, + ) -> RoleAssignmentInstance: + """ + Asynchronously create the RoleAssignmentInstance + + :param public_api_create_role_assignment_request: + + :returns: The created RoleAssignmentInstance + """ + data = public_api_create_role_assignment_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleAssignmentInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + def stream( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoleAssignmentInstance]: + """ + Streams RoleAssignmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str identity: + :param str scope: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, scope=scope, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RoleAssignmentInstance]: + """ + Asynchronously streams RoleAssignmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str identity: + :param str scope: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + identity=identity, scope=scope, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleAssignmentInstance]: + """ + Lists RoleAssignmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str identity: + :param str scope: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + identity=identity, + scope=scope, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleAssignmentInstance]: + """ + Asynchronously lists RoleAssignmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str identity: + :param str scope: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + identity=identity, + scope=scope, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RoleAssignmentPage: + """ + Retrieve a single page of RoleAssignmentInstance records from the API. + Request is executed immediately + + :param identity: + :param scope: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleAssignmentInstance + """ + data = values.of( + { + "Identity": identity, + "Scope": scope, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RoleAssignmentPage(self._version, response, self._solution) + + async def page_async( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RoleAssignmentPage: + """ + Asynchronously retrieve a single page of RoleAssignmentInstance records from the API. + Request is executed immediately + + :param identity: + :param scope: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleAssignmentInstance + """ + data = values.of( + { + "Identity": identity, + "Scope": scope, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RoleAssignmentPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RoleAssignmentPage: + """ + Retrieve a specific page of RoleAssignmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleAssignmentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RoleAssignmentPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RoleAssignmentPage: + """ + Asynchronously retrieve a specific page of RoleAssignmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleAssignmentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RoleAssignmentPage(self._version, response, self._solution) + + def get(self, sid: str) -> RoleAssignmentContext: + """ + Constructs a RoleAssignmentContext + + :param sid: + """ + return RoleAssignmentContext( + self._version, organization_sid=self._solution["organization_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RoleAssignmentContext: + """ + Constructs a RoleAssignmentContext + + :param sid: + """ + return RoleAssignmentContext( + self._version, organization_sid=self._solution["organization_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/organization/user.py b/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/organization/user.py new file mode 100644 index 00000000..166f76b4 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/preview_iam/versionless/organization/user.py @@ -0,0 +1,1050 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UserInstance(InstanceResource): + + class ScimEmailAddress(object): + """ + :ivar primary: Indicates if this email address is the primary one + :ivar value: The actual email address value + :ivar type: The type of email address (e.g., work, home, etc.) + """ + + def __init__(self, payload: Dict[str, Any]): + + self.primary: Optional[bool] = payload.get("primary") + self.value: Optional[str] = payload.get("value") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "primary": self.primary, + "value": self.value, + "type": self.type, + } + + class ScimMeta(object): + """ + :ivar resource_type: Indicates the type of the resource + :ivar created: The date and time when the resource was created in the system + :ivar last_modified: The date and time when the resource was last modified + :ivar version: A version identifier for the resource. This can be used to manage resource versioning and concurrency control. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.resource_type: Optional[str] = payload.get("resource_type") + self.created: Optional[datetime] = payload.get("created") + self.last_modified: Optional[datetime] = payload.get("last_modified") + self.version: Optional[str] = payload.get("version") + + def to_dict(self): + return { + "resource_type": self.resource_type, + "created": self.created, + "last_modified": self.last_modified, + "version": self.version, + } + + class ScimName(object): + """ + :ivar given_name: The user's first or given name + :ivar family_name: The user's last or family name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.given_name: Optional[str] = payload.get("given_name") + self.family_name: Optional[str] = payload.get("family_name") + + def to_dict(self): + return { + "given_name": self.given_name, + "family_name": self.family_name, + } + + class ScimUser(object): + """ + :ivar id: Unique Twilio user sid + :ivar external_id: External unique resource id defined by provisioning client + :ivar user_name: Unique username, MUST be same as primary email address + :ivar display_name: User friendly display name + :ivar name: + :ivar emails: Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + :ivar active: Indicates whether the user is active + :ivar locale: User's locale + :ivar timezone: User's time zone + :ivar schemas: An array of URIs that indicate the schemas supported for this user resource + :ivar meta: + :ivar detail: A human-readable description of the error + :ivar scim_type: A scimType error code as defined in RFC7644 + :ivar status: Http status code + :ivar code: Twilio-specific error code + :ivar more_info: Link to Error Code References + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.external_id: Optional[str] = payload.get("external_id") + self.user_name: Optional[str] = payload.get("user_name") + self.display_name: Optional[str] = payload.get("display_name") + self.name: Optional[UserList.ScimName] = payload.get("name") + self.emails: Optional[List[UserList.ScimEmailAddress]] = payload.get( + "emails" + ) + self.active: Optional[bool] = payload.get("active") + self.locale: Optional[str] = payload.get("locale") + self.timezone: Optional[str] = payload.get("timezone") + self.schemas: Optional[List[str]] = payload.get("schemas") + self.meta: Optional[UserList.ScimMeta] = payload.get("meta") + self.detail: Optional[str] = payload.get("detail") + self.scim_type: Optional[str] = payload.get("scim_type") + self.status: Optional[str] = payload.get("status") + self.code: Optional[int] = payload.get("code") + self.more_info: Optional[str] = payload.get("more_info") + + def to_dict(self): + return { + "id": self.id, + "externalId": self.external_id, + "userName": self.user_name, + "displayName": self.display_name, + "name": self.name.to_dict() if self.name is not None else None, + "emails": ( + [emails.to_dict() for emails in self.emails] + if self.emails is not None + else None + ), + "active": self.active, + "locale": self.locale, + "timezone": self.timezone, + "schemas": self.schemas, + "meta": self.meta.to_dict() if self.meta is not None else None, + "detail": self.detail, + "scimType": self.scim_type, + "status": self.status, + "code": self.code, + "moreInfo": self.more_info, + } + + """ + :ivar id: Unique Twilio user sid + :ivar external_id: External unique resource id defined by provisioning client + :ivar user_name: Unique username, MUST be same as primary email address + :ivar display_name: User friendly display name + :ivar name: + :ivar emails: Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + :ivar active: Indicates whether the user is active + :ivar locale: User's locale + :ivar timezone: User's time zone + :ivar schemas: An array of URIs that indicate the schemas supported for this user resource + :ivar meta: + :ivar detail: A human-readable description of the error + :ivar scim_type: A scimType error code as defined in RFC7644 + :ivar status: Http status code + :ivar code: Twilio-specific error code + :ivar more_info: Link to Error Code References + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + organization_sid: str, + id: Optional[str] = None, + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.external_id: Optional[str] = payload.get("externalId") + self.user_name: Optional[str] = payload.get("userName") + self.display_name: Optional[str] = payload.get("displayName") + self.name: Optional[UserList.str] = payload.get("name") + self.emails: Optional[List[UserList.str]] = payload.get("emails") + self.active: Optional[bool] = payload.get("active") + self.locale: Optional[str] = payload.get("locale") + self.timezone: Optional[str] = payload.get("timezone") + self.schemas: Optional[List[str]] = payload.get("schemas") + self.meta: Optional[UserList.str] = payload.get("meta") + self.detail: Optional[str] = payload.get("detail") + self.scim_type: Optional[str] = payload.get("scimType") + self.status: Optional[str] = payload.get("status") + self.code: Optional[int] = payload.get("code") + self.more_info: Optional[str] = payload.get("moreInfo") + + self._solution = { + "organization_sid": organization_sid, + "id": id or self.id, + } + self._context: Optional[UserContext] = None + + @property + def _proxy(self) -> "UserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserContext for this UserInstance + """ + if self._context is None: + self._context = UserContext( + self._version, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "UserInstance": + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserInstance": + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return await self._proxy.fetch_async() + + def update( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> "UserInstance": + """ + Update the UserInstance + + :param scim_user: + :param if_match: + + :returns: The updated UserInstance + """ + return self._proxy.update( + scim_user=scim_user, + if_match=if_match, + ) + + async def update_async( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> "UserInstance": + """ + Asynchronous coroutine to update the UserInstance + + :param scim_user: + :param if_match: + + :returns: The updated UserInstance + """ + return await self._proxy.update_async( + scim_user=scim_user, + if_match=if_match, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserContext(InstanceContext): + + class ScimEmailAddress(object): + """ + :ivar primary: Indicates if this email address is the primary one + :ivar value: The actual email address value + :ivar type: The type of email address (e.g., work, home, etc.) + """ + + def __init__(self, payload: Dict[str, Any]): + + self.primary: Optional[bool] = payload.get("primary") + self.value: Optional[str] = payload.get("value") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "primary": self.primary, + "value": self.value, + "type": self.type, + } + + class ScimMeta(object): + """ + :ivar resource_type: Indicates the type of the resource + :ivar created: The date and time when the resource was created in the system + :ivar last_modified: The date and time when the resource was last modified + :ivar version: A version identifier for the resource. This can be used to manage resource versioning and concurrency control. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.resource_type: Optional[str] = payload.get("resource_type") + self.created: Optional[datetime] = payload.get("created") + self.last_modified: Optional[datetime] = payload.get("last_modified") + self.version: Optional[str] = payload.get("version") + + def to_dict(self): + return { + "resource_type": self.resource_type, + "created": self.created, + "last_modified": self.last_modified, + "version": self.version, + } + + class ScimName(object): + """ + :ivar given_name: The user's first or given name + :ivar family_name: The user's last or family name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.given_name: Optional[str] = payload.get("given_name") + self.family_name: Optional[str] = payload.get("family_name") + + def to_dict(self): + return { + "given_name": self.given_name, + "family_name": self.family_name, + } + + class ScimUser(object): + """ + :ivar id: Unique Twilio user sid + :ivar external_id: External unique resource id defined by provisioning client + :ivar user_name: Unique username, MUST be same as primary email address + :ivar display_name: User friendly display name + :ivar name: + :ivar emails: Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + :ivar active: Indicates whether the user is active + :ivar locale: User's locale + :ivar timezone: User's time zone + :ivar schemas: An array of URIs that indicate the schemas supported for this user resource + :ivar meta: + :ivar detail: A human-readable description of the error + :ivar scim_type: A scimType error code as defined in RFC7644 + :ivar status: Http status code + :ivar code: Twilio-specific error code + :ivar more_info: Link to Error Code References + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.external_id: Optional[str] = payload.get("external_id") + self.user_name: Optional[str] = payload.get("user_name") + self.display_name: Optional[str] = payload.get("display_name") + self.name: Optional[UserList.ScimName] = payload.get("name") + self.emails: Optional[List[UserList.ScimEmailAddress]] = payload.get( + "emails" + ) + self.active: Optional[bool] = payload.get("active") + self.locale: Optional[str] = payload.get("locale") + self.timezone: Optional[str] = payload.get("timezone") + self.schemas: Optional[List[str]] = payload.get("schemas") + self.meta: Optional[UserList.ScimMeta] = payload.get("meta") + self.detail: Optional[str] = payload.get("detail") + self.scim_type: Optional[str] = payload.get("scim_type") + self.status: Optional[str] = payload.get("status") + self.code: Optional[int] = payload.get("code") + self.more_info: Optional[str] = payload.get("more_info") + + def to_dict(self): + return { + "id": self.id, + "externalId": self.external_id, + "userName": self.user_name, + "displayName": self.display_name, + "name": self.name.to_dict() if self.name is not None else None, + "emails": ( + [emails.to_dict() for emails in self.emails] + if self.emails is not None + else None + ), + "active": self.active, + "locale": self.locale, + "timezone": self.timezone, + "schemas": self.schemas, + "meta": self.meta.to_dict() if self.meta is not None else None, + "detail": self.detail, + "scimType": self.scim_type, + "status": self.status, + "code": self.code, + "moreInfo": self.more_info, + } + + def __init__(self, version: Version, organization_sid: str, id: str): + """ + Initialize the UserContext + + :param version: Version that contains the resource + :param organization_sid: + :param id: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + "id": id, + } + self._uri = "/{organization_sid}/scim/Users/{id}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + + def update( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> UserInstance: + """ + Update the UserInstance + + :param scim_user: + :param if_match: + + :returns: The updated UserInstance + """ + data = scim_user.to_dict() + + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/json" + + headers["Content-Type"] = "application/scim+json" + + headers["Accept"] = "application/scim+json" + + payload = self._version.update( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + + async def update_async( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param scim_user: + :param if_match: + + :returns: The updated UserInstance + """ + data = scim_user.to_dict() + + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/json" + + headers["Content-Type"] = "application/scim+json" + + headers["Accept"] = "application/scim+json" + + payload = await self._version.update_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: + """ + Build an instance of UserInstance + + :param payload: Payload response from the API + """ + return UserInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class UserList(ListResource): + + class ScimEmailAddress(object): + """ + :ivar primary: Indicates if this email address is the primary one + :ivar value: The actual email address value + :ivar type: The type of email address (e.g., work, home, etc.) + """ + + def __init__(self, payload: Dict[str, Any]): + + self.primary: Optional[bool] = payload.get("primary") + self.value: Optional[str] = payload.get("value") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "primary": self.primary, + "value": self.value, + "type": self.type, + } + + class ScimMeta(object): + """ + :ivar resource_type: Indicates the type of the resource + :ivar created: The date and time when the resource was created in the system + :ivar last_modified: The date and time when the resource was last modified + :ivar version: A version identifier for the resource. This can be used to manage resource versioning and concurrency control. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.resource_type: Optional[str] = payload.get("resource_type") + self.created: Optional[datetime] = payload.get("created") + self.last_modified: Optional[datetime] = payload.get("last_modified") + self.version: Optional[str] = payload.get("version") + + def to_dict(self): + return { + "resource_type": self.resource_type, + "created": self.created, + "last_modified": self.last_modified, + "version": self.version, + } + + class ScimName(object): + """ + :ivar given_name: The user's first or given name + :ivar family_name: The user's last or family name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.given_name: Optional[str] = payload.get("given_name") + self.family_name: Optional[str] = payload.get("family_name") + + def to_dict(self): + return { + "given_name": self.given_name, + "family_name": self.family_name, + } + + class ScimUser(object): + """ + :ivar id: Unique Twilio user sid + :ivar external_id: External unique resource id defined by provisioning client + :ivar user_name: Unique username, MUST be same as primary email address + :ivar display_name: User friendly display name + :ivar name: + :ivar emails: Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + :ivar active: Indicates whether the user is active + :ivar locale: User's locale + :ivar timezone: User's time zone + :ivar schemas: An array of URIs that indicate the schemas supported for this user resource + :ivar meta: + :ivar detail: A human-readable description of the error + :ivar scim_type: A scimType error code as defined in RFC7644 + :ivar status: Http status code + :ivar code: Twilio-specific error code + :ivar more_info: Link to Error Code References + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.external_id: Optional[str] = payload.get("external_id") + self.user_name: Optional[str] = payload.get("user_name") + self.display_name: Optional[str] = payload.get("display_name") + self.name: Optional[UserList.ScimName] = payload.get("name") + self.emails: Optional[List[UserList.ScimEmailAddress]] = payload.get( + "emails" + ) + self.active: Optional[bool] = payload.get("active") + self.locale: Optional[str] = payload.get("locale") + self.timezone: Optional[str] = payload.get("timezone") + self.schemas: Optional[List[str]] = payload.get("schemas") + self.meta: Optional[UserList.ScimMeta] = payload.get("meta") + self.detail: Optional[str] = payload.get("detail") + self.scim_type: Optional[str] = payload.get("scim_type") + self.status: Optional[str] = payload.get("status") + self.code: Optional[int] = payload.get("code") + self.more_info: Optional[str] = payload.get("more_info") + + def to_dict(self): + return { + "id": self.id, + "externalId": self.external_id, + "userName": self.user_name, + "displayName": self.display_name, + "name": self.name.to_dict() if self.name is not None else None, + "emails": ( + [emails.to_dict() for emails in self.emails] + if self.emails is not None + else None + ), + "active": self.active, + "locale": self.locale, + "timezone": self.timezone, + "schemas": self.schemas, + "meta": self.meta.to_dict() if self.meta is not None else None, + "detail": self.detail, + "scimType": self.scim_type, + "status": self.status, + "code": self.code, + "moreInfo": self.more_info, + } + + def __init__(self, version: Version, organization_sid: str): + """ + Initialize the UserList + + :param version: Version that contains the resource + :param organization_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + } + self._uri = "/{organization_sid}/scim/Users".format(**self._solution) + + def create(self, scim_user: ScimUser) -> UserInstance: + """ + Create the UserInstance + + :param scim_user: + + :returns: The created UserInstance + """ + data = scim_user.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Content-Type"] = "application/scim+json" + + headers["Accept"] = "application/scim+json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + async def create_async(self, scim_user: ScimUser) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param scim_user: + + :returns: The created UserInstance + """ + data = scim_user.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Content-Type"] = "application/scim+json" + + headers["Accept"] = "application/scim+json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + def stream( + self, + filter: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserInstance]: + """ + Streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str filter: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(filter=filter, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + filter: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserInstance]: + """ + Asynchronously streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str filter: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(filter=filter, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + filter: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str filter: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + filter=filter, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + filter: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Asynchronously lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str filter: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + filter=filter, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + filter: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param filter: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "filter": filter, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/scim+json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + async def page_async( + self, + filter: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Asynchronously retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param filter: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "filter": filter, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/scim+json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserPage: + """ + Retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserPage: + """ + Asynchronously retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserPage(self._version, response, self._solution) + + def get(self, id: str) -> UserContext: + """ + Constructs a UserContext + + :param id: + """ + return UserContext( + self._version, organization_sid=self._solution["organization_sid"], id=id + ) + + def __call__(self, id: str) -> UserContext: + """ + Constructs a UserContext + + :param id: + """ + return UserContext( + self._version, organization_sid=self._solution["organization_sid"], id=id + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/pricing/PricingBase.py b/venv/Lib/site-packages/twilio/rest/pricing/PricingBase.py new file mode 100644 index 00000000..cf624e18 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/pricing/PricingBase.py @@ -0,0 +1,55 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.pricing.v1 import V1 +from twilio.rest.pricing.v2 import V2 + + +class PricingBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Pricing Domain + + :returns: Domain for Pricing + """ + super().__init__(twilio, "https://pricing.twilio.com") + self._v1: Optional[V1] = None + self._v2: Optional[V2] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Pricing + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Pricing + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/pricing/__init__.py b/venv/Lib/site-packages/twilio/rest/pricing/__init__.py new file mode 100644 index 00000000..91da8751 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/pricing/__init__.py @@ -0,0 +1,55 @@ +from warnings import warn + +from twilio.rest.pricing.PricingBase import PricingBase +from twilio.rest.pricing.v1.messaging import MessagingList +from twilio.rest.pricing.v1.phone_number import PhoneNumberList +from twilio.rest.pricing.v2.country import CountryList +from twilio.rest.pricing.v2.number import NumberList +from twilio.rest.pricing.v2.voice import VoiceList + + +class Pricing(PricingBase): + @property + def messaging(self) -> MessagingList: + warn( + "messaging is deprecated. Use v1.messaging instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.messaging + + @property + def phone_numbers(self) -> PhoneNumberList: + warn( + "phone_numbers is deprecated. Use v1.phone_numbers instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.phone_numbers + + @property + def voice(self) -> VoiceList: + warn( + "voice is deprecated. Use v2.voice instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.voice + + @property + def countries(self) -> CountryList: + warn( + "countries is deprecated. Use v2.countries instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.countries + + @property + def numbers(self) -> NumberList: + warn( + "numbers is deprecated. Use v2.numbers instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.numbers diff --git a/venv/Lib/site-packages/twilio/rest/pricing/__pycache__/PricingBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/pricing/__pycache__/PricingBase.cpython-312.pyc new file mode 100644 index 00000000..e8273227 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/pricing/__pycache__/PricingBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/pricing/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/pricing/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..500a49e5 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/pricing/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/pricing/v1/__init__.py new file mode 100644 index 00000000..ba8b6588 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/pricing/v1/__init__.py @@ -0,0 +1,59 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.pricing.v1.messaging import MessagingList +from twilio.rest.pricing.v1.phone_number import PhoneNumberList +from twilio.rest.pricing.v1.voice import VoiceList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Pricing + + :param domain: The Twilio.pricing domain + """ + super().__init__(domain, "v1") + self._messaging: Optional[MessagingList] = None + self._phone_numbers: Optional[PhoneNumberList] = None + self._voice: Optional[VoiceList] = None + + @property + def messaging(self) -> MessagingList: + if self._messaging is None: + self._messaging = MessagingList(self) + return self._messaging + + @property + def phone_numbers(self) -> PhoneNumberList: + if self._phone_numbers is None: + self._phone_numbers = PhoneNumberList(self) + return self._phone_numbers + + @property + def voice(self) -> VoiceList: + if self._voice is None: + self._voice = VoiceList(self) + return self._voice + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/pricing/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..6986be7d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/pricing/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v1/messaging/__init__.py b/venv/Lib/site-packages/twilio/rest/pricing/v1/messaging/__init__.py new file mode 100644 index 00000000..df5c148b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/pricing/v1/messaging/__init__.py @@ -0,0 +1,54 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.pricing.v1.messaging.country import CountryList + + +class MessagingList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the MessagingList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Messaging" + + self._countries: Optional[CountryList] = None + + @property + def countries(self) -> CountryList: + """ + Access the countries + """ + if self._countries is None: + self._countries = CountryList(self._version) + return self._countries + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v1/messaging/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/pricing/v1/messaging/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..08ff0e70 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/pricing/v1/messaging/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v1/messaging/__pycache__/country.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/pricing/v1/messaging/__pycache__/country.cpython-312.pyc new file mode 100644 index 00000000..c5b84896 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/pricing/v1/messaging/__pycache__/country.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v1/messaging/country.py b/venv/Lib/site-packages/twilio/rest/pricing/v1/messaging/country.py new file mode 100644 index 00000000..49360cd8 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/pricing/v1/messaging/country.py @@ -0,0 +1,415 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CountryInstance(InstanceResource): + """ + :ivar country: The name of the country. + :ivar iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + :ivar outbound_sms_prices: The list of [OutboundSMSPrice](https://www.twilio.com/docs/sms/api/pricing#outbound-sms-price) records that represent the price to send a message for each MCC/MNC applicable in this country. + :ivar inbound_sms_prices: The list of [InboundPrice](https://www.twilio.com/docs/sms/api/pricing#inbound-price) records that describe the price to receive an inbound SMS to the different Twilio phone number types supported in this country + :ivar price_unit: The currency in which prices are measured, specified in [ISO 4127](http://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + iso_country: Optional[str] = None, + ): + super().__init__(version) + + self.country: Optional[str] = payload.get("country") + self.iso_country: Optional[str] = payload.get("iso_country") + self.outbound_sms_prices: Optional[List[str]] = payload.get( + "outbound_sms_prices" + ) + self.inbound_sms_prices: Optional[List[str]] = payload.get("inbound_sms_prices") + self.price_unit: Optional[str] = payload.get("price_unit") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "iso_country": iso_country or self.iso_country, + } + self._context: Optional[CountryContext] = None + + @property + def _proxy(self) -> "CountryContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CountryContext for this CountryInstance + """ + if self._context is None: + self._context = CountryContext( + self._version, + iso_country=self._solution["iso_country"], + ) + return self._context + + def fetch(self) -> "CountryInstance": + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CountryInstance": + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CountryContext(InstanceContext): + + def __init__(self, version: Version, iso_country: str): + """ + Initialize the CountryContext + + :param version: Version that contains the resource + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "iso_country": iso_country, + } + self._uri = "/Messaging/Countries/{iso_country}".format(**self._solution) + + def fetch(self) -> CountryInstance: + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + async def fetch_async(self) -> CountryInstance: + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CountryPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: + """ + Build an instance of CountryInstance + + :param payload: Payload response from the API + """ + return CountryInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CountryList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CountryList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Messaging/Countries" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CountryInstance]: + """ + Streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CountryInstance]: + """ + Asynchronously streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Asynchronously lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Asynchronously retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + def get_page(self, target_url: str) -> CountryPage: + """ + Retrieve a specific page of CountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CountryPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CountryPage: + """ + Asynchronously retrieve a specific page of CountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CountryPage(self._version, response) + + def get(self, iso_country: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) + + def __call__(self, iso_country: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v1/phone_number/__init__.py b/venv/Lib/site-packages/twilio/rest/pricing/v1/phone_number/__init__.py new file mode 100644 index 00000000..429ce9b1 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/pricing/v1/phone_number/__init__.py @@ -0,0 +1,54 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.pricing.v1.phone_number.country import CountryList + + +class PhoneNumberList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PhoneNumberList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/PhoneNumbers" + + self._countries: Optional[CountryList] = None + + @property + def countries(self) -> CountryList: + """ + Access the countries + """ + if self._countries is None: + self._countries = CountryList(self._version) + return self._countries + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v1/phone_number/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/pricing/v1/phone_number/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..964d1476 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/pricing/v1/phone_number/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v1/phone_number/__pycache__/country.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/pricing/v1/phone_number/__pycache__/country.cpython-312.pyc new file mode 100644 index 00000000..b17aaf89 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/pricing/v1/phone_number/__pycache__/country.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v1/phone_number/country.py b/venv/Lib/site-packages/twilio/rest/pricing/v1/phone_number/country.py new file mode 100644 index 00000000..2d11cd1c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/pricing/v1/phone_number/country.py @@ -0,0 +1,413 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CountryInstance(InstanceResource): + """ + :ivar country: The name of the country. + :ivar iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + :ivar phone_number_prices: The list of [PhoneNumberPrice](https://www.twilio.com/docs/phone-numbers/pricing#phone-number-price) records. + :ivar price_unit: The currency in which prices are measured, specified in [ISO 4127](http://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + iso_country: Optional[str] = None, + ): + super().__init__(version) + + self.country: Optional[str] = payload.get("country") + self.iso_country: Optional[str] = payload.get("iso_country") + self.phone_number_prices: Optional[List[str]] = payload.get( + "phone_number_prices" + ) + self.price_unit: Optional[str] = payload.get("price_unit") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "iso_country": iso_country or self.iso_country, + } + self._context: Optional[CountryContext] = None + + @property + def _proxy(self) -> "CountryContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CountryContext for this CountryInstance + """ + if self._context is None: + self._context = CountryContext( + self._version, + iso_country=self._solution["iso_country"], + ) + return self._context + + def fetch(self) -> "CountryInstance": + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CountryInstance": + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CountryContext(InstanceContext): + + def __init__(self, version: Version, iso_country: str): + """ + Initialize the CountryContext + + :param version: Version that contains the resource + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "iso_country": iso_country, + } + self._uri = "/PhoneNumbers/Countries/{iso_country}".format(**self._solution) + + def fetch(self) -> CountryInstance: + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + async def fetch_async(self) -> CountryInstance: + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CountryPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: + """ + Build an instance of CountryInstance + + :param payload: Payload response from the API + """ + return CountryInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CountryList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CountryList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/PhoneNumbers/Countries" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CountryInstance]: + """ + Streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CountryInstance]: + """ + Asynchronously streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Asynchronously lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Asynchronously retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + def get_page(self, target_url: str) -> CountryPage: + """ + Retrieve a specific page of CountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CountryPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CountryPage: + """ + Asynchronously retrieve a specific page of CountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CountryPage(self._version, response) + + def get(self, iso_country: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) + + def __call__(self, iso_country: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v1/voice/__init__.py b/venv/Lib/site-packages/twilio/rest/pricing/v1/voice/__init__.py new file mode 100644 index 00000000..a801a300 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/pricing/v1/voice/__init__.py @@ -0,0 +1,65 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.pricing.v1.voice.country import CountryList +from twilio.rest.pricing.v1.voice.number import NumberList + + +class VoiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the VoiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Voice" + + self._countries: Optional[CountryList] = None + self._numbers: Optional[NumberList] = None + + @property + def countries(self) -> CountryList: + """ + Access the countries + """ + if self._countries is None: + self._countries = CountryList(self._version) + return self._countries + + @property + def numbers(self) -> NumberList: + """ + Access the numbers + """ + if self._numbers is None: + self._numbers = NumberList(self._version) + return self._numbers + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v1/voice/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/pricing/v1/voice/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..40a3974b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/pricing/v1/voice/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v1/voice/__pycache__/country.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/pricing/v1/voice/__pycache__/country.cpython-312.pyc new file mode 100644 index 00000000..7bd8bee6 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/pricing/v1/voice/__pycache__/country.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v1/voice/__pycache__/number.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/pricing/v1/voice/__pycache__/number.cpython-312.pyc new file mode 100644 index 00000000..d4692f5d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/pricing/v1/voice/__pycache__/number.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v1/voice/country.py b/venv/Lib/site-packages/twilio/rest/pricing/v1/voice/country.py new file mode 100644 index 00000000..7fb0da88 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/pricing/v1/voice/country.py @@ -0,0 +1,417 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CountryInstance(InstanceResource): + """ + :ivar country: The name of the country. + :ivar iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + :ivar outbound_prefix_prices: The list of OutboundPrefixPrice records, which include a list of the `prefixes`, the `friendly_name`, `base_price`, and the `current_price` for those prefixes. + :ivar inbound_call_prices: The list of [InboundCallPrice](https://www.twilio.com/docs/voice/pricing#inbound-call-price) records. + :ivar price_unit: The currency in which prices are measured, specified in [ISO 4127](http://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + iso_country: Optional[str] = None, + ): + super().__init__(version) + + self.country: Optional[str] = payload.get("country") + self.iso_country: Optional[str] = payload.get("iso_country") + self.outbound_prefix_prices: Optional[List[str]] = payload.get( + "outbound_prefix_prices" + ) + self.inbound_call_prices: Optional[List[str]] = payload.get( + "inbound_call_prices" + ) + self.price_unit: Optional[str] = payload.get("price_unit") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "iso_country": iso_country or self.iso_country, + } + self._context: Optional[CountryContext] = None + + @property + def _proxy(self) -> "CountryContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CountryContext for this CountryInstance + """ + if self._context is None: + self._context = CountryContext( + self._version, + iso_country=self._solution["iso_country"], + ) + return self._context + + def fetch(self) -> "CountryInstance": + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CountryInstance": + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CountryContext(InstanceContext): + + def __init__(self, version: Version, iso_country: str): + """ + Initialize the CountryContext + + :param version: Version that contains the resource + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "iso_country": iso_country, + } + self._uri = "/Voice/Countries/{iso_country}".format(**self._solution) + + def fetch(self) -> CountryInstance: + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + async def fetch_async(self) -> CountryInstance: + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CountryPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: + """ + Build an instance of CountryInstance + + :param payload: Payload response from the API + """ + return CountryInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CountryList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CountryList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Voice/Countries" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CountryInstance]: + """ + Streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CountryInstance]: + """ + Asynchronously streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Asynchronously lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Asynchronously retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + def get_page(self, target_url: str) -> CountryPage: + """ + Retrieve a specific page of CountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CountryPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CountryPage: + """ + Asynchronously retrieve a specific page of CountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CountryPage(self._version, response) + + def get(self, iso_country: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) + + def __call__(self, iso_country: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v1/voice/number.py b/venv/Lib/site-packages/twilio/rest/pricing/v1/voice/number.py new file mode 100644 index 00000000..5bff8cd5 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/pricing/v1/voice/number.py @@ -0,0 +1,197 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NumberInstance(InstanceResource): + """ + :ivar number: The phone number. + :ivar country: The name of the country. + :ivar iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + :ivar outbound_call_price: + :ivar inbound_call_price: + :ivar price_unit: The currency in which prices are measured, specified in [ISO 4127](http://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], number: Optional[str] = None + ): + super().__init__(version) + + self.number: Optional[str] = payload.get("number") + self.country: Optional[str] = payload.get("country") + self.iso_country: Optional[str] = payload.get("iso_country") + self.outbound_call_price: Optional[str] = payload.get("outbound_call_price") + self.inbound_call_price: Optional[str] = payload.get("inbound_call_price") + self.price_unit: Optional[str] = payload.get("price_unit") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "number": number or self.number, + } + self._context: Optional[NumberContext] = None + + @property + def _proxy(self) -> "NumberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: NumberContext for this NumberInstance + """ + if self._context is None: + self._context = NumberContext( + self._version, + number=self._solution["number"], + ) + return self._context + + def fetch(self) -> "NumberInstance": + """ + Fetch the NumberInstance + + + :returns: The fetched NumberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "NumberInstance": + """ + Asynchronous coroutine to fetch the NumberInstance + + + :returns: The fetched NumberInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NumberContext(InstanceContext): + + def __init__(self, version: Version, number: str): + """ + Initialize the NumberContext + + :param version: Version that contains the resource + :param number: The phone number to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "number": number, + } + self._uri = "/Voice/Numbers/{number}".format(**self._solution) + + def fetch(self) -> NumberInstance: + """ + Fetch the NumberInstance + + + :returns: The fetched NumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return NumberInstance( + self._version, + payload, + number=self._solution["number"], + ) + + async def fetch_async(self) -> NumberInstance: + """ + Asynchronous coroutine to fetch the NumberInstance + + + :returns: The fetched NumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return NumberInstance( + self._version, + payload, + number=self._solution["number"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NumberList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the NumberList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, number: str) -> NumberContext: + """ + Constructs a NumberContext + + :param number: The phone number to fetch. + """ + return NumberContext(self._version, number=number) + + def __call__(self, number: str) -> NumberContext: + """ + Constructs a NumberContext + + :param number: The phone number to fetch. + """ + return NumberContext(self._version, number=number) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v2/__init__.py b/venv/Lib/site-packages/twilio/rest/pricing/v2/__init__.py new file mode 100644 index 00000000..d0fd67f7 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/pricing/v2/__init__.py @@ -0,0 +1,59 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.pricing.v2.country import CountryList +from twilio.rest.pricing.v2.number import NumberList +from twilio.rest.pricing.v2.voice import VoiceList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Pricing + + :param domain: The Twilio.pricing domain + """ + super().__init__(domain, "v2") + self._countries: Optional[CountryList] = None + self._numbers: Optional[NumberList] = None + self._voice: Optional[VoiceList] = None + + @property + def countries(self) -> CountryList: + if self._countries is None: + self._countries = CountryList(self) + return self._countries + + @property + def numbers(self) -> NumberList: + if self._numbers is None: + self._numbers = NumberList(self) + return self._numbers + + @property + def voice(self) -> VoiceList: + if self._voice is None: + self._voice = VoiceList(self) + return self._voice + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v2/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/pricing/v2/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..af85e989 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/pricing/v2/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v2/__pycache__/country.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/pricing/v2/__pycache__/country.cpython-312.pyc new file mode 100644 index 00000000..2502243b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/pricing/v2/__pycache__/country.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v2/__pycache__/number.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/pricing/v2/__pycache__/number.cpython-312.pyc new file mode 100644 index 00000000..4661c3a5 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/pricing/v2/__pycache__/number.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v2/country.py b/venv/Lib/site-packages/twilio/rest/pricing/v2/country.py new file mode 100644 index 00000000..30672235 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/pricing/v2/country.py @@ -0,0 +1,417 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CountryInstance(InstanceResource): + """ + :ivar country: The name of the country. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + :ivar terminating_prefix_prices: The list of [TerminatingPrefixPrice](https://www.twilio.com/docs/voice/pricing#outbound-prefix-price-with-origin) records. + :ivar originating_call_prices: The list of [OriginatingCallPrice](https://www.twilio.com/docs/voice/pricing#inbound-call-price) records. + :ivar price_unit: The currency in which prices are measured, specified in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + iso_country: Optional[str] = None, + ): + super().__init__(version) + + self.country: Optional[str] = payload.get("country") + self.iso_country: Optional[str] = payload.get("iso_country") + self.terminating_prefix_prices: Optional[List[str]] = payload.get( + "terminating_prefix_prices" + ) + self.originating_call_prices: Optional[List[str]] = payload.get( + "originating_call_prices" + ) + self.price_unit: Optional[str] = payload.get("price_unit") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "iso_country": iso_country or self.iso_country, + } + self._context: Optional[CountryContext] = None + + @property + def _proxy(self) -> "CountryContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CountryContext for this CountryInstance + """ + if self._context is None: + self._context = CountryContext( + self._version, + iso_country=self._solution["iso_country"], + ) + return self._context + + def fetch(self) -> "CountryInstance": + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CountryInstance": + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CountryContext(InstanceContext): + + def __init__(self, version: Version, iso_country: str): + """ + Initialize the CountryContext + + :param version: Version that contains the resource + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the origin-based voice pricing information to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "iso_country": iso_country, + } + self._uri = "/Trunking/Countries/{iso_country}".format(**self._solution) + + def fetch(self) -> CountryInstance: + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + async def fetch_async(self) -> CountryInstance: + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CountryPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: + """ + Build an instance of CountryInstance + + :param payload: Payload response from the API + """ + return CountryInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CountryList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CountryList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Trunking/Countries" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CountryInstance]: + """ + Streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CountryInstance]: + """ + Asynchronously streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Asynchronously lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Asynchronously retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + def get_page(self, target_url: str) -> CountryPage: + """ + Retrieve a specific page of CountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CountryPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CountryPage: + """ + Asynchronously retrieve a specific page of CountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CountryPage(self._version, response) + + def get(self, iso_country: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the origin-based voice pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) + + def __call__(self, iso_country: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the origin-based voice pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v2/number.py b/venv/Lib/site-packages/twilio/rest/pricing/v2/number.py new file mode 100644 index 00000000..1dead393 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/pricing/v2/number.py @@ -0,0 +1,236 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NumberInstance(InstanceResource): + """ + :ivar destination_number: The destination phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar origination_number: The origination phone number in [[E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar country: The name of the country. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :ivar terminating_prefix_prices: + :ivar originating_call_price: + :ivar price_unit: The currency in which prices are measured, specified in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + destination_number: Optional[str] = None, + ): + super().__init__(version) + + self.destination_number: Optional[str] = payload.get("destination_number") + self.origination_number: Optional[str] = payload.get("origination_number") + self.country: Optional[str] = payload.get("country") + self.iso_country: Optional[str] = payload.get("iso_country") + self.terminating_prefix_prices: Optional[List[str]] = payload.get( + "terminating_prefix_prices" + ) + self.originating_call_price: Optional[str] = payload.get( + "originating_call_price" + ) + self.price_unit: Optional[str] = payload.get("price_unit") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "destination_number": destination_number or self.destination_number, + } + self._context: Optional[NumberContext] = None + + @property + def _proxy(self) -> "NumberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: NumberContext for this NumberInstance + """ + if self._context is None: + self._context = NumberContext( + self._version, + destination_number=self._solution["destination_number"], + ) + return self._context + + def fetch( + self, origination_number: Union[str, object] = values.unset + ) -> "NumberInstance": + """ + Fetch the NumberInstance + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: The fetched NumberInstance + """ + return self._proxy.fetch( + origination_number=origination_number, + ) + + async def fetch_async( + self, origination_number: Union[str, object] = values.unset + ) -> "NumberInstance": + """ + Asynchronous coroutine to fetch the NumberInstance + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: The fetched NumberInstance + """ + return await self._proxy.fetch_async( + origination_number=origination_number, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NumberContext(InstanceContext): + + def __init__(self, version: Version, destination_number: str): + """ + Initialize the NumberContext + + :param version: Version that contains the resource + :param destination_number: The destination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "destination_number": destination_number, + } + self._uri = "/Trunking/Numbers/{destination_number}".format(**self._solution) + + def fetch( + self, origination_number: Union[str, object] = values.unset + ) -> NumberInstance: + """ + Fetch the NumberInstance + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: The fetched NumberInstance + """ + + data = values.of( + { + "OriginationNumber": origination_number, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return NumberInstance( + self._version, + payload, + destination_number=self._solution["destination_number"], + ) + + async def fetch_async( + self, origination_number: Union[str, object] = values.unset + ) -> NumberInstance: + """ + Asynchronous coroutine to fetch the NumberInstance + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: The fetched NumberInstance + """ + + data = values.of( + { + "OriginationNumber": origination_number, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return NumberInstance( + self._version, + payload, + destination_number=self._solution["destination_number"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NumberList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the NumberList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, destination_number: str) -> NumberContext: + """ + Constructs a NumberContext + + :param destination_number: The destination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + """ + return NumberContext(self._version, destination_number=destination_number) + + def __call__(self, destination_number: str) -> NumberContext: + """ + Constructs a NumberContext + + :param destination_number: The destination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + """ + return NumberContext(self._version, destination_number=destination_number) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v2/voice/__init__.py b/venv/Lib/site-packages/twilio/rest/pricing/v2/voice/__init__.py new file mode 100644 index 00000000..1ebbcbb6 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/pricing/v2/voice/__init__.py @@ -0,0 +1,65 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.pricing.v2.voice.country import CountryList +from twilio.rest.pricing.v2.voice.number import NumberList + + +class VoiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the VoiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Voice" + + self._countries: Optional[CountryList] = None + self._numbers: Optional[NumberList] = None + + @property + def countries(self) -> CountryList: + """ + Access the countries + """ + if self._countries is None: + self._countries = CountryList(self._version) + return self._countries + + @property + def numbers(self) -> NumberList: + """ + Access the numbers + """ + if self._numbers is None: + self._numbers = NumberList(self._version) + return self._numbers + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v2/voice/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/pricing/v2/voice/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..ae700395 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/pricing/v2/voice/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v2/voice/__pycache__/country.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/pricing/v2/voice/__pycache__/country.cpython-312.pyc new file mode 100644 index 00000000..0d99ee15 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/pricing/v2/voice/__pycache__/country.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v2/voice/__pycache__/number.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/pricing/v2/voice/__pycache__/number.cpython-312.pyc new file mode 100644 index 00000000..f317aa88 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/pricing/v2/voice/__pycache__/number.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v2/voice/country.py b/venv/Lib/site-packages/twilio/rest/pricing/v2/voice/country.py new file mode 100644 index 00000000..997f3684 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/pricing/v2/voice/country.py @@ -0,0 +1,417 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CountryInstance(InstanceResource): + """ + :ivar country: The name of the country. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + :ivar outbound_prefix_prices: The list of [OutboundPrefixPriceWithOrigin](https://www.twilio.com/docs/voice/pricing#outbound-prefix-price-with-origin) records. + :ivar inbound_call_prices: The list of [InboundCallPrice](https://www.twilio.com/docs/voice/pricing#inbound-call-price) records. + :ivar price_unit: The currency in which prices are measured, specified in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + iso_country: Optional[str] = None, + ): + super().__init__(version) + + self.country: Optional[str] = payload.get("country") + self.iso_country: Optional[str] = payload.get("iso_country") + self.outbound_prefix_prices: Optional[List[str]] = payload.get( + "outbound_prefix_prices" + ) + self.inbound_call_prices: Optional[List[str]] = payload.get( + "inbound_call_prices" + ) + self.price_unit: Optional[str] = payload.get("price_unit") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "iso_country": iso_country or self.iso_country, + } + self._context: Optional[CountryContext] = None + + @property + def _proxy(self) -> "CountryContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CountryContext for this CountryInstance + """ + if self._context is None: + self._context = CountryContext( + self._version, + iso_country=self._solution["iso_country"], + ) + return self._context + + def fetch(self) -> "CountryInstance": + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CountryInstance": + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CountryContext(InstanceContext): + + def __init__(self, version: Version, iso_country: str): + """ + Initialize the CountryContext + + :param version: Version that contains the resource + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the origin-based voice pricing information to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "iso_country": iso_country, + } + self._uri = "/Voice/Countries/{iso_country}".format(**self._solution) + + def fetch(self) -> CountryInstance: + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + async def fetch_async(self) -> CountryInstance: + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CountryPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: + """ + Build an instance of CountryInstance + + :param payload: Payload response from the API + """ + return CountryInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CountryList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CountryList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Voice/Countries" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CountryInstance]: + """ + Streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CountryInstance]: + """ + Asynchronously streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Asynchronously lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Asynchronously retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + def get_page(self, target_url: str) -> CountryPage: + """ + Retrieve a specific page of CountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CountryPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CountryPage: + """ + Asynchronously retrieve a specific page of CountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CountryPage(self._version, response) + + def get(self, iso_country: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the origin-based voice pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) + + def __call__(self, iso_country: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the origin-based voice pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/pricing/v2/voice/number.py b/venv/Lib/site-packages/twilio/rest/pricing/v2/voice/number.py new file mode 100644 index 00000000..97a3a526 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/pricing/v2/voice/number.py @@ -0,0 +1,234 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NumberInstance(InstanceResource): + """ + :ivar destination_number: The destination phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar origination_number: The origination phone number in [[E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar country: The name of the country. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :ivar outbound_call_prices: The list of [OutboundCallPriceWithOrigin](https://www.twilio.com/docs/voice/pricing#outbound-call-price-with-origin) records. + :ivar inbound_call_price: + :ivar price_unit: The currency in which prices are measured, specified in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + destination_number: Optional[str] = None, + ): + super().__init__(version) + + self.destination_number: Optional[str] = payload.get("destination_number") + self.origination_number: Optional[str] = payload.get("origination_number") + self.country: Optional[str] = payload.get("country") + self.iso_country: Optional[str] = payload.get("iso_country") + self.outbound_call_prices: Optional[List[str]] = payload.get( + "outbound_call_prices" + ) + self.inbound_call_price: Optional[str] = payload.get("inbound_call_price") + self.price_unit: Optional[str] = payload.get("price_unit") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "destination_number": destination_number or self.destination_number, + } + self._context: Optional[NumberContext] = None + + @property + def _proxy(self) -> "NumberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: NumberContext for this NumberInstance + """ + if self._context is None: + self._context = NumberContext( + self._version, + destination_number=self._solution["destination_number"], + ) + return self._context + + def fetch( + self, origination_number: Union[str, object] = values.unset + ) -> "NumberInstance": + """ + Fetch the NumberInstance + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: The fetched NumberInstance + """ + return self._proxy.fetch( + origination_number=origination_number, + ) + + async def fetch_async( + self, origination_number: Union[str, object] = values.unset + ) -> "NumberInstance": + """ + Asynchronous coroutine to fetch the NumberInstance + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: The fetched NumberInstance + """ + return await self._proxy.fetch_async( + origination_number=origination_number, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NumberContext(InstanceContext): + + def __init__(self, version: Version, destination_number: str): + """ + Initialize the NumberContext + + :param version: Version that contains the resource + :param destination_number: The destination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "destination_number": destination_number, + } + self._uri = "/Voice/Numbers/{destination_number}".format(**self._solution) + + def fetch( + self, origination_number: Union[str, object] = values.unset + ) -> NumberInstance: + """ + Fetch the NumberInstance + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: The fetched NumberInstance + """ + + data = values.of( + { + "OriginationNumber": origination_number, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return NumberInstance( + self._version, + payload, + destination_number=self._solution["destination_number"], + ) + + async def fetch_async( + self, origination_number: Union[str, object] = values.unset + ) -> NumberInstance: + """ + Asynchronous coroutine to fetch the NumberInstance + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: The fetched NumberInstance + """ + + data = values.of( + { + "OriginationNumber": origination_number, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return NumberInstance( + self._version, + payload, + destination_number=self._solution["destination_number"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NumberList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the NumberList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, destination_number: str) -> NumberContext: + """ + Constructs a NumberContext + + :param destination_number: The destination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + """ + return NumberContext(self._version, destination_number=destination_number) + + def __call__(self, destination_number: str) -> NumberContext: + """ + Constructs a NumberContext + + :param destination_number: The destination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + """ + return NumberContext(self._version, destination_number=destination_number) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/proxy/ProxyBase.py b/venv/Lib/site-packages/twilio/rest/proxy/ProxyBase.py new file mode 100644 index 00000000..da1baec1 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/proxy/ProxyBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.proxy.v1 import V1 + + +class ProxyBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Proxy Domain + + :returns: Domain for Proxy + """ + super().__init__(twilio, "https://proxy.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Proxy + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/proxy/__init__.py b/venv/Lib/site-packages/twilio/rest/proxy/__init__.py new file mode 100644 index 00000000..aec2a3d1 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/proxy/__init__.py @@ -0,0 +1,15 @@ +from warnings import warn + +from twilio.rest.proxy.ProxyBase import ProxyBase +from twilio.rest.proxy.v1.service import ServiceList + + +class Proxy(ProxyBase): + @property + def services(self) -> ServiceList: + warn( + "services is deprecated. Use v1.services instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.services diff --git a/venv/Lib/site-packages/twilio/rest/proxy/__pycache__/ProxyBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/proxy/__pycache__/ProxyBase.cpython-312.pyc new file mode 100644 index 00000000..6d841524 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/proxy/__pycache__/ProxyBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/proxy/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/proxy/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..82d46403 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/proxy/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/proxy/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/proxy/v1/__init__.py new file mode 100644 index 00000000..83737dc0 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/proxy/v1/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Proxy + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.proxy.v1.service import ServiceList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Proxy + + :param domain: The Twilio.proxy domain + """ + super().__init__(domain, "v1") + self._services: Optional[ServiceList] = None + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/proxy/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/proxy/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..f7ca17fb Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/proxy/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/proxy/v1/service/__init__.py b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/__init__.py new file mode 100644 index 00000000..ff1e7ed7 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/__init__.py @@ -0,0 +1,844 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Proxy + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.proxy.v1.service.phone_number import PhoneNumberList +from twilio.rest.proxy.v1.service.session import SessionList +from twilio.rest.proxy.v1.service.short_code import ShortCodeList + + +class ServiceInstance(InstanceResource): + + class GeoMatchLevel(object): + AREA_CODE = "area-code" + OVERLAY = "overlay" + RADIUS = "radius" + COUNTRY = "country" + + class NumberSelectionBehavior(object): + AVOID_STICKY = "avoid-sticky" + PREFER_STICKY = "prefer-sticky" + + """ + :ivar sid: The unique string that we created to identify the Service resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. Supports UTF-8 characters. **This value should not have PII.** + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + :ivar chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + :ivar callback_url: The URL we call when the interaction status changes. + :ivar default_ttl: The default `ttl` value for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :ivar number_selection_behavior: + :ivar geo_match_level: + :ivar intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :ivar out_of_session_callback_url: The URL we call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :ivar date_created: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was created. + :ivar date_updated: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. + :ivar url: The absolute URL of the Service resource. + :ivar links: The URLs of resources related to the Service. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_instance_sid: Optional[str] = payload.get("chat_instance_sid") + self.callback_url: Optional[str] = payload.get("callback_url") + self.default_ttl: Optional[int] = deserialize.integer( + payload.get("default_ttl") + ) + self.number_selection_behavior: Optional[ + "ServiceInstance.NumberSelectionBehavior" + ] = payload.get("number_selection_behavior") + self.geo_match_level: Optional["ServiceInstance.GeoMatchLevel"] = payload.get( + "geo_match_level" + ) + self.intercept_callback_url: Optional[str] = payload.get( + "intercept_callback_url" + ) + self.out_of_session_callback_url: Optional[str] = payload.get( + "out_of_session_callback_url" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + unique_name: Union[str, object] = values.unset, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) + + @property + def phone_numbers(self) -> PhoneNumberList: + """ + Access the phone_numbers + """ + return self._proxy.phone_numbers + + @property + def sessions(self) -> SessionList: + """ + Access the sessions + """ + return self._proxy.sessions + + @property + def short_codes(self) -> ShortCodeList: + """ + Access the short_codes + """ + return self._proxy.short_codes + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._phone_numbers: Optional[PhoneNumberList] = None + self._sessions: Optional[SessionList] = None + self._short_codes: Optional[ShortCodeList] = None + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + unique_name: Union[str, object] = values.unset, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "DefaultTtl": default_ttl, + "CallbackUrl": callback_url, + "GeoMatchLevel": geo_match_level, + "NumberSelectionBehavior": number_selection_behavior, + "InterceptCallbackUrl": intercept_callback_url, + "OutOfSessionCallbackUrl": out_of_session_callback_url, + "ChatInstanceSid": chat_instance_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "DefaultTtl": default_ttl, + "CallbackUrl": callback_url, + "GeoMatchLevel": geo_match_level, + "NumberSelectionBehavior": number_selection_behavior, + "InterceptCallbackUrl": intercept_callback_url, + "OutOfSessionCallbackUrl": out_of_session_callback_url, + "ChatInstanceSid": chat_instance_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def phone_numbers(self) -> PhoneNumberList: + """ + Access the phone_numbers + """ + if self._phone_numbers is None: + self._phone_numbers = PhoneNumberList( + self._version, + self._solution["sid"], + ) + return self._phone_numbers + + @property + def sessions(self) -> SessionList: + """ + Access the sessions + """ + if self._sessions is None: + self._sessions = SessionList( + self._version, + self._solution["sid"], + ) + return self._sessions + + @property + def short_codes(self) -> ShortCodeList: + """ + Access the short_codes + """ + if self._short_codes is None: + self._short_codes = ShortCodeList( + self._version, + self._solution["sid"], + ) + return self._short_codes + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def create( + self, + unique_name: str, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> ServiceInstance: + """ + Create the ServiceInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "DefaultTtl": default_ttl, + "CallbackUrl": callback_url, + "GeoMatchLevel": geo_match_level, + "NumberSelectionBehavior": number_selection_behavior, + "InterceptCallbackUrl": intercept_callback_url, + "OutOfSessionCallbackUrl": out_of_session_callback_url, + "ChatInstanceSid": chat_instance_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async( + self, + unique_name: str, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "DefaultTtl": default_ttl, + "CallbackUrl": callback_url, + "GeoMatchLevel": geo_match_level, + "NumberSelectionBehavior": number_selection_behavior, + "InterceptCallbackUrl": intercept_callback_url, + "OutOfSessionCallbackUrl": out_of_session_callback_url, + "ChatInstanceSid": chat_instance_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/proxy/v1/service/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..11d19404 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/proxy/v1/service/__pycache__/phone_number.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/__pycache__/phone_number.cpython-312.pyc new file mode 100644 index 00000000..ff8a74ec Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/__pycache__/phone_number.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/proxy/v1/service/__pycache__/short_code.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/__pycache__/short_code.cpython-312.pyc new file mode 100644 index 00000000..2f62cf99 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/__pycache__/short_code.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/proxy/v1/service/phone_number.py b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/phone_number.py new file mode 100644 index 00000000..3c8517ce --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/phone_number.py @@ -0,0 +1,662 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Proxy + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class PhoneNumberInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the PhoneNumber resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the PhoneNumber resource. + :ivar service_sid: The SID of the PhoneNumber resource's parent [Service](https://www.twilio.com/docs/proxy/api/service) resource. + :ivar date_created: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was created. + :ivar date_updated: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar iso_country: The ISO Country Code for the phone number. + :ivar capabilities: + :ivar url: The absolute URL of the PhoneNumber resource. + :ivar is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + :ivar in_use: The number of open session assigned to the number. See the [How many Phone Numbers do I need?](https://www.twilio.com/docs/proxy/phone-numbers-needed) guide for more information. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.phone_number: Optional[str] = payload.get("phone_number") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.iso_country: Optional[str] = payload.get("iso_country") + self.capabilities: Optional[str] = payload.get("capabilities") + self.url: Optional[str] = payload.get("url") + self.is_reserved: Optional[bool] = payload.get("is_reserved") + self.in_use: Optional[int] = deserialize.integer(payload.get("in_use")) + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[PhoneNumberContext] = None + + @property + def _proxy(self) -> "PhoneNumberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PhoneNumberContext for this PhoneNumberInstance + """ + if self._context is None: + self._context = PhoneNumberContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the PhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "PhoneNumberInstance": + """ + Fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PhoneNumberInstance": + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + return await self._proxy.fetch_async() + + def update( + self, is_reserved: Union[bool, object] = values.unset + ) -> "PhoneNumberInstance": + """ + Update the PhoneNumberInstance + + :param is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The updated PhoneNumberInstance + """ + return self._proxy.update( + is_reserved=is_reserved, + ) + + async def update_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> "PhoneNumberInstance": + """ + Asynchronous coroutine to update the PhoneNumberInstance + + :param is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The updated PhoneNumberInstance + """ + return await self._proxy.update_async( + is_reserved=is_reserved, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PhoneNumberContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the PhoneNumberContext + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the PhoneNumber resource to update. + :param sid: The Twilio-provided string that uniquely identifies the PhoneNumber resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/PhoneNumbers/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the PhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> PhoneNumberInstance: + """ + Fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> PhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, is_reserved: Union[bool, object] = values.unset + ) -> PhoneNumberInstance: + """ + Update the PhoneNumberInstance + + :param is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The updated PhoneNumberInstance + """ + + data = values.of( + { + "IsReserved": serialize.boolean_to_string(is_reserved), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> PhoneNumberInstance: + """ + Asynchronous coroutine to update the PhoneNumberInstance + + :param is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The updated PhoneNumberInstance + """ + + data = values.of( + { + "IsReserved": serialize.boolean_to_string(is_reserved), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PhoneNumberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PhoneNumberInstance: + """ + Build an instance of PhoneNumberInstance + + :param payload: Payload response from the API + """ + return PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class PhoneNumberList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the PhoneNumberList + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the PhoneNumber resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/PhoneNumbers".format(**self._solution) + + def create( + self, + sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + is_reserved: Union[bool, object] = values.unset, + ) -> PhoneNumberInstance: + """ + Create the PhoneNumberInstance + + :param sid: The SID of a Twilio [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the Twilio Number you would like to assign to your Proxy Service. + :param phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param is_reserved: Whether the new phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The created PhoneNumberInstance + """ + + data = values.of( + { + "Sid": sid, + "PhoneNumber": phone_number, + "IsReserved": serialize.boolean_to_string(is_reserved), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + is_reserved: Union[bool, object] = values.unset, + ) -> PhoneNumberInstance: + """ + Asynchronously create the PhoneNumberInstance + + :param sid: The SID of a Twilio [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the Twilio Number you would like to assign to your Proxy Service. + :param phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param is_reserved: Whether the new phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The created PhoneNumberInstance + """ + + data = values.of( + { + "Sid": sid, + "PhoneNumber": phone_number, + "IsReserved": serialize.boolean_to_string(is_reserved), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PhoneNumberInstance]: + """ + Streams PhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PhoneNumberInstance]: + """ + Asynchronously streams PhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PhoneNumberInstance]: + """ + Lists PhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PhoneNumberInstance]: + """ + Asynchronously lists PhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PhoneNumberPage: + """ + Retrieve a single page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PhoneNumberInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PhoneNumberPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PhoneNumberPage: + """ + Asynchronously retrieve a single page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PhoneNumberInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PhoneNumberPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> PhoneNumberPage: + """ + Retrieve a specific page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PhoneNumberInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PhoneNumberPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> PhoneNumberPage: + """ + Asynchronously retrieve a specific page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PhoneNumberInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PhoneNumberPage(self._version, response, self._solution) + + def get(self, sid: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param sid: The Twilio-provided string that uniquely identifies the PhoneNumber resource to update. + """ + return PhoneNumberContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param sid: The Twilio-provided string that uniquely identifies the PhoneNumber resource to update. + """ + return PhoneNumberContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/proxy/v1/service/session/__init__.py b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/session/__init__.py new file mode 100644 index 00000000..839db075 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/session/__init__.py @@ -0,0 +1,784 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Proxy + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.proxy.v1.service.session.interaction import InteractionList +from twilio.rest.proxy.v1.service.session.participant import ParticipantList + + +class SessionInstance(InstanceResource): + + class Mode(object): + MESSAGE_ONLY = "message-only" + VOICE_ONLY = "voice-only" + VOICE_AND_MESSAGE = "voice-and-message" + + class Status(object): + OPEN = "open" + IN_PROGRESS = "in-progress" + CLOSED = "closed" + FAILED = "failed" + UNKNOWN = "unknown" + + """ + :ivar sid: The unique string that we created to identify the Session resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/proxy/api/service) the session is associated with. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Session resource. + :ivar date_started: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session started. + :ivar date_ended: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session ended. + :ivar date_last_interaction: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session last had an interaction. + :ivar date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :ivar unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. Supports UTF-8 characters. **This value should not have PII.** + :ivar status: + :ivar closed_reason: The reason the Session ended. + :ivar ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :ivar mode: + :ivar date_created: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was created. + :ivar date_updated: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. + :ivar url: The absolute URL of the Session resource. + :ivar links: The URLs of resources related to the Session. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_started: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_started") + ) + self.date_ended: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_ended") + ) + self.date_last_interaction: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_last_interaction") + ) + self.date_expiry: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_expiry") + ) + self.unique_name: Optional[str] = payload.get("unique_name") + self.status: Optional["SessionInstance.Status"] = payload.get("status") + self.closed_reason: Optional[str] = payload.get("closed_reason") + self.ttl: Optional[int] = deserialize.integer(payload.get("ttl")) + self.mode: Optional["SessionInstance.Mode"] = payload.get("mode") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[SessionContext] = None + + @property + def _proxy(self) -> "SessionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SessionContext for this SessionInstance + """ + if self._context is None: + self._context = SessionContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SessionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SessionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SessionInstance": + """ + Fetch the SessionInstance + + + :returns: The fetched SessionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SessionInstance": + """ + Asynchronous coroutine to fetch the SessionInstance + + + :returns: The fetched SessionInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> "SessionInstance": + """ + Update the SessionInstance + + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param status: + + :returns: The updated SessionInstance + """ + return self._proxy.update( + date_expiry=date_expiry, + ttl=ttl, + status=status, + ) + + async def update_async( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> "SessionInstance": + """ + Asynchronous coroutine to update the SessionInstance + + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param status: + + :returns: The updated SessionInstance + """ + return await self._proxy.update_async( + date_expiry=date_expiry, + ttl=ttl, + status=status, + ) + + @property + def interactions(self) -> InteractionList: + """ + Access the interactions + """ + return self._proxy.interactions + + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + return self._proxy.participants + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SessionContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the SessionContext + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the resource to update. + :param sid: The Twilio-provided string that uniquely identifies the Session resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Sessions/{sid}".format(**self._solution) + + self._interactions: Optional[InteractionList] = None + self._participants: Optional[ParticipantList] = None + + def delete(self) -> bool: + """ + Deletes the SessionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SessionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SessionInstance: + """ + Fetch the SessionInstance + + + :returns: The fetched SessionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SessionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SessionInstance: + """ + Asynchronous coroutine to fetch the SessionInstance + + + :returns: The fetched SessionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SessionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> SessionInstance: + """ + Update the SessionInstance + + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param status: + + :returns: The updated SessionInstance + """ + + data = values.of( + { + "DateExpiry": serialize.iso8601_datetime(date_expiry), + "Ttl": ttl, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SessionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> SessionInstance: + """ + Asynchronous coroutine to update the SessionInstance + + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param status: + + :returns: The updated SessionInstance + """ + + data = values.of( + { + "DateExpiry": serialize.iso8601_datetime(date_expiry), + "Ttl": ttl, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SessionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def interactions(self) -> InteractionList: + """ + Access the interactions + """ + if self._interactions is None: + self._interactions = InteractionList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._interactions + + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + if self._participants is None: + self._participants = ParticipantList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._participants + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SessionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SessionInstance: + """ + Build an instance of SessionInstance + + :param payload: Payload response from the API + """ + return SessionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SessionList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the SessionList + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the resource to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Sessions".format(**self._solution) + + def create( + self, + unique_name: Union[str, object] = values.unset, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + mode: Union["SessionInstance.Mode", object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + participants: Union[List[object], object] = values.unset, + ) -> SessionInstance: + """ + Create the SessionInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param mode: + :param status: + :param participants: The Participant objects to include in the new session. + + :returns: The created SessionInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "DateExpiry": serialize.iso8601_datetime(date_expiry), + "Ttl": ttl, + "Mode": mode, + "Status": status, + "Participants": serialize.map( + participants, lambda e: serialize.object(e) + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SessionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + mode: Union["SessionInstance.Mode", object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + participants: Union[List[object], object] = values.unset, + ) -> SessionInstance: + """ + Asynchronously create the SessionInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param mode: + :param status: + :param participants: The Participant objects to include in the new session. + + :returns: The created SessionInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "DateExpiry": serialize.iso8601_datetime(date_expiry), + "Ttl": ttl, + "Mode": mode, + "Status": status, + "Participants": serialize.map( + participants, lambda e: serialize.object(e) + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SessionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SessionInstance]: + """ + Streams SessionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SessionInstance]: + """ + Asynchronously streams SessionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SessionInstance]: + """ + Lists SessionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SessionInstance]: + """ + Asynchronously lists SessionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SessionPage: + """ + Retrieve a single page of SessionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SessionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SessionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SessionPage: + """ + Asynchronously retrieve a single page of SessionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SessionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SessionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SessionPage: + """ + Retrieve a specific page of SessionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SessionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SessionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SessionPage: + """ + Asynchronously retrieve a specific page of SessionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SessionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SessionPage(self._version, response, self._solution) + + def get(self, sid: str) -> SessionContext: + """ + Constructs a SessionContext + + :param sid: The Twilio-provided string that uniquely identifies the Session resource to update. + """ + return SessionContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> SessionContext: + """ + Constructs a SessionContext + + :param sid: The Twilio-provided string that uniquely identifies the Session resource to update. + """ + return SessionContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/proxy/v1/service/session/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/session/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..35d08ca4 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/session/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/proxy/v1/service/session/__pycache__/interaction.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/session/__pycache__/interaction.cpython-312.pyc new file mode 100644 index 00000000..f5b3db41 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/session/__pycache__/interaction.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/proxy/v1/service/session/interaction.py b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/session/interaction.py new file mode 100644 index 00000000..7eeccda5 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/session/interaction.py @@ -0,0 +1,571 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Proxy + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InteractionInstance(InstanceResource): + + class ResourceStatus(object): + ACCEPTED = "accepted" + ANSWERED = "answered" + BUSY = "busy" + CANCELED = "canceled" + COMPLETED = "completed" + DELETED = "deleted" + DELIVERED = "delivered" + DELIVERY_UNKNOWN = "delivery-unknown" + FAILED = "failed" + IN_PROGRESS = "in-progress" + INITIATED = "initiated" + NO_ANSWER = "no-answer" + QUEUED = "queued" + RECEIVED = "received" + RECEIVING = "receiving" + RINGING = "ringing" + SCHEDULED = "scheduled" + SENDING = "sending" + SENT = "sent" + UNDELIVERED = "undelivered" + UNKNOWN = "unknown" + + class Type(object): + MESSAGE = "message" + VOICE = "voice" + UNKNOWN = "unknown" + + """ + :ivar sid: The unique string that we created to identify the Interaction resource. + :ivar session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) resource. + :ivar service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Interaction resource. + :ivar data: A JSON string that includes the message body of message interactions (e.g. `{\"body\": \"hello\"}`) or the call duration (when available) of a call (e.g. `{\"duration\": \"5\"}`). + :ivar type: + :ivar inbound_participant_sid: The SID of the inbound [Participant](https://www.twilio.com/docs/proxy/api/participant) resource. + :ivar inbound_resource_sid: The SID of the inbound resource; either the [Call](https://www.twilio.com/docs/voice/api/call-resource) or [Message](https://www.twilio.com/docs/sms/api/message-resource). + :ivar inbound_resource_status: + :ivar inbound_resource_type: The inbound resource type. Can be [Call](https://www.twilio.com/docs/voice/api/call-resource) or [Message](https://www.twilio.com/docs/sms/api/message-resource). + :ivar inbound_resource_url: The URL of the Twilio inbound resource + :ivar outbound_participant_sid: The SID of the outbound [Participant](https://www.twilio.com/docs/proxy/api/participant)). + :ivar outbound_resource_sid: The SID of the outbound resource; either the [Call](https://www.twilio.com/docs/voice/api/call-resource) or [Message](https://www.twilio.com/docs/sms/api/message-resource). + :ivar outbound_resource_status: + :ivar outbound_resource_type: The outbound resource type. Can be: [Call](https://www.twilio.com/docs/voice/api/call-resource) or [Message](https://www.twilio.com/docs/sms/api/message-resource). + :ivar outbound_resource_url: The URL of the Twilio outbound resource. + :ivar date_created: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the Interaction was created. + :ivar date_updated: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. + :ivar url: The absolute URL of the Interaction resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + session_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.session_sid: Optional[str] = payload.get("session_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.data: Optional[str] = payload.get("data") + self.type: Optional["InteractionInstance.Type"] = payload.get("type") + self.inbound_participant_sid: Optional[str] = payload.get( + "inbound_participant_sid" + ) + self.inbound_resource_sid: Optional[str] = payload.get("inbound_resource_sid") + self.inbound_resource_status: Optional["InteractionInstance.ResourceStatus"] = ( + payload.get("inbound_resource_status") + ) + self.inbound_resource_type: Optional[str] = payload.get("inbound_resource_type") + self.inbound_resource_url: Optional[str] = payload.get("inbound_resource_url") + self.outbound_participant_sid: Optional[str] = payload.get( + "outbound_participant_sid" + ) + self.outbound_resource_sid: Optional[str] = payload.get("outbound_resource_sid") + self.outbound_resource_status: Optional[ + "InteractionInstance.ResourceStatus" + ] = payload.get("outbound_resource_status") + self.outbound_resource_type: Optional[str] = payload.get( + "outbound_resource_type" + ) + self.outbound_resource_url: Optional[str] = payload.get("outbound_resource_url") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + "sid": sid or self.sid, + } + self._context: Optional[InteractionContext] = None + + @property + def _proxy(self) -> "InteractionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InteractionContext for this InteractionInstance + """ + if self._context is None: + self._context = InteractionContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the InteractionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InteractionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "InteractionInstance": + """ + Fetch the InteractionInstance + + + :returns: The fetched InteractionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InteractionInstance": + """ + Asynchronous coroutine to fetch the InteractionInstance + + + :returns: The fetched InteractionInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InteractionContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, session_sid: str, sid: str): + """ + Initialize the InteractionContext + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the resource to fetch. + :param session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) of the resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Interaction resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Sessions/{session_sid}/Interactions/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the InteractionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InteractionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> InteractionInstance: + """ + Fetch the InteractionInstance + + + :returns: The fetched InteractionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> InteractionInstance: + """ + Asynchronous coroutine to fetch the InteractionInstance + + + :returns: The fetched InteractionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InteractionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InteractionInstance: + """ + Build an instance of InteractionInstance + + :param payload: Payload response from the API + """ + return InteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class InteractionList(ListResource): + + def __init__(self, version: Version, service_sid: str, session_sid: str): + """ + Initialize the InteractionList + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) to read the resources from. + :param session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + } + self._uri = ( + "/Services/{service_sid}/Sessions/{session_sid}/Interactions".format( + **self._solution + ) + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InteractionInstance]: + """ + Streams InteractionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InteractionInstance]: + """ + Asynchronously streams InteractionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InteractionInstance]: + """ + Lists InteractionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InteractionInstance]: + """ + Asynchronously lists InteractionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InteractionPage: + """ + Retrieve a single page of InteractionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InteractionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InteractionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InteractionPage: + """ + Asynchronously retrieve a single page of InteractionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InteractionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InteractionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> InteractionPage: + """ + Retrieve a specific page of InteractionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InteractionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InteractionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> InteractionPage: + """ + Asynchronously retrieve a specific page of InteractionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InteractionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InteractionPage(self._version, response, self._solution) + + def get(self, sid: str) -> InteractionContext: + """ + Constructs a InteractionContext + + :param sid: The Twilio-provided string that uniquely identifies the Interaction resource to fetch. + """ + return InteractionContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InteractionContext: + """ + Constructs a InteractionContext + + :param sid: The Twilio-provided string that uniquely identifies the Interaction resource to fetch. + """ + return InteractionContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/proxy/v1/service/session/participant/__init__.py b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/session/participant/__init__.py new file mode 100644 index 00000000..7ad20fcf --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/session/participant/__init__.py @@ -0,0 +1,634 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Proxy + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.proxy.v1.service.session.participant.message_interaction import ( + MessageInteractionList, +) + + +class ParticipantInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Participant resource. + :ivar session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) resource. + :ivar service_sid: The SID of the resource's parent [Service](https://www.twilio.com/docs/proxy/api/service) resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Participant resource. + :ivar friendly_name: The string that you assigned to describe the participant. This value must be 255 characters or fewer. Supports UTF-8 characters. **This value should not have PII.** + :ivar identifier: The phone number or channel identifier of the Participant. This value must be 191 characters or fewer. Supports UTF-8 characters. + :ivar proxy_identifier: The phone number or short code (masked number) of the participant's partner. The participant will call or message the partner participant at this number. + :ivar proxy_identifier_sid: The SID of the Proxy Identifier assigned to the Participant. + :ivar date_deleted: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Participant was removed from the session. + :ivar date_created: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was created. + :ivar date_updated: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. + :ivar url: The absolute URL of the Participant resource. + :ivar links: The URLs to resources related the participant. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + session_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.session_sid: Optional[str] = payload.get("session_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.identifier: Optional[str] = payload.get("identifier") + self.proxy_identifier: Optional[str] = payload.get("proxy_identifier") + self.proxy_identifier_sid: Optional[str] = payload.get("proxy_identifier_sid") + self.date_deleted: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_deleted") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + "sid": sid or self.sid, + } + self._context: Optional[ParticipantContext] = None + + @property + def _proxy(self) -> "ParticipantContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ParticipantContext for this ParticipantInstance + """ + if self._context is None: + self._context = ParticipantContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ParticipantInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ParticipantInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ParticipantInstance": + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ParticipantInstance": + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return await self._proxy.fetch_async() + + @property + def message_interactions(self) -> MessageInteractionList: + """ + Access the message_interactions + """ + return self._proxy.message_interactions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ParticipantContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, session_sid: str, sid: str): + """ + Initialize the ParticipantContext + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the resource to fetch. + :param session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) of the resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Participant resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Sessions/{session_sid}/Participants/{sid}".format( + **self._solution + ) + ) + + self._message_interactions: Optional[MessageInteractionList] = None + + def delete(self) -> bool: + """ + Deletes the ParticipantInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ParticipantInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ParticipantInstance: + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], + ) + + @property + def message_interactions(self) -> MessageInteractionList: + """ + Access the message_interactions + """ + if self._message_interactions is None: + self._message_interactions = MessageInteractionList( + self._version, + self._solution["service_sid"], + self._solution["session_sid"], + self._solution["sid"], + ) + return self._message_interactions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ParticipantPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: + """ + Build an instance of ParticipantInstance + + :param payload: Payload response from the API + """ + return ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ParticipantList(ListResource): + + def __init__(self, version: Version, service_sid: str, session_sid: str): + """ + Initialize the ParticipantList + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the resources to read. + :param session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) of the resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + } + self._uri = ( + "/Services/{service_sid}/Sessions/{session_sid}/Participants".format( + **self._solution + ) + ) + + def create( + self, + identifier: str, + friendly_name: Union[str, object] = values.unset, + proxy_identifier: Union[str, object] = values.unset, + proxy_identifier_sid: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Create the ParticipantInstance + + :param identifier: The phone number of the Participant. + :param friendly_name: The string that you assigned to describe the participant. This value must be 255 characters or fewer. **This value should not have PII.** + :param proxy_identifier: The proxy phone number to use for the Participant. If not specified, Proxy will select a number from the pool. + :param proxy_identifier_sid: The SID of the Proxy Identifier to assign to the Participant. + + :returns: The created ParticipantInstance + """ + + data = values.of( + { + "Identifier": identifier, + "FriendlyName": friendly_name, + "ProxyIdentifier": proxy_identifier, + "ProxyIdentifierSid": proxy_identifier_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + ) + + async def create_async( + self, + identifier: str, + friendly_name: Union[str, object] = values.unset, + proxy_identifier: Union[str, object] = values.unset, + proxy_identifier_sid: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronously create the ParticipantInstance + + :param identifier: The phone number of the Participant. + :param friendly_name: The string that you assigned to describe the participant. This value must be 255 characters or fewer. **This value should not have PII.** + :param proxy_identifier: The proxy phone number to use for the Participant. If not specified, Proxy will select a number from the pool. + :param proxy_identifier_sid: The SID of the Proxy Identifier to assign to the Participant. + + :returns: The created ParticipantInstance + """ + + data = values.of( + { + "Identifier": identifier, + "FriendlyName": friendly_name, + "ProxyIdentifier": proxy_identifier, + "ProxyIdentifierSid": proxy_identifier_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ParticipantInstance]: + """ + Streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ParticipantInstance]: + """ + Asynchronously streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Asynchronously lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Asynchronously retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ParticipantPage: + """ + Retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ParticipantPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ParticipantPage: + """ + Asynchronously retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ParticipantPage(self._version, response, self._solution) + + def get(self, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param sid: The Twilio-provided string that uniquely identifies the Participant resource to fetch. + """ + return ParticipantContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param sid: The Twilio-provided string that uniquely identifies the Participant resource to fetch. + """ + return ParticipantContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/proxy/v1/service/session/participant/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/session/participant/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..66547232 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/session/participant/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/proxy/v1/service/session/participant/__pycache__/message_interaction.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/session/participant/__pycache__/message_interaction.cpython-312.pyc new file mode 100644 index 00000000..f3ff1903 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/session/participant/__pycache__/message_interaction.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/proxy/v1/service/session/participant/message_interaction.py b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/session/participant/message_interaction.py new file mode 100644 index 00000000..4ffe6796 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/session/participant/message_interaction.py @@ -0,0 +1,622 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Proxy + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MessageInteractionInstance(InstanceResource): + + class ResourceStatus(object): + ACCEPTED = "accepted" + ANSWERED = "answered" + BUSY = "busy" + CANCELED = "canceled" + COMPLETED = "completed" + DELETED = "deleted" + DELIVERED = "delivered" + DELIVERY_UNKNOWN = "delivery-unknown" + FAILED = "failed" + IN_PROGRESS = "in-progress" + INITIATED = "initiated" + NO_ANSWER = "no-answer" + QUEUED = "queued" + RECEIVED = "received" + RECEIVING = "receiving" + RINGING = "ringing" + SCHEDULED = "scheduled" + SENDING = "sending" + SENT = "sent" + UNDELIVERED = "undelivered" + UNKNOWN = "unknown" + + class Type(object): + MESSAGE = "message" + VOICE = "voice" + UNKNOWN = "unknown" + + """ + :ivar sid: The unique string that we created to identify the MessageInteraction resource. + :ivar session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) resource. + :ivar service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the MessageInteraction resource. + :ivar data: A JSON string that includes the message body sent to the participant. (e.g. `{\"body\": \"hello\"}`) + :ivar type: + :ivar participant_sid: The SID of the [Participant](https://www.twilio.com/docs/proxy/api/participant) resource. + :ivar inbound_participant_sid: Always empty for created Message Interactions. + :ivar inbound_resource_sid: Always empty for created Message Interactions. + :ivar inbound_resource_status: + :ivar inbound_resource_type: Always empty for created Message Interactions. + :ivar inbound_resource_url: Always empty for created Message Interactions. + :ivar outbound_participant_sid: The SID of the outbound [Participant](https://www.twilio.com/docs/proxy/api/participant) resource. + :ivar outbound_resource_sid: The SID of the outbound [Message](https://www.twilio.com/docs/sms/api/message-resource) resource. + :ivar outbound_resource_status: + :ivar outbound_resource_type: The outbound resource type. This value is always `Message`. + :ivar outbound_resource_url: The URL of the Twilio message resource. + :ivar date_created: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was created. + :ivar date_updated: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. + :ivar url: The absolute URL of the MessageInteraction resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + session_sid: str, + participant_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.session_sid: Optional[str] = payload.get("session_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.data: Optional[str] = payload.get("data") + self.type: Optional["MessageInteractionInstance.Type"] = payload.get("type") + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.inbound_participant_sid: Optional[str] = payload.get( + "inbound_participant_sid" + ) + self.inbound_resource_sid: Optional[str] = payload.get("inbound_resource_sid") + self.inbound_resource_status: Optional[ + "MessageInteractionInstance.ResourceStatus" + ] = payload.get("inbound_resource_status") + self.inbound_resource_type: Optional[str] = payload.get("inbound_resource_type") + self.inbound_resource_url: Optional[str] = payload.get("inbound_resource_url") + self.outbound_participant_sid: Optional[str] = payload.get( + "outbound_participant_sid" + ) + self.outbound_resource_sid: Optional[str] = payload.get("outbound_resource_sid") + self.outbound_resource_status: Optional[ + "MessageInteractionInstance.ResourceStatus" + ] = payload.get("outbound_resource_status") + self.outbound_resource_type: Optional[str] = payload.get( + "outbound_resource_type" + ) + self.outbound_resource_url: Optional[str] = payload.get("outbound_resource_url") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + "participant_sid": participant_sid, + "sid": sid or self.sid, + } + self._context: Optional[MessageInteractionContext] = None + + @property + def _proxy(self) -> "MessageInteractionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MessageInteractionContext for this MessageInteractionInstance + """ + if self._context is None: + self._context = MessageInteractionContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "MessageInteractionInstance": + """ + Fetch the MessageInteractionInstance + + + :returns: The fetched MessageInteractionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MessageInteractionInstance": + """ + Asynchronous coroutine to fetch the MessageInteractionInstance + + + :returns: The fetched MessageInteractionInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MessageInteractionContext(InstanceContext): + + def __init__( + self, + version: Version, + service_sid: str, + session_sid: str, + participant_sid: str, + sid: str, + ): + """ + Initialize the MessageInteractionContext + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the resource to fetch. + :param session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) of the resource to fetch. + :param participant_sid: The SID of the [Participant](https://www.twilio.com/docs/proxy/api/participant) resource. + :param sid: The Twilio-provided string that uniquely identifies the MessageInteraction resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + "participant_sid": participant_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Sessions/{session_sid}/Participants/{participant_sid}/MessageInteractions/{sid}".format( + **self._solution + ) + + def fetch(self) -> MessageInteractionInstance: + """ + Fetch the MessageInteractionInstance + + + :returns: The fetched MessageInteractionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MessageInteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MessageInteractionInstance: + """ + Asynchronous coroutine to fetch the MessageInteractionInstance + + + :returns: The fetched MessageInteractionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MessageInteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MessageInteractionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MessageInteractionInstance: + """ + Build an instance of MessageInteractionInstance + + :param payload: Payload response from the API + """ + return MessageInteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MessageInteractionList(ListResource): + + def __init__( + self, version: Version, service_sid: str, session_sid: str, participant_sid: str + ): + """ + Initialize the MessageInteractionList + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) to read the resources from. + :param session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) to read the resources from. + :param participant_sid: The SID of the [Participant](https://www.twilio.com/docs/proxy/api/participant) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + "participant_sid": participant_sid, + } + self._uri = "/Services/{service_sid}/Sessions/{session_sid}/Participants/{participant_sid}/MessageInteractions".format( + **self._solution + ) + + def create( + self, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + ) -> MessageInteractionInstance: + """ + Create the MessageInteractionInstance + + :param body: The message to send to the participant + :param media_url: Reserved. Not currently supported. + + :returns: The created MessageInteractionInstance + """ + + data = values.of( + { + "Body": body, + "MediaUrl": serialize.map(media_url, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + ) + + async def create_async( + self, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + ) -> MessageInteractionInstance: + """ + Asynchronously create the MessageInteractionInstance + + :param body: The message to send to the participant + :param media_url: Reserved. Not currently supported. + + :returns: The created MessageInteractionInstance + """ + + data = values.of( + { + "Body": body, + "MediaUrl": serialize.map(media_url, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInteractionInstance]: + """ + Streams MessageInteractionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessageInteractionInstance]: + """ + Asynchronously streams MessageInteractionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInteractionInstance]: + """ + Lists MessageInteractionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInteractionInstance]: + """ + Asynchronously lists MessageInteractionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessageInteractionPage: + """ + Retrieve a single page of MessageInteractionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInteractionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessageInteractionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessageInteractionPage: + """ + Asynchronously retrieve a single page of MessageInteractionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInteractionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessageInteractionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MessageInteractionPage: + """ + Retrieve a specific page of MessageInteractionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInteractionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MessageInteractionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MessageInteractionPage: + """ + Asynchronously retrieve a specific page of MessageInteractionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInteractionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessageInteractionPage(self._version, response, self._solution) + + def get(self, sid: str) -> MessageInteractionContext: + """ + Constructs a MessageInteractionContext + + :param sid: The Twilio-provided string that uniquely identifies the MessageInteraction resource to fetch. + """ + return MessageInteractionContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> MessageInteractionContext: + """ + Constructs a MessageInteractionContext + + :param sid: The Twilio-provided string that uniquely identifies the MessageInteraction resource to fetch. + """ + return MessageInteractionContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/proxy/v1/service/short_code.py b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/short_code.py new file mode 100644 index 00000000..df71d4bd --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/proxy/v1/service/short_code.py @@ -0,0 +1,638 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Proxy + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ShortCodeInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the ShortCode resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ShortCode resource. + :ivar service_sid: The SID of the ShortCode resource's parent [Service](https://www.twilio.com/docs/proxy/api/service) resource. + :ivar date_created: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was created. + :ivar date_updated: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. + :ivar short_code: The short code's number. + :ivar iso_country: The ISO Country Code for the short code. + :ivar capabilities: + :ivar url: The absolute URL of the ShortCode resource. + :ivar is_reserved: Whether the short code should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.short_code: Optional[str] = payload.get("short_code") + self.iso_country: Optional[str] = payload.get("iso_country") + self.capabilities: Optional[str] = payload.get("capabilities") + self.url: Optional[str] = payload.get("url") + self.is_reserved: Optional[bool] = payload.get("is_reserved") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ShortCodeContext] = None + + @property + def _proxy(self) -> "ShortCodeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ShortCodeContext for this ShortCodeInstance + """ + if self._context is None: + self._context = ShortCodeContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ShortCodeInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ShortCodeInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ShortCodeInstance": + """ + Fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ShortCodeInstance": + """ + Asynchronous coroutine to fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + return await self._proxy.fetch_async() + + def update( + self, is_reserved: Union[bool, object] = values.unset + ) -> "ShortCodeInstance": + """ + Update the ShortCodeInstance + + :param is_reserved: Whether the short code should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The updated ShortCodeInstance + """ + return self._proxy.update( + is_reserved=is_reserved, + ) + + async def update_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> "ShortCodeInstance": + """ + Asynchronous coroutine to update the ShortCodeInstance + + :param is_reserved: Whether the short code should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The updated ShortCodeInstance + """ + return await self._proxy.update_async( + is_reserved=is_reserved, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ShortCodeContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the ShortCodeContext + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the resource to update. + :param sid: The Twilio-provided string that uniquely identifies the ShortCode resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/ShortCodes/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the ShortCodeInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ShortCodeInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ShortCodeInstance: + """ + Fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ShortCodeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ShortCodeInstance: + """ + Asynchronous coroutine to fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ShortCodeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, is_reserved: Union[bool, object] = values.unset + ) -> ShortCodeInstance: + """ + Update the ShortCodeInstance + + :param is_reserved: Whether the short code should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The updated ShortCodeInstance + """ + + data = values.of( + { + "IsReserved": serialize.boolean_to_string(is_reserved), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ShortCodeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> ShortCodeInstance: + """ + Asynchronous coroutine to update the ShortCodeInstance + + :param is_reserved: Whether the short code should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The updated ShortCodeInstance + """ + + data = values.of( + { + "IsReserved": serialize.boolean_to_string(is_reserved), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ShortCodeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ShortCodePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ShortCodeInstance: + """ + Build an instance of ShortCodeInstance + + :param payload: Payload response from the API + """ + return ShortCodeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ShortCodeList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the ShortCodeList + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/ShortCodes".format(**self._solution) + + def create(self, sid: str) -> ShortCodeInstance: + """ + Create the ShortCodeInstance + + :param sid: The SID of a Twilio [ShortCode](https://www.twilio.com/en-us/messaging/channels/sms/short-codes) resource that represents the short code you would like to assign to your Proxy Service. + + :returns: The created ShortCodeInstance + """ + + data = values.of( + { + "Sid": sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ShortCodeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async(self, sid: str) -> ShortCodeInstance: + """ + Asynchronously create the ShortCodeInstance + + :param sid: The SID of a Twilio [ShortCode](https://www.twilio.com/en-us/messaging/channels/sms/short-codes) resource that represents the short code you would like to assign to your Proxy Service. + + :returns: The created ShortCodeInstance + """ + + data = values.of( + { + "Sid": sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ShortCodeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ShortCodeInstance]: + """ + Streams ShortCodeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ShortCodeInstance]: + """ + Asynchronously streams ShortCodeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ShortCodeInstance]: + """ + Lists ShortCodeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ShortCodeInstance]: + """ + Asynchronously lists ShortCodeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ShortCodePage: + """ + Retrieve a single page of ShortCodeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ShortCodeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ShortCodePage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ShortCodePage: + """ + Asynchronously retrieve a single page of ShortCodeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ShortCodeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ShortCodePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ShortCodePage: + """ + Retrieve a specific page of ShortCodeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ShortCodeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ShortCodePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ShortCodePage: + """ + Asynchronously retrieve a specific page of ShortCodeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ShortCodeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ShortCodePage(self._version, response, self._solution) + + def get(self, sid: str) -> ShortCodeContext: + """ + Constructs a ShortCodeContext + + :param sid: The Twilio-provided string that uniquely identifies the ShortCode resource to update. + """ + return ShortCodeContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ShortCodeContext: + """ + Constructs a ShortCodeContext + + :param sid: The Twilio-provided string that uniquely identifies the ShortCode resource to update. + """ + return ShortCodeContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/routes/RoutesBase.py b/venv/Lib/site-packages/twilio/rest/routes/RoutesBase.py new file mode 100644 index 00000000..a47d67f0 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/routes/RoutesBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.routes.v2 import V2 + + +class RoutesBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Routes Domain + + :returns: Domain for Routes + """ + super().__init__(twilio, "https://routes.twilio.com") + self._v2: Optional[V2] = None + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Routes + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/routes/__init__.py b/venv/Lib/site-packages/twilio/rest/routes/__init__.py new file mode 100644 index 00000000..a559ba0d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/routes/__init__.py @@ -0,0 +1,35 @@ +from warnings import warn + +from twilio.rest.routes.RoutesBase import RoutesBase +from twilio.rest.routes.v2.phone_number import PhoneNumberList +from twilio.rest.routes.v2.sip_domain import SipDomainList +from twilio.rest.routes.v2.trunk import TrunkList + + +class Routes(RoutesBase): + @property + def phone_numbers(self) -> PhoneNumberList: + warn( + "phone_numbers is deprecated. Use v2.phone_numbers instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.phone_numbers + + @property + def sip_domains(self) -> SipDomainList: + warn( + "sip_domains is deprecated. Use v2.sip_domains instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.sip_domains + + @property + def trunks(self) -> TrunkList: + warn( + "trunks is deprecated. Use v2.trunks instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.trunks diff --git a/venv/Lib/site-packages/twilio/rest/routes/__pycache__/RoutesBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/routes/__pycache__/RoutesBase.cpython-312.pyc new file mode 100644 index 00000000..125817f8 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/routes/__pycache__/RoutesBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/routes/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/routes/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..d58e3ce3 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/routes/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/routes/v2/__init__.py b/venv/Lib/site-packages/twilio/rest/routes/v2/__init__.py new file mode 100644 index 00000000..56a140ef --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/routes/v2/__init__.py @@ -0,0 +1,59 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Routes + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.routes.v2.phone_number import PhoneNumberList +from twilio.rest.routes.v2.sip_domain import SipDomainList +from twilio.rest.routes.v2.trunk import TrunkList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Routes + + :param domain: The Twilio.routes domain + """ + super().__init__(domain, "v2") + self._phone_numbers: Optional[PhoneNumberList] = None + self._sip_domains: Optional[SipDomainList] = None + self._trunks: Optional[TrunkList] = None + + @property + def phone_numbers(self) -> PhoneNumberList: + if self._phone_numbers is None: + self._phone_numbers = PhoneNumberList(self) + return self._phone_numbers + + @property + def sip_domains(self) -> SipDomainList: + if self._sip_domains is None: + self._sip_domains = SipDomainList(self) + return self._sip_domains + + @property + def trunks(self) -> TrunkList: + if self._trunks is None: + self._trunks = TrunkList(self) + return self._trunks + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/routes/v2/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/routes/v2/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..1e574426 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/routes/v2/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/routes/v2/__pycache__/phone_number.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/routes/v2/__pycache__/phone_number.cpython-312.pyc new file mode 100644 index 00000000..ed8883e9 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/routes/v2/__pycache__/phone_number.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/routes/v2/__pycache__/sip_domain.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/routes/v2/__pycache__/sip_domain.cpython-312.pyc new file mode 100644 index 00000000..2b4e6745 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/routes/v2/__pycache__/sip_domain.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/routes/v2/__pycache__/trunk.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/routes/v2/__pycache__/trunk.cpython-312.pyc new file mode 100644 index 00000000..3502e8e2 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/routes/v2/__pycache__/trunk.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/routes/v2/phone_number.py b/venv/Lib/site-packages/twilio/rest/routes/v2/phone_number.py new file mode 100644 index 00000000..1b67509b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/routes/v2/phone_number.py @@ -0,0 +1,311 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Routes + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PhoneNumberInstance(InstanceResource): + """ + :ivar phone_number: The phone number in E.164 format + :ivar url: The absolute URL of the resource. + :ivar sid: A 34 character string that uniquely identifies the Inbound Processing Region assignments for this phone number. + :ivar account_sid: The unique SID identifier of the Account. + :ivar friendly_name: A human readable description of the Inbound Processing Region assignments for this phone number, up to 64 characters. + :ivar voice_region: The Inbound Processing Region used for this phone number for voice. + :ivar date_created: The date that this phone number was assigned an Inbound Processing Region, given in ISO 8601 format. + :ivar date_updated: The date that the Inbound Processing Region was updated for this phone number, given in ISO 8601 format. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + phone_number: Optional[str] = None, + ): + super().__init__(version) + + self.phone_number: Optional[str] = payload.get("phone_number") + self.url: Optional[str] = payload.get("url") + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.voice_region: Optional[str] = payload.get("voice_region") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "phone_number": phone_number or self.phone_number, + } + self._context: Optional[PhoneNumberContext] = None + + @property + def _proxy(self) -> "PhoneNumberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PhoneNumberContext for this PhoneNumberInstance + """ + if self._context is None: + self._context = PhoneNumberContext( + self._version, + phone_number=self._solution["phone_number"], + ) + return self._context + + def fetch(self) -> "PhoneNumberInstance": + """ + Fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PhoneNumberInstance": + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "PhoneNumberInstance": + """ + Update the PhoneNumberInstance + + :param voice_region: The Inbound Processing Region used for this phone number for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: The updated PhoneNumberInstance + """ + return self._proxy.update( + voice_region=voice_region, + friendly_name=friendly_name, + ) + + async def update_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "PhoneNumberInstance": + """ + Asynchronous coroutine to update the PhoneNumberInstance + + :param voice_region: The Inbound Processing Region used for this phone number for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: The updated PhoneNumberInstance + """ + return await self._proxy.update_async( + voice_region=voice_region, + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PhoneNumberContext(InstanceContext): + + def __init__(self, version: Version, phone_number: str): + """ + Initialize the PhoneNumberContext + + :param version: Version that contains the resource + :param phone_number: The phone number in E.164 format + """ + super().__init__(version) + + # Path Solution + self._solution = { + "phone_number": phone_number, + } + self._uri = "/PhoneNumbers/{phone_number}".format(**self._solution) + + def fetch(self) -> PhoneNumberInstance: + """ + Fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + async def fetch_async(self) -> PhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + def update( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> PhoneNumberInstance: + """ + Update the PhoneNumberInstance + + :param voice_region: The Inbound Processing Region used for this phone number for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: The updated PhoneNumberInstance + """ + + data = values.of( + { + "VoiceRegion": voice_region, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, payload, phone_number=self._solution["phone_number"] + ) + + async def update_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> PhoneNumberInstance: + """ + Asynchronous coroutine to update the PhoneNumberInstance + + :param voice_region: The Inbound Processing Region used for this phone number for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: The updated PhoneNumberInstance + """ + + data = values.of( + { + "VoiceRegion": voice_region, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, payload, phone_number=self._solution["phone_number"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PhoneNumberList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PhoneNumberList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, phone_number: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param phone_number: The phone number in E.164 format + """ + return PhoneNumberContext(self._version, phone_number=phone_number) + + def __call__(self, phone_number: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param phone_number: The phone number in E.164 format + """ + return PhoneNumberContext(self._version, phone_number=phone_number) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/routes/v2/sip_domain.py b/venv/Lib/site-packages/twilio/rest/routes/v2/sip_domain.py new file mode 100644 index 00000000..2326a5db --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/routes/v2/sip_domain.py @@ -0,0 +1,311 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Routes + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class SipDomainInstance(InstanceResource): + """ + :ivar sip_domain: + :ivar url: + :ivar sid: + :ivar account_sid: + :ivar friendly_name: + :ivar voice_region: + :ivar date_created: + :ivar date_updated: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + sip_domain: Optional[str] = None, + ): + super().__init__(version) + + self.sip_domain: Optional[str] = payload.get("sip_domain") + self.url: Optional[str] = payload.get("url") + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.voice_region: Optional[str] = payload.get("voice_region") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "sip_domain": sip_domain or self.sip_domain, + } + self._context: Optional[SipDomainContext] = None + + @property + def _proxy(self) -> "SipDomainContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SipDomainContext for this SipDomainInstance + """ + if self._context is None: + self._context = SipDomainContext( + self._version, + sip_domain=self._solution["sip_domain"], + ) + return self._context + + def fetch(self) -> "SipDomainInstance": + """ + Fetch the SipDomainInstance + + + :returns: The fetched SipDomainInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SipDomainInstance": + """ + Asynchronous coroutine to fetch the SipDomainInstance + + + :returns: The fetched SipDomainInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "SipDomainInstance": + """ + Update the SipDomainInstance + + :param voice_region: + :param friendly_name: + + :returns: The updated SipDomainInstance + """ + return self._proxy.update( + voice_region=voice_region, + friendly_name=friendly_name, + ) + + async def update_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "SipDomainInstance": + """ + Asynchronous coroutine to update the SipDomainInstance + + :param voice_region: + :param friendly_name: + + :returns: The updated SipDomainInstance + """ + return await self._proxy.update_async( + voice_region=voice_region, + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SipDomainContext(InstanceContext): + + def __init__(self, version: Version, sip_domain: str): + """ + Initialize the SipDomainContext + + :param version: Version that contains the resource + :param sip_domain: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sip_domain": sip_domain, + } + self._uri = "/SipDomains/{sip_domain}".format(**self._solution) + + def fetch(self) -> SipDomainInstance: + """ + Fetch the SipDomainInstance + + + :returns: The fetched SipDomainInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SipDomainInstance( + self._version, + payload, + sip_domain=self._solution["sip_domain"], + ) + + async def fetch_async(self) -> SipDomainInstance: + """ + Asynchronous coroutine to fetch the SipDomainInstance + + + :returns: The fetched SipDomainInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SipDomainInstance( + self._version, + payload, + sip_domain=self._solution["sip_domain"], + ) + + def update( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> SipDomainInstance: + """ + Update the SipDomainInstance + + :param voice_region: + :param friendly_name: + + :returns: The updated SipDomainInstance + """ + + data = values.of( + { + "VoiceRegion": voice_region, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SipDomainInstance( + self._version, payload, sip_domain=self._solution["sip_domain"] + ) + + async def update_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> SipDomainInstance: + """ + Asynchronous coroutine to update the SipDomainInstance + + :param voice_region: + :param friendly_name: + + :returns: The updated SipDomainInstance + """ + + data = values.of( + { + "VoiceRegion": voice_region, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SipDomainInstance( + self._version, payload, sip_domain=self._solution["sip_domain"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SipDomainList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SipDomainList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, sip_domain: str) -> SipDomainContext: + """ + Constructs a SipDomainContext + + :param sip_domain: + """ + return SipDomainContext(self._version, sip_domain=sip_domain) + + def __call__(self, sip_domain: str) -> SipDomainContext: + """ + Constructs a SipDomainContext + + :param sip_domain: + """ + return SipDomainContext(self._version, sip_domain=sip_domain) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/routes/v2/trunk.py b/venv/Lib/site-packages/twilio/rest/routes/v2/trunk.py new file mode 100644 index 00000000..f783ce92 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/routes/v2/trunk.py @@ -0,0 +1,311 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Routes + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TrunkInstance(InstanceResource): + """ + :ivar sip_trunk_domain: The absolute URL of the SIP Trunk + :ivar url: The absolute URL of the resource. + :ivar sid: A 34 character string that uniquely identifies the Inbound Processing Region assignments for this SIP Trunk. + :ivar account_sid: The unique SID identifier of the Account. + :ivar friendly_name: A human readable description of the Inbound Processing Region assignments for this SIP Trunk, up to 64 characters. + :ivar voice_region: The Inbound Processing Region used for this SIP Trunk for voice. + :ivar date_created: The date that this SIP Trunk was assigned an Inbound Processing Region, given in ISO 8601 format. + :ivar date_updated: The date that the Inbound Processing Region was updated for this SIP Trunk, given in ISO 8601 format. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + sip_trunk_domain: Optional[str] = None, + ): + super().__init__(version) + + self.sip_trunk_domain: Optional[str] = payload.get("sip_trunk_domain") + self.url: Optional[str] = payload.get("url") + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.voice_region: Optional[str] = payload.get("voice_region") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "sip_trunk_domain": sip_trunk_domain or self.sip_trunk_domain, + } + self._context: Optional[TrunkContext] = None + + @property + def _proxy(self) -> "TrunkContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TrunkContext for this TrunkInstance + """ + if self._context is None: + self._context = TrunkContext( + self._version, + sip_trunk_domain=self._solution["sip_trunk_domain"], + ) + return self._context + + def fetch(self) -> "TrunkInstance": + """ + Fetch the TrunkInstance + + + :returns: The fetched TrunkInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TrunkInstance": + """ + Asynchronous coroutine to fetch the TrunkInstance + + + :returns: The fetched TrunkInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "TrunkInstance": + """ + Update the TrunkInstance + + :param voice_region: The Inbound Processing Region used for this SIP Trunk for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: The updated TrunkInstance + """ + return self._proxy.update( + voice_region=voice_region, + friendly_name=friendly_name, + ) + + async def update_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "TrunkInstance": + """ + Asynchronous coroutine to update the TrunkInstance + + :param voice_region: The Inbound Processing Region used for this SIP Trunk for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: The updated TrunkInstance + """ + return await self._proxy.update_async( + voice_region=voice_region, + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TrunkContext(InstanceContext): + + def __init__(self, version: Version, sip_trunk_domain: str): + """ + Initialize the TrunkContext + + :param version: Version that contains the resource + :param sip_trunk_domain: The absolute URL of the SIP Trunk + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sip_trunk_domain": sip_trunk_domain, + } + self._uri = "/Trunks/{sip_trunk_domain}".format(**self._solution) + + def fetch(self) -> TrunkInstance: + """ + Fetch the TrunkInstance + + + :returns: The fetched TrunkInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TrunkInstance( + self._version, + payload, + sip_trunk_domain=self._solution["sip_trunk_domain"], + ) + + async def fetch_async(self) -> TrunkInstance: + """ + Asynchronous coroutine to fetch the TrunkInstance + + + :returns: The fetched TrunkInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TrunkInstance( + self._version, + payload, + sip_trunk_domain=self._solution["sip_trunk_domain"], + ) + + def update( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> TrunkInstance: + """ + Update the TrunkInstance + + :param voice_region: The Inbound Processing Region used for this SIP Trunk for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: The updated TrunkInstance + """ + + data = values.of( + { + "VoiceRegion": voice_region, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrunkInstance( + self._version, payload, sip_trunk_domain=self._solution["sip_trunk_domain"] + ) + + async def update_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> TrunkInstance: + """ + Asynchronous coroutine to update the TrunkInstance + + :param voice_region: The Inbound Processing Region used for this SIP Trunk for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: The updated TrunkInstance + """ + + data = values.of( + { + "VoiceRegion": voice_region, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrunkInstance( + self._version, payload, sip_trunk_domain=self._solution["sip_trunk_domain"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TrunkList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TrunkList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, sip_trunk_domain: str) -> TrunkContext: + """ + Constructs a TrunkContext + + :param sip_trunk_domain: The absolute URL of the SIP Trunk + """ + return TrunkContext(self._version, sip_trunk_domain=sip_trunk_domain) + + def __call__(self, sip_trunk_domain: str) -> TrunkContext: + """ + Constructs a TrunkContext + + :param sip_trunk_domain: The absolute URL of the SIP Trunk + """ + return TrunkContext(self._version, sip_trunk_domain=sip_trunk_domain) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/serverless/ServerlessBase.py b/venv/Lib/site-packages/twilio/rest/serverless/ServerlessBase.py new file mode 100644 index 00000000..d6e227c0 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/serverless/ServerlessBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.serverless.v1 import V1 + + +class ServerlessBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Serverless Domain + + :returns: Domain for Serverless + """ + super().__init__(twilio, "https://serverless.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Serverless + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/serverless/__init__.py b/venv/Lib/site-packages/twilio/rest/serverless/__init__.py new file mode 100644 index 00000000..a9f32edb --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/serverless/__init__.py @@ -0,0 +1,15 @@ +from warnings import warn + +from twilio.rest.serverless.ServerlessBase import ServerlessBase +from twilio.rest.serverless.v1.service import ServiceList + + +class Serverless(ServerlessBase): + @property + def services(self) -> ServiceList: + warn( + "services is deprecated. Use v1.services instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.services diff --git a/venv/Lib/site-packages/twilio/rest/serverless/__pycache__/ServerlessBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/serverless/__pycache__/ServerlessBase.cpython-312.pyc new file mode 100644 index 00000000..8167e64e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/serverless/__pycache__/ServerlessBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/serverless/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/serverless/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..bedaa71c Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/serverless/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/serverless/v1/__init__.py new file mode 100644 index 00000000..e494615c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/serverless/v1/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.serverless.v1.service import ServiceList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Serverless + + :param domain: The Twilio.serverless domain + """ + super().__init__(domain, "v1") + self._services: Optional[ServiceList] = None + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/serverless/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..463c0c22 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/serverless/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/service/__init__.py b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/__init__.py new file mode 100644 index 00000000..f6e4e584 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/__init__.py @@ -0,0 +1,742 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.serverless.v1.service.asset import AssetList +from twilio.rest.serverless.v1.service.build import BuildList +from twilio.rest.serverless.v1.service.environment import EnvironmentList +from twilio.rest.serverless.v1.service.function import FunctionList + + +class ServiceInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Service resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + :ivar friendly_name: The string that you assigned to describe the Service resource. + :ivar unique_name: A user-defined string that uniquely identifies the Service resource. It can be used in place of the Service resource's `sid` in the URL to address the Service resource. + :ivar include_credentials: Whether to inject Account credentials into a function invocation context. + :ivar ui_editable: Whether the Service resource's properties and subresources can be edited via the UI. + :ivar domain_base: The base domain name for this Service, which is a combination of the unique name and a randomly generated string. + :ivar date_created: The date and time in GMT when the Service resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Service resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Service resource. + :ivar links: The URLs of the Service's nested resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.include_credentials: Optional[bool] = payload.get("include_credentials") + self.ui_editable: Optional[bool] = payload.get("ui_editable") + self.domain_base: Optional[str] = payload.get("domain_base") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + include_credentials: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param include_credentials: Whether to inject Account credentials into a function invocation context. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param ui_editable: Whether the Service resource's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + include_credentials=include_credentials, + friendly_name=friendly_name, + ui_editable=ui_editable, + ) + + async def update_async( + self, + include_credentials: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param include_credentials: Whether to inject Account credentials into a function invocation context. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param ui_editable: Whether the Service resource's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + include_credentials=include_credentials, + friendly_name=friendly_name, + ui_editable=ui_editable, + ) + + @property + def assets(self) -> AssetList: + """ + Access the assets + """ + return self._proxy.assets + + @property + def builds(self) -> BuildList: + """ + Access the builds + """ + return self._proxy.builds + + @property + def environments(self) -> EnvironmentList: + """ + Access the environments + """ + return self._proxy.environments + + @property + def functions(self) -> FunctionList: + """ + Access the functions + """ + return self._proxy.functions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: The `sid` or `unique_name` of the Service resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._assets: Optional[AssetList] = None + self._builds: Optional[BuildList] = None + self._environments: Optional[EnvironmentList] = None + self._functions: Optional[FunctionList] = None + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + include_credentials: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param include_credentials: Whether to inject Account credentials into a function invocation context. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param ui_editable: Whether the Service resource's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "IncludeCredentials": serialize.boolean_to_string(include_credentials), + "FriendlyName": friendly_name, + "UiEditable": serialize.boolean_to_string(ui_editable), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + include_credentials: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param include_credentials: Whether to inject Account credentials into a function invocation context. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param ui_editable: Whether the Service resource's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "IncludeCredentials": serialize.boolean_to_string(include_credentials), + "FriendlyName": friendly_name, + "UiEditable": serialize.boolean_to_string(ui_editable), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def assets(self) -> AssetList: + """ + Access the assets + """ + if self._assets is None: + self._assets = AssetList( + self._version, + self._solution["sid"], + ) + return self._assets + + @property + def builds(self) -> BuildList: + """ + Access the builds + """ + if self._builds is None: + self._builds = BuildList( + self._version, + self._solution["sid"], + ) + return self._builds + + @property + def environments(self) -> EnvironmentList: + """ + Access the environments + """ + if self._environments is None: + self._environments = EnvironmentList( + self._version, + self._solution["sid"], + ) + return self._environments + + @property + def functions(self) -> FunctionList: + """ + Access the functions + """ + if self._functions is None: + self._functions = FunctionList( + self._version, + self._solution["sid"], + ) + return self._functions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def create( + self, + unique_name: str, + friendly_name: str, + include_credentials: Union[bool, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Create the ServiceInstance + + :param unique_name: A user-defined string that uniquely identifies the Service resource. It can be used as an alternative to the `sid` in the URL path to address the Service resource. This value must be 50 characters or less in length and be unique. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param include_credentials: Whether to inject Account credentials into a function invocation context. The default value is `true`. + :param ui_editable: Whether the Service's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + "IncludeCredentials": serialize.boolean_to_string(include_credentials), + "UiEditable": serialize.boolean_to_string(ui_editable), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async( + self, + unique_name: str, + friendly_name: str, + include_credentials: Union[bool, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param unique_name: A user-defined string that uniquely identifies the Service resource. It can be used as an alternative to the `sid` in the URL path to address the Service resource. This value must be 50 characters or less in length and be unique. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param include_credentials: Whether to inject Account credentials into a function invocation context. The default value is `true`. + :param ui_editable: Whether the Service's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + "IncludeCredentials": serialize.boolean_to_string(include_credentials), + "UiEditable": serialize.boolean_to_string(ui_editable), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The `sid` or `unique_name` of the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The `sid` or `unique_name` of the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/service/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..59867c16 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/service/asset/__init__.py b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/asset/__init__.py new file mode 100644 index 00000000..de68b969 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/asset/__init__.py @@ -0,0 +1,649 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.serverless.v1.service.asset.asset_version import AssetVersionList + + +class AssetInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Asset resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Asset resource. + :ivar service_sid: The SID of the Service that the Asset resource is associated with. + :ivar friendly_name: The string that you assigned to describe the Asset resource. It can be a maximum of 255 characters. + :ivar date_created: The date and time in GMT when the Asset resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Asset resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Asset resource. + :ivar links: The URLs of the Asset resource's nested resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[AssetContext] = None + + @property + def _proxy(self) -> "AssetContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AssetContext for this AssetInstance + """ + if self._context is None: + self._context = AssetContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AssetInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AssetInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AssetInstance": + """ + Fetch the AssetInstance + + + :returns: The fetched AssetInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AssetInstance": + """ + Asynchronous coroutine to fetch the AssetInstance + + + :returns: The fetched AssetInstance + """ + return await self._proxy.fetch_async() + + def update(self, friendly_name: str) -> "AssetInstance": + """ + Update the AssetInstance + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: The updated AssetInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async(self, friendly_name: str) -> "AssetInstance": + """ + Asynchronous coroutine to update the AssetInstance + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: The updated AssetInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + @property + def asset_versions(self) -> AssetVersionList: + """ + Access the asset_versions + """ + return self._proxy.asset_versions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AssetContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the AssetContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to update the Asset resource from. + :param sid: The SID that identifies the Asset resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Assets/{sid}".format(**self._solution) + + self._asset_versions: Optional[AssetVersionList] = None + + def delete(self) -> bool: + """ + Deletes the AssetInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AssetInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AssetInstance: + """ + Fetch the AssetInstance + + + :returns: The fetched AssetInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AssetInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AssetInstance: + """ + Asynchronous coroutine to fetch the AssetInstance + + + :returns: The fetched AssetInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AssetInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update(self, friendly_name: str) -> AssetInstance: + """ + Update the AssetInstance + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: The updated AssetInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AssetInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, friendly_name: str) -> AssetInstance: + """ + Asynchronous coroutine to update the AssetInstance + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: The updated AssetInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AssetInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def asset_versions(self) -> AssetVersionList: + """ + Access the asset_versions + """ + if self._asset_versions is None: + self._asset_versions = AssetVersionList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._asset_versions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AssetPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AssetInstance: + """ + Build an instance of AssetInstance + + :param payload: Payload response from the API + """ + return AssetInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AssetList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the AssetList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Asset resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Assets".format(**self._solution) + + def create(self, friendly_name: str) -> AssetInstance: + """ + Create the AssetInstance + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: The created AssetInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AssetInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async(self, friendly_name: str) -> AssetInstance: + """ + Asynchronously create the AssetInstance + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: The created AssetInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AssetInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AssetInstance]: + """ + Streams AssetInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AssetInstance]: + """ + Asynchronously streams AssetInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssetInstance]: + """ + Lists AssetInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssetInstance]: + """ + Asynchronously lists AssetInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssetPage: + """ + Retrieve a single page of AssetInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssetInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssetPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssetPage: + """ + Asynchronously retrieve a single page of AssetInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssetInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssetPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AssetPage: + """ + Retrieve a specific page of AssetInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssetInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AssetPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AssetPage: + """ + Asynchronously retrieve a specific page of AssetInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssetInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AssetPage(self._version, response, self._solution) + + def get(self, sid: str) -> AssetContext: + """ + Constructs a AssetContext + + :param sid: The SID that identifies the Asset resource to update. + """ + return AssetContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> AssetContext: + """ + Constructs a AssetContext + + :param sid: The SID that identifies the Asset resource to update. + """ + return AssetContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/service/asset/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/asset/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..9c2a2959 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/asset/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/service/asset/__pycache__/asset_version.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/asset/__pycache__/asset_version.cpython-312.pyc new file mode 100644 index 00000000..2e6020c8 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/asset/__pycache__/asset_version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/service/asset/asset_version.py b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/asset/asset_version.py new file mode 100644 index 00000000..31f85d4c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/asset/asset_version.py @@ -0,0 +1,468 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AssetVersionInstance(InstanceResource): + + class Visibility(object): + PUBLIC = "public" + PRIVATE = "private" + PROTECTED = "protected" + + """ + :ivar sid: The unique string that we created to identify the Asset Version resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Asset Version resource. + :ivar service_sid: The SID of the Service that the Asset Version resource is associated with. + :ivar asset_sid: The SID of the Asset resource that is the parent of the Asset Version. + :ivar path: The URL-friendly string by which the Asset Version can be referenced. It can be a maximum of 255 characters. All paths begin with a forward slash ('/'). If an Asset Version creation request is submitted with a path not containing a leading slash, the path will automatically be prepended with one. + :ivar visibility: + :ivar date_created: The date and time in GMT when the Asset Version resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Asset Version resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + asset_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.asset_sid: Optional[str] = payload.get("asset_sid") + self.path: Optional[str] = payload.get("path") + self.visibility: Optional["AssetVersionInstance.Visibility"] = payload.get( + "visibility" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "asset_sid": asset_sid, + "sid": sid or self.sid, + } + self._context: Optional[AssetVersionContext] = None + + @property + def _proxy(self) -> "AssetVersionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AssetVersionContext for this AssetVersionInstance + """ + if self._context is None: + self._context = AssetVersionContext( + self._version, + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "AssetVersionInstance": + """ + Fetch the AssetVersionInstance + + + :returns: The fetched AssetVersionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AssetVersionInstance": + """ + Asynchronous coroutine to fetch the AssetVersionInstance + + + :returns: The fetched AssetVersionInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AssetVersionContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, asset_sid: str, sid: str): + """ + Initialize the AssetVersionContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Asset Version resource from. + :param asset_sid: The SID of the Asset resource that is the parent of the Asset Version resource to fetch. + :param sid: The SID of the Asset Version resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "asset_sid": asset_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Assets/{asset_sid}/Versions/{sid}".format( + **self._solution + ) + + def fetch(self) -> AssetVersionInstance: + """ + Fetch the AssetVersionInstance + + + :returns: The fetched AssetVersionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AssetVersionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AssetVersionInstance: + """ + Asynchronous coroutine to fetch the AssetVersionInstance + + + :returns: The fetched AssetVersionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AssetVersionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AssetVersionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AssetVersionInstance: + """ + Build an instance of AssetVersionInstance + + :param payload: Payload response from the API + """ + return AssetVersionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AssetVersionList(ListResource): + + def __init__(self, version: Version, service_sid: str, asset_sid: str): + """ + Initialize the AssetVersionList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Asset Version resource from. + :param asset_sid: The SID of the Asset resource that is the parent of the Asset Version resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "asset_sid": asset_sid, + } + self._uri = "/Services/{service_sid}/Assets/{asset_sid}/Versions".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AssetVersionInstance]: + """ + Streams AssetVersionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AssetVersionInstance]: + """ + Asynchronously streams AssetVersionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssetVersionInstance]: + """ + Lists AssetVersionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssetVersionInstance]: + """ + Asynchronously lists AssetVersionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssetVersionPage: + """ + Retrieve a single page of AssetVersionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssetVersionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssetVersionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssetVersionPage: + """ + Asynchronously retrieve a single page of AssetVersionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssetVersionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssetVersionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AssetVersionPage: + """ + Retrieve a specific page of AssetVersionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssetVersionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AssetVersionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AssetVersionPage: + """ + Asynchronously retrieve a specific page of AssetVersionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssetVersionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AssetVersionPage(self._version, response, self._solution) + + def get(self, sid: str) -> AssetVersionContext: + """ + Constructs a AssetVersionContext + + :param sid: The SID of the Asset Version resource to fetch. + """ + return AssetVersionContext( + self._version, + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> AssetVersionContext: + """ + Constructs a AssetVersionContext + + :param sid: The SID of the Asset Version resource to fetch. + """ + return AssetVersionContext( + self._version, + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/service/build/__init__.py b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/build/__init__.py new file mode 100644 index 00000000..5a7b6b70 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/build/__init__.py @@ -0,0 +1,614 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.serverless.v1.service.build.build_status import BuildStatusList + + +class BuildInstance(InstanceResource): + + + class Runtime(object): + NODE8 = "node8" + NODE10 = "node10" + NODE12 = "node12" + NODE14 = "node14" + NODE16 = "node16" + NODE18 = "node18" + NODE20 = "node20" + NODE22 = "node22" + + class Status(object): + BUILDING = "building" + COMPLETED = "completed" + FAILED = "failed" + + """ + :ivar sid: The unique string that we created to identify the Build resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Build resource. + :ivar service_sid: The SID of the Service that the Build resource is associated with. + :ivar status: + :ivar asset_versions: The list of Asset Version resource SIDs that are included in the Build. + :ivar function_versions: The list of Function Version resource SIDs that are included in the Build. + :ivar dependencies: A list of objects that describe the Dependencies included in the Build. Each object contains the `name` and `version` of the dependency. + :ivar runtime: + :ivar date_created: The date and time in GMT when the Build resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Build resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Build resource. + :ivar links: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], service_sid: str, sid: Optional[str] = None): + super().__init__(version) + + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.status: Optional["BuildInstance.Status"] = payload.get("status") + self.asset_versions: Optional[List[Dict[str, object]]] = payload.get("asset_versions") + self.function_versions: Optional[List[Dict[str, object]]] = payload.get("function_versions") + self.dependencies: Optional[List[Dict[str, object]]] = payload.get("dependencies") + self.runtime: Optional["BuildInstance.Runtime"] = payload.get("runtime") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime(payload.get("date_created")) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime(payload.get("date_updated")) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[BuildContext] = None + + @property + def _proxy(self) -> "BuildContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BuildContext for this BuildInstance + """ + if self._context is None: + self._context = BuildContext(self._version, service_sid=self._solution['service_sid'], sid=self._solution['sid'],) + return self._context + + + def delete(self) -> bool: + """ + Deletes the BuildInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BuildInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + + def fetch(self) -> "BuildInstance": + """ + Fetch the BuildInstance + + + :returns: The fetched BuildInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BuildInstance": + """ + Asynchronous coroutine to fetch the BuildInstance + + + :returns: The fetched BuildInstance + """ + return await self._proxy.fetch_async() + + @property + def build_status(self) -> BuildStatusList: + """ + Access the build_status + """ + return self._proxy.build_status + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) + return ''.format(context) + +class BuildContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the BuildContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Build resource from. + :param sid: The SID of the Build resource to fetch. + """ + super().__init__(version) + + + # Path Solution + self._solution = { + 'service_sid': service_sid, + 'sid': sid, + } + self._uri = '/Services/{service_sid}/Builds/{sid}'.format(**self._solution) + + self._build_status: Optional[BuildStatusList] = None + + + def delete(self) -> bool: + """ + Deletes the BuildInstance + + + :returns: True if delete succeeds, False otherwise + """ + + + headers = values.of({}) + + + + return self._version.delete(method='DELETE', uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BuildInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + + + return await self._version.delete_async(method='DELETE', uri=self._uri, headers=headers) + + + def fetch(self) -> BuildInstance: + """ + Fetch the BuildInstance + + + :returns: The fetched BuildInstance + """ + + + headers = values.of({}) + + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method='GET', uri=self._uri , headers=headers) + + return BuildInstance( + self._version, + payload, + service_sid=self._solution['service_sid'], + sid=self._solution['sid'], + + ) + + async def fetch_async(self) -> BuildInstance: + """ + Asynchronous coroutine to fetch the BuildInstance + + + :returns: The fetched BuildInstance + """ + + + headers = values.of({}) + + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async(method='GET', uri=self._uri , headers=headers) + + return BuildInstance( + self._version, + payload, + service_sid=self._solution['service_sid'], + sid=self._solution['sid'], + + ) + + + @property + def build_status(self) -> BuildStatusList: + """ + Access the build_status + """ + if self._build_status is None: + self._build_status = BuildStatusList( + self._version, + self._solution['service_sid'], + self._solution['sid'], + ) + return self._build_status + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) + return ''.format(context) + + + + + + + + + +class BuildPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> BuildInstance: + """ + Build an instance of BuildInstance + + :param payload: Payload response from the API + """ + return BuildInstance(self._version, payload, service_sid=self._solution["service_sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + + + + +class BuildList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the BuildList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Build resources from. + + """ + super().__init__(version) + + + # Path Solution + self._solution = { 'service_sid': service_sid, } + self._uri = '/Services/{service_sid}/Builds'.format(**self._solution) + + + + + + def create(self, asset_versions: Union[List[str], object]=values.unset, function_versions: Union[List[str], object]=values.unset, dependencies: Union[str, object]=values.unset, runtime: Union[str, object]=values.unset) -> BuildInstance: + """ + Create the BuildInstance + + :param asset_versions: The list of Asset Version resource SIDs to include in the Build. + :param function_versions: The list of the Function Version resource SIDs to include in the Build. + :param dependencies: A list of objects that describe the Dependencies included in the Build. Each object contains the `name` and `version` of the dependency. + :param runtime: The Runtime version that will be used to run the Build resource when it is deployed. + + :returns: The created BuildInstance + """ + + data = values.of({ + 'AssetVersions': serialize.map(asset_versions, lambda e: e), + 'FunctionVersions': serialize.map(function_versions, lambda e: e), + 'Dependencies': dependencies, + 'Runtime': runtime, + }) + headers = values.of({ + 'Content-Type': 'application/x-www-form-urlencoded' + }) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + + headers["Accept"] = "application/json" + + + payload = self._version.create(method='POST', uri=self._uri, data=data, headers=headers) + + return BuildInstance(self._version, payload, service_sid=self._solution['service_sid']) + + async def create_async(self, asset_versions: Union[List[str], object]=values.unset, function_versions: Union[List[str], object]=values.unset, dependencies: Union[str, object]=values.unset, runtime: Union[str, object]=values.unset) -> BuildInstance: + """ + Asynchronously create the BuildInstance + + :param asset_versions: The list of Asset Version resource SIDs to include in the Build. + :param function_versions: The list of the Function Version resource SIDs to include in the Build. + :param dependencies: A list of objects that describe the Dependencies included in the Build. Each object contains the `name` and `version` of the dependency. + :param runtime: The Runtime version that will be used to run the Build resource when it is deployed. + + :returns: The created BuildInstance + """ + + data = values.of({ + 'AssetVersions': serialize.map(asset_versions, lambda e: e), + 'FunctionVersions': serialize.map(function_versions, lambda e: e), + 'Dependencies': dependencies, + 'Runtime': runtime, + }) + headers = values.of({ + 'Content-Type': 'application/x-www-form-urlencoded' + }) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + + headers["Accept"] = "application/json" + + + payload = await self._version.create_async(method='POST', uri=self._uri, data=data, headers=headers) + + return BuildInstance(self._version, payload, service_sid=self._solution['service_sid']) + + + def stream(self, + + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BuildInstance]: + """ + Streams BuildInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page_size=limits['page_size'] + ) + + return self._version.stream(page, limits['limit']) + + async def stream_async(self, + + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BuildInstance]: + """ + Asynchronously streams BuildInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_size=limits['page_size'] + ) + + return self._version.stream_async(page, limits['limit']) + + def list(self, + + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BuildInstance]: + """ + Lists BuildInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list(self.stream( + limit=limit, + page_size=page_size, + )) + + async def list_async(self, + + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BuildInstance]: + """ + Asynchronously lists BuildInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [record async for record in await self.stream_async( + limit=limit, + page_size=page_size, + )] + + def page(self, + + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BuildPage: + """ + Retrieve a single page of BuildInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BuildInstance + """ + data = values.of({ + 'PageToken': page_token, + 'Page': page_number, + 'PageSize': page_size, + }) + + headers = values.of({ + 'Content-Type': 'application/x-www-form-urlencoded' + }) + + + headers["Accept"] = "application/json" + + + response = self._version.page(method='GET', uri=self._uri, params=data, headers=headers) + return BuildPage(self._version, response, self._solution) + + async def page_async(self, + + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BuildPage: + """ + Asynchronously retrieve a single page of BuildInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BuildInstance + """ + data = values.of({ + 'PageToken': page_token, + 'Page': page_number, + 'PageSize': page_size, + }) + + headers = values.of({ + 'Content-Type': 'application/x-www-form-urlencoded' + }) + + + headers["Accept"] = "application/json" + + + response = await self._version.page_async(method='GET', uri=self._uri, params=data, headers=headers) + return BuildPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> BuildPage: + """ + Retrieve a specific page of BuildInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BuildInstance + """ + response = self._version.domain.twilio.request( + 'GET', + target_url + ) + return BuildPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> BuildPage: + """ + Asynchronously retrieve a specific page of BuildInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BuildInstance + """ + response = await self._version.domain.twilio.request_async( + 'GET', + target_url + ) + return BuildPage(self._version, response, self._solution) + + + + + + def get(self, sid: str) -> BuildContext: + """ + Constructs a BuildContext + + :param sid: The SID of the Build resource to fetch. + """ + return BuildContext(self._version, service_sid=self._solution['service_sid'], sid=sid) + + def __call__(self, sid: str) -> BuildContext: + """ + Constructs a BuildContext + + :param sid: The SID of the Build resource to fetch. + """ + return BuildContext(self._version, service_sid=self._solution['service_sid'], sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return '' + diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/service/build/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/build/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..f45345ea Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/build/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/service/build/__pycache__/build_status.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/build/__pycache__/build_status.cpython-312.pyc new file mode 100644 index 00000000..aeeee8eb Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/build/__pycache__/build_status.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/service/build/build_status.py b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/build/build_status.py new file mode 100644 index 00000000..e67c00e0 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/build/build_status.py @@ -0,0 +1,221 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + + +class BuildStatusInstance(InstanceResource): + + + class Status(object): + BUILDING = "building" + COMPLETED = "completed" + FAILED = "failed" + + """ + :ivar sid: The unique string that we created to identify the Build resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Build resource. + :ivar service_sid: The SID of the Service that the Build resource is associated with. + :ivar status: + :ivar url: The absolute URL of the Build Status resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], service_sid: str, sid: str): + super().__init__(version) + + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.status: Optional["BuildStatusInstance.Status"] = payload.get("status") + self.url: Optional[str] = payload.get("url") + + + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._context: Optional[BuildStatusContext] = None + + @property + def _proxy(self) -> "BuildStatusContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BuildStatusContext for this BuildStatusInstance + """ + if self._context is None: + self._context = BuildStatusContext(self._version, service_sid=self._solution['service_sid'], sid=self._solution['sid'],) + return self._context + + + def fetch(self) -> "BuildStatusInstance": + """ + Fetch the BuildStatusInstance + + + :returns: The fetched BuildStatusInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BuildStatusInstance": + """ + Asynchronous coroutine to fetch the BuildStatusInstance + + + :returns: The fetched BuildStatusInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) + return ''.format(context) + +class BuildStatusContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the BuildStatusContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Build resource from. + :param sid: The SID of the Build resource to fetch. + """ + super().__init__(version) + + + # Path Solution + self._solution = { + 'service_sid': service_sid, + 'sid': sid, + } + self._uri = '/Services/{service_sid}/Builds/{sid}/Status'.format(**self._solution) + + + + def fetch(self) -> BuildStatusInstance: + """ + Fetch the BuildStatusInstance + + + :returns: The fetched BuildStatusInstance + """ + + + headers = values.of({}) + + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method='GET', uri=self._uri , headers=headers) + + return BuildStatusInstance( + self._version, + payload, + service_sid=self._solution['service_sid'], + sid=self._solution['sid'], + + ) + + async def fetch_async(self) -> BuildStatusInstance: + """ + Asynchronous coroutine to fetch the BuildStatusInstance + + + :returns: The fetched BuildStatusInstance + """ + + + headers = values.of({}) + + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async(method='GET', uri=self._uri , headers=headers) + + return BuildStatusInstance( + self._version, + payload, + service_sid=self._solution['service_sid'], + sid=self._solution['sid'], + + ) + + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) + return ''.format(context) + + + +class BuildStatusList(ListResource): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the BuildStatusList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Build resource from. + :param sid: The SID of the Build resource to fetch. + + """ + super().__init__(version) + + + # Path Solution + self._solution = { 'service_sid': service_sid, 'sid': sid, } + + + + + def get(self) -> BuildStatusContext: + """ + Constructs a BuildStatusContext + + """ + return BuildStatusContext(self._version, service_sid=self._solution['service_sid'], sid=self._solution['sid']) + + def __call__(self) -> BuildStatusContext: + """ + Constructs a BuildStatusContext + + """ + return BuildStatusContext(self._version, service_sid=self._solution['service_sid'], sid=self._solution['sid']) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return '' + diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/service/environment/__init__.py b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/environment/__init__.py new file mode 100644 index 00000000..cdad0504 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/environment/__init__.py @@ -0,0 +1,623 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.serverless.v1.service.environment.deployment import DeploymentList +from twilio.rest.serverless.v1.service.environment.log import LogList +from twilio.rest.serverless.v1.service.environment.variable import VariableList + + +class EnvironmentInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Environment resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Environment resource. + :ivar service_sid: The SID of the Service that the Environment resource is associated with. + :ivar build_sid: The SID of the build deployed in the environment. + :ivar unique_name: A user-defined string that uniquely identifies the Environment resource. + :ivar domain_suffix: A URL-friendly name that represents the environment and forms part of the domain name. + :ivar domain_name: The domain name for all Functions and Assets deployed in the Environment, using the Service unique name, a randomly-generated Service suffix, and an optional Environment domain suffix. + :ivar date_created: The date and time in GMT when the Environment resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Environment resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Environment resource. + :ivar links: The URLs of the Environment resource's nested resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.build_sid: Optional[str] = payload.get("build_sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.domain_suffix: Optional[str] = payload.get("domain_suffix") + self.domain_name: Optional[str] = payload.get("domain_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[EnvironmentContext] = None + + @property + def _proxy(self) -> "EnvironmentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EnvironmentContext for this EnvironmentInstance + """ + if self._context is None: + self._context = EnvironmentContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the EnvironmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the EnvironmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "EnvironmentInstance": + """ + Fetch the EnvironmentInstance + + + :returns: The fetched EnvironmentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EnvironmentInstance": + """ + Asynchronous coroutine to fetch the EnvironmentInstance + + + :returns: The fetched EnvironmentInstance + """ + return await self._proxy.fetch_async() + + @property + def deployments(self) -> DeploymentList: + """ + Access the deployments + """ + return self._proxy.deployments + + @property + def logs(self) -> LogList: + """ + Access the logs + """ + return self._proxy.logs + + @property + def variables(self) -> VariableList: + """ + Access the variables + """ + return self._proxy.variables + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EnvironmentContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the EnvironmentContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Environment resource from. + :param sid: The SID of the Environment resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Environments/{sid}".format( + **self._solution + ) + + self._deployments: Optional[DeploymentList] = None + self._logs: Optional[LogList] = None + self._variables: Optional[VariableList] = None + + def delete(self) -> bool: + """ + Deletes the EnvironmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the EnvironmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> EnvironmentInstance: + """ + Fetch the EnvironmentInstance + + + :returns: The fetched EnvironmentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EnvironmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> EnvironmentInstance: + """ + Asynchronous coroutine to fetch the EnvironmentInstance + + + :returns: The fetched EnvironmentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EnvironmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def deployments(self) -> DeploymentList: + """ + Access the deployments + """ + if self._deployments is None: + self._deployments = DeploymentList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._deployments + + @property + def logs(self) -> LogList: + """ + Access the logs + """ + if self._logs is None: + self._logs = LogList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._logs + + @property + def variables(self) -> VariableList: + """ + Access the variables + """ + if self._variables is None: + self._variables = VariableList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._variables + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EnvironmentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EnvironmentInstance: + """ + Build an instance of EnvironmentInstance + + :param payload: Payload response from the API + """ + return EnvironmentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class EnvironmentList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the EnvironmentList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Environment resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Environments".format(**self._solution) + + def create( + self, unique_name: str, domain_suffix: Union[str, object] = values.unset + ) -> EnvironmentInstance: + """ + Create the EnvironmentInstance + + :param unique_name: A user-defined string that uniquely identifies the Environment resource. It can be a maximum of 100 characters. + :param domain_suffix: A URL-friendly name that represents the environment and forms part of the domain name. It can be a maximum of 16 characters. + + :returns: The created EnvironmentInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "DomainSuffix": domain_suffix, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EnvironmentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, unique_name: str, domain_suffix: Union[str, object] = values.unset + ) -> EnvironmentInstance: + """ + Asynchronously create the EnvironmentInstance + + :param unique_name: A user-defined string that uniquely identifies the Environment resource. It can be a maximum of 100 characters. + :param domain_suffix: A URL-friendly name that represents the environment and forms part of the domain name. It can be a maximum of 16 characters. + + :returns: The created EnvironmentInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "DomainSuffix": domain_suffix, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EnvironmentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EnvironmentInstance]: + """ + Streams EnvironmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EnvironmentInstance]: + """ + Asynchronously streams EnvironmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EnvironmentInstance]: + """ + Lists EnvironmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EnvironmentInstance]: + """ + Asynchronously lists EnvironmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EnvironmentPage: + """ + Retrieve a single page of EnvironmentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EnvironmentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EnvironmentPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EnvironmentPage: + """ + Asynchronously retrieve a single page of EnvironmentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EnvironmentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EnvironmentPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> EnvironmentPage: + """ + Retrieve a specific page of EnvironmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EnvironmentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EnvironmentPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> EnvironmentPage: + """ + Asynchronously retrieve a specific page of EnvironmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EnvironmentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EnvironmentPage(self._version, response, self._solution) + + def get(self, sid: str) -> EnvironmentContext: + """ + Constructs a EnvironmentContext + + :param sid: The SID of the Environment resource to fetch. + """ + return EnvironmentContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> EnvironmentContext: + """ + Constructs a EnvironmentContext + + :param sid: The SID of the Environment resource to fetch. + """ + return EnvironmentContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/service/environment/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/environment/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..1dffb7ac Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/environment/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/service/environment/__pycache__/deployment.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/environment/__pycache__/deployment.cpython-312.pyc new file mode 100644 index 00000000..55a8a261 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/environment/__pycache__/deployment.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/service/environment/__pycache__/log.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/environment/__pycache__/log.cpython-312.pyc new file mode 100644 index 00000000..0ac6578b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/environment/__pycache__/log.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/service/environment/__pycache__/variable.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/environment/__pycache__/variable.cpython-312.pyc new file mode 100644 index 00000000..fd15f7d8 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/environment/__pycache__/variable.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/service/environment/deployment.py b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/environment/deployment.py new file mode 100644 index 00000000..d28a4b8d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/environment/deployment.py @@ -0,0 +1,540 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DeploymentInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Deployment resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Deployment resource. + :ivar service_sid: The SID of the Service that the Deployment resource is associated with. + :ivar environment_sid: The SID of the Environment for the Deployment. + :ivar build_sid: The SID of the Build for the deployment. + :ivar date_created: The date and time in GMT when the Deployment resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Deployment resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Deployment resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + environment_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.environment_sid: Optional[str] = payload.get("environment_sid") + self.build_sid: Optional[str] = payload.get("build_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + "sid": sid or self.sid, + } + self._context: Optional[DeploymentContext] = None + + @property + def _proxy(self) -> "DeploymentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DeploymentContext for this DeploymentInstance + """ + if self._context is None: + self._context = DeploymentContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "DeploymentInstance": + """ + Fetch the DeploymentInstance + + + :returns: The fetched DeploymentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DeploymentInstance": + """ + Asynchronous coroutine to fetch the DeploymentInstance + + + :returns: The fetched DeploymentInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DeploymentContext(InstanceContext): + + def __init__( + self, version: Version, service_sid: str, environment_sid: str, sid: str + ): + """ + Initialize the DeploymentContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Deployment resource from. + :param environment_sid: The SID of the Environment used by the Deployment to fetch. + :param sid: The SID that identifies the Deployment resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Environments/{environment_sid}/Deployments/{sid}".format( + **self._solution + ) + + def fetch(self) -> DeploymentInstance: + """ + Fetch the DeploymentInstance + + + :returns: The fetched DeploymentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DeploymentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> DeploymentInstance: + """ + Asynchronous coroutine to fetch the DeploymentInstance + + + :returns: The fetched DeploymentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DeploymentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DeploymentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DeploymentInstance: + """ + Build an instance of DeploymentInstance + + :param payload: Payload response from the API + """ + return DeploymentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class DeploymentList(ListResource): + + def __init__(self, version: Version, service_sid: str, environment_sid: str): + """ + Initialize the DeploymentList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Deployment resources from. + :param environment_sid: The SID of the Environment used by the Deployment resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + } + self._uri = ( + "/Services/{service_sid}/Environments/{environment_sid}/Deployments".format( + **self._solution + ) + ) + + def create( + self, + build_sid: Union[str, object] = values.unset, + is_plugin: Union[bool, object] = values.unset, + ) -> DeploymentInstance: + """ + Create the DeploymentInstance + + :param build_sid: The SID of the Build for the Deployment. + :param is_plugin: Whether the Deployment is a plugin. + + :returns: The created DeploymentInstance + """ + + data = values.of( + { + "BuildSid": build_sid, + "IsPlugin": serialize.boolean_to_string(is_plugin), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DeploymentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + ) + + async def create_async( + self, + build_sid: Union[str, object] = values.unset, + is_plugin: Union[bool, object] = values.unset, + ) -> DeploymentInstance: + """ + Asynchronously create the DeploymentInstance + + :param build_sid: The SID of the Build for the Deployment. + :param is_plugin: Whether the Deployment is a plugin. + + :returns: The created DeploymentInstance + """ + + data = values.of( + { + "BuildSid": build_sid, + "IsPlugin": serialize.boolean_to_string(is_plugin), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DeploymentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DeploymentInstance]: + """ + Streams DeploymentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DeploymentInstance]: + """ + Asynchronously streams DeploymentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DeploymentInstance]: + """ + Lists DeploymentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DeploymentInstance]: + """ + Asynchronously lists DeploymentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DeploymentPage: + """ + Retrieve a single page of DeploymentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DeploymentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DeploymentPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DeploymentPage: + """ + Asynchronously retrieve a single page of DeploymentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DeploymentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DeploymentPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DeploymentPage: + """ + Retrieve a specific page of DeploymentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DeploymentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DeploymentPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DeploymentPage: + """ + Asynchronously retrieve a specific page of DeploymentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DeploymentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DeploymentPage(self._version, response, self._solution) + + def get(self, sid: str) -> DeploymentContext: + """ + Constructs a DeploymentContext + + :param sid: The SID that identifies the Deployment resource to fetch. + """ + return DeploymentContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> DeploymentContext: + """ + Constructs a DeploymentContext + + :param sid: The SID that identifies the Deployment resource to fetch. + """ + return DeploymentContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/service/environment/log.py b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/environment/log.py new file mode 100644 index 00000000..a3c9a6c2 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/environment/log.py @@ -0,0 +1,538 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class LogInstance(InstanceResource): + + class Level(object): + INFO = "info" + WARN = "warn" + ERROR = "error" + + """ + :ivar sid: The unique string that we created to identify the Log resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Log resource. + :ivar service_sid: The SID of the Service that the Log resource is associated with. + :ivar environment_sid: The SID of the environment in which the log occurred. + :ivar build_sid: The SID of the build that corresponds to the log. + :ivar deployment_sid: The SID of the deployment that corresponds to the log. + :ivar function_sid: The SID of the function whose invocation produced the log. + :ivar request_sid: The SID of the request associated with the log. + :ivar level: + :ivar message: The log message. + :ivar date_created: The date and time in GMT when the Log resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Log resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + environment_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.environment_sid: Optional[str] = payload.get("environment_sid") + self.build_sid: Optional[str] = payload.get("build_sid") + self.deployment_sid: Optional[str] = payload.get("deployment_sid") + self.function_sid: Optional[str] = payload.get("function_sid") + self.request_sid: Optional[str] = payload.get("request_sid") + self.level: Optional["LogInstance.Level"] = payload.get("level") + self.message: Optional[str] = payload.get("message") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + "sid": sid or self.sid, + } + self._context: Optional[LogContext] = None + + @property + def _proxy(self) -> "LogContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: LogContext for this LogInstance + """ + if self._context is None: + self._context = LogContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "LogInstance": + """ + Fetch the LogInstance + + + :returns: The fetched LogInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "LogInstance": + """ + Asynchronous coroutine to fetch the LogInstance + + + :returns: The fetched LogInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class LogContext(InstanceContext): + + def __init__( + self, version: Version, service_sid: str, environment_sid: str, sid: str + ): + """ + Initialize the LogContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Log resource from. + :param environment_sid: The SID of the environment with the Log resource to fetch. + :param sid: The SID of the Log resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Environments/{environment_sid}/Logs/{sid}".format( + **self._solution + ) + ) + + def fetch(self) -> LogInstance: + """ + Fetch the LogInstance + + + :returns: The fetched LogInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return LogInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> LogInstance: + """ + Asynchronous coroutine to fetch the LogInstance + + + :returns: The fetched LogInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return LogInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class LogPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> LogInstance: + """ + Build an instance of LogInstance + + :param payload: Payload response from the API + """ + return LogInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class LogList(ListResource): + + def __init__(self, version: Version, service_sid: str, environment_sid: str): + """ + Initialize the LogList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Log resource from. + :param environment_sid: The SID of the environment with the Log resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + } + self._uri = ( + "/Services/{service_sid}/Environments/{environment_sid}/Logs".format( + **self._solution + ) + ) + + def stream( + self, + function_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[LogInstance]: + """ + Streams LogInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str function_sid: The SID of the function whose invocation produced the Log resources to read. + :param datetime start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param datetime end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + function_sid=function_sid, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + function_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[LogInstance]: + """ + Asynchronously streams LogInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str function_sid: The SID of the function whose invocation produced the Log resources to read. + :param datetime start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param datetime end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + function_sid=function_sid, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + function_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[LogInstance]: + """ + Lists LogInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str function_sid: The SID of the function whose invocation produced the Log resources to read. + :param datetime start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param datetime end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + function_sid=function_sid, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + function_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[LogInstance]: + """ + Asynchronously lists LogInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str function_sid: The SID of the function whose invocation produced the Log resources to read. + :param datetime start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param datetime end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + function_sid=function_sid, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + function_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> LogPage: + """ + Retrieve a single page of LogInstance records from the API. + Request is executed immediately + + :param function_sid: The SID of the function whose invocation produced the Log resources to read. + :param start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of LogInstance + """ + data = values.of( + { + "FunctionSid": function_sid, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LogPage(self._version, response, self._solution) + + async def page_async( + self, + function_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> LogPage: + """ + Asynchronously retrieve a single page of LogInstance records from the API. + Request is executed immediately + + :param function_sid: The SID of the function whose invocation produced the Log resources to read. + :param start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of LogInstance + """ + data = values.of( + { + "FunctionSid": function_sid, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LogPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> LogPage: + """ + Retrieve a specific page of LogInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of LogInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return LogPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> LogPage: + """ + Asynchronously retrieve a specific page of LogInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of LogInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return LogPage(self._version, response, self._solution) + + def get(self, sid: str) -> LogContext: + """ + Constructs a LogContext + + :param sid: The SID of the Log resource to fetch. + """ + return LogContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> LogContext: + """ + Constructs a LogContext + + :param sid: The SID of the Log resource to fetch. + """ + return LogContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/service/environment/variable.py b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/environment/variable.py new file mode 100644 index 00000000..fbc6b48a --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/environment/variable.py @@ -0,0 +1,690 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class VariableInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Variable resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Variable resource. + :ivar service_sid: The SID of the Service that the Variable resource is associated with. + :ivar environment_sid: The SID of the Environment in which the Variable exists. + :ivar key: A string by which the Variable resource can be referenced. + :ivar value: A string that contains the actual value of the Variable. + :ivar date_created: The date and time in GMT when the Variable resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Variable resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Variable resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + environment_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.environment_sid: Optional[str] = payload.get("environment_sid") + self.key: Optional[str] = payload.get("key") + self.value: Optional[str] = payload.get("value") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + "sid": sid or self.sid, + } + self._context: Optional[VariableContext] = None + + @property + def _proxy(self) -> "VariableContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: VariableContext for this VariableInstance + """ + if self._context is None: + self._context = VariableContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the VariableInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the VariableInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "VariableInstance": + """ + Fetch the VariableInstance + + + :returns: The fetched VariableInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "VariableInstance": + """ + Asynchronous coroutine to fetch the VariableInstance + + + :returns: The fetched VariableInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> "VariableInstance": + """ + Update the VariableInstance + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: The updated VariableInstance + """ + return self._proxy.update( + key=key, + value=value, + ) + + async def update_async( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> "VariableInstance": + """ + Asynchronous coroutine to update the VariableInstance + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: The updated VariableInstance + """ + return await self._proxy.update_async( + key=key, + value=value, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class VariableContext(InstanceContext): + + def __init__( + self, version: Version, service_sid: str, environment_sid: str, sid: str + ): + """ + Initialize the VariableContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to update the Variable resource under. + :param environment_sid: The SID of the Environment with the Variable resource to update. + :param sid: The SID of the Variable resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Environments/{environment_sid}/Variables/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the VariableInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the VariableInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> VariableInstance: + """ + Fetch the VariableInstance + + + :returns: The fetched VariableInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> VariableInstance: + """ + Asynchronous coroutine to fetch the VariableInstance + + + :returns: The fetched VariableInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> VariableInstance: + """ + Update the VariableInstance + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: The updated VariableInstance + """ + + data = values.of( + { + "Key": key, + "Value": value, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> VariableInstance: + """ + Asynchronous coroutine to update the VariableInstance + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: The updated VariableInstance + """ + + data = values.of( + { + "Key": key, + "Value": value, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class VariablePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> VariableInstance: + """ + Build an instance of VariableInstance + + :param payload: Payload response from the API + """ + return VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class VariableList(ListResource): + + def __init__(self, version: Version, service_sid: str, environment_sid: str): + """ + Initialize the VariableList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Variable resources from. + :param environment_sid: The SID of the Environment with the Variable resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + } + self._uri = ( + "/Services/{service_sid}/Environments/{environment_sid}/Variables".format( + **self._solution + ) + ) + + def create(self, key: str, value: str) -> VariableInstance: + """ + Create the VariableInstance + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: The created VariableInstance + """ + + data = values.of( + { + "Key": key, + "Value": value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + ) + + async def create_async(self, key: str, value: str) -> VariableInstance: + """ + Asynchronously create the VariableInstance + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: The created VariableInstance + """ + + data = values.of( + { + "Key": key, + "Value": value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[VariableInstance]: + """ + Streams VariableInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[VariableInstance]: + """ + Asynchronously streams VariableInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[VariableInstance]: + """ + Lists VariableInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[VariableInstance]: + """ + Asynchronously lists VariableInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> VariablePage: + """ + Retrieve a single page of VariableInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of VariableInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return VariablePage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> VariablePage: + """ + Asynchronously retrieve a single page of VariableInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of VariableInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return VariablePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> VariablePage: + """ + Retrieve a specific page of VariableInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of VariableInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return VariablePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> VariablePage: + """ + Asynchronously retrieve a specific page of VariableInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of VariableInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return VariablePage(self._version, response, self._solution) + + def get(self, sid: str) -> VariableContext: + """ + Constructs a VariableContext + + :param sid: The SID of the Variable resource to update. + """ + return VariableContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> VariableContext: + """ + Constructs a VariableContext + + :param sid: The SID of the Variable resource to update. + """ + return VariableContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/service/function/__init__.py b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/function/__init__.py new file mode 100644 index 00000000..7697587e --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/function/__init__.py @@ -0,0 +1,651 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.serverless.v1.service.function.function_version import ( + FunctionVersionList, +) + + +class FunctionInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Function resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Function resource. + :ivar service_sid: The SID of the Service that the Function resource is associated with. + :ivar friendly_name: The string that you assigned to describe the Function resource. It can be a maximum of 255 characters. + :ivar date_created: The date and time in GMT when the Function resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Function resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Function resource. + :ivar links: The URLs of nested resources of the Function resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[FunctionContext] = None + + @property + def _proxy(self) -> "FunctionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FunctionContext for this FunctionInstance + """ + if self._context is None: + self._context = FunctionContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the FunctionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FunctionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "FunctionInstance": + """ + Fetch the FunctionInstance + + + :returns: The fetched FunctionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FunctionInstance": + """ + Asynchronous coroutine to fetch the FunctionInstance + + + :returns: The fetched FunctionInstance + """ + return await self._proxy.fetch_async() + + def update(self, friendly_name: str) -> "FunctionInstance": + """ + Update the FunctionInstance + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: The updated FunctionInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async(self, friendly_name: str) -> "FunctionInstance": + """ + Asynchronous coroutine to update the FunctionInstance + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: The updated FunctionInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + @property + def function_versions(self) -> FunctionVersionList: + """ + Access the function_versions + """ + return self._proxy.function_versions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FunctionContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the FunctionContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to update the Function resource from. + :param sid: The SID of the Function resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Functions/{sid}".format(**self._solution) + + self._function_versions: Optional[FunctionVersionList] = None + + def delete(self) -> bool: + """ + Deletes the FunctionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FunctionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> FunctionInstance: + """ + Fetch the FunctionInstance + + + :returns: The fetched FunctionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FunctionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> FunctionInstance: + """ + Asynchronous coroutine to fetch the FunctionInstance + + + :returns: The fetched FunctionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FunctionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update(self, friendly_name: str) -> FunctionInstance: + """ + Update the FunctionInstance + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: The updated FunctionInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FunctionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, friendly_name: str) -> FunctionInstance: + """ + Asynchronous coroutine to update the FunctionInstance + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: The updated FunctionInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FunctionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def function_versions(self) -> FunctionVersionList: + """ + Access the function_versions + """ + if self._function_versions is None: + self._function_versions = FunctionVersionList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._function_versions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FunctionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> FunctionInstance: + """ + Build an instance of FunctionInstance + + :param payload: Payload response from the API + """ + return FunctionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class FunctionList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the FunctionList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Function resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Functions".format(**self._solution) + + def create(self, friendly_name: str) -> FunctionInstance: + """ + Create the FunctionInstance + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: The created FunctionInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FunctionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async(self, friendly_name: str) -> FunctionInstance: + """ + Asynchronously create the FunctionInstance + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: The created FunctionInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FunctionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FunctionInstance]: + """ + Streams FunctionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FunctionInstance]: + """ + Asynchronously streams FunctionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FunctionInstance]: + """ + Lists FunctionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FunctionInstance]: + """ + Asynchronously lists FunctionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FunctionPage: + """ + Retrieve a single page of FunctionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FunctionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FunctionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FunctionPage: + """ + Asynchronously retrieve a single page of FunctionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FunctionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FunctionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> FunctionPage: + """ + Retrieve a specific page of FunctionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FunctionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return FunctionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> FunctionPage: + """ + Asynchronously retrieve a specific page of FunctionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FunctionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return FunctionPage(self._version, response, self._solution) + + def get(self, sid: str) -> FunctionContext: + """ + Constructs a FunctionContext + + :param sid: The SID of the Function resource to update. + """ + return FunctionContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> FunctionContext: + """ + Constructs a FunctionContext + + :param sid: The SID of the Function resource to update. + """ + return FunctionContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/service/function/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/function/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..123aae1a Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/function/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/service/function/function_version/__init__.py b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/function/function_version/__init__.py new file mode 100644 index 00000000..88b66620 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/function/function_version/__init__.py @@ -0,0 +1,498 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.serverless.v1.service.function.function_version.function_version_content import ( + FunctionVersionContentList, +) + + +class FunctionVersionInstance(InstanceResource): + + class Visibility(object): + PUBLIC = "public" + PRIVATE = "private" + PROTECTED = "protected" + + """ + :ivar sid: The unique string that we created to identify the Function Version resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Function Version resource. + :ivar service_sid: The SID of the Service that the Function Version resource is associated with. + :ivar function_sid: The SID of the Function resource that is the parent of the Function Version resource. + :ivar path: The URL-friendly string by which the Function Version resource can be referenced. It can be a maximum of 255 characters. All paths begin with a forward slash ('/'). If a Function Version creation request is submitted with a path not containing a leading slash, the path will automatically be prepended with one. + :ivar visibility: + :ivar date_created: The date and time in GMT when the Function Version resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Function Version resource. + :ivar links: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + function_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.function_sid: Optional[str] = payload.get("function_sid") + self.path: Optional[str] = payload.get("path") + self.visibility: Optional["FunctionVersionInstance.Visibility"] = payload.get( + "visibility" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "function_sid": function_sid, + "sid": sid or self.sid, + } + self._context: Optional[FunctionVersionContext] = None + + @property + def _proxy(self) -> "FunctionVersionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FunctionVersionContext for this FunctionVersionInstance + """ + if self._context is None: + self._context = FunctionVersionContext( + self._version, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "FunctionVersionInstance": + """ + Fetch the FunctionVersionInstance + + + :returns: The fetched FunctionVersionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FunctionVersionInstance": + """ + Asynchronous coroutine to fetch the FunctionVersionInstance + + + :returns: The fetched FunctionVersionInstance + """ + return await self._proxy.fetch_async() + + @property + def function_version_content(self) -> FunctionVersionContentList: + """ + Access the function_version_content + """ + return self._proxy.function_version_content + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FunctionVersionContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, function_sid: str, sid: str): + """ + Initialize the FunctionVersionContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Function Version resource from. + :param function_sid: The SID of the function that is the parent of the Function Version resource to fetch. + :param sid: The SID of the Function Version resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "function_sid": function_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Functions/{function_sid}/Versions/{sid}".format( + **self._solution + ) + ) + + self._function_version_content: Optional[FunctionVersionContentList] = None + + def fetch(self) -> FunctionVersionInstance: + """ + Fetch the FunctionVersionInstance + + + :returns: The fetched FunctionVersionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FunctionVersionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> FunctionVersionInstance: + """ + Asynchronous coroutine to fetch the FunctionVersionInstance + + + :returns: The fetched FunctionVersionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FunctionVersionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) + + @property + def function_version_content(self) -> FunctionVersionContentList: + """ + Access the function_version_content + """ + if self._function_version_content is None: + self._function_version_content = FunctionVersionContentList( + self._version, + self._solution["service_sid"], + self._solution["function_sid"], + self._solution["sid"], + ) + return self._function_version_content + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FunctionVersionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> FunctionVersionInstance: + """ + Build an instance of FunctionVersionInstance + + :param payload: Payload response from the API + """ + return FunctionVersionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class FunctionVersionList(ListResource): + + def __init__(self, version: Version, service_sid: str, function_sid: str): + """ + Initialize the FunctionVersionList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Function Version resources from. + :param function_sid: The SID of the function that is the parent of the Function Version resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "function_sid": function_sid, + } + self._uri = "/Services/{service_sid}/Functions/{function_sid}/Versions".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FunctionVersionInstance]: + """ + Streams FunctionVersionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FunctionVersionInstance]: + """ + Asynchronously streams FunctionVersionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FunctionVersionInstance]: + """ + Lists FunctionVersionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FunctionVersionInstance]: + """ + Asynchronously lists FunctionVersionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FunctionVersionPage: + """ + Retrieve a single page of FunctionVersionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FunctionVersionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FunctionVersionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FunctionVersionPage: + """ + Asynchronously retrieve a single page of FunctionVersionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FunctionVersionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FunctionVersionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> FunctionVersionPage: + """ + Retrieve a specific page of FunctionVersionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FunctionVersionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return FunctionVersionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> FunctionVersionPage: + """ + Asynchronously retrieve a specific page of FunctionVersionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FunctionVersionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return FunctionVersionPage(self._version, response, self._solution) + + def get(self, sid: str) -> FunctionVersionContext: + """ + Constructs a FunctionVersionContext + + :param sid: The SID of the Function Version resource to fetch. + """ + return FunctionVersionContext( + self._version, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> FunctionVersionContext: + """ + Constructs a FunctionVersionContext + + :param sid: The SID of the Function Version resource to fetch. + """ + return FunctionVersionContext( + self._version, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/service/function/function_version/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/function/function_version/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..5655acf2 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/function/function_version/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/service/function/function_version/__pycache__/function_version_content.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/function/function_version/__pycache__/function_version_content.cpython-312.pyc new file mode 100644 index 00000000..911f6688 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/function/function_version/__pycache__/function_version_content.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/serverless/v1/service/function/function_version/function_version_content.py b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/function/function_version/function_version_content.py new file mode 100644 index 00000000..f16833da --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/serverless/v1/service/function/function_version/function_version_content.py @@ -0,0 +1,234 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class FunctionVersionContentInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Function Version resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Function Version resource. + :ivar service_sid: The SID of the Service that the Function Version resource is associated with. + :ivar function_sid: The SID of the Function that is the parent of the Function Version. + :ivar content: The content of the Function Version resource. + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + function_sid: str, + sid: str, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.function_sid: Optional[str] = payload.get("function_sid") + self.content: Optional[str] = payload.get("content") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "function_sid": function_sid, + "sid": sid, + } + self._context: Optional[FunctionVersionContentContext] = None + + @property + def _proxy(self) -> "FunctionVersionContentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FunctionVersionContentContext for this FunctionVersionContentInstance + """ + if self._context is None: + self._context = FunctionVersionContentContext( + self._version, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "FunctionVersionContentInstance": + """ + Fetch the FunctionVersionContentInstance + + + :returns: The fetched FunctionVersionContentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FunctionVersionContentInstance": + """ + Asynchronous coroutine to fetch the FunctionVersionContentInstance + + + :returns: The fetched FunctionVersionContentInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class FunctionVersionContentContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, function_sid: str, sid: str): + """ + Initialize the FunctionVersionContentContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Function Version content from. + :param function_sid: The SID of the Function that is the parent of the Function Version content to fetch. + :param sid: The SID of the Function Version content to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "function_sid": function_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Functions/{function_sid}/Versions/{sid}/Content".format( + **self._solution + ) + + def fetch(self) -> FunctionVersionContentInstance: + """ + Fetch the FunctionVersionContentInstance + + + :returns: The fetched FunctionVersionContentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FunctionVersionContentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> FunctionVersionContentInstance: + """ + Asynchronous coroutine to fetch the FunctionVersionContentInstance + + + :returns: The fetched FunctionVersionContentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FunctionVersionContentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FunctionVersionContentList(ListResource): + + def __init__(self, version: Version, service_sid: str, function_sid: str, sid: str): + """ + Initialize the FunctionVersionContentList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Function Version content from. + :param function_sid: The SID of the Function that is the parent of the Function Version content to fetch. + :param sid: The SID of the Function Version content to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "function_sid": function_sid, + "sid": sid, + } + + def get(self) -> FunctionVersionContentContext: + """ + Constructs a FunctionVersionContentContext + + """ + return FunctionVersionContentContext( + self._version, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) + + def __call__(self) -> FunctionVersionContentContext: + """ + Constructs a FunctionVersionContentContext + + """ + return FunctionVersionContentContext( + self._version, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/studio/StudioBase.py b/venv/Lib/site-packages/twilio/rest/studio/StudioBase.py new file mode 100644 index 00000000..3b218775 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/studio/StudioBase.py @@ -0,0 +1,55 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.studio.v1 import V1 +from twilio.rest.studio.v2 import V2 + + +class StudioBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Studio Domain + + :returns: Domain for Studio + """ + super().__init__(twilio, "https://studio.twilio.com") + self._v1: Optional[V1] = None + self._v2: Optional[V2] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Studio + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Studio + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/studio/__init__.py b/venv/Lib/site-packages/twilio/rest/studio/__init__.py new file mode 100644 index 00000000..986e6942 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/studio/__init__.py @@ -0,0 +1,25 @@ +from warnings import warn + +from twilio.rest.studio.StudioBase import StudioBase +from twilio.rest.studio.v2.flow import FlowList +from twilio.rest.studio.v2.flow_validate import FlowValidateList + + +class Studio(StudioBase): + @property + def flows(self) -> FlowList: + warn( + "flows is deprecated. Use v2.flows instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.flows + + @property + def flow_validate(self) -> FlowValidateList: + warn( + "flow_validate is deprecated. Use v2.flow_validate instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.flow_validate diff --git a/venv/Lib/site-packages/twilio/rest/studio/__pycache__/StudioBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/studio/__pycache__/StudioBase.cpython-312.pyc new file mode 100644 index 00000000..d1673f32 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/studio/__pycache__/StudioBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/studio/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/studio/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..ea628299 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/studio/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/studio/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/studio/v1/__init__.py new file mode 100644 index 00000000..8ab7d71b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/studio/v1/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.studio.v1.flow import FlowList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Studio + + :param domain: The Twilio.studio domain + """ + super().__init__(domain, "v1") + self._flows: Optional[FlowList] = None + + @property + def flows(self) -> FlowList: + if self._flows is None: + self._flows = FlowList(self) + return self._flows + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/studio/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/studio/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..72e017a1 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/studio/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/studio/v1/flow/__init__.py b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/__init__.py new file mode 100644 index 00000000..533c1a45 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/__init__.py @@ -0,0 +1,513 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.studio.v1.flow.engagement import EngagementList +from twilio.rest.studio.v1.flow.execution import ExecutionList + + +class FlowInstance(InstanceResource): + + class Status(object): + DRAFT = "draft" + PUBLISHED = "published" + + """ + :ivar sid: The unique string that we created to identify the Flow resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flow resource. + :ivar friendly_name: The string that you assigned to describe the Flow. + :ivar status: + :ivar version: The latest version number of the Flow's definition. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of the Flow's nested resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["FlowInstance.Status"] = payload.get("status") + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[FlowContext] = None + + @property + def _proxy(self) -> "FlowContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FlowContext for this FlowInstance + """ + if self._context is None: + self._context = FlowContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the FlowInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FlowInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "FlowInstance": + """ + Fetch the FlowInstance + + + :returns: The fetched FlowInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FlowInstance": + """ + Asynchronous coroutine to fetch the FlowInstance + + + :returns: The fetched FlowInstance + """ + return await self._proxy.fetch_async() + + @property + def engagements(self) -> EngagementList: + """ + Access the engagements + """ + return self._proxy.engagements + + @property + def executions(self) -> ExecutionList: + """ + Access the executions + """ + return self._proxy.executions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FlowContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the FlowContext + + :param version: Version that contains the resource + :param sid: The SID of the Flow resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Flows/{sid}".format(**self._solution) + + self._engagements: Optional[EngagementList] = None + self._executions: Optional[ExecutionList] = None + + def delete(self) -> bool: + """ + Deletes the FlowInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FlowInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> FlowInstance: + """ + Fetch the FlowInstance + + + :returns: The fetched FlowInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> FlowInstance: + """ + Asynchronous coroutine to fetch the FlowInstance + + + :returns: The fetched FlowInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + @property + def engagements(self) -> EngagementList: + """ + Access the engagements + """ + if self._engagements is None: + self._engagements = EngagementList( + self._version, + self._solution["sid"], + ) + return self._engagements + + @property + def executions(self) -> ExecutionList: + """ + Access the executions + """ + if self._executions is None: + self._executions = ExecutionList( + self._version, + self._solution["sid"], + ) + return self._executions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FlowPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> FlowInstance: + """ + Build an instance of FlowInstance + + :param payload: Payload response from the API + """ + return FlowInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class FlowList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the FlowList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Flows" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FlowInstance]: + """ + Streams FlowInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FlowInstance]: + """ + Asynchronously streams FlowInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FlowInstance]: + """ + Lists FlowInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FlowInstance]: + """ + Asynchronously lists FlowInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FlowPage: + """ + Retrieve a single page of FlowInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FlowInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FlowPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FlowPage: + """ + Asynchronously retrieve a single page of FlowInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FlowInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FlowPage(self._version, response) + + def get_page(self, target_url: str) -> FlowPage: + """ + Retrieve a specific page of FlowInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FlowInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return FlowPage(self._version, response) + + async def get_page_async(self, target_url: str) -> FlowPage: + """ + Asynchronously retrieve a specific page of FlowInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FlowInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return FlowPage(self._version, response) + + def get(self, sid: str) -> FlowContext: + """ + Constructs a FlowContext + + :param sid: The SID of the Flow resource to fetch. + """ + return FlowContext(self._version, sid=sid) + + def __call__(self, sid: str) -> FlowContext: + """ + Constructs a FlowContext + + :param sid: The SID of the Flow resource to fetch. + """ + return FlowContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/studio/v1/flow/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..c375d234 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/studio/v1/flow/engagement/__init__.py b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/engagement/__init__.py new file mode 100644 index 00000000..759d9250 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/engagement/__init__.py @@ -0,0 +1,612 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.studio.v1.flow.engagement.engagement_context import ( + EngagementContextList, +) +from twilio.rest.studio.v1.flow.engagement.step import StepList + + +class EngagementInstance(InstanceResource): + + class Status(object): + ACTIVE = "active" + ENDED = "ended" + + """ + :ivar sid: The unique string that we created to identify the Engagement resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Engagement resource. + :ivar flow_sid: The SID of the Flow. + :ivar contact_sid: The SID of the Contact. + :ivar contact_channel_address: The phone number, SIP address or Client identifier that triggered this Engagement. Phone numbers are in E.164 format (+16175551212). SIP addresses are formatted as `name@company.com`. Client identifiers are formatted `client:name`. + :ivar context: The current state of the execution flow. As your flow executes, we save the state in a flow context. Your widgets can access the data in the flow context as variables, either in configuration fields or in text areas as variable substitution. + :ivar status: + :ivar date_created: The date and time in GMT when the Engagement was created in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Engagement was updated in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of the Engagement's nested resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.contact_sid: Optional[str] = payload.get("contact_sid") + self.contact_channel_address: Optional[str] = payload.get( + "contact_channel_address" + ) + self.context: Optional[Dict[str, object]] = payload.get("context") + self.status: Optional["EngagementInstance.Status"] = payload.get("status") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "flow_sid": flow_sid, + "sid": sid or self.sid, + } + self._context: Optional[EngagementContext] = None + + @property + def _proxy(self) -> "EngagementContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EngagementContext for this EngagementInstance + """ + if self._context is None: + self._context = EngagementContext( + self._version, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the EngagementInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the EngagementInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "EngagementInstance": + """ + Fetch the EngagementInstance + + + :returns: The fetched EngagementInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EngagementInstance": + """ + Asynchronous coroutine to fetch the EngagementInstance + + + :returns: The fetched EngagementInstance + """ + return await self._proxy.fetch_async() + + @property + def engagement_context(self) -> EngagementContextList: + """ + Access the engagement_context + """ + return self._proxy.engagement_context + + @property + def steps(self) -> StepList: + """ + Access the steps + """ + return self._proxy.steps + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EngagementContext(InstanceContext): + + def __init__(self, version: Version, flow_sid: str, sid: str): + """ + Initialize the EngagementContext + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow. + :param sid: The SID of the Engagement resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "sid": sid, + } + self._uri = "/Flows/{flow_sid}/Engagements/{sid}".format(**self._solution) + + self._engagement_context: Optional[EngagementContextList] = None + self._steps: Optional[StepList] = None + + def delete(self) -> bool: + """ + Deletes the EngagementInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the EngagementInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> EngagementInstance: + """ + Fetch the EngagementInstance + + + :returns: The fetched EngagementInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EngagementInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> EngagementInstance: + """ + Asynchronous coroutine to fetch the EngagementInstance + + + :returns: The fetched EngagementInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EngagementInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + @property + def engagement_context(self) -> EngagementContextList: + """ + Access the engagement_context + """ + if self._engagement_context is None: + self._engagement_context = EngagementContextList( + self._version, + self._solution["flow_sid"], + self._solution["sid"], + ) + return self._engagement_context + + @property + def steps(self) -> StepList: + """ + Access the steps + """ + if self._steps is None: + self._steps = StepList( + self._version, + self._solution["flow_sid"], + self._solution["sid"], + ) + return self._steps + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EngagementPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EngagementInstance: + """ + Build an instance of EngagementInstance + + :param payload: Payload response from the API + """ + return EngagementInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class EngagementList(ListResource): + + def __init__(self, version: Version, flow_sid: str): + """ + Initialize the EngagementList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow to read Engagements from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + } + self._uri = "/Flows/{flow_sid}/Engagements".format(**self._solution) + + def create( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> EngagementInstance: + """ + Create the EngagementInstance + + :param to: The Contact phone number to start a Studio Flow Engagement, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow Engagement. Available as variable `{{flow.channel.address}}` + :param parameters: A JSON string we will add to your flow's context and that you can access as variables inside your flow. For example, if you pass in `Parameters={'name':'Zeke'}` then inside a widget you can reference the variable `{{flow.data.name}}` which will return the string 'Zeke'. Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode your JSON string. + + :returns: The created EngagementInstance + """ + + data = values.of( + { + "To": to, + "From": from_, + "Parameters": serialize.object(parameters), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EngagementInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + async def create_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> EngagementInstance: + """ + Asynchronously create the EngagementInstance + + :param to: The Contact phone number to start a Studio Flow Engagement, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow Engagement. Available as variable `{{flow.channel.address}}` + :param parameters: A JSON string we will add to your flow's context and that you can access as variables inside your flow. For example, if you pass in `Parameters={'name':'Zeke'}` then inside a widget you can reference the variable `{{flow.data.name}}` which will return the string 'Zeke'. Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode your JSON string. + + :returns: The created EngagementInstance + """ + + data = values.of( + { + "To": to, + "From": from_, + "Parameters": serialize.object(parameters), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EngagementInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EngagementInstance]: + """ + Streams EngagementInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EngagementInstance]: + """ + Asynchronously streams EngagementInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EngagementInstance]: + """ + Lists EngagementInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EngagementInstance]: + """ + Asynchronously lists EngagementInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EngagementPage: + """ + Retrieve a single page of EngagementInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EngagementInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EngagementPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EngagementPage: + """ + Asynchronously retrieve a single page of EngagementInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EngagementInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EngagementPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> EngagementPage: + """ + Retrieve a specific page of EngagementInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EngagementInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EngagementPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> EngagementPage: + """ + Asynchronously retrieve a specific page of EngagementInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EngagementInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EngagementPage(self._version, response, self._solution) + + def get(self, sid: str) -> EngagementContext: + """ + Constructs a EngagementContext + + :param sid: The SID of the Engagement resource to fetch. + """ + return EngagementContext( + self._version, flow_sid=self._solution["flow_sid"], sid=sid + ) + + def __call__(self, sid: str) -> EngagementContext: + """ + Constructs a EngagementContext + + :param sid: The SID of the Engagement resource to fetch. + """ + return EngagementContext( + self._version, flow_sid=self._solution["flow_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/studio/v1/flow/engagement/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/engagement/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..2078902e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/engagement/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/studio/v1/flow/engagement/__pycache__/engagement_context.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/engagement/__pycache__/engagement_context.cpython-312.pyc new file mode 100644 index 00000000..0c82482b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/engagement/__pycache__/engagement_context.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/studio/v1/flow/engagement/engagement_context.py b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/engagement/engagement_context.py new file mode 100644 index 00000000..73161011 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/engagement/engagement_context.py @@ -0,0 +1,219 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class EngagementContextInstance(InstanceResource): + """ + :ivar account_sid: The SID of the Account. + :ivar context: As your flow executes, we save the state in what's called the Flow Context. Any data in the flow context can be accessed by your widgets as variables, either in configuration fields or in text areas as variable substitution. + :ivar engagement_sid: The SID of the Engagement. + :ivar flow_sid: The SID of the Flow. + :ivar url: The URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + engagement_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.context: Optional[Dict[str, object]] = payload.get("context") + self.engagement_sid: Optional[str] = payload.get("engagement_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + } + self._context: Optional[EngagementContextContext] = None + + @property + def _proxy(self) -> "EngagementContextContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EngagementContextContext for this EngagementContextInstance + """ + if self._context is None: + self._context = EngagementContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + ) + return self._context + + def fetch(self) -> "EngagementContextInstance": + """ + Fetch the EngagementContextInstance + + + :returns: The fetched EngagementContextInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EngagementContextInstance": + """ + Asynchronous coroutine to fetch the EngagementContextInstance + + + :returns: The fetched EngagementContextInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EngagementContextContext(InstanceContext): + + def __init__(self, version: Version, flow_sid: str, engagement_sid: str): + """ + Initialize the EngagementContextContext + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow. + :param engagement_sid: The SID of the Engagement. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + } + self._uri = "/Flows/{flow_sid}/Engagements/{engagement_sid}/Context".format( + **self._solution + ) + + def fetch(self) -> EngagementContextInstance: + """ + Fetch the EngagementContextInstance + + + :returns: The fetched EngagementContextInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EngagementContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + ) + + async def fetch_async(self) -> EngagementContextInstance: + """ + Asynchronous coroutine to fetch the EngagementContextInstance + + + :returns: The fetched EngagementContextInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EngagementContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EngagementContextList(ListResource): + + def __init__(self, version: Version, flow_sid: str, engagement_sid: str): + """ + Initialize the EngagementContextList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow. + :param engagement_sid: The SID of the Engagement. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + } + + def get(self) -> EngagementContextContext: + """ + Constructs a EngagementContextContext + + """ + return EngagementContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + ) + + def __call__(self) -> EngagementContextContext: + """ + Constructs a EngagementContextContext + + """ + return EngagementContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/studio/v1/flow/engagement/step/__init__.py b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/engagement/step/__init__.py new file mode 100644 index 00000000..a5017c33 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/engagement/step/__init__.py @@ -0,0 +1,496 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.studio.v1.flow.engagement.step.step_context import StepContextList + + +class StepInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Step resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Step resource. + :ivar flow_sid: The SID of the Flow. + :ivar engagement_sid: The SID of the Engagement. + :ivar name: The event that caused the Flow to transition to the Step. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar parent_step_sid: The SID of the parent Step. + :ivar transitioned_from: The Widget that preceded the Widget for the Step. + :ivar transitioned_to: The Widget that will follow the Widget for the Step. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + engagement_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.engagement_sid: Optional[str] = payload.get("engagement_sid") + self.name: Optional[str] = payload.get("name") + self.context: Optional[Dict[str, object]] = payload.get("context") + self.parent_step_sid: Optional[str] = payload.get("parent_step_sid") + self.transitioned_from: Optional[str] = payload.get("transitioned_from") + self.transitioned_to: Optional[str] = payload.get("transitioned_to") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + "sid": sid or self.sid, + } + self._context: Optional[StepContext] = None + + @property + def _proxy(self) -> "StepContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: StepContext for this StepInstance + """ + if self._context is None: + self._context = StepContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "StepInstance": + """ + Fetch the StepInstance + + + :returns: The fetched StepInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "StepInstance": + """ + Asynchronous coroutine to fetch the StepInstance + + + :returns: The fetched StepInstance + """ + return await self._proxy.fetch_async() + + @property + def step_context(self) -> StepContextList: + """ + Access the step_context + """ + return self._proxy.step_context + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class StepContext(InstanceContext): + + def __init__(self, version: Version, flow_sid: str, engagement_sid: str, sid: str): + """ + Initialize the StepContext + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to fetch. + :param engagement_sid: The SID of the Engagement with the Step to fetch. + :param sid: The SID of the Step resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + "sid": sid, + } + self._uri = "/Flows/{flow_sid}/Engagements/{engagement_sid}/Steps/{sid}".format( + **self._solution + ) + + self._step_context: Optional[StepContextList] = None + + def fetch(self) -> StepInstance: + """ + Fetch the StepInstance + + + :returns: The fetched StepInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return StepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> StepInstance: + """ + Asynchronous coroutine to fetch the StepInstance + + + :returns: The fetched StepInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return StepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + sid=self._solution["sid"], + ) + + @property + def step_context(self) -> StepContextList: + """ + Access the step_context + """ + if self._step_context is None: + self._step_context = StepContextList( + self._version, + self._solution["flow_sid"], + self._solution["engagement_sid"], + self._solution["sid"], + ) + return self._step_context + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class StepPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> StepInstance: + """ + Build an instance of StepInstance + + :param payload: Payload response from the API + """ + return StepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class StepList(ListResource): + + def __init__(self, version: Version, flow_sid: str, engagement_sid: str): + """ + Initialize the StepList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to read. + :param engagement_sid: The SID of the Engagement with the Step to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + } + self._uri = "/Flows/{flow_sid}/Engagements/{engagement_sid}/Steps".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[StepInstance]: + """ + Streams StepInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[StepInstance]: + """ + Asynchronously streams StepInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[StepInstance]: + """ + Lists StepInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[StepInstance]: + """ + Asynchronously lists StepInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> StepPage: + """ + Retrieve a single page of StepInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of StepInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return StepPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> StepPage: + """ + Asynchronously retrieve a single page of StepInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of StepInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return StepPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> StepPage: + """ + Retrieve a specific page of StepInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of StepInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return StepPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> StepPage: + """ + Asynchronously retrieve a specific page of StepInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of StepInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return StepPage(self._version, response, self._solution) + + def get(self, sid: str) -> StepContext: + """ + Constructs a StepContext + + :param sid: The SID of the Step resource to fetch. + """ + return StepContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> StepContext: + """ + Constructs a StepContext + + :param sid: The SID of the Step resource to fetch. + """ + return StepContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/studio/v1/flow/engagement/step/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/engagement/step/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..22ed98ca Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/engagement/step/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/studio/v1/flow/engagement/step/__pycache__/step_context.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/engagement/step/__pycache__/step_context.cpython-312.pyc new file mode 100644 index 00000000..b3da6fc3 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/engagement/step/__pycache__/step_context.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/studio/v1/flow/engagement/step/step_context.py b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/engagement/step/step_context.py new file mode 100644 index 00000000..6b299ebe --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/engagement/step/step_context.py @@ -0,0 +1,236 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class StepContextInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the StepContext resource. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar engagement_sid: The SID of the Engagement. + :ivar flow_sid: The SID of the Flow. + :ivar step_sid: The SID of the Step the context is associated with. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + engagement_sid: str, + step_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.context: Optional[Dict[str, object]] = payload.get("context") + self.engagement_sid: Optional[str] = payload.get("engagement_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.step_sid: Optional[str] = payload.get("step_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + "step_sid": step_sid, + } + self._context: Optional[StepContextContext] = None + + @property + def _proxy(self) -> "StepContextContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: StepContextContext for this StepContextInstance + """ + if self._context is None: + self._context = StepContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + step_sid=self._solution["step_sid"], + ) + return self._context + + def fetch(self) -> "StepContextInstance": + """ + Fetch the StepContextInstance + + + :returns: The fetched StepContextInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "StepContextInstance": + """ + Asynchronous coroutine to fetch the StepContextInstance + + + :returns: The fetched StepContextInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class StepContextContext(InstanceContext): + + def __init__( + self, version: Version, flow_sid: str, engagement_sid: str, step_sid: str + ): + """ + Initialize the StepContextContext + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to fetch. + :param engagement_sid: The SID of the Engagement with the Step to fetch. + :param step_sid: The SID of the Step to fetch + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + "step_sid": step_sid, + } + self._uri = "/Flows/{flow_sid}/Engagements/{engagement_sid}/Steps/{step_sid}/Context".format( + **self._solution + ) + + def fetch(self) -> StepContextInstance: + """ + Fetch the StepContextInstance + + + :returns: The fetched StepContextInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return StepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + step_sid=self._solution["step_sid"], + ) + + async def fetch_async(self) -> StepContextInstance: + """ + Asynchronous coroutine to fetch the StepContextInstance + + + :returns: The fetched StepContextInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return StepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + step_sid=self._solution["step_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class StepContextList(ListResource): + + def __init__( + self, version: Version, flow_sid: str, engagement_sid: str, step_sid: str + ): + """ + Initialize the StepContextList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to fetch. + :param engagement_sid: The SID of the Engagement with the Step to fetch. + :param step_sid: The SID of the Step to fetch + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + "step_sid": step_sid, + } + + def get(self) -> StepContextContext: + """ + Constructs a StepContextContext + + """ + return StepContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + step_sid=self._solution["step_sid"], + ) + + def __call__(self) -> StepContextContext: + """ + Constructs a StepContextContext + + """ + return StepContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + step_sid=self._solution["step_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/studio/v1/flow/execution/__init__.py b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/execution/__init__.py new file mode 100644 index 00000000..624b3817 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/execution/__init__.py @@ -0,0 +1,740 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.studio.v1.flow.execution.execution_context import ExecutionContextList +from twilio.rest.studio.v1.flow.execution.execution_step import ExecutionStepList + + +class ExecutionInstance(InstanceResource): + + class Status(object): + ACTIVE = "active" + ENDED = "ended" + + """ + :ivar sid: The unique string that we created to identify the Execution resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Execution resource. + :ivar flow_sid: The SID of the Flow. + :ivar contact_sid: The SID of the Contact. + :ivar contact_channel_address: The phone number, SIP address or Client identifier that triggered the Execution. Phone numbers are in E.164 format (e.g. +16175551212). SIP addresses are formatted as `name@company.com`. Client identifiers are formatted `client:name`. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar status: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of nested resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.contact_sid: Optional[str] = payload.get("contact_sid") + self.contact_channel_address: Optional[str] = payload.get( + "contact_channel_address" + ) + self.context: Optional[Dict[str, object]] = payload.get("context") + self.status: Optional["ExecutionInstance.Status"] = payload.get("status") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "flow_sid": flow_sid, + "sid": sid or self.sid, + } + self._context: Optional[ExecutionContext] = None + + @property + def _proxy(self) -> "ExecutionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ExecutionContext for this ExecutionInstance + """ + if self._context is None: + self._context = ExecutionContext( + self._version, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ExecutionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ExecutionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ExecutionInstance": + """ + Fetch the ExecutionInstance + + + :returns: The fetched ExecutionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ExecutionInstance": + """ + Asynchronous coroutine to fetch the ExecutionInstance + + + :returns: The fetched ExecutionInstance + """ + return await self._proxy.fetch_async() + + def update(self, status: "ExecutionInstance.Status") -> "ExecutionInstance": + """ + Update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + return self._proxy.update( + status=status, + ) + + async def update_async( + self, status: "ExecutionInstance.Status" + ) -> "ExecutionInstance": + """ + Asynchronous coroutine to update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + return await self._proxy.update_async( + status=status, + ) + + @property + def execution_context(self) -> ExecutionContextList: + """ + Access the execution_context + """ + return self._proxy.execution_context + + @property + def steps(self) -> ExecutionStepList: + """ + Access the steps + """ + return self._proxy.steps + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ExecutionContext(InstanceContext): + + def __init__(self, version: Version, flow_sid: str, sid: str): + """ + Initialize the ExecutionContext + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Execution resources to update. + :param sid: The SID of the Execution resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "sid": sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{sid}".format(**self._solution) + + self._execution_context: Optional[ExecutionContextList] = None + self._steps: Optional[ExecutionStepList] = None + + def delete(self) -> bool: + """ + Deletes the ExecutionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ExecutionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ExecutionInstance: + """ + Fetch the ExecutionInstance + + + :returns: The fetched ExecutionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ExecutionInstance: + """ + Asynchronous coroutine to fetch the ExecutionInstance + + + :returns: The fetched ExecutionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + def update(self, status: "ExecutionInstance.Status") -> ExecutionInstance: + """ + Update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, status: "ExecutionInstance.Status" + ) -> ExecutionInstance: + """ + Asynchronous coroutine to update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + @property + def execution_context(self) -> ExecutionContextList: + """ + Access the execution_context + """ + if self._execution_context is None: + self._execution_context = ExecutionContextList( + self._version, + self._solution["flow_sid"], + self._solution["sid"], + ) + return self._execution_context + + @property + def steps(self) -> ExecutionStepList: + """ + Access the steps + """ + if self._steps is None: + self._steps = ExecutionStepList( + self._version, + self._solution["flow_sid"], + self._solution["sid"], + ) + return self._steps + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ExecutionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ExecutionInstance: + """ + Build an instance of ExecutionInstance + + :param payload: Payload response from the API + """ + return ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ExecutionList(ListResource): + + def __init__(self, version: Version, flow_sid: str): + """ + Initialize the ExecutionList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Execution resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + } + self._uri = "/Flows/{flow_sid}/Executions".format(**self._solution) + + def create( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ExecutionInstance: + """ + Create the ExecutionInstance + + :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. + :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. + + :returns: The created ExecutionInstance + """ + + data = values.of( + { + "To": to, + "From": from_, + "Parameters": serialize.object(parameters), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + async def create_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ExecutionInstance: + """ + Asynchronously create the ExecutionInstance + + :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. + :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. + + :returns: The created ExecutionInstance + """ + + data = values.of( + { + "To": to, + "From": from_, + "Parameters": serialize.object(parameters), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + def stream( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ExecutionInstance]: + """ + Streams ExecutionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + date_created_from=date_created_from, + date_created_to=date_created_to, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ExecutionInstance]: + """ + Asynchronously streams ExecutionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + date_created_from=date_created_from, + date_created_to=date_created_to, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExecutionInstance]: + """ + Lists ExecutionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + date_created_from=date_created_from, + date_created_to=date_created_to, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExecutionInstance]: + """ + Asynchronously lists ExecutionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + date_created_from=date_created_from, + date_created_to=date_created_to, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ExecutionPage: + """ + Retrieve a single page of ExecutionInstance records from the API. + Request is executed immediately + + :param date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ExecutionInstance + """ + data = values.of( + { + "DateCreatedFrom": serialize.iso8601_datetime(date_created_from), + "DateCreatedTo": serialize.iso8601_datetime(date_created_to), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExecutionPage(self._version, response, self._solution) + + async def page_async( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ExecutionPage: + """ + Asynchronously retrieve a single page of ExecutionInstance records from the API. + Request is executed immediately + + :param date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ExecutionInstance + """ + data = values.of( + { + "DateCreatedFrom": serialize.iso8601_datetime(date_created_from), + "DateCreatedTo": serialize.iso8601_datetime(date_created_to), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExecutionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ExecutionPage: + """ + Retrieve a specific page of ExecutionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ExecutionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ExecutionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ExecutionPage: + """ + Asynchronously retrieve a specific page of ExecutionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ExecutionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ExecutionPage(self._version, response, self._solution) + + def get(self, sid: str) -> ExecutionContext: + """ + Constructs a ExecutionContext + + :param sid: The SID of the Execution resource to update. + """ + return ExecutionContext( + self._version, flow_sid=self._solution["flow_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ExecutionContext: + """ + Constructs a ExecutionContext + + :param sid: The SID of the Execution resource to update. + """ + return ExecutionContext( + self._version, flow_sid=self._solution["flow_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/studio/v1/flow/execution/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/execution/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..a53370d0 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/execution/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/studio/v1/flow/execution/__pycache__/execution_context.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/execution/__pycache__/execution_context.cpython-312.pyc new file mode 100644 index 00000000..e8ec4e34 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/execution/__pycache__/execution_context.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/studio/v1/flow/execution/execution_context.py b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/execution/execution_context.py new file mode 100644 index 00000000..0841a9ef --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/execution/execution_context.py @@ -0,0 +1,219 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ExecutionContextInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionContext resource. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar flow_sid: The SID of the Flow. + :ivar execution_sid: The SID of the context's Execution resource. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + execution_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.context: Optional[Dict[str, object]] = payload.get("context") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.execution_sid: Optional[str] = payload.get("execution_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } + self._context: Optional[ExecutionContextContext] = None + + @property + def _proxy(self) -> "ExecutionContextContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ExecutionContextContext for this ExecutionContextInstance + """ + if self._context is None: + self._context = ExecutionContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + return self._context + + def fetch(self) -> "ExecutionContextInstance": + """ + Fetch the ExecutionContextInstance + + + :returns: The fetched ExecutionContextInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ExecutionContextInstance": + """ + Asynchronous coroutine to fetch the ExecutionContextInstance + + + :returns: The fetched ExecutionContextInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ExecutionContextContext(InstanceContext): + + def __init__(self, version: Version, flow_sid: str, execution_sid: str): + """ + Initialize the ExecutionContextContext + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Execution context to fetch. + :param execution_sid: The SID of the Execution context to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Context".format( + **self._solution + ) + + def fetch(self) -> ExecutionContextInstance: + """ + Fetch the ExecutionContextInstance + + + :returns: The fetched ExecutionContextInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ExecutionContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + + async def fetch_async(self) -> ExecutionContextInstance: + """ + Asynchronous coroutine to fetch the ExecutionContextInstance + + + :returns: The fetched ExecutionContextInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ExecutionContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ExecutionContextList(ListResource): + + def __init__(self, version: Version, flow_sid: str, execution_sid: str): + """ + Initialize the ExecutionContextList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Execution context to fetch. + :param execution_sid: The SID of the Execution context to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } + + def get(self) -> ExecutionContextContext: + """ + Constructs a ExecutionContextContext + + """ + return ExecutionContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + + def __call__(self) -> ExecutionContextContext: + """ + Constructs a ExecutionContextContext + + """ + return ExecutionContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/studio/v1/flow/execution/execution_step/__init__.py b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/execution/execution_step/__init__.py new file mode 100644 index 00000000..50a1e237 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/execution/execution_step/__init__.py @@ -0,0 +1,498 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context import ( + ExecutionStepContextList, +) + + +class ExecutionStepInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the ExecutionStep resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionStep resource. + :ivar flow_sid: The SID of the Flow. + :ivar execution_sid: The SID of the Step's Execution resource. + :ivar parent_step_sid: This field shows the Step SID of the Widget in the parent Flow that started the Subflow. If this Step is not part of a Subflow execution, the value is null. + :ivar name: The event that caused the Flow to transition to the Step. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar transitioned_from: The Widget that preceded the Widget for the Step. + :ivar transitioned_to: The Widget that will follow the Widget for the Step. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + execution_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.execution_sid: Optional[str] = payload.get("execution_sid") + self.parent_step_sid: Optional[str] = payload.get("parent_step_sid") + self.name: Optional[str] = payload.get("name") + self.context: Optional[Dict[str, object]] = payload.get("context") + self.transitioned_from: Optional[str] = payload.get("transitioned_from") + self.transitioned_to: Optional[str] = payload.get("transitioned_to") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "sid": sid or self.sid, + } + self._context: Optional[ExecutionStepContext] = None + + @property + def _proxy(self) -> "ExecutionStepContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ExecutionStepContext for this ExecutionStepInstance + """ + if self._context is None: + self._context = ExecutionStepContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "ExecutionStepInstance": + """ + Fetch the ExecutionStepInstance + + + :returns: The fetched ExecutionStepInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ExecutionStepInstance": + """ + Asynchronous coroutine to fetch the ExecutionStepInstance + + + :returns: The fetched ExecutionStepInstance + """ + return await self._proxy.fetch_async() + + @property + def step_context(self) -> ExecutionStepContextList: + """ + Access the step_context + """ + return self._proxy.step_context + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ExecutionStepContext(InstanceContext): + + def __init__(self, version: Version, flow_sid: str, execution_sid: str, sid: str): + """ + Initialize the ExecutionStepContext + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to fetch. + :param execution_sid: The SID of the Execution resource with the Step to fetch. + :param sid: The SID of the ExecutionStep resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "sid": sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Steps/{sid}".format( + **self._solution + ) + + self._step_context: Optional[ExecutionStepContextList] = None + + def fetch(self) -> ExecutionStepInstance: + """ + Fetch the ExecutionStepInstance + + + :returns: The fetched ExecutionStepInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ExecutionStepInstance: + """ + Asynchronous coroutine to fetch the ExecutionStepInstance + + + :returns: The fetched ExecutionStepInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], + ) + + @property + def step_context(self) -> ExecutionStepContextList: + """ + Access the step_context + """ + if self._step_context is None: + self._step_context = ExecutionStepContextList( + self._version, + self._solution["flow_sid"], + self._solution["execution_sid"], + self._solution["sid"], + ) + return self._step_context + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ExecutionStepPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ExecutionStepInstance: + """ + Build an instance of ExecutionStepInstance + + :param payload: Payload response from the API + """ + return ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ExecutionStepList(ListResource): + + def __init__(self, version: Version, flow_sid: str, execution_sid: str): + """ + Initialize the ExecutionStepList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Steps to read. + :param execution_sid: The SID of the Execution with the Steps to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Steps".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ExecutionStepInstance]: + """ + Streams ExecutionStepInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ExecutionStepInstance]: + """ + Asynchronously streams ExecutionStepInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExecutionStepInstance]: + """ + Lists ExecutionStepInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExecutionStepInstance]: + """ + Asynchronously lists ExecutionStepInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ExecutionStepPage: + """ + Retrieve a single page of ExecutionStepInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ExecutionStepInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExecutionStepPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ExecutionStepPage: + """ + Asynchronously retrieve a single page of ExecutionStepInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ExecutionStepInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExecutionStepPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ExecutionStepPage: + """ + Retrieve a specific page of ExecutionStepInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ExecutionStepInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ExecutionStepPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ExecutionStepPage: + """ + Asynchronously retrieve a specific page of ExecutionStepInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ExecutionStepInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ExecutionStepPage(self._version, response, self._solution) + + def get(self, sid: str) -> ExecutionStepContext: + """ + Constructs a ExecutionStepContext + + :param sid: The SID of the ExecutionStep resource to fetch. + """ + return ExecutionStepContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> ExecutionStepContext: + """ + Constructs a ExecutionStepContext + + :param sid: The SID of the ExecutionStep resource to fetch. + """ + return ExecutionStepContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/studio/v1/flow/execution/execution_step/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/execution/execution_step/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..bdd29cda Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/execution/execution_step/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/studio/v1/flow/execution/execution_step/__pycache__/execution_step_context.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/execution/execution_step/__pycache__/execution_step_context.cpython-312.pyc new file mode 100644 index 00000000..0461d36c Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/execution/execution_step/__pycache__/execution_step_context.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/studio/v1/flow/execution/execution_step/execution_step_context.py b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/execution/execution_step/execution_step_context.py new file mode 100644 index 00000000..78249a95 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/studio/v1/flow/execution/execution_step/execution_step_context.py @@ -0,0 +1,236 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ExecutionStepContextInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionStepContext resource. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar execution_sid: The SID of the context's Execution resource. + :ivar flow_sid: The SID of the Flow. + :ivar step_sid: The SID of the Step that the context is associated with. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + execution_sid: str, + step_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.context: Optional[Dict[str, object]] = payload.get("context") + self.execution_sid: Optional[str] = payload.get("execution_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.step_sid: Optional[str] = payload.get("step_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "step_sid": step_sid, + } + self._context: Optional[ExecutionStepContextContext] = None + + @property + def _proxy(self) -> "ExecutionStepContextContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ExecutionStepContextContext for this ExecutionStepContextInstance + """ + if self._context is None: + self._context = ExecutionStepContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + return self._context + + def fetch(self) -> "ExecutionStepContextInstance": + """ + Fetch the ExecutionStepContextInstance + + + :returns: The fetched ExecutionStepContextInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ExecutionStepContextInstance": + """ + Asynchronous coroutine to fetch the ExecutionStepContextInstance + + + :returns: The fetched ExecutionStepContextInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ExecutionStepContextContext(InstanceContext): + + def __init__( + self, version: Version, flow_sid: str, execution_sid: str, step_sid: str + ): + """ + Initialize the ExecutionStepContextContext + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to fetch. + :param execution_sid: The SID of the Execution resource with the Step to fetch. + :param step_sid: The SID of the Step to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "step_sid": step_sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Steps/{step_sid}/Context".format( + **self._solution + ) + + def fetch(self) -> ExecutionStepContextInstance: + """ + Fetch the ExecutionStepContextInstance + + + :returns: The fetched ExecutionStepContextInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ExecutionStepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + + async def fetch_async(self) -> ExecutionStepContextInstance: + """ + Asynchronous coroutine to fetch the ExecutionStepContextInstance + + + :returns: The fetched ExecutionStepContextInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ExecutionStepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ExecutionStepContextList(ListResource): + + def __init__( + self, version: Version, flow_sid: str, execution_sid: str, step_sid: str + ): + """ + Initialize the ExecutionStepContextList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to fetch. + :param execution_sid: The SID of the Execution resource with the Step to fetch. + :param step_sid: The SID of the Step to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "step_sid": step_sid, + } + + def get(self) -> ExecutionStepContextContext: + """ + Constructs a ExecutionStepContextContext + + """ + return ExecutionStepContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + + def __call__(self) -> ExecutionStepContextContext: + """ + Constructs a ExecutionStepContextContext + + """ + return ExecutionStepContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/studio/v2/__init__.py b/venv/Lib/site-packages/twilio/rest/studio/v2/__init__.py new file mode 100644 index 00000000..83ccc8e0 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/studio/v2/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.studio.v2.flow import FlowList +from twilio.rest.studio.v2.flow_validate import FlowValidateList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Studio + + :param domain: The Twilio.studio domain + """ + super().__init__(domain, "v2") + self._flows: Optional[FlowList] = None + self._flow_validate: Optional[FlowValidateList] = None + + @property + def flows(self) -> FlowList: + if self._flows is None: + self._flows = FlowList(self) + return self._flows + + @property + def flow_validate(self) -> FlowValidateList: + if self._flow_validate is None: + self._flow_validate = FlowValidateList(self) + return self._flow_validate + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/studio/v2/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/studio/v2/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..b044b47e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/studio/v2/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/studio/v2/__pycache__/flow_validate.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/studio/v2/__pycache__/flow_validate.cpython-312.pyc new file mode 100644 index 00000000..dba1aae7 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/studio/v2/__pycache__/flow_validate.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/studio/v2/flow/__init__.py b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/__init__.py new file mode 100644 index 00000000..b4c542fd --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/__init__.py @@ -0,0 +1,746 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.studio.v2.flow.execution import ExecutionList +from twilio.rest.studio.v2.flow.flow_revision import FlowRevisionList +from twilio.rest.studio.v2.flow.flow_test_user import FlowTestUserList + + +class FlowInstance(InstanceResource): + + class Status(object): + DRAFT = "draft" + PUBLISHED = "published" + + """ + :ivar sid: The unique string that we created to identify the Flow resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flow resource. + :ivar friendly_name: The string that you assigned to describe the Flow. + :ivar definition: JSON representation of flow definition. + :ivar status: + :ivar revision: The latest revision number of the Flow's definition. + :ivar commit_message: Description of change made in the revision. + :ivar valid: Boolean if the flow definition is valid. + :ivar errors: List of error in the flow definition. + :ivar warnings: List of warnings in the flow definition. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar webhook_url: + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of the Flow's nested resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.definition: Optional[Dict[str, object]] = payload.get("definition") + self.status: Optional["FlowInstance.Status"] = payload.get("status") + self.revision: Optional[int] = deserialize.integer(payload.get("revision")) + self.commit_message: Optional[str] = payload.get("commit_message") + self.valid: Optional[bool] = payload.get("valid") + self.errors: Optional[List[Dict[str, object]]] = payload.get("errors") + self.warnings: Optional[List[Dict[str, object]]] = payload.get("warnings") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.webhook_url: Optional[str] = payload.get("webhook_url") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[FlowContext] = None + + @property + def _proxy(self) -> "FlowContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FlowContext for this FlowInstance + """ + if self._context is None: + self._context = FlowContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the FlowInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FlowInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "FlowInstance": + """ + Fetch the FlowInstance + + + :returns: The fetched FlowInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FlowInstance": + """ + Asynchronous coroutine to fetch the FlowInstance + + + :returns: The fetched FlowInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + status: "FlowInstance.Status", + friendly_name: Union[str, object] = values.unset, + definition: Union[object, object] = values.unset, + commit_message: Union[str, object] = values.unset, + ) -> "FlowInstance": + """ + Update the FlowInstance + + :param status: + :param friendly_name: The string that you assigned to describe the Flow. + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + + :returns: The updated FlowInstance + """ + return self._proxy.update( + status=status, + friendly_name=friendly_name, + definition=definition, + commit_message=commit_message, + ) + + async def update_async( + self, + status: "FlowInstance.Status", + friendly_name: Union[str, object] = values.unset, + definition: Union[object, object] = values.unset, + commit_message: Union[str, object] = values.unset, + ) -> "FlowInstance": + """ + Asynchronous coroutine to update the FlowInstance + + :param status: + :param friendly_name: The string that you assigned to describe the Flow. + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + + :returns: The updated FlowInstance + """ + return await self._proxy.update_async( + status=status, + friendly_name=friendly_name, + definition=definition, + commit_message=commit_message, + ) + + @property + def executions(self) -> ExecutionList: + """ + Access the executions + """ + return self._proxy.executions + + @property + def revisions(self) -> FlowRevisionList: + """ + Access the revisions + """ + return self._proxy.revisions + + @property + def test_users(self) -> FlowTestUserList: + """ + Access the test_users + """ + return self._proxy.test_users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FlowContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the FlowContext + + :param version: Version that contains the resource + :param sid: The SID of the Flow resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Flows/{sid}".format(**self._solution) + + self._executions: Optional[ExecutionList] = None + self._revisions: Optional[FlowRevisionList] = None + self._test_users: Optional[FlowTestUserList] = None + + def delete(self) -> bool: + """ + Deletes the FlowInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FlowInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> FlowInstance: + """ + Fetch the FlowInstance + + + :returns: The fetched FlowInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> FlowInstance: + """ + Asynchronous coroutine to fetch the FlowInstance + + + :returns: The fetched FlowInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + status: "FlowInstance.Status", + friendly_name: Union[str, object] = values.unset, + definition: Union[object, object] = values.unset, + commit_message: Union[str, object] = values.unset, + ) -> FlowInstance: + """ + Update the FlowInstance + + :param status: + :param friendly_name: The string that you assigned to describe the Flow. + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + + :returns: The updated FlowInstance + """ + + data = values.of( + { + "Status": status, + "FriendlyName": friendly_name, + "Definition": serialize.object(definition), + "CommitMessage": commit_message, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlowInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + status: "FlowInstance.Status", + friendly_name: Union[str, object] = values.unset, + definition: Union[object, object] = values.unset, + commit_message: Union[str, object] = values.unset, + ) -> FlowInstance: + """ + Asynchronous coroutine to update the FlowInstance + + :param status: + :param friendly_name: The string that you assigned to describe the Flow. + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + + :returns: The updated FlowInstance + """ + + data = values.of( + { + "Status": status, + "FriendlyName": friendly_name, + "Definition": serialize.object(definition), + "CommitMessage": commit_message, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlowInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def executions(self) -> ExecutionList: + """ + Access the executions + """ + if self._executions is None: + self._executions = ExecutionList( + self._version, + self._solution["sid"], + ) + return self._executions + + @property + def revisions(self) -> FlowRevisionList: + """ + Access the revisions + """ + if self._revisions is None: + self._revisions = FlowRevisionList( + self._version, + self._solution["sid"], + ) + return self._revisions + + @property + def test_users(self) -> FlowTestUserList: + """ + Access the test_users + """ + if self._test_users is None: + self._test_users = FlowTestUserList( + self._version, + self._solution["sid"], + ) + return self._test_users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FlowPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> FlowInstance: + """ + Build an instance of FlowInstance + + :param payload: Payload response from the API + """ + return FlowInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class FlowList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the FlowList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Flows" + + def create( + self, + friendly_name: str, + status: "FlowInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + ) -> FlowInstance: + """ + Create the FlowInstance + + :param friendly_name: The string that you assigned to describe the Flow. + :param status: + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + + :returns: The created FlowInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + "Definition": serialize.object(definition), + "CommitMessage": commit_message, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlowInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + status: "FlowInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + ) -> FlowInstance: + """ + Asynchronously create the FlowInstance + + :param friendly_name: The string that you assigned to describe the Flow. + :param status: + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + + :returns: The created FlowInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + "Definition": serialize.object(definition), + "CommitMessage": commit_message, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlowInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FlowInstance]: + """ + Streams FlowInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FlowInstance]: + """ + Asynchronously streams FlowInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FlowInstance]: + """ + Lists FlowInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FlowInstance]: + """ + Asynchronously lists FlowInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FlowPage: + """ + Retrieve a single page of FlowInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FlowInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FlowPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FlowPage: + """ + Asynchronously retrieve a single page of FlowInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FlowInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FlowPage(self._version, response) + + def get_page(self, target_url: str) -> FlowPage: + """ + Retrieve a specific page of FlowInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FlowInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return FlowPage(self._version, response) + + async def get_page_async(self, target_url: str) -> FlowPage: + """ + Asynchronously retrieve a specific page of FlowInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FlowInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return FlowPage(self._version, response) + + def get(self, sid: str) -> FlowContext: + """ + Constructs a FlowContext + + :param sid: The SID of the Flow resource to fetch. + """ + return FlowContext(self._version, sid=sid) + + def __call__(self, sid: str) -> FlowContext: + """ + Constructs a FlowContext + + :param sid: The SID of the Flow resource to fetch. + """ + return FlowContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/studio/v2/flow/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..70f765e9 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/studio/v2/flow/__pycache__/flow_revision.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/__pycache__/flow_revision.cpython-312.pyc new file mode 100644 index 00000000..ea5db474 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/__pycache__/flow_revision.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/studio/v2/flow/__pycache__/flow_test_user.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/__pycache__/flow_test_user.cpython-312.pyc new file mode 100644 index 00000000..eb69fbf7 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/__pycache__/flow_test_user.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/studio/v2/flow/execution/__init__.py b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/execution/__init__.py new file mode 100644 index 00000000..c47a3fbb --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/execution/__init__.py @@ -0,0 +1,738 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.studio.v2.flow.execution.execution_context import ExecutionContextList +from twilio.rest.studio.v2.flow.execution.execution_step import ExecutionStepList + + +class ExecutionInstance(InstanceResource): + + class Status(object): + ACTIVE = "active" + ENDED = "ended" + + """ + :ivar sid: The unique string that we created to identify the Execution resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Execution resource. + :ivar flow_sid: The SID of the Flow. + :ivar contact_channel_address: The phone number, SIP address or Client identifier that triggered the Execution. Phone numbers are in E.164 format (e.g. +16175551212). SIP addresses are formatted as `name@company.com`. Client identifiers are formatted `client:name`. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar status: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of nested resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.contact_channel_address: Optional[str] = payload.get( + "contact_channel_address" + ) + self.context: Optional[Dict[str, object]] = payload.get("context") + self.status: Optional["ExecutionInstance.Status"] = payload.get("status") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "flow_sid": flow_sid, + "sid": sid or self.sid, + } + self._context: Optional[ExecutionContext] = None + + @property + def _proxy(self) -> "ExecutionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ExecutionContext for this ExecutionInstance + """ + if self._context is None: + self._context = ExecutionContext( + self._version, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ExecutionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ExecutionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ExecutionInstance": + """ + Fetch the ExecutionInstance + + + :returns: The fetched ExecutionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ExecutionInstance": + """ + Asynchronous coroutine to fetch the ExecutionInstance + + + :returns: The fetched ExecutionInstance + """ + return await self._proxy.fetch_async() + + def update(self, status: "ExecutionInstance.Status") -> "ExecutionInstance": + """ + Update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + return self._proxy.update( + status=status, + ) + + async def update_async( + self, status: "ExecutionInstance.Status" + ) -> "ExecutionInstance": + """ + Asynchronous coroutine to update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + return await self._proxy.update_async( + status=status, + ) + + @property + def execution_context(self) -> ExecutionContextList: + """ + Access the execution_context + """ + return self._proxy.execution_context + + @property + def steps(self) -> ExecutionStepList: + """ + Access the steps + """ + return self._proxy.steps + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ExecutionContext(InstanceContext): + + def __init__(self, version: Version, flow_sid: str, sid: str): + """ + Initialize the ExecutionContext + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Execution resources to update. + :param sid: The SID of the Execution resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "sid": sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{sid}".format(**self._solution) + + self._execution_context: Optional[ExecutionContextList] = None + self._steps: Optional[ExecutionStepList] = None + + def delete(self) -> bool: + """ + Deletes the ExecutionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ExecutionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ExecutionInstance: + """ + Fetch the ExecutionInstance + + + :returns: The fetched ExecutionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ExecutionInstance: + """ + Asynchronous coroutine to fetch the ExecutionInstance + + + :returns: The fetched ExecutionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + def update(self, status: "ExecutionInstance.Status") -> ExecutionInstance: + """ + Update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, status: "ExecutionInstance.Status" + ) -> ExecutionInstance: + """ + Asynchronous coroutine to update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + @property + def execution_context(self) -> ExecutionContextList: + """ + Access the execution_context + """ + if self._execution_context is None: + self._execution_context = ExecutionContextList( + self._version, + self._solution["flow_sid"], + self._solution["sid"], + ) + return self._execution_context + + @property + def steps(self) -> ExecutionStepList: + """ + Access the steps + """ + if self._steps is None: + self._steps = ExecutionStepList( + self._version, + self._solution["flow_sid"], + self._solution["sid"], + ) + return self._steps + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ExecutionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ExecutionInstance: + """ + Build an instance of ExecutionInstance + + :param payload: Payload response from the API + """ + return ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ExecutionList(ListResource): + + def __init__(self, version: Version, flow_sid: str): + """ + Initialize the ExecutionList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Execution resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + } + self._uri = "/Flows/{flow_sid}/Executions".format(**self._solution) + + def create( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ExecutionInstance: + """ + Create the ExecutionInstance + + :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. + :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. + + :returns: The created ExecutionInstance + """ + + data = values.of( + { + "To": to, + "From": from_, + "Parameters": serialize.object(parameters), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + async def create_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ExecutionInstance: + """ + Asynchronously create the ExecutionInstance + + :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. + :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. + + :returns: The created ExecutionInstance + """ + + data = values.of( + { + "To": to, + "From": from_, + "Parameters": serialize.object(parameters), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + def stream( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ExecutionInstance]: + """ + Streams ExecutionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + date_created_from=date_created_from, + date_created_to=date_created_to, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ExecutionInstance]: + """ + Asynchronously streams ExecutionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + date_created_from=date_created_from, + date_created_to=date_created_to, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExecutionInstance]: + """ + Lists ExecutionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + date_created_from=date_created_from, + date_created_to=date_created_to, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExecutionInstance]: + """ + Asynchronously lists ExecutionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + date_created_from=date_created_from, + date_created_to=date_created_to, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ExecutionPage: + """ + Retrieve a single page of ExecutionInstance records from the API. + Request is executed immediately + + :param date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ExecutionInstance + """ + data = values.of( + { + "DateCreatedFrom": serialize.iso8601_datetime(date_created_from), + "DateCreatedTo": serialize.iso8601_datetime(date_created_to), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExecutionPage(self._version, response, self._solution) + + async def page_async( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ExecutionPage: + """ + Asynchronously retrieve a single page of ExecutionInstance records from the API. + Request is executed immediately + + :param date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ExecutionInstance + """ + data = values.of( + { + "DateCreatedFrom": serialize.iso8601_datetime(date_created_from), + "DateCreatedTo": serialize.iso8601_datetime(date_created_to), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExecutionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ExecutionPage: + """ + Retrieve a specific page of ExecutionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ExecutionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ExecutionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ExecutionPage: + """ + Asynchronously retrieve a specific page of ExecutionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ExecutionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ExecutionPage(self._version, response, self._solution) + + def get(self, sid: str) -> ExecutionContext: + """ + Constructs a ExecutionContext + + :param sid: The SID of the Execution resource to update. + """ + return ExecutionContext( + self._version, flow_sid=self._solution["flow_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ExecutionContext: + """ + Constructs a ExecutionContext + + :param sid: The SID of the Execution resource to update. + """ + return ExecutionContext( + self._version, flow_sid=self._solution["flow_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/studio/v2/flow/execution/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/execution/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..03ea071a Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/execution/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/studio/v2/flow/execution/__pycache__/execution_context.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/execution/__pycache__/execution_context.cpython-312.pyc new file mode 100644 index 00000000..2acdb318 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/execution/__pycache__/execution_context.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/studio/v2/flow/execution/execution_context.py b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/execution/execution_context.py new file mode 100644 index 00000000..4c18f81d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/execution/execution_context.py @@ -0,0 +1,219 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ExecutionContextInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionContext resource. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar flow_sid: The SID of the Flow. + :ivar execution_sid: The SID of the context's Execution resource. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + execution_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.context: Optional[Dict[str, object]] = payload.get("context") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.execution_sid: Optional[str] = payload.get("execution_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } + self._context: Optional[ExecutionContextContext] = None + + @property + def _proxy(self) -> "ExecutionContextContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ExecutionContextContext for this ExecutionContextInstance + """ + if self._context is None: + self._context = ExecutionContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + return self._context + + def fetch(self) -> "ExecutionContextInstance": + """ + Fetch the ExecutionContextInstance + + + :returns: The fetched ExecutionContextInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ExecutionContextInstance": + """ + Asynchronous coroutine to fetch the ExecutionContextInstance + + + :returns: The fetched ExecutionContextInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ExecutionContextContext(InstanceContext): + + def __init__(self, version: Version, flow_sid: str, execution_sid: str): + """ + Initialize the ExecutionContextContext + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Execution context to fetch. + :param execution_sid: The SID of the Execution context to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Context".format( + **self._solution + ) + + def fetch(self) -> ExecutionContextInstance: + """ + Fetch the ExecutionContextInstance + + + :returns: The fetched ExecutionContextInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ExecutionContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + + async def fetch_async(self) -> ExecutionContextInstance: + """ + Asynchronous coroutine to fetch the ExecutionContextInstance + + + :returns: The fetched ExecutionContextInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ExecutionContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ExecutionContextList(ListResource): + + def __init__(self, version: Version, flow_sid: str, execution_sid: str): + """ + Initialize the ExecutionContextList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Execution context to fetch. + :param execution_sid: The SID of the Execution context to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } + + def get(self) -> ExecutionContextContext: + """ + Constructs a ExecutionContextContext + + """ + return ExecutionContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + + def __call__(self) -> ExecutionContextContext: + """ + Constructs a ExecutionContextContext + + """ + return ExecutionContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/studio/v2/flow/execution/execution_step/__init__.py b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/execution/execution_step/__init__.py new file mode 100644 index 00000000..9ffb2502 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/execution/execution_step/__init__.py @@ -0,0 +1,498 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context import ( + ExecutionStepContextList, +) + + +class ExecutionStepInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the ExecutionStep resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionStep resource. + :ivar flow_sid: The SID of the Flow. + :ivar execution_sid: The SID of the Step's Execution resource. + :ivar parent_step_sid: The SID of the parent Step. + :ivar name: The event that caused the Flow to transition to the Step. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar transitioned_from: The Widget that preceded the Widget for the Step. + :ivar transitioned_to: The Widget that will follow the Widget for the Step. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + execution_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.execution_sid: Optional[str] = payload.get("execution_sid") + self.parent_step_sid: Optional[str] = payload.get("parent_step_sid") + self.name: Optional[str] = payload.get("name") + self.context: Optional[Dict[str, object]] = payload.get("context") + self.transitioned_from: Optional[str] = payload.get("transitioned_from") + self.transitioned_to: Optional[str] = payload.get("transitioned_to") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "sid": sid or self.sid, + } + self._context: Optional[ExecutionStepContext] = None + + @property + def _proxy(self) -> "ExecutionStepContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ExecutionStepContext for this ExecutionStepInstance + """ + if self._context is None: + self._context = ExecutionStepContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "ExecutionStepInstance": + """ + Fetch the ExecutionStepInstance + + + :returns: The fetched ExecutionStepInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ExecutionStepInstance": + """ + Asynchronous coroutine to fetch the ExecutionStepInstance + + + :returns: The fetched ExecutionStepInstance + """ + return await self._proxy.fetch_async() + + @property + def step_context(self) -> ExecutionStepContextList: + """ + Access the step_context + """ + return self._proxy.step_context + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ExecutionStepContext(InstanceContext): + + def __init__(self, version: Version, flow_sid: str, execution_sid: str, sid: str): + """ + Initialize the ExecutionStepContext + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to fetch. + :param execution_sid: The SID of the Execution resource with the Step to fetch. + :param sid: The SID of the ExecutionStep resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "sid": sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Steps/{sid}".format( + **self._solution + ) + + self._step_context: Optional[ExecutionStepContextList] = None + + def fetch(self) -> ExecutionStepInstance: + """ + Fetch the ExecutionStepInstance + + + :returns: The fetched ExecutionStepInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ExecutionStepInstance: + """ + Asynchronous coroutine to fetch the ExecutionStepInstance + + + :returns: The fetched ExecutionStepInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], + ) + + @property + def step_context(self) -> ExecutionStepContextList: + """ + Access the step_context + """ + if self._step_context is None: + self._step_context = ExecutionStepContextList( + self._version, + self._solution["flow_sid"], + self._solution["execution_sid"], + self._solution["sid"], + ) + return self._step_context + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ExecutionStepPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ExecutionStepInstance: + """ + Build an instance of ExecutionStepInstance + + :param payload: Payload response from the API + """ + return ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ExecutionStepList(ListResource): + + def __init__(self, version: Version, flow_sid: str, execution_sid: str): + """ + Initialize the ExecutionStepList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Steps to read. + :param execution_sid: The SID of the Execution with the Steps to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Steps".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ExecutionStepInstance]: + """ + Streams ExecutionStepInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ExecutionStepInstance]: + """ + Asynchronously streams ExecutionStepInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExecutionStepInstance]: + """ + Lists ExecutionStepInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExecutionStepInstance]: + """ + Asynchronously lists ExecutionStepInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ExecutionStepPage: + """ + Retrieve a single page of ExecutionStepInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ExecutionStepInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExecutionStepPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ExecutionStepPage: + """ + Asynchronously retrieve a single page of ExecutionStepInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ExecutionStepInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExecutionStepPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ExecutionStepPage: + """ + Retrieve a specific page of ExecutionStepInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ExecutionStepInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ExecutionStepPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ExecutionStepPage: + """ + Asynchronously retrieve a specific page of ExecutionStepInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ExecutionStepInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ExecutionStepPage(self._version, response, self._solution) + + def get(self, sid: str) -> ExecutionStepContext: + """ + Constructs a ExecutionStepContext + + :param sid: The SID of the ExecutionStep resource to fetch. + """ + return ExecutionStepContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> ExecutionStepContext: + """ + Constructs a ExecutionStepContext + + :param sid: The SID of the ExecutionStep resource to fetch. + """ + return ExecutionStepContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/studio/v2/flow/execution/execution_step/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/execution/execution_step/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..ecfdf444 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/execution/execution_step/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/studio/v2/flow/execution/execution_step/__pycache__/execution_step_context.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/execution/execution_step/__pycache__/execution_step_context.cpython-312.pyc new file mode 100644 index 00000000..40f97a2b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/execution/execution_step/__pycache__/execution_step_context.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/studio/v2/flow/execution/execution_step/execution_step_context.py b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/execution/execution_step/execution_step_context.py new file mode 100644 index 00000000..7f00e0d1 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/execution/execution_step/execution_step_context.py @@ -0,0 +1,236 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ExecutionStepContextInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionStepContext resource. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar execution_sid: The SID of the context's Execution resource. + :ivar flow_sid: The SID of the Flow. + :ivar step_sid: The SID of the Step that the context is associated with. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + execution_sid: str, + step_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.context: Optional[Dict[str, object]] = payload.get("context") + self.execution_sid: Optional[str] = payload.get("execution_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.step_sid: Optional[str] = payload.get("step_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "step_sid": step_sid, + } + self._context: Optional[ExecutionStepContextContext] = None + + @property + def _proxy(self) -> "ExecutionStepContextContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ExecutionStepContextContext for this ExecutionStepContextInstance + """ + if self._context is None: + self._context = ExecutionStepContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + return self._context + + def fetch(self) -> "ExecutionStepContextInstance": + """ + Fetch the ExecutionStepContextInstance + + + :returns: The fetched ExecutionStepContextInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ExecutionStepContextInstance": + """ + Asynchronous coroutine to fetch the ExecutionStepContextInstance + + + :returns: The fetched ExecutionStepContextInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ExecutionStepContextContext(InstanceContext): + + def __init__( + self, version: Version, flow_sid: str, execution_sid: str, step_sid: str + ): + """ + Initialize the ExecutionStepContextContext + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to fetch. + :param execution_sid: The SID of the Execution resource with the Step to fetch. + :param step_sid: The SID of the Step to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "step_sid": step_sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Steps/{step_sid}/Context".format( + **self._solution + ) + + def fetch(self) -> ExecutionStepContextInstance: + """ + Fetch the ExecutionStepContextInstance + + + :returns: The fetched ExecutionStepContextInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ExecutionStepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + + async def fetch_async(self) -> ExecutionStepContextInstance: + """ + Asynchronous coroutine to fetch the ExecutionStepContextInstance + + + :returns: The fetched ExecutionStepContextInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ExecutionStepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ExecutionStepContextList(ListResource): + + def __init__( + self, version: Version, flow_sid: str, execution_sid: str, step_sid: str + ): + """ + Initialize the ExecutionStepContextList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to fetch. + :param execution_sid: The SID of the Execution resource with the Step to fetch. + :param step_sid: The SID of the Step to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "step_sid": step_sid, + } + + def get(self) -> ExecutionStepContextContext: + """ + Constructs a ExecutionStepContextContext + + """ + return ExecutionStepContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + + def __call__(self) -> ExecutionStepContextContext: + """ + Constructs a ExecutionStepContextContext + + """ + return ExecutionStepContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/studio/v2/flow/flow_revision.py b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/flow_revision.py new file mode 100644 index 00000000..aa065074 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/flow_revision.py @@ -0,0 +1,451 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class FlowRevisionInstance(InstanceResource): + + class Status(object): + DRAFT = "draft" + PUBLISHED = "published" + + """ + :ivar sid: The unique string that we created to identify the Flow resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flow resource. + :ivar friendly_name: The string that you assigned to describe the Flow. + :ivar definition: JSON representation of flow definition. + :ivar status: + :ivar revision: The latest revision number of the Flow's definition. + :ivar commit_message: Description of change made in the revision. + :ivar valid: Boolean if the flow definition is valid. + :ivar errors: List of error in the flow definition. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + sid: str, + revision: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.definition: Optional[Dict[str, object]] = payload.get("definition") + self.status: Optional["FlowRevisionInstance.Status"] = payload.get("status") + self.revision: Optional[int] = deserialize.integer(payload.get("revision")) + self.commit_message: Optional[str] = payload.get("commit_message") + self.valid: Optional[bool] = payload.get("valid") + self.errors: Optional[List[Dict[str, object]]] = payload.get("errors") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid, + "revision": revision or self.revision, + } + self._context: Optional[FlowRevisionContext] = None + + @property + def _proxy(self) -> "FlowRevisionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FlowRevisionContext for this FlowRevisionInstance + """ + if self._context is None: + self._context = FlowRevisionContext( + self._version, + sid=self._solution["sid"], + revision=self._solution["revision"], + ) + return self._context + + def fetch(self) -> "FlowRevisionInstance": + """ + Fetch the FlowRevisionInstance + + + :returns: The fetched FlowRevisionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FlowRevisionInstance": + """ + Asynchronous coroutine to fetch the FlowRevisionInstance + + + :returns: The fetched FlowRevisionInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FlowRevisionContext(InstanceContext): + + def __init__(self, version: Version, sid: str, revision: str): + """ + Initialize the FlowRevisionContext + + :param version: Version that contains the resource + :param sid: The SID of the Flow resource to fetch. + :param revision: Specific Revision number or can be `LatestPublished` and `LatestRevision`. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + "revision": revision, + } + self._uri = "/Flows/{sid}/Revisions/{revision}".format(**self._solution) + + def fetch(self) -> FlowRevisionInstance: + """ + Fetch the FlowRevisionInstance + + + :returns: The fetched FlowRevisionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FlowRevisionInstance( + self._version, + payload, + sid=self._solution["sid"], + revision=self._solution["revision"], + ) + + async def fetch_async(self) -> FlowRevisionInstance: + """ + Asynchronous coroutine to fetch the FlowRevisionInstance + + + :returns: The fetched FlowRevisionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FlowRevisionInstance( + self._version, + payload, + sid=self._solution["sid"], + revision=self._solution["revision"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FlowRevisionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> FlowRevisionInstance: + """ + Build an instance of FlowRevisionInstance + + :param payload: Payload response from the API + """ + return FlowRevisionInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class FlowRevisionList(ListResource): + + def __init__(self, version: Version, sid: str): + """ + Initialize the FlowRevisionList + + :param version: Version that contains the resource + :param sid: The SID of the Flow resource to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Flows/{sid}/Revisions".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FlowRevisionInstance]: + """ + Streams FlowRevisionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FlowRevisionInstance]: + """ + Asynchronously streams FlowRevisionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FlowRevisionInstance]: + """ + Lists FlowRevisionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FlowRevisionInstance]: + """ + Asynchronously lists FlowRevisionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FlowRevisionPage: + """ + Retrieve a single page of FlowRevisionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FlowRevisionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FlowRevisionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FlowRevisionPage: + """ + Asynchronously retrieve a single page of FlowRevisionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FlowRevisionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FlowRevisionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> FlowRevisionPage: + """ + Retrieve a specific page of FlowRevisionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FlowRevisionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return FlowRevisionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> FlowRevisionPage: + """ + Asynchronously retrieve a specific page of FlowRevisionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FlowRevisionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return FlowRevisionPage(self._version, response, self._solution) + + def get(self, revision: str) -> FlowRevisionContext: + """ + Constructs a FlowRevisionContext + + :param revision: Specific Revision number or can be `LatestPublished` and `LatestRevision`. + """ + return FlowRevisionContext( + self._version, sid=self._solution["sid"], revision=revision + ) + + def __call__(self, revision: str) -> FlowRevisionContext: + """ + Constructs a FlowRevisionContext + + :param revision: Specific Revision number or can be `LatestPublished` and `LatestRevision`. + """ + return FlowRevisionContext( + self._version, sid=self._solution["sid"], revision=revision + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/studio/v2/flow/flow_test_user.py b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/flow_test_user.py new file mode 100644 index 00000000..cff41cd7 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/studio/v2/flow/flow_test_user.py @@ -0,0 +1,267 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class FlowTestUserInstance(InstanceResource): + """ + :ivar sid: Unique identifier of the flow. + :ivar test_users: List of test user identities that can test draft versions of the flow. + :ivar url: The URL of this resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.test_users: Optional[List[str]] = payload.get("test_users") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid, + } + self._context: Optional[FlowTestUserContext] = None + + @property + def _proxy(self) -> "FlowTestUserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FlowTestUserContext for this FlowTestUserInstance + """ + if self._context is None: + self._context = FlowTestUserContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "FlowTestUserInstance": + """ + Fetch the FlowTestUserInstance + + + :returns: The fetched FlowTestUserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FlowTestUserInstance": + """ + Asynchronous coroutine to fetch the FlowTestUserInstance + + + :returns: The fetched FlowTestUserInstance + """ + return await self._proxy.fetch_async() + + def update(self, test_users: List[str]) -> "FlowTestUserInstance": + """ + Update the FlowTestUserInstance + + :param test_users: List of test user identities that can test draft versions of the flow. + + :returns: The updated FlowTestUserInstance + """ + return self._proxy.update( + test_users=test_users, + ) + + async def update_async(self, test_users: List[str]) -> "FlowTestUserInstance": + """ + Asynchronous coroutine to update the FlowTestUserInstance + + :param test_users: List of test user identities that can test draft versions of the flow. + + :returns: The updated FlowTestUserInstance + """ + return await self._proxy.update_async( + test_users=test_users, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FlowTestUserContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the FlowTestUserContext + + :param version: Version that contains the resource + :param sid: Unique identifier of the flow. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Flows/{sid}/TestUsers".format(**self._solution) + + def fetch(self) -> FlowTestUserInstance: + """ + Fetch the FlowTestUserInstance + + + :returns: The fetched FlowTestUserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FlowTestUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> FlowTestUserInstance: + """ + Asynchronous coroutine to fetch the FlowTestUserInstance + + + :returns: The fetched FlowTestUserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FlowTestUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update(self, test_users: List[str]) -> FlowTestUserInstance: + """ + Update the FlowTestUserInstance + + :param test_users: List of test user identities that can test draft versions of the flow. + + :returns: The updated FlowTestUserInstance + """ + + data = values.of( + { + "TestUsers": serialize.map(test_users, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlowTestUserInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async(self, test_users: List[str]) -> FlowTestUserInstance: + """ + Asynchronous coroutine to update the FlowTestUserInstance + + :param test_users: List of test user identities that can test draft versions of the flow. + + :returns: The updated FlowTestUserInstance + """ + + data = values.of( + { + "TestUsers": serialize.map(test_users, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlowTestUserInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FlowTestUserList(ListResource): + + def __init__(self, version: Version, sid: str): + """ + Initialize the FlowTestUserList + + :param version: Version that contains the resource + :param sid: Unique identifier of the flow. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + + def get(self) -> FlowTestUserContext: + """ + Constructs a FlowTestUserContext + + """ + return FlowTestUserContext(self._version, sid=self._solution["sid"]) + + def __call__(self) -> FlowTestUserContext: + """ + Constructs a FlowTestUserContext + + """ + return FlowTestUserContext(self._version, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/studio/v2/flow_validate.py b/venv/Lib/site-packages/twilio/rest/studio/v2/flow_validate.py new file mode 100644 index 00000000..5f8b3085 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/studio/v2/flow_validate.py @@ -0,0 +1,143 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class FlowValidateInstance(InstanceResource): + + class Status(object): + DRAFT = "draft" + PUBLISHED = "published" + + """ + :ivar valid: Boolean if the flow definition is valid. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.valid: Optional[bool] = payload.get("valid") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class FlowValidateList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the FlowValidateList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Flows/Validate" + + def update( + self, + friendly_name: str, + status: "FlowValidateInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + ) -> FlowValidateInstance: + """ + Update the FlowValidateInstance + + :param friendly_name: The string that you assigned to describe the Flow. + :param status: + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + + :returns: The created FlowValidateInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + "Definition": serialize.object(definition), + "CommitMessage": commit_message, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlowValidateInstance(self._version, payload) + + async def update_async( + self, + friendly_name: str, + status: "FlowValidateInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + ) -> FlowValidateInstance: + """ + Asynchronously update the FlowValidateInstance + + :param friendly_name: The string that you assigned to describe the Flow. + :param status: + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + + :returns: The created FlowValidateInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + "Definition": serialize.object(definition), + "CommitMessage": commit_message, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlowValidateInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/supersim/SupersimBase.py b/venv/Lib/site-packages/twilio/rest/supersim/SupersimBase.py new file mode 100644 index 00000000..dd73d122 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/supersim/SupersimBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.supersim.v1 import V1 + + +class SupersimBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Supersim Domain + + :returns: Domain for Supersim + """ + super().__init__(twilio, "https://supersim.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Supersim + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/supersim/__init__.py b/venv/Lib/site-packages/twilio/rest/supersim/__init__.py new file mode 100644 index 00000000..98928dad --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/supersim/__init__.py @@ -0,0 +1,93 @@ +from warnings import warn + +from twilio.rest.supersim.SupersimBase import SupersimBase +from twilio.rest.supersim.v1.esim_profile import EsimProfileList +from twilio.rest.supersim.v1.fleet import FleetList +from twilio.rest.supersim.v1.ip_command import IpCommandList +from twilio.rest.supersim.v1.network import NetworkList +from twilio.rest.supersim.v1.network_access_profile import NetworkAccessProfileList +from twilio.rest.supersim.v1.settings_update import SettingsUpdateList +from twilio.rest.supersim.v1.sim import SimList +from twilio.rest.supersim.v1.sms_command import SmsCommandList +from twilio.rest.supersim.v1.usage_record import UsageRecordList + + +class Supersim(SupersimBase): + @property + def esim_profiles(self) -> EsimProfileList: + warn( + "esim_profiles is deprecated. Use v1.esim_profiles instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.esim_profiles + + @property + def fleets(self) -> FleetList: + warn( + "fleets is deprecated. Use v1.fleets instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.fleets + + @property + def ip_commands(self) -> IpCommandList: + warn( + "ip_commands is deprecated. Use v1.ip_commands instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.ip_commands + + @property + def networks(self) -> NetworkList: + warn( + "networks is deprecated. Use v1.networks instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.networks + + @property + def network_access_profiles(self) -> NetworkAccessProfileList: + warn( + "network_access_profiles is deprecated. Use v1.network_access_profiles instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.network_access_profiles + + @property + def settings_updates(self) -> SettingsUpdateList: + warn( + "settings_updates is deprecated. Use v1.settings_updates instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.settings_updates + + @property + def sims(self) -> SimList: + warn( + "sims is deprecated. Use v1.sims instead.", DeprecationWarning, stacklevel=2 + ) + return self.v1.sims + + @property + def sms_commands(self) -> SmsCommandList: + warn( + "sms_commands is deprecated. Use v1.sms_commands instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.sms_commands + + @property + def usage_records(self) -> UsageRecordList: + warn( + "usage_records is deprecated. Use v1.usage_records instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.usage_records diff --git a/venv/Lib/site-packages/twilio/rest/supersim/__pycache__/SupersimBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/supersim/__pycache__/SupersimBase.cpython-312.pyc new file mode 100644 index 00000000..72cabce7 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/supersim/__pycache__/SupersimBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/supersim/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/supersim/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..4d1019d5 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/supersim/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/supersim/v1/__init__.py new file mode 100644 index 00000000..2336da26 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/supersim/v1/__init__.py @@ -0,0 +1,107 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.supersim.v1.esim_profile import EsimProfileList +from twilio.rest.supersim.v1.fleet import FleetList +from twilio.rest.supersim.v1.ip_command import IpCommandList +from twilio.rest.supersim.v1.network import NetworkList +from twilio.rest.supersim.v1.network_access_profile import NetworkAccessProfileList +from twilio.rest.supersim.v1.settings_update import SettingsUpdateList +from twilio.rest.supersim.v1.sim import SimList +from twilio.rest.supersim.v1.sms_command import SmsCommandList +from twilio.rest.supersim.v1.usage_record import UsageRecordList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Supersim + + :param domain: The Twilio.supersim domain + """ + super().__init__(domain, "v1") + self._esim_profiles: Optional[EsimProfileList] = None + self._fleets: Optional[FleetList] = None + self._ip_commands: Optional[IpCommandList] = None + self._networks: Optional[NetworkList] = None + self._network_access_profiles: Optional[NetworkAccessProfileList] = None + self._settings_updates: Optional[SettingsUpdateList] = None + self._sims: Optional[SimList] = None + self._sms_commands: Optional[SmsCommandList] = None + self._usage_records: Optional[UsageRecordList] = None + + @property + def esim_profiles(self) -> EsimProfileList: + if self._esim_profiles is None: + self._esim_profiles = EsimProfileList(self) + return self._esim_profiles + + @property + def fleets(self) -> FleetList: + if self._fleets is None: + self._fleets = FleetList(self) + return self._fleets + + @property + def ip_commands(self) -> IpCommandList: + if self._ip_commands is None: + self._ip_commands = IpCommandList(self) + return self._ip_commands + + @property + def networks(self) -> NetworkList: + if self._networks is None: + self._networks = NetworkList(self) + return self._networks + + @property + def network_access_profiles(self) -> NetworkAccessProfileList: + if self._network_access_profiles is None: + self._network_access_profiles = NetworkAccessProfileList(self) + return self._network_access_profiles + + @property + def settings_updates(self) -> SettingsUpdateList: + if self._settings_updates is None: + self._settings_updates = SettingsUpdateList(self) + return self._settings_updates + + @property + def sims(self) -> SimList: + if self._sims is None: + self._sims = SimList(self) + return self._sims + + @property + def sms_commands(self) -> SmsCommandList: + if self._sms_commands is None: + self._sms_commands = SmsCommandList(self) + return self._sms_commands + + @property + def usage_records(self) -> UsageRecordList: + if self._usage_records is None: + self._usage_records = UsageRecordList(self) + return self._usage_records + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/supersim/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..c635f361 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/supersim/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/__pycache__/esim_profile.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/supersim/v1/__pycache__/esim_profile.cpython-312.pyc new file mode 100644 index 00000000..c5ddf4a0 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/supersim/v1/__pycache__/esim_profile.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/__pycache__/fleet.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/supersim/v1/__pycache__/fleet.cpython-312.pyc new file mode 100644 index 00000000..8da84c78 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/supersim/v1/__pycache__/fleet.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/__pycache__/ip_command.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/supersim/v1/__pycache__/ip_command.cpython-312.pyc new file mode 100644 index 00000000..559495ef Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/supersim/v1/__pycache__/ip_command.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/__pycache__/network.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/supersim/v1/__pycache__/network.cpython-312.pyc new file mode 100644 index 00000000..37f446cf Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/supersim/v1/__pycache__/network.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/__pycache__/settings_update.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/supersim/v1/__pycache__/settings_update.cpython-312.pyc new file mode 100644 index 00000000..79486850 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/supersim/v1/__pycache__/settings_update.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/__pycache__/sms_command.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/supersim/v1/__pycache__/sms_command.cpython-312.pyc new file mode 100644 index 00000000..9ef688fe Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/supersim/v1/__pycache__/sms_command.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/__pycache__/usage_record.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/supersim/v1/__pycache__/usage_record.cpython-312.pyc new file mode 100644 index 00000000..e78733f4 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/supersim/v1/__pycache__/usage_record.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/esim_profile.py b/venv/Lib/site-packages/twilio/rest/supersim/v1/esim_profile.py new file mode 100644 index 00000000..d12bb9b7 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/supersim/v1/esim_profile.py @@ -0,0 +1,568 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class EsimProfileInstance(InstanceResource): + + class Status(object): + NEW = "new" + RESERVING = "reserving" + AVAILABLE = "available" + DOWNLOADED = "downloaded" + INSTALLED = "installed" + FAILED = "failed" + + """ + :ivar sid: The unique string that we created to identify the eSIM Profile resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the eSIM Profile resource belongs. + :ivar iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with the Sim resource. + :ivar sim_sid: The SID of the [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource that this eSIM Profile controls. + :ivar status: + :ivar eid: Identifier of the eUICC that can claim the eSIM Profile. + :ivar smdp_plus_address: Address of the SM-DP+ server from which the Profile will be downloaded. The URL will appear once the eSIM Profile reaches the status `available`. + :ivar matching_id: Unique identifier of the eSIM profile that can be used to identify and download the eSIM profile from the SM-DP+ server. Populated if `generate_matching_id` is set to `true` when creating the eSIM profile reservation. + :ivar activation_code: Combined machine-readable activation code for acquiring an eSIM Profile with the Activation Code download method. Can be used in a QR code to download an eSIM profile. + :ivar error_code: Code indicating the failure if the download of the SIM Profile failed and the eSIM Profile is in `failed` state. + :ivar error_message: Error message describing the failure if the download of the SIM Profile failed and the eSIM Profile is in `failed` state. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the eSIM Profile resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.iccid: Optional[str] = payload.get("iccid") + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.status: Optional["EsimProfileInstance.Status"] = payload.get("status") + self.eid: Optional[str] = payload.get("eid") + self.smdp_plus_address: Optional[str] = payload.get("smdp_plus_address") + self.matching_id: Optional[str] = payload.get("matching_id") + self.activation_code: Optional[str] = payload.get("activation_code") + self.error_code: Optional[str] = payload.get("error_code") + self.error_message: Optional[str] = payload.get("error_message") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[EsimProfileContext] = None + + @property + def _proxy(self) -> "EsimProfileContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EsimProfileContext for this EsimProfileInstance + """ + if self._context is None: + self._context = EsimProfileContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "EsimProfileInstance": + """ + Fetch the EsimProfileInstance + + + :returns: The fetched EsimProfileInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EsimProfileInstance": + """ + Asynchronous coroutine to fetch the EsimProfileInstance + + + :returns: The fetched EsimProfileInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EsimProfileContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the EsimProfileContext + + :param version: Version that contains the resource + :param sid: The SID of the eSIM Profile resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/ESimProfiles/{sid}".format(**self._solution) + + def fetch(self) -> EsimProfileInstance: + """ + Fetch the EsimProfileInstance + + + :returns: The fetched EsimProfileInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EsimProfileInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> EsimProfileInstance: + """ + Asynchronous coroutine to fetch the EsimProfileInstance + + + :returns: The fetched EsimProfileInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EsimProfileInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EsimProfilePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EsimProfileInstance: + """ + Build an instance of EsimProfileInstance + + :param payload: Payload response from the API + """ + return EsimProfileInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class EsimProfileList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the EsimProfileList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ESimProfiles" + + def create( + self, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + generate_matching_id: Union[bool, object] = values.unset, + eid: Union[str, object] = values.unset, + ) -> EsimProfileInstance: + """ + Create the EsimProfileInstance + + :param callback_url: The URL we should call using the `callback_method` when the status of the eSIM Profile changes. At this stage of the eSIM Profile pilot, the a request to the URL will only be called when the ESimProfile resource changes from `reserving` to `available`. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param generate_matching_id: When set to `true`, a value for `Eid` does not need to be provided. Instead, when the eSIM profile is reserved, a matching ID will be generated and returned via the `matching_id` property. This identifies the specific eSIM profile that can be used by any capable device to claim and download the profile. + :param eid: Identifier of the eUICC that will claim the eSIM Profile. + + :returns: The created EsimProfileInstance + """ + + data = values.of( + { + "CallbackUrl": callback_url, + "CallbackMethod": callback_method, + "GenerateMatchingId": serialize.boolean_to_string(generate_matching_id), + "Eid": eid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EsimProfileInstance(self._version, payload) + + async def create_async( + self, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + generate_matching_id: Union[bool, object] = values.unset, + eid: Union[str, object] = values.unset, + ) -> EsimProfileInstance: + """ + Asynchronously create the EsimProfileInstance + + :param callback_url: The URL we should call using the `callback_method` when the status of the eSIM Profile changes. At this stage of the eSIM Profile pilot, the a request to the URL will only be called when the ESimProfile resource changes from `reserving` to `available`. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param generate_matching_id: When set to `true`, a value for `Eid` does not need to be provided. Instead, when the eSIM profile is reserved, a matching ID will be generated and returned via the `matching_id` property. This identifies the specific eSIM profile that can be used by any capable device to claim and download the profile. + :param eid: Identifier of the eUICC that will claim the eSIM Profile. + + :returns: The created EsimProfileInstance + """ + + data = values.of( + { + "CallbackUrl": callback_url, + "CallbackMethod": callback_method, + "GenerateMatchingId": serialize.boolean_to_string(generate_matching_id), + "Eid": eid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EsimProfileInstance(self._version, payload) + + def stream( + self, + eid: Union[str, object] = values.unset, + sim_sid: Union[str, object] = values.unset, + status: Union["EsimProfileInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EsimProfileInstance]: + """ + Streams EsimProfileInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str eid: List the eSIM Profiles that have been associated with an EId. + :param str sim_sid: Find the eSIM Profile resource related to a [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. + :param "EsimProfileInstance.Status" status: List the eSIM Profiles that are in a given status. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + eid=eid, sim_sid=sim_sid, status=status, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + eid: Union[str, object] = values.unset, + sim_sid: Union[str, object] = values.unset, + status: Union["EsimProfileInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EsimProfileInstance]: + """ + Asynchronously streams EsimProfileInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str eid: List the eSIM Profiles that have been associated with an EId. + :param str sim_sid: Find the eSIM Profile resource related to a [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. + :param "EsimProfileInstance.Status" status: List the eSIM Profiles that are in a given status. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + eid=eid, sim_sid=sim_sid, status=status, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + eid: Union[str, object] = values.unset, + sim_sid: Union[str, object] = values.unset, + status: Union["EsimProfileInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EsimProfileInstance]: + """ + Lists EsimProfileInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str eid: List the eSIM Profiles that have been associated with an EId. + :param str sim_sid: Find the eSIM Profile resource related to a [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. + :param "EsimProfileInstance.Status" status: List the eSIM Profiles that are in a given status. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + eid=eid, + sim_sid=sim_sid, + status=status, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + eid: Union[str, object] = values.unset, + sim_sid: Union[str, object] = values.unset, + status: Union["EsimProfileInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EsimProfileInstance]: + """ + Asynchronously lists EsimProfileInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str eid: List the eSIM Profiles that have been associated with an EId. + :param str sim_sid: Find the eSIM Profile resource related to a [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. + :param "EsimProfileInstance.Status" status: List the eSIM Profiles that are in a given status. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + eid=eid, + sim_sid=sim_sid, + status=status, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + eid: Union[str, object] = values.unset, + sim_sid: Union[str, object] = values.unset, + status: Union["EsimProfileInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EsimProfilePage: + """ + Retrieve a single page of EsimProfileInstance records from the API. + Request is executed immediately + + :param eid: List the eSIM Profiles that have been associated with an EId. + :param sim_sid: Find the eSIM Profile resource related to a [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. + :param status: List the eSIM Profiles that are in a given status. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EsimProfileInstance + """ + data = values.of( + { + "Eid": eid, + "SimSid": sim_sid, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EsimProfilePage(self._version, response) + + async def page_async( + self, + eid: Union[str, object] = values.unset, + sim_sid: Union[str, object] = values.unset, + status: Union["EsimProfileInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EsimProfilePage: + """ + Asynchronously retrieve a single page of EsimProfileInstance records from the API. + Request is executed immediately + + :param eid: List the eSIM Profiles that have been associated with an EId. + :param sim_sid: Find the eSIM Profile resource related to a [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. + :param status: List the eSIM Profiles that are in a given status. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EsimProfileInstance + """ + data = values.of( + { + "Eid": eid, + "SimSid": sim_sid, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EsimProfilePage(self._version, response) + + def get_page(self, target_url: str) -> EsimProfilePage: + """ + Retrieve a specific page of EsimProfileInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EsimProfileInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EsimProfilePage(self._version, response) + + async def get_page_async(self, target_url: str) -> EsimProfilePage: + """ + Asynchronously retrieve a specific page of EsimProfileInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EsimProfileInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EsimProfilePage(self._version, response) + + def get(self, sid: str) -> EsimProfileContext: + """ + Constructs a EsimProfileContext + + :param sid: The SID of the eSIM Profile resource to fetch. + """ + return EsimProfileContext(self._version, sid=sid) + + def __call__(self, sid: str) -> EsimProfileContext: + """ + Constructs a EsimProfileContext + + :param sid: The SID of the eSIM Profile resource to fetch. + """ + return EsimProfileContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/fleet.py b/venv/Lib/site-packages/twilio/rest/supersim/v1/fleet.py new file mode 100644 index 00000000..3ea067cf --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/supersim/v1/fleet.py @@ -0,0 +1,727 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class FleetInstance(InstanceResource): + + class DataMetering(object): + PAYG = "payg" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Fleet resource. + :ivar sid: The unique string that we created to identify the Fleet resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Fleet resource. + :ivar data_enabled: Defines whether SIMs in the Fleet are capable of using 2G/3G/4G/LTE/CAT-M data connectivity. Defaults to `true`. + :ivar data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 250MB. + :ivar data_metering: + :ivar sms_commands_enabled: Defines whether SIMs in the Fleet are capable of sending and receiving machine-to-machine SMS via Commands. Defaults to `false`. + :ivar sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :ivar sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :ivar network_access_profile_sid: The SID of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :ivar ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :ivar ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.data_enabled: Optional[bool] = payload.get("data_enabled") + self.data_limit: Optional[int] = deserialize.integer(payload.get("data_limit")) + self.data_metering: Optional["FleetInstance.DataMetering"] = payload.get( + "data_metering" + ) + self.sms_commands_enabled: Optional[bool] = payload.get("sms_commands_enabled") + self.sms_commands_url: Optional[str] = payload.get("sms_commands_url") + self.sms_commands_method: Optional[str] = payload.get("sms_commands_method") + self.network_access_profile_sid: Optional[str] = payload.get( + "network_access_profile_sid" + ) + self.ip_commands_url: Optional[str] = payload.get("ip_commands_url") + self.ip_commands_method: Optional[str] = payload.get("ip_commands_method") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[FleetContext] = None + + @property + def _proxy(self) -> "FleetContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FleetContext for this FleetInstance + """ + if self._context is None: + self._context = FleetContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "FleetInstance": + """ + Fetch the FleetInstance + + + :returns: The fetched FleetInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FleetInstance": + """ + Asynchronous coroutine to fetch the FleetInstance + + + :returns: The fetched FleetInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + unique_name: Union[str, object] = values.unset, + network_access_profile: Union[str, object] = values.unset, + ip_commands_url: Union[str, object] = values.unset, + ip_commands_method: Union[str, object] = values.unset, + sms_commands_url: Union[str, object] = values.unset, + sms_commands_method: Union[str, object] = values.unset, + data_limit: Union[int, object] = values.unset, + ) -> "FleetInstance": + """ + Update the FleetInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. + :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). + + :returns: The updated FleetInstance + """ + return self._proxy.update( + unique_name=unique_name, + network_access_profile=network_access_profile, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + data_limit=data_limit, + ) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + network_access_profile: Union[str, object] = values.unset, + ip_commands_url: Union[str, object] = values.unset, + ip_commands_method: Union[str, object] = values.unset, + sms_commands_url: Union[str, object] = values.unset, + sms_commands_method: Union[str, object] = values.unset, + data_limit: Union[int, object] = values.unset, + ) -> "FleetInstance": + """ + Asynchronous coroutine to update the FleetInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. + :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). + + :returns: The updated FleetInstance + """ + return await self._proxy.update_async( + unique_name=unique_name, + network_access_profile=network_access_profile, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + data_limit=data_limit, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FleetContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the FleetContext + + :param version: Version that contains the resource + :param sid: The SID of the Fleet resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Fleets/{sid}".format(**self._solution) + + def fetch(self) -> FleetInstance: + """ + Fetch the FleetInstance + + + :returns: The fetched FleetInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FleetInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> FleetInstance: + """ + Asynchronous coroutine to fetch the FleetInstance + + + :returns: The fetched FleetInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FleetInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + unique_name: Union[str, object] = values.unset, + network_access_profile: Union[str, object] = values.unset, + ip_commands_url: Union[str, object] = values.unset, + ip_commands_method: Union[str, object] = values.unset, + sms_commands_url: Union[str, object] = values.unset, + sms_commands_method: Union[str, object] = values.unset, + data_limit: Union[int, object] = values.unset, + ) -> FleetInstance: + """ + Update the FleetInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. + :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). + + :returns: The updated FleetInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "NetworkAccessProfile": network_access_profile, + "IpCommandsUrl": ip_commands_url, + "IpCommandsMethod": ip_commands_method, + "SmsCommandsUrl": sms_commands_url, + "SmsCommandsMethod": sms_commands_method, + "DataLimit": data_limit, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FleetInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + network_access_profile: Union[str, object] = values.unset, + ip_commands_url: Union[str, object] = values.unset, + ip_commands_method: Union[str, object] = values.unset, + sms_commands_url: Union[str, object] = values.unset, + sms_commands_method: Union[str, object] = values.unset, + data_limit: Union[int, object] = values.unset, + ) -> FleetInstance: + """ + Asynchronous coroutine to update the FleetInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. + :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). + + :returns: The updated FleetInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "NetworkAccessProfile": network_access_profile, + "IpCommandsUrl": ip_commands_url, + "IpCommandsMethod": ip_commands_method, + "SmsCommandsUrl": sms_commands_url, + "SmsCommandsMethod": sms_commands_method, + "DataLimit": data_limit, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FleetInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FleetPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> FleetInstance: + """ + Build an instance of FleetInstance + + :param payload: Payload response from the API + """ + return FleetInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class FleetList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the FleetList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Fleets" + + def create( + self, + network_access_profile: str, + unique_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + ip_commands_url: Union[str, object] = values.unset, + ip_commands_method: Union[str, object] = values.unset, + sms_commands_enabled: Union[bool, object] = values.unset, + sms_commands_url: Union[str, object] = values.unset, + sms_commands_method: Union[str, object] = values.unset, + ) -> FleetInstance: + """ + Create the FleetInstance + + :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param data_enabled: Defines whether SIMs in the Fleet are capable of using 2G/3G/4G/LTE/CAT-M data connectivity. Defaults to `true`. + :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). + :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param sms_commands_enabled: Defines whether SIMs in the Fleet are capable of sending and receiving machine-to-machine SMS via Commands. Defaults to `true`. + :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + + :returns: The created FleetInstance + """ + + data = values.of( + { + "NetworkAccessProfile": network_access_profile, + "UniqueName": unique_name, + "DataEnabled": serialize.boolean_to_string(data_enabled), + "DataLimit": data_limit, + "IpCommandsUrl": ip_commands_url, + "IpCommandsMethod": ip_commands_method, + "SmsCommandsEnabled": serialize.boolean_to_string(sms_commands_enabled), + "SmsCommandsUrl": sms_commands_url, + "SmsCommandsMethod": sms_commands_method, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FleetInstance(self._version, payload) + + async def create_async( + self, + network_access_profile: str, + unique_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + ip_commands_url: Union[str, object] = values.unset, + ip_commands_method: Union[str, object] = values.unset, + sms_commands_enabled: Union[bool, object] = values.unset, + sms_commands_url: Union[str, object] = values.unset, + sms_commands_method: Union[str, object] = values.unset, + ) -> FleetInstance: + """ + Asynchronously create the FleetInstance + + :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param data_enabled: Defines whether SIMs in the Fleet are capable of using 2G/3G/4G/LTE/CAT-M data connectivity. Defaults to `true`. + :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). + :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param sms_commands_enabled: Defines whether SIMs in the Fleet are capable of sending and receiving machine-to-machine SMS via Commands. Defaults to `true`. + :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + + :returns: The created FleetInstance + """ + + data = values.of( + { + "NetworkAccessProfile": network_access_profile, + "UniqueName": unique_name, + "DataEnabled": serialize.boolean_to_string(data_enabled), + "DataLimit": data_limit, + "IpCommandsUrl": ip_commands_url, + "IpCommandsMethod": ip_commands_method, + "SmsCommandsEnabled": serialize.boolean_to_string(sms_commands_enabled), + "SmsCommandsUrl": sms_commands_url, + "SmsCommandsMethod": sms_commands_method, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FleetInstance(self._version, payload) + + def stream( + self, + network_access_profile: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FleetInstance]: + """ + Streams FleetInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str network_access_profile: The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + network_access_profile=network_access_profile, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + network_access_profile: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FleetInstance]: + """ + Asynchronously streams FleetInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str network_access_profile: The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + network_access_profile=network_access_profile, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + network_access_profile: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FleetInstance]: + """ + Lists FleetInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str network_access_profile: The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + network_access_profile=network_access_profile, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + network_access_profile: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FleetInstance]: + """ + Asynchronously lists FleetInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str network_access_profile: The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + network_access_profile=network_access_profile, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + network_access_profile: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FleetPage: + """ + Retrieve a single page of FleetInstance records from the API. + Request is executed immediately + + :param network_access_profile: The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FleetInstance + """ + data = values.of( + { + "NetworkAccessProfile": network_access_profile, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FleetPage(self._version, response) + + async def page_async( + self, + network_access_profile: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FleetPage: + """ + Asynchronously retrieve a single page of FleetInstance records from the API. + Request is executed immediately + + :param network_access_profile: The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FleetInstance + """ + data = values.of( + { + "NetworkAccessProfile": network_access_profile, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FleetPage(self._version, response) + + def get_page(self, target_url: str) -> FleetPage: + """ + Retrieve a specific page of FleetInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FleetInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return FleetPage(self._version, response) + + async def get_page_async(self, target_url: str) -> FleetPage: + """ + Asynchronously retrieve a specific page of FleetInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FleetInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return FleetPage(self._version, response) + + def get(self, sid: str) -> FleetContext: + """ + Constructs a FleetContext + + :param sid: The SID of the Fleet resource to update. + """ + return FleetContext(self._version, sid=sid) + + def __call__(self, sid: str) -> FleetContext: + """ + Constructs a FleetContext + + :param sid: The SID of the Fleet resource to update. + """ + return FleetContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/ip_command.py b/venv/Lib/site-packages/twilio/rest/supersim/v1/ip_command.py new file mode 100644 index 00000000..72bf7829 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/supersim/v1/ip_command.py @@ -0,0 +1,614 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class IpCommandInstance(InstanceResource): + + class Direction(object): + TO_SIM = "to_sim" + FROM_SIM = "from_sim" + + class PayloadType(object): + TEXT = "text" + BINARY = "binary" + + class Status(object): + QUEUED = "queued" + SENT = "sent" + RECEIVED = "received" + FAILED = "failed" + + """ + :ivar sid: The unique string that we created to identify the IP Command resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IP Command resource. + :ivar sim_sid: The SID of the [Super SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) that this IP Command was sent to or from. + :ivar sim_iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) of the [Super SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) that this IP Command was sent to or from. + :ivar status: + :ivar direction: + :ivar device_ip: The IP address of the device that the IP Command was sent to or received from. For an IP Command sent to a Super SIM, `device_ip` starts out as `null`, and once the IP Command is “sent”, the `device_ip` will be filled out. An IP Command sent from a Super SIM have its `device_ip` always set. + :ivar device_port: For an IP Command sent to a Super SIM, it would be the destination port of the IP message. For an IP Command sent from a Super SIM, it would be the source port of the IP message. + :ivar payload_type: + :ivar payload: The payload that is carried in the IP/UDP message. The payload can be encoded in either text or binary format. For text payload, UTF-8 encoding must be used. For an IP Command sent to a Super SIM, the payload is appended to the IP/UDP message “as is”. The payload should not exceed 1300 bytes. For an IP Command sent from a Super SIM, the payload from the received IP/UDP message is extracted and sent in binary encoding. For an IP Command sent from a Super SIM, the payload should not exceed 1300 bytes. If it is larger than 1300 bytes, there might be fragmentation on the upstream and the message may appear truncated. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the IP Command resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.sim_iccid: Optional[str] = payload.get("sim_iccid") + self.status: Optional["IpCommandInstance.Status"] = payload.get("status") + self.direction: Optional["IpCommandInstance.Direction"] = payload.get( + "direction" + ) + self.device_ip: Optional[str] = payload.get("device_ip") + self.device_port: Optional[int] = deserialize.integer( + payload.get("device_port") + ) + self.payload_type: Optional["IpCommandInstance.PayloadType"] = payload.get( + "payload_type" + ) + self.payload: Optional[str] = payload.get("payload") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[IpCommandContext] = None + + @property + def _proxy(self) -> "IpCommandContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: IpCommandContext for this IpCommandInstance + """ + if self._context is None: + self._context = IpCommandContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "IpCommandInstance": + """ + Fetch the IpCommandInstance + + + :returns: The fetched IpCommandInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "IpCommandInstance": + """ + Asynchronous coroutine to fetch the IpCommandInstance + + + :returns: The fetched IpCommandInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class IpCommandContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the IpCommandContext + + :param version: Version that contains the resource + :param sid: The SID of the IP Command resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/IpCommands/{sid}".format(**self._solution) + + def fetch(self) -> IpCommandInstance: + """ + Fetch the IpCommandInstance + + + :returns: The fetched IpCommandInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return IpCommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> IpCommandInstance: + """ + Asynchronous coroutine to fetch the IpCommandInstance + + + :returns: The fetched IpCommandInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return IpCommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class IpCommandPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> IpCommandInstance: + """ + Build an instance of IpCommandInstance + + :param payload: Payload response from the API + """ + return IpCommandInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class IpCommandList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the IpCommandList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/IpCommands" + + def create( + self, + sim: str, + payload: str, + device_port: int, + payload_type: Union["IpCommandInstance.PayloadType", object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + ) -> IpCommandInstance: + """ + Create the IpCommandInstance + + :param sim: The `sid` or `unique_name` of the [Super SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the IP Command to. + :param payload: The data that will be sent to the device. The payload cannot exceed 1300 bytes. If the PayloadType is set to text, the payload is encoded in UTF-8. If PayloadType is set to binary, the payload is encoded in Base64. + :param device_port: The device port to which the IP Command will be sent. + :param payload_type: + :param callback_url: The URL we should call using the `callback_method` after we have sent the IP Command. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be `GET` or `POST`, and the default is `POST`. + + :returns: The created IpCommandInstance + """ + + data = values.of( + { + "Sim": sim, + "Payload": payload, + "DevicePort": device_port, + "PayloadType": payload_type, + "CallbackUrl": callback_url, + "CallbackMethod": callback_method, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpCommandInstance(self._version, payload) + + async def create_async( + self, + sim: str, + payload: str, + device_port: int, + payload_type: Union["IpCommandInstance.PayloadType", object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + ) -> IpCommandInstance: + """ + Asynchronously create the IpCommandInstance + + :param sim: The `sid` or `unique_name` of the [Super SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the IP Command to. + :param payload: The data that will be sent to the device. The payload cannot exceed 1300 bytes. If the PayloadType is set to text, the payload is encoded in UTF-8. If PayloadType is set to binary, the payload is encoded in Base64. + :param device_port: The device port to which the IP Command will be sent. + :param payload_type: + :param callback_url: The URL we should call using the `callback_method` after we have sent the IP Command. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be `GET` or `POST`, and the default is `POST`. + + :returns: The created IpCommandInstance + """ + + data = values.of( + { + "Sim": sim, + "Payload": payload, + "DevicePort": device_port, + "PayloadType": payload_type, + "CallbackUrl": callback_url, + "CallbackMethod": callback_method, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpCommandInstance(self._version, payload) + + def stream( + self, + sim: Union[str, object] = values.unset, + sim_iccid: Union[str, object] = values.unset, + status: Union["IpCommandInstance.Status", object] = values.unset, + direction: Union["IpCommandInstance.Direction", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[IpCommandInstance]: + """ + Streams IpCommandInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sim: The SID or unique name of the Sim resource that IP Command was sent to or from. + :param str sim_iccid: The ICCID of the Sim resource that IP Command was sent to or from. + :param "IpCommandInstance.Status" status: The status of the IP Command. Can be: `queued`, `sent`, `received` or `failed`. See the [IP Command Status Values](https://www.twilio.com/docs/iot/supersim/api/ipcommand-resource#status-values) for a description of each. + :param "IpCommandInstance.Direction" direction: The direction of the IP Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + sim=sim, + sim_iccid=sim_iccid, + status=status, + direction=direction, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + sim: Union[str, object] = values.unset, + sim_iccid: Union[str, object] = values.unset, + status: Union["IpCommandInstance.Status", object] = values.unset, + direction: Union["IpCommandInstance.Direction", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IpCommandInstance]: + """ + Asynchronously streams IpCommandInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sim: The SID or unique name of the Sim resource that IP Command was sent to or from. + :param str sim_iccid: The ICCID of the Sim resource that IP Command was sent to or from. + :param "IpCommandInstance.Status" status: The status of the IP Command. Can be: `queued`, `sent`, `received` or `failed`. See the [IP Command Status Values](https://www.twilio.com/docs/iot/supersim/api/ipcommand-resource#status-values) for a description of each. + :param "IpCommandInstance.Direction" direction: The direction of the IP Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + sim=sim, + sim_iccid=sim_iccid, + status=status, + direction=direction, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + sim: Union[str, object] = values.unset, + sim_iccid: Union[str, object] = values.unset, + status: Union["IpCommandInstance.Status", object] = values.unset, + direction: Union["IpCommandInstance.Direction", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpCommandInstance]: + """ + Lists IpCommandInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sim: The SID or unique name of the Sim resource that IP Command was sent to or from. + :param str sim_iccid: The ICCID of the Sim resource that IP Command was sent to or from. + :param "IpCommandInstance.Status" status: The status of the IP Command. Can be: `queued`, `sent`, `received` or `failed`. See the [IP Command Status Values](https://www.twilio.com/docs/iot/supersim/api/ipcommand-resource#status-values) for a description of each. + :param "IpCommandInstance.Direction" direction: The direction of the IP Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + sim=sim, + sim_iccid=sim_iccid, + status=status, + direction=direction, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + sim: Union[str, object] = values.unset, + sim_iccid: Union[str, object] = values.unset, + status: Union["IpCommandInstance.Status", object] = values.unset, + direction: Union["IpCommandInstance.Direction", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpCommandInstance]: + """ + Asynchronously lists IpCommandInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sim: The SID or unique name of the Sim resource that IP Command was sent to or from. + :param str sim_iccid: The ICCID of the Sim resource that IP Command was sent to or from. + :param "IpCommandInstance.Status" status: The status of the IP Command. Can be: `queued`, `sent`, `received` or `failed`. See the [IP Command Status Values](https://www.twilio.com/docs/iot/supersim/api/ipcommand-resource#status-values) for a description of each. + :param "IpCommandInstance.Direction" direction: The direction of the IP Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + sim=sim, + sim_iccid=sim_iccid, + status=status, + direction=direction, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + sim: Union[str, object] = values.unset, + sim_iccid: Union[str, object] = values.unset, + status: Union["IpCommandInstance.Status", object] = values.unset, + direction: Union["IpCommandInstance.Direction", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpCommandPage: + """ + Retrieve a single page of IpCommandInstance records from the API. + Request is executed immediately + + :param sim: The SID or unique name of the Sim resource that IP Command was sent to or from. + :param sim_iccid: The ICCID of the Sim resource that IP Command was sent to or from. + :param status: The status of the IP Command. Can be: `queued`, `sent`, `received` or `failed`. See the [IP Command Status Values](https://www.twilio.com/docs/iot/supersim/api/ipcommand-resource#status-values) for a description of each. + :param direction: The direction of the IP Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpCommandInstance + """ + data = values.of( + { + "Sim": sim, + "SimIccid": sim_iccid, + "Status": status, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpCommandPage(self._version, response) + + async def page_async( + self, + sim: Union[str, object] = values.unset, + sim_iccid: Union[str, object] = values.unset, + status: Union["IpCommandInstance.Status", object] = values.unset, + direction: Union["IpCommandInstance.Direction", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpCommandPage: + """ + Asynchronously retrieve a single page of IpCommandInstance records from the API. + Request is executed immediately + + :param sim: The SID or unique name of the Sim resource that IP Command was sent to or from. + :param sim_iccid: The ICCID of the Sim resource that IP Command was sent to or from. + :param status: The status of the IP Command. Can be: `queued`, `sent`, `received` or `failed`. See the [IP Command Status Values](https://www.twilio.com/docs/iot/supersim/api/ipcommand-resource#status-values) for a description of each. + :param direction: The direction of the IP Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpCommandInstance + """ + data = values.of( + { + "Sim": sim, + "SimIccid": sim_iccid, + "Status": status, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpCommandPage(self._version, response) + + def get_page(self, target_url: str) -> IpCommandPage: + """ + Retrieve a specific page of IpCommandInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpCommandInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return IpCommandPage(self._version, response) + + async def get_page_async(self, target_url: str) -> IpCommandPage: + """ + Asynchronously retrieve a specific page of IpCommandInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpCommandInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return IpCommandPage(self._version, response) + + def get(self, sid: str) -> IpCommandContext: + """ + Constructs a IpCommandContext + + :param sid: The SID of the IP Command resource to fetch. + """ + return IpCommandContext(self._version, sid=sid) + + def __call__(self, sid: str) -> IpCommandContext: + """ + Constructs a IpCommandContext + + :param sid: The SID of the IP Command resource to fetch. + """ + return IpCommandContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/network.py b/venv/Lib/site-packages/twilio/rest/supersim/v1/network.py new file mode 100644 index 00000000..211068d0 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/supersim/v1/network.py @@ -0,0 +1,460 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class NetworkInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Network resource. + :ivar friendly_name: A human readable identifier of this resource. + :ivar url: The absolute URL of the Network resource. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resource. + :ivar identifiers: Array of objects identifying the [MCC-MNCs](https://en.wikipedia.org/wiki/Mobile_country_code) that are included in the Network resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.url: Optional[str] = payload.get("url") + self.iso_country: Optional[str] = payload.get("iso_country") + self.identifiers: Optional[List[Dict[str, object]]] = payload.get("identifiers") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[NetworkContext] = None + + @property + def _proxy(self) -> "NetworkContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: NetworkContext for this NetworkInstance + """ + if self._context is None: + self._context = NetworkContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "NetworkInstance": + """ + Fetch the NetworkInstance + + + :returns: The fetched NetworkInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "NetworkInstance": + """ + Asynchronous coroutine to fetch the NetworkInstance + + + :returns: The fetched NetworkInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NetworkContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the NetworkContext + + :param version: Version that contains the resource + :param sid: The SID of the Network resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Networks/{sid}".format(**self._solution) + + def fetch(self) -> NetworkInstance: + """ + Fetch the NetworkInstance + + + :returns: The fetched NetworkInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return NetworkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> NetworkInstance: + """ + Asynchronous coroutine to fetch the NetworkInstance + + + :returns: The fetched NetworkInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return NetworkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NetworkPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> NetworkInstance: + """ + Build an instance of NetworkInstance + + :param payload: Payload response from the API + """ + return NetworkInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class NetworkList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the NetworkList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Networks" + + def stream( + self, + iso_country: Union[str, object] = values.unset, + mcc: Union[str, object] = values.unset, + mnc: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[NetworkInstance]: + """ + Streams NetworkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. + :param str mcc: The 'mobile country code' of a country. Network resources with this `mcc` in their `identifiers` will be read. + :param str mnc: The 'mobile network code' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + iso_country=iso_country, mcc=mcc, mnc=mnc, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + iso_country: Union[str, object] = values.unset, + mcc: Union[str, object] = values.unset, + mnc: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[NetworkInstance]: + """ + Asynchronously streams NetworkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. + :param str mcc: The 'mobile country code' of a country. Network resources with this `mcc` in their `identifiers` will be read. + :param str mnc: The 'mobile network code' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + iso_country=iso_country, mcc=mcc, mnc=mnc, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + iso_country: Union[str, object] = values.unset, + mcc: Union[str, object] = values.unset, + mnc: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NetworkInstance]: + """ + Lists NetworkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. + :param str mcc: The 'mobile country code' of a country. Network resources with this `mcc` in their `identifiers` will be read. + :param str mnc: The 'mobile network code' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + iso_country=iso_country, + mcc=mcc, + mnc=mnc, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + iso_country: Union[str, object] = values.unset, + mcc: Union[str, object] = values.unset, + mnc: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NetworkInstance]: + """ + Asynchronously lists NetworkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. + :param str mcc: The 'mobile country code' of a country. Network resources with this `mcc` in their `identifiers` will be read. + :param str mnc: The 'mobile network code' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + iso_country=iso_country, + mcc=mcc, + mnc=mnc, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + iso_country: Union[str, object] = values.unset, + mcc: Union[str, object] = values.unset, + mnc: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NetworkPage: + """ + Retrieve a single page of NetworkInstance records from the API. + Request is executed immediately + + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. + :param mcc: The 'mobile country code' of a country. Network resources with this `mcc` in their `identifiers` will be read. + :param mnc: The 'mobile network code' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NetworkInstance + """ + data = values.of( + { + "IsoCountry": iso_country, + "Mcc": mcc, + "Mnc": mnc, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NetworkPage(self._version, response) + + async def page_async( + self, + iso_country: Union[str, object] = values.unset, + mcc: Union[str, object] = values.unset, + mnc: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NetworkPage: + """ + Asynchronously retrieve a single page of NetworkInstance records from the API. + Request is executed immediately + + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. + :param mcc: The 'mobile country code' of a country. Network resources with this `mcc` in their `identifiers` will be read. + :param mnc: The 'mobile network code' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NetworkInstance + """ + data = values.of( + { + "IsoCountry": iso_country, + "Mcc": mcc, + "Mnc": mnc, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NetworkPage(self._version, response) + + def get_page(self, target_url: str) -> NetworkPage: + """ + Retrieve a specific page of NetworkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NetworkInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return NetworkPage(self._version, response) + + async def get_page_async(self, target_url: str) -> NetworkPage: + """ + Asynchronously retrieve a specific page of NetworkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NetworkInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return NetworkPage(self._version, response) + + def get(self, sid: str) -> NetworkContext: + """ + Constructs a NetworkContext + + :param sid: The SID of the Network resource to fetch. + """ + return NetworkContext(self._version, sid=sid) + + def __call__(self, sid: str) -> NetworkContext: + """ + Constructs a NetworkContext + + :param sid: The SID of the Network resource to fetch. + """ + return NetworkContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/network_access_profile/__init__.py b/venv/Lib/site-packages/twilio/rest/supersim/v1/network_access_profile/__init__.py new file mode 100644 index 00000000..15b0cc56 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/supersim/v1/network_access_profile/__init__.py @@ -0,0 +1,593 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.supersim.v1.network_access_profile.network_access_profile_network import ( + NetworkAccessProfileNetworkList, +) + + +class NetworkAccessProfileInstance(InstanceResource): + """ + :ivar sid: The unique string that identifies the Network Access Profile resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the Network Access Profile belongs to. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Network Access Profile resource. + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[NetworkAccessProfileContext] = None + + @property + def _proxy(self) -> "NetworkAccessProfileContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: NetworkAccessProfileContext for this NetworkAccessProfileInstance + """ + if self._context is None: + self._context = NetworkAccessProfileContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "NetworkAccessProfileInstance": + """ + Fetch the NetworkAccessProfileInstance + + + :returns: The fetched NetworkAccessProfileInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "NetworkAccessProfileInstance": + """ + Asynchronous coroutine to fetch the NetworkAccessProfileInstance + + + :returns: The fetched NetworkAccessProfileInstance + """ + return await self._proxy.fetch_async() + + def update( + self, unique_name: Union[str, object] = values.unset + ) -> "NetworkAccessProfileInstance": + """ + Update the NetworkAccessProfileInstance + + :param unique_name: The new unique name of the Network Access Profile. + + :returns: The updated NetworkAccessProfileInstance + """ + return self._proxy.update( + unique_name=unique_name, + ) + + async def update_async( + self, unique_name: Union[str, object] = values.unset + ) -> "NetworkAccessProfileInstance": + """ + Asynchronous coroutine to update the NetworkAccessProfileInstance + + :param unique_name: The new unique name of the Network Access Profile. + + :returns: The updated NetworkAccessProfileInstance + """ + return await self._proxy.update_async( + unique_name=unique_name, + ) + + @property + def networks(self) -> NetworkAccessProfileNetworkList: + """ + Access the networks + """ + return self._proxy.networks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NetworkAccessProfileContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the NetworkAccessProfileContext + + :param version: Version that contains the resource + :param sid: The SID of the Network Access Profile to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/NetworkAccessProfiles/{sid}".format(**self._solution) + + self._networks: Optional[NetworkAccessProfileNetworkList] = None + + def fetch(self) -> NetworkAccessProfileInstance: + """ + Fetch the NetworkAccessProfileInstance + + + :returns: The fetched NetworkAccessProfileInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return NetworkAccessProfileInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> NetworkAccessProfileInstance: + """ + Asynchronous coroutine to fetch the NetworkAccessProfileInstance + + + :returns: The fetched NetworkAccessProfileInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return NetworkAccessProfileInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, unique_name: Union[str, object] = values.unset + ) -> NetworkAccessProfileInstance: + """ + Update the NetworkAccessProfileInstance + + :param unique_name: The new unique name of the Network Access Profile. + + :returns: The updated NetworkAccessProfileInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NetworkAccessProfileInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, unique_name: Union[str, object] = values.unset + ) -> NetworkAccessProfileInstance: + """ + Asynchronous coroutine to update the NetworkAccessProfileInstance + + :param unique_name: The new unique name of the Network Access Profile. + + :returns: The updated NetworkAccessProfileInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NetworkAccessProfileInstance( + self._version, payload, sid=self._solution["sid"] + ) + + @property + def networks(self) -> NetworkAccessProfileNetworkList: + """ + Access the networks + """ + if self._networks is None: + self._networks = NetworkAccessProfileNetworkList( + self._version, + self._solution["sid"], + ) + return self._networks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NetworkAccessProfilePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> NetworkAccessProfileInstance: + """ + Build an instance of NetworkAccessProfileInstance + + :param payload: Payload response from the API + """ + return NetworkAccessProfileInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class NetworkAccessProfileList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the NetworkAccessProfileList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/NetworkAccessProfiles" + + def create( + self, + unique_name: Union[str, object] = values.unset, + networks: Union[List[str], object] = values.unset, + ) -> NetworkAccessProfileInstance: + """ + Create the NetworkAccessProfileInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param networks: List of Network SIDs that this Network Access Profile will allow connections to. + + :returns: The created NetworkAccessProfileInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Networks": serialize.map(networks, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NetworkAccessProfileInstance(self._version, payload) + + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + networks: Union[List[str], object] = values.unset, + ) -> NetworkAccessProfileInstance: + """ + Asynchronously create the NetworkAccessProfileInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param networks: List of Network SIDs that this Network Access Profile will allow connections to. + + :returns: The created NetworkAccessProfileInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Networks": serialize.map(networks, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NetworkAccessProfileInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[NetworkAccessProfileInstance]: + """ + Streams NetworkAccessProfileInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[NetworkAccessProfileInstance]: + """ + Asynchronously streams NetworkAccessProfileInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NetworkAccessProfileInstance]: + """ + Lists NetworkAccessProfileInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NetworkAccessProfileInstance]: + """ + Asynchronously lists NetworkAccessProfileInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NetworkAccessProfilePage: + """ + Retrieve a single page of NetworkAccessProfileInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NetworkAccessProfileInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NetworkAccessProfilePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NetworkAccessProfilePage: + """ + Asynchronously retrieve a single page of NetworkAccessProfileInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NetworkAccessProfileInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NetworkAccessProfilePage(self._version, response) + + def get_page(self, target_url: str) -> NetworkAccessProfilePage: + """ + Retrieve a specific page of NetworkAccessProfileInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NetworkAccessProfileInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return NetworkAccessProfilePage(self._version, response) + + async def get_page_async(self, target_url: str) -> NetworkAccessProfilePage: + """ + Asynchronously retrieve a specific page of NetworkAccessProfileInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NetworkAccessProfileInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return NetworkAccessProfilePage(self._version, response) + + def get(self, sid: str) -> NetworkAccessProfileContext: + """ + Constructs a NetworkAccessProfileContext + + :param sid: The SID of the Network Access Profile to update. + """ + return NetworkAccessProfileContext(self._version, sid=sid) + + def __call__(self, sid: str) -> NetworkAccessProfileContext: + """ + Constructs a NetworkAccessProfileContext + + :param sid: The SID of the Network Access Profile to update. + """ + return NetworkAccessProfileContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/network_access_profile/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/supersim/v1/network_access_profile/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..705b80e4 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/supersim/v1/network_access_profile/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/network_access_profile/__pycache__/network_access_profile_network.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/supersim/v1/network_access_profile/__pycache__/network_access_profile_network.cpython-312.pyc new file mode 100644 index 00000000..04f8e420 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/supersim/v1/network_access_profile/__pycache__/network_access_profile_network.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/network_access_profile/network_access_profile_network.py b/venv/Lib/site-packages/twilio/rest/supersim/v1/network_access_profile/network_access_profile_network.py new file mode 100644 index 00000000..c7099b8a --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/supersim/v1/network_access_profile/network_access_profile_network.py @@ -0,0 +1,557 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class NetworkAccessProfileNetworkInstance(InstanceResource): + """ + :ivar sid: The unique string that identifies the Network resource. + :ivar network_access_profile_sid: The unique string that identifies the Network resource's Network Access Profile resource. + :ivar friendly_name: A human readable identifier of the Network this resource refers to. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resource. + :ivar identifiers: Array of objects identifying the [MCC-MNCs](https://en.wikipedia.org/wiki/Mobile_country_code) that are included in the Network resource. + :ivar url: The absolute URL of the Network resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + network_access_profile_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.network_access_profile_sid: Optional[str] = payload.get( + "network_access_profile_sid" + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.iso_country: Optional[str] = payload.get("iso_country") + self.identifiers: Optional[List[Dict[str, object]]] = payload.get("identifiers") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "network_access_profile_sid": network_access_profile_sid, + "sid": sid or self.sid, + } + self._context: Optional[NetworkAccessProfileNetworkContext] = None + + @property + def _proxy(self) -> "NetworkAccessProfileNetworkContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: NetworkAccessProfileNetworkContext for this NetworkAccessProfileNetworkInstance + """ + if self._context is None: + self._context = NetworkAccessProfileNetworkContext( + self._version, + network_access_profile_sid=self._solution["network_access_profile_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the NetworkAccessProfileNetworkInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the NetworkAccessProfileNetworkInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "NetworkAccessProfileNetworkInstance": + """ + Fetch the NetworkAccessProfileNetworkInstance + + + :returns: The fetched NetworkAccessProfileNetworkInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "NetworkAccessProfileNetworkInstance": + """ + Asynchronous coroutine to fetch the NetworkAccessProfileNetworkInstance + + + :returns: The fetched NetworkAccessProfileNetworkInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class NetworkAccessProfileNetworkContext(InstanceContext): + + def __init__(self, version: Version, network_access_profile_sid: str, sid: str): + """ + Initialize the NetworkAccessProfileNetworkContext + + :param version: Version that contains the resource + :param network_access_profile_sid: The unique string that identifies the Network Access Profile resource. + :param sid: The SID of the Network resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "network_access_profile_sid": network_access_profile_sid, + "sid": sid, + } + self._uri = ( + "/NetworkAccessProfiles/{network_access_profile_sid}/Networks/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the NetworkAccessProfileNetworkInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the NetworkAccessProfileNetworkInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> NetworkAccessProfileNetworkInstance: + """ + Fetch the NetworkAccessProfileNetworkInstance + + + :returns: The fetched NetworkAccessProfileNetworkInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> NetworkAccessProfileNetworkInstance: + """ + Asynchronous coroutine to fetch the NetworkAccessProfileNetworkInstance + + + :returns: The fetched NetworkAccessProfileNetworkInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class NetworkAccessProfileNetworkPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> NetworkAccessProfileNetworkInstance: + """ + Build an instance of NetworkAccessProfileNetworkInstance + + :param payload: Payload response from the API + """ + return NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class NetworkAccessProfileNetworkList(ListResource): + + def __init__(self, version: Version, network_access_profile_sid: str): + """ + Initialize the NetworkAccessProfileNetworkList + + :param version: Version that contains the resource + :param network_access_profile_sid: The unique string that identifies the Network Access Profile resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "network_access_profile_sid": network_access_profile_sid, + } + self._uri = ( + "/NetworkAccessProfiles/{network_access_profile_sid}/Networks".format( + **self._solution + ) + ) + + def create(self, network: str) -> NetworkAccessProfileNetworkInstance: + """ + Create the NetworkAccessProfileNetworkInstance + + :param network: The SID of the Network resource to be added to the Network Access Profile resource. + + :returns: The created NetworkAccessProfileNetworkInstance + """ + + data = values.of( + { + "Network": network, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + ) + + async def create_async(self, network: str) -> NetworkAccessProfileNetworkInstance: + """ + Asynchronously create the NetworkAccessProfileNetworkInstance + + :param network: The SID of the Network resource to be added to the Network Access Profile resource. + + :returns: The created NetworkAccessProfileNetworkInstance + """ + + data = values.of( + { + "Network": network, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[NetworkAccessProfileNetworkInstance]: + """ + Streams NetworkAccessProfileNetworkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[NetworkAccessProfileNetworkInstance]: + """ + Asynchronously streams NetworkAccessProfileNetworkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NetworkAccessProfileNetworkInstance]: + """ + Lists NetworkAccessProfileNetworkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NetworkAccessProfileNetworkInstance]: + """ + Asynchronously lists NetworkAccessProfileNetworkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NetworkAccessProfileNetworkPage: + """ + Retrieve a single page of NetworkAccessProfileNetworkInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NetworkAccessProfileNetworkInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NetworkAccessProfileNetworkPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NetworkAccessProfileNetworkPage: + """ + Asynchronously retrieve a single page of NetworkAccessProfileNetworkInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NetworkAccessProfileNetworkInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NetworkAccessProfileNetworkPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> NetworkAccessProfileNetworkPage: + """ + Retrieve a specific page of NetworkAccessProfileNetworkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NetworkAccessProfileNetworkInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return NetworkAccessProfileNetworkPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> NetworkAccessProfileNetworkPage: + """ + Asynchronously retrieve a specific page of NetworkAccessProfileNetworkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NetworkAccessProfileNetworkInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return NetworkAccessProfileNetworkPage(self._version, response, self._solution) + + def get(self, sid: str) -> NetworkAccessProfileNetworkContext: + """ + Constructs a NetworkAccessProfileNetworkContext + + :param sid: The SID of the Network resource to fetch. + """ + return NetworkAccessProfileNetworkContext( + self._version, + network_access_profile_sid=self._solution["network_access_profile_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> NetworkAccessProfileNetworkContext: + """ + Constructs a NetworkAccessProfileNetworkContext + + :param sid: The SID of the Network resource to fetch. + """ + return NetworkAccessProfileNetworkContext( + self._version, + network_access_profile_sid=self._solution["network_access_profile_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/settings_update.py b/venv/Lib/site-packages/twilio/rest/supersim/v1/settings_update.py new file mode 100644 index 00000000..294e1102 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/supersim/v1/settings_update.py @@ -0,0 +1,337 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SettingsUpdateInstance(InstanceResource): + + class Status(object): + SCHEDULED = "scheduled" + IN_PROGRESS = "in-progress" + SUCCESSFUL = "successful" + FAILED = "failed" + + """ + :ivar sid: The unique identifier of this Settings Update. + :ivar iccid: The [ICCID](https://en.wikipedia.org/wiki/SIM_card#ICCID) associated with the SIM. + :ivar sim_sid: The SID of the Super SIM to which this Settings Update was applied. + :ivar status: + :ivar packages: Array containing the different Settings Packages that will be applied to the SIM after the update completes. Each object within the array indicates the name and the version of the Settings Package that will be on the SIM if the update is successful. + :ivar date_completed: The time, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, when the update successfully completed and the new settings were applied to the SIM. + :ivar date_created: The date that this Settings Update was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date that this Settings Update was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.iccid: Optional[str] = payload.get("iccid") + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.status: Optional["SettingsUpdateInstance.Status"] = payload.get("status") + self.packages: Optional[List[Dict[str, object]]] = payload.get("packages") + self.date_completed: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_completed") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class SettingsUpdatePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SettingsUpdateInstance: + """ + Build an instance of SettingsUpdateInstance + + :param payload: Payload response from the API + """ + return SettingsUpdateInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SettingsUpdateList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SettingsUpdateList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/SettingsUpdates" + + def stream( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SettingsUpdateInstance]: + """ + Streams SettingsUpdateInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sim: Filter the Settings Updates by a Super SIM's SID or UniqueName. + :param "SettingsUpdateInstance.Status" status: Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(sim=sim, status=status, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SettingsUpdateInstance]: + """ + Asynchronously streams SettingsUpdateInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sim: Filter the Settings Updates by a Super SIM's SID or UniqueName. + :param "SettingsUpdateInstance.Status" status: Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + sim=sim, status=status, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SettingsUpdateInstance]: + """ + Lists SettingsUpdateInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sim: Filter the Settings Updates by a Super SIM's SID or UniqueName. + :param "SettingsUpdateInstance.Status" status: Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + sim=sim, + status=status, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SettingsUpdateInstance]: + """ + Asynchronously lists SettingsUpdateInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sim: Filter the Settings Updates by a Super SIM's SID or UniqueName. + :param "SettingsUpdateInstance.Status" status: Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + sim=sim, + status=status, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SettingsUpdatePage: + """ + Retrieve a single page of SettingsUpdateInstance records from the API. + Request is executed immediately + + :param sim: Filter the Settings Updates by a Super SIM's SID or UniqueName. + :param status: Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SettingsUpdateInstance + """ + data = values.of( + { + "Sim": sim, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SettingsUpdatePage(self._version, response) + + async def page_async( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SettingsUpdatePage: + """ + Asynchronously retrieve a single page of SettingsUpdateInstance records from the API. + Request is executed immediately + + :param sim: Filter the Settings Updates by a Super SIM's SID or UniqueName. + :param status: Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SettingsUpdateInstance + """ + data = values.of( + { + "Sim": sim, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SettingsUpdatePage(self._version, response) + + def get_page(self, target_url: str) -> SettingsUpdatePage: + """ + Retrieve a specific page of SettingsUpdateInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SettingsUpdateInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SettingsUpdatePage(self._version, response) + + async def get_page_async(self, target_url: str) -> SettingsUpdatePage: + """ + Asynchronously retrieve a specific page of SettingsUpdateInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SettingsUpdateInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SettingsUpdatePage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/sim/__init__.py b/venv/Lib/site-packages/twilio/rest/supersim/v1/sim/__init__.py new file mode 100644 index 00000000..fa878a16 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/supersim/v1/sim/__init__.py @@ -0,0 +1,735 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.supersim.v1.sim.billing_period import BillingPeriodList +from twilio.rest.supersim.v1.sim.sim_ip_address import SimIpAddressList + + +class SimInstance(InstanceResource): + + class Status(object): + NEW = "new" + READY = "ready" + ACTIVE = "active" + INACTIVE = "inactive" + SCHEDULED = "scheduled" + + class StatusUpdate(object): + READY = "ready" + ACTIVE = "active" + INACTIVE = "inactive" + + """ + :ivar sid: The unique string that identifies the Sim resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the Super SIM belongs to. + :ivar iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with the SIM. + :ivar status: + :ivar fleet_sid: The unique ID of the Fleet configured for this SIM. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Sim Resource. + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.iccid: Optional[str] = payload.get("iccid") + self.status: Optional["SimInstance.Status"] = payload.get("status") + self.fleet_sid: Optional[str] = payload.get("fleet_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SimContext] = None + + @property + def _proxy(self) -> "SimContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SimContext for this SimInstance + """ + if self._context is None: + self._context = SimContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "SimInstance": + """ + Fetch the SimInstance + + + :returns: The fetched SimInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SimInstance": + """ + Asynchronous coroutine to fetch the SimInstance + + + :returns: The fetched SimInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + unique_name: Union[str, object] = values.unset, + status: Union["SimInstance.StatusUpdate", object] = values.unset, + fleet: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> "SimInstance": + """ + Update the SimInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param status: + :param fleet: The SID or unique name of the Fleet to which the SIM resource should be assigned. + :param callback_url: The URL we should call using the `callback_method` after an asynchronous update has finished. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param account_sid: The SID of the Account to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a Subaccount of the requesting Account. Only valid when the Sim resource's status is new. + + :returns: The updated SimInstance + """ + return self._proxy.update( + unique_name=unique_name, + status=status, + fleet=fleet, + callback_url=callback_url, + callback_method=callback_method, + account_sid=account_sid, + ) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + status: Union["SimInstance.StatusUpdate", object] = values.unset, + fleet: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> "SimInstance": + """ + Asynchronous coroutine to update the SimInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param status: + :param fleet: The SID or unique name of the Fleet to which the SIM resource should be assigned. + :param callback_url: The URL we should call using the `callback_method` after an asynchronous update has finished. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param account_sid: The SID of the Account to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a Subaccount of the requesting Account. Only valid when the Sim resource's status is new. + + :returns: The updated SimInstance + """ + return await self._proxy.update_async( + unique_name=unique_name, + status=status, + fleet=fleet, + callback_url=callback_url, + callback_method=callback_method, + account_sid=account_sid, + ) + + @property + def billing_periods(self) -> BillingPeriodList: + """ + Access the billing_periods + """ + return self._proxy.billing_periods + + @property + def sim_ip_addresses(self) -> SimIpAddressList: + """ + Access the sim_ip_addresses + """ + return self._proxy.sim_ip_addresses + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SimContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SimContext + + :param version: Version that contains the resource + :param sid: The SID of the Sim resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Sims/{sid}".format(**self._solution) + + self._billing_periods: Optional[BillingPeriodList] = None + self._sim_ip_addresses: Optional[SimIpAddressList] = None + + def fetch(self) -> SimInstance: + """ + Fetch the SimInstance + + + :returns: The fetched SimInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SimInstance: + """ + Asynchronous coroutine to fetch the SimInstance + + + :returns: The fetched SimInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + unique_name: Union[str, object] = values.unset, + status: Union["SimInstance.StatusUpdate", object] = values.unset, + fleet: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> SimInstance: + """ + Update the SimInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param status: + :param fleet: The SID or unique name of the Fleet to which the SIM resource should be assigned. + :param callback_url: The URL we should call using the `callback_method` after an asynchronous update has finished. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param account_sid: The SID of the Account to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a Subaccount of the requesting Account. Only valid when the Sim resource's status is new. + + :returns: The updated SimInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Status": status, + "Fleet": fleet, + "CallbackUrl": callback_url, + "CallbackMethod": callback_method, + "AccountSid": account_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SimInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + status: Union["SimInstance.StatusUpdate", object] = values.unset, + fleet: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> SimInstance: + """ + Asynchronous coroutine to update the SimInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param status: + :param fleet: The SID or unique name of the Fleet to which the SIM resource should be assigned. + :param callback_url: The URL we should call using the `callback_method` after an asynchronous update has finished. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param account_sid: The SID of the Account to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a Subaccount of the requesting Account. Only valid when the Sim resource's status is new. + + :returns: The updated SimInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Status": status, + "Fleet": fleet, + "CallbackUrl": callback_url, + "CallbackMethod": callback_method, + "AccountSid": account_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SimInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def billing_periods(self) -> BillingPeriodList: + """ + Access the billing_periods + """ + if self._billing_periods is None: + self._billing_periods = BillingPeriodList( + self._version, + self._solution["sid"], + ) + return self._billing_periods + + @property + def sim_ip_addresses(self) -> SimIpAddressList: + """ + Access the sim_ip_addresses + """ + if self._sim_ip_addresses is None: + self._sim_ip_addresses = SimIpAddressList( + self._version, + self._solution["sid"], + ) + return self._sim_ip_addresses + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SimPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SimInstance: + """ + Build an instance of SimInstance + + :param payload: Payload response from the API + """ + return SimInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SimList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SimList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Sims" + + def create(self, iccid: str, registration_code: str) -> SimInstance: + """ + Create the SimInstance + + :param iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) of the Super SIM to be added to your Account. + :param registration_code: The 10-digit code required to claim the Super SIM for your Account. + + :returns: The created SimInstance + """ + + data = values.of( + { + "Iccid": iccid, + "RegistrationCode": registration_code, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SimInstance(self._version, payload) + + async def create_async(self, iccid: str, registration_code: str) -> SimInstance: + """ + Asynchronously create the SimInstance + + :param iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) of the Super SIM to be added to your Account. + :param registration_code: The 10-digit code required to claim the Super SIM for your Account. + + :returns: The created SimInstance + """ + + data = values.of( + { + "Iccid": iccid, + "RegistrationCode": registration_code, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SimInstance(self._version, payload) + + def stream( + self, + status: Union["SimInstance.Status", object] = values.unset, + fleet: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SimInstance]: + """ + Streams SimInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "SimInstance.Status" status: The status of the Sim resources to read. Can be `new`, `ready`, `active`, `inactive`, or `scheduled`. + :param str fleet: The SID or unique name of the Fleet to which a list of Sims are assigned. + :param str iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with a Super SIM to filter the list by. Passing this parameter will always return a list containing zero or one SIMs. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, fleet=fleet, iccid=iccid, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["SimInstance.Status", object] = values.unset, + fleet: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SimInstance]: + """ + Asynchronously streams SimInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "SimInstance.Status" status: The status of the Sim resources to read. Can be `new`, `ready`, `active`, `inactive`, or `scheduled`. + :param str fleet: The SID or unique name of the Fleet to which a list of Sims are assigned. + :param str iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with a Super SIM to filter the list by. Passing this parameter will always return a list containing zero or one SIMs. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, fleet=fleet, iccid=iccid, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["SimInstance.Status", object] = values.unset, + fleet: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SimInstance]: + """ + Lists SimInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "SimInstance.Status" status: The status of the Sim resources to read. Can be `new`, `ready`, `active`, `inactive`, or `scheduled`. + :param str fleet: The SID or unique name of the Fleet to which a list of Sims are assigned. + :param str iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with a Super SIM to filter the list by. Passing this parameter will always return a list containing zero or one SIMs. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + fleet=fleet, + iccid=iccid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["SimInstance.Status", object] = values.unset, + fleet: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SimInstance]: + """ + Asynchronously lists SimInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "SimInstance.Status" status: The status of the Sim resources to read. Can be `new`, `ready`, `active`, `inactive`, or `scheduled`. + :param str fleet: The SID or unique name of the Fleet to which a list of Sims are assigned. + :param str iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with a Super SIM to filter the list by. Passing this parameter will always return a list containing zero or one SIMs. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + fleet=fleet, + iccid=iccid, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["SimInstance.Status", object] = values.unset, + fleet: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SimPage: + """ + Retrieve a single page of SimInstance records from the API. + Request is executed immediately + + :param status: The status of the Sim resources to read. Can be `new`, `ready`, `active`, `inactive`, or `scheduled`. + :param fleet: The SID or unique name of the Fleet to which a list of Sims are assigned. + :param iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with a Super SIM to filter the list by. Passing this parameter will always return a list containing zero or one SIMs. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SimInstance + """ + data = values.of( + { + "Status": status, + "Fleet": fleet, + "Iccid": iccid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SimPage(self._version, response) + + async def page_async( + self, + status: Union["SimInstance.Status", object] = values.unset, + fleet: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SimPage: + """ + Asynchronously retrieve a single page of SimInstance records from the API. + Request is executed immediately + + :param status: The status of the Sim resources to read. Can be `new`, `ready`, `active`, `inactive`, or `scheduled`. + :param fleet: The SID or unique name of the Fleet to which a list of Sims are assigned. + :param iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with a Super SIM to filter the list by. Passing this parameter will always return a list containing zero or one SIMs. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SimInstance + """ + data = values.of( + { + "Status": status, + "Fleet": fleet, + "Iccid": iccid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SimPage(self._version, response) + + def get_page(self, target_url: str) -> SimPage: + """ + Retrieve a specific page of SimInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SimInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SimPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SimPage: + """ + Asynchronously retrieve a specific page of SimInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SimInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SimPage(self._version, response) + + def get(self, sid: str) -> SimContext: + """ + Constructs a SimContext + + :param sid: The SID of the Sim resource to update. + """ + return SimContext(self._version, sid=sid) + + def __call__(self, sid: str) -> SimContext: + """ + Constructs a SimContext + + :param sid: The SID of the Sim resource to update. + """ + return SimContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/sim/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/supersim/v1/sim/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..057dd7ee Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/supersim/v1/sim/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/sim/__pycache__/billing_period.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/supersim/v1/sim/__pycache__/billing_period.cpython-312.pyc new file mode 100644 index 00000000..8f620366 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/supersim/v1/sim/__pycache__/billing_period.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/sim/__pycache__/sim_ip_address.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/supersim/v1/sim/__pycache__/sim_ip_address.cpython-312.pyc new file mode 100644 index 00000000..1bf512a6 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/supersim/v1/sim/__pycache__/sim_ip_address.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/sim/billing_period.py b/venv/Lib/site-packages/twilio/rest/supersim/v1/sim/billing_period.py new file mode 100644 index 00000000..27cbe122 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/supersim/v1/sim/billing_period.py @@ -0,0 +1,316 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class BillingPeriodInstance(InstanceResource): + + class BpType(object): + READY = "ready" + ACTIVE = "active" + + """ + :ivar sid: The SID of the Billing Period. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) the Super SIM belongs to. + :ivar sim_sid: The SID of the Super SIM the Billing Period belongs to. + :ivar start_time: The start time of the Billing Period specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar end_time: The end time of the Billing Period specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar period_type: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], sim_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.period_type: Optional["BillingPeriodInstance.BpType"] = payload.get( + "period_type" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "sim_sid": sim_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BillingPeriodPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> BillingPeriodInstance: + """ + Build an instance of BillingPeriodInstance + + :param payload: Payload response from the API + """ + return BillingPeriodInstance( + self._version, payload, sim_sid=self._solution["sim_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class BillingPeriodList(ListResource): + + def __init__(self, version: Version, sim_sid: str): + """ + Initialize the BillingPeriodList + + :param version: Version that contains the resource + :param sim_sid: The SID of the Super SIM to list Billing Periods for. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sim_sid": sim_sid, + } + self._uri = "/Sims/{sim_sid}/BillingPeriods".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BillingPeriodInstance]: + """ + Streams BillingPeriodInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BillingPeriodInstance]: + """ + Asynchronously streams BillingPeriodInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BillingPeriodInstance]: + """ + Lists BillingPeriodInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BillingPeriodInstance]: + """ + Asynchronously lists BillingPeriodInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BillingPeriodPage: + """ + Retrieve a single page of BillingPeriodInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BillingPeriodInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BillingPeriodPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BillingPeriodPage: + """ + Asynchronously retrieve a single page of BillingPeriodInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BillingPeriodInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BillingPeriodPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> BillingPeriodPage: + """ + Retrieve a specific page of BillingPeriodInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BillingPeriodInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return BillingPeriodPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> BillingPeriodPage: + """ + Asynchronously retrieve a specific page of BillingPeriodInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BillingPeriodInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return BillingPeriodPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/sim/sim_ip_address.py b/venv/Lib/site-packages/twilio/rest/supersim/v1/sim/sim_ip_address.py new file mode 100644 index 00000000..0c4c3163 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/supersim/v1/sim/sim_ip_address.py @@ -0,0 +1,295 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SimIpAddressInstance(InstanceResource): + + class IpAddressVersion(object): + IPV4 = "IPv4" + IPV6 = "IPv6" + + """ + :ivar ip_address: IP address assigned to the given Super SIM + :ivar ip_address_version: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], sim_sid: str): + super().__init__(version) + + self.ip_address: Optional[str] = payload.get("ip_address") + self.ip_address_version: Optional["SimIpAddressInstance.IpAddressVersion"] = ( + payload.get("ip_address_version") + ) + + self._solution = { + "sim_sid": sim_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SimIpAddressPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SimIpAddressInstance: + """ + Build an instance of SimIpAddressInstance + + :param payload: Payload response from the API + """ + return SimIpAddressInstance( + self._version, payload, sim_sid=self._solution["sim_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SimIpAddressList(ListResource): + + def __init__(self, version: Version, sim_sid: str): + """ + Initialize the SimIpAddressList + + :param version: Version that contains the resource + :param sim_sid: The SID of the Super SIM to list IP Addresses for. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sim_sid": sim_sid, + } + self._uri = "/Sims/{sim_sid}/IpAddresses".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SimIpAddressInstance]: + """ + Streams SimIpAddressInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SimIpAddressInstance]: + """ + Asynchronously streams SimIpAddressInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SimIpAddressInstance]: + """ + Lists SimIpAddressInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SimIpAddressInstance]: + """ + Asynchronously lists SimIpAddressInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SimIpAddressPage: + """ + Retrieve a single page of SimIpAddressInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SimIpAddressInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SimIpAddressPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SimIpAddressPage: + """ + Asynchronously retrieve a single page of SimIpAddressInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SimIpAddressInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SimIpAddressPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SimIpAddressPage: + """ + Retrieve a specific page of SimIpAddressInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SimIpAddressInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SimIpAddressPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SimIpAddressPage: + """ + Asynchronously retrieve a specific page of SimIpAddressInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SimIpAddressInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SimIpAddressPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/sms_command.py b/venv/Lib/site-packages/twilio/rest/supersim/v1/sms_command.py new file mode 100644 index 00000000..dd70d242 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/supersim/v1/sms_command.py @@ -0,0 +1,563 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SmsCommandInstance(InstanceResource): + + class Direction(object): + TO_SIM = "to_sim" + FROM_SIM = "from_sim" + + class Status(object): + QUEUED = "queued" + SENT = "sent" + DELIVERED = "delivered" + RECEIVED = "received" + FAILED = "failed" + + """ + :ivar sid: The unique string that we created to identify the SMS Command resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the SMS Command resource. + :ivar sim_sid: The SID of the [SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) that this SMS Command was sent to or from. + :ivar payload: The message body of the SMS Command sent to or from the SIM. For text mode messages, this can be up to 160 characters. + :ivar status: + :ivar direction: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the SMS Command resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.payload: Optional[str] = payload.get("payload") + self.status: Optional["SmsCommandInstance.Status"] = payload.get("status") + self.direction: Optional["SmsCommandInstance.Direction"] = payload.get( + "direction" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SmsCommandContext] = None + + @property + def _proxy(self) -> "SmsCommandContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SmsCommandContext for this SmsCommandInstance + """ + if self._context is None: + self._context = SmsCommandContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "SmsCommandInstance": + """ + Fetch the SmsCommandInstance + + + :returns: The fetched SmsCommandInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SmsCommandInstance": + """ + Asynchronous coroutine to fetch the SmsCommandInstance + + + :returns: The fetched SmsCommandInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SmsCommandContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SmsCommandContext + + :param version: Version that contains the resource + :param sid: The SID of the SMS Command resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/SmsCommands/{sid}".format(**self._solution) + + def fetch(self) -> SmsCommandInstance: + """ + Fetch the SmsCommandInstance + + + :returns: The fetched SmsCommandInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SmsCommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SmsCommandInstance: + """ + Asynchronous coroutine to fetch the SmsCommandInstance + + + :returns: The fetched SmsCommandInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SmsCommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SmsCommandPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SmsCommandInstance: + """ + Build an instance of SmsCommandInstance + + :param payload: Payload response from the API + """ + return SmsCommandInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SmsCommandList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SmsCommandList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/SmsCommands" + + def create( + self, + sim: str, + payload: str, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + ) -> SmsCommandInstance: + """ + Create the SmsCommandInstance + + :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the SMS Command to. + :param payload: The message body of the SMS Command. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param callback_url: The URL we should call using the `callback_method` after we have sent the command. + + :returns: The created SmsCommandInstance + """ + + data = values.of( + { + "Sim": sim, + "Payload": payload, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SmsCommandInstance(self._version, payload) + + async def create_async( + self, + sim: str, + payload: str, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + ) -> SmsCommandInstance: + """ + Asynchronously create the SmsCommandInstance + + :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the SMS Command to. + :param payload: The message body of the SMS Command. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param callback_url: The URL we should call using the `callback_method` after we have sent the command. + + :returns: The created SmsCommandInstance + """ + + data = values.of( + { + "Sim": sim, + "Payload": payload, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SmsCommandInstance(self._version, payload) + + def stream( + self, + sim: Union[str, object] = values.unset, + status: Union["SmsCommandInstance.Status", object] = values.unset, + direction: Union["SmsCommandInstance.Direction", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SmsCommandInstance]: + """ + Streams SmsCommandInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sim: The SID or unique name of the Sim resource that SMS Command was sent to or from. + :param "SmsCommandInstance.Status" status: The status of the SMS Command. Can be: `queued`, `sent`, `delivered`, `received` or `failed`. See the [SMS Command Status Values](https://www.twilio.com/docs/iot/supersim/api/smscommand-resource#status-values) for a description of each. + :param "SmsCommandInstance.Direction" direction: The direction of the SMS Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + sim=sim, status=status, direction=direction, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + sim: Union[str, object] = values.unset, + status: Union["SmsCommandInstance.Status", object] = values.unset, + direction: Union["SmsCommandInstance.Direction", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SmsCommandInstance]: + """ + Asynchronously streams SmsCommandInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sim: The SID or unique name of the Sim resource that SMS Command was sent to or from. + :param "SmsCommandInstance.Status" status: The status of the SMS Command. Can be: `queued`, `sent`, `delivered`, `received` or `failed`. See the [SMS Command Status Values](https://www.twilio.com/docs/iot/supersim/api/smscommand-resource#status-values) for a description of each. + :param "SmsCommandInstance.Direction" direction: The direction of the SMS Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + sim=sim, status=status, direction=direction, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + sim: Union[str, object] = values.unset, + status: Union["SmsCommandInstance.Status", object] = values.unset, + direction: Union["SmsCommandInstance.Direction", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SmsCommandInstance]: + """ + Lists SmsCommandInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sim: The SID or unique name of the Sim resource that SMS Command was sent to or from. + :param "SmsCommandInstance.Status" status: The status of the SMS Command. Can be: `queued`, `sent`, `delivered`, `received` or `failed`. See the [SMS Command Status Values](https://www.twilio.com/docs/iot/supersim/api/smscommand-resource#status-values) for a description of each. + :param "SmsCommandInstance.Direction" direction: The direction of the SMS Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + sim=sim, + status=status, + direction=direction, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + sim: Union[str, object] = values.unset, + status: Union["SmsCommandInstance.Status", object] = values.unset, + direction: Union["SmsCommandInstance.Direction", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SmsCommandInstance]: + """ + Asynchronously lists SmsCommandInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sim: The SID or unique name of the Sim resource that SMS Command was sent to or from. + :param "SmsCommandInstance.Status" status: The status of the SMS Command. Can be: `queued`, `sent`, `delivered`, `received` or `failed`. See the [SMS Command Status Values](https://www.twilio.com/docs/iot/supersim/api/smscommand-resource#status-values) for a description of each. + :param "SmsCommandInstance.Direction" direction: The direction of the SMS Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + sim=sim, + status=status, + direction=direction, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + sim: Union[str, object] = values.unset, + status: Union["SmsCommandInstance.Status", object] = values.unset, + direction: Union["SmsCommandInstance.Direction", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SmsCommandPage: + """ + Retrieve a single page of SmsCommandInstance records from the API. + Request is executed immediately + + :param sim: The SID or unique name of the Sim resource that SMS Command was sent to or from. + :param status: The status of the SMS Command. Can be: `queued`, `sent`, `delivered`, `received` or `failed`. See the [SMS Command Status Values](https://www.twilio.com/docs/iot/supersim/api/smscommand-resource#status-values) for a description of each. + :param direction: The direction of the SMS Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SmsCommandInstance + """ + data = values.of( + { + "Sim": sim, + "Status": status, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SmsCommandPage(self._version, response) + + async def page_async( + self, + sim: Union[str, object] = values.unset, + status: Union["SmsCommandInstance.Status", object] = values.unset, + direction: Union["SmsCommandInstance.Direction", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SmsCommandPage: + """ + Asynchronously retrieve a single page of SmsCommandInstance records from the API. + Request is executed immediately + + :param sim: The SID or unique name of the Sim resource that SMS Command was sent to or from. + :param status: The status of the SMS Command. Can be: `queued`, `sent`, `delivered`, `received` or `failed`. See the [SMS Command Status Values](https://www.twilio.com/docs/iot/supersim/api/smscommand-resource#status-values) for a description of each. + :param direction: The direction of the SMS Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SmsCommandInstance + """ + data = values.of( + { + "Sim": sim, + "Status": status, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SmsCommandPage(self._version, response) + + def get_page(self, target_url: str) -> SmsCommandPage: + """ + Retrieve a specific page of SmsCommandInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SmsCommandInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SmsCommandPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SmsCommandPage: + """ + Asynchronously retrieve a specific page of SmsCommandInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SmsCommandInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SmsCommandPage(self._version, response) + + def get(self, sid: str) -> SmsCommandContext: + """ + Constructs a SmsCommandContext + + :param sid: The SID of the SMS Command resource to fetch. + """ + return SmsCommandContext(self._version, sid=sid) + + def __call__(self, sid: str) -> SmsCommandContext: + """ + Constructs a SmsCommandContext + + :param sid: The SID of the SMS Command resource to fetch. + """ + return SmsCommandContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/supersim/v1/usage_record.py b/venv/Lib/site-packages/twilio/rest/supersim/v1/usage_record.py new file mode 100644 index 00000000..94072a51 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/supersim/v1/usage_record.py @@ -0,0 +1,458 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UsageRecordInstance(InstanceResource): + + class Granularity(object): + HOUR = "hour" + DAY = "day" + ALL = "all" + + class Group(object): + SIM = "sim" + FLEET = "fleet" + NETWORK = "network" + ISOCOUNTRY = "isoCountry" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that incurred the usage. + :ivar sim_sid: SID of a Sim resource to which the UsageRecord belongs. Value will only be present when either a value for the `Sim` query parameter is provided or when UsageRecords are grouped by `sim`. Otherwise, the value will be `null`. + :ivar network_sid: SID of the Network resource the usage occurred on. Value will only be present when either a value for the `Network` query parameter is provided or when UsageRecords are grouped by `network`. Otherwise, the value will be `null`. + :ivar fleet_sid: SID of the Fleet resource the usage occurred on. Value will only be present when either a value for the `Fleet` query parameter is provided or when UsageRecords are grouped by `fleet`. Otherwise, the value will be `null`. + :ivar iso_country: Alpha-2 ISO Country Code that the usage occurred in. Value will only be present when either a value for the `IsoCountry` query parameter is provided or when UsageRecords are grouped by `isoCountry`. Otherwise, the value will be `null`. + :ivar period: The time period for which the usage is reported. The period is represented as a pair of `start_time` and `end_time` timestamps specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar data_upload: Total data uploaded in bytes, aggregated by the query parameters. + :ivar data_download: Total data downloaded in bytes, aggregated by the query parameters. + :ivar data_total: Total of data_upload and data_download. + :ivar data_total_billed: Total amount in the `billed_unit` that was charged for the data uploaded or downloaded. Will return 0 for usage prior to February 1, 2022. Value may be 0 despite `data_total` being greater than 0 if the data usage is still being processed by Twilio's billing system. Refer to [Data Usage Processing](https://www.twilio.com/docs/iot/supersim/api/usage-record-resource#data-usage-processing) for more details. + :ivar billed_unit: The currency in which the billed amounts are measured, specified in the 3 letter ISO 4127 format (e.g. `USD`, `EUR`, `JPY`). This can be null when data_toal_billed is 0 and we do not yet have billing information for the corresponding data usage. Refer to [Data Usage Processing](https://www.twilio.com/docs/iot/supersim/api/usage-record-resource#data-usage-processing) for more details. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.network_sid: Optional[str] = payload.get("network_sid") + self.fleet_sid: Optional[str] = payload.get("fleet_sid") + self.iso_country: Optional[str] = payload.get("iso_country") + self.period: Optional[Dict[str, object]] = payload.get("period") + self.data_upload: Optional[int] = payload.get("data_upload") + self.data_download: Optional[int] = payload.get("data_download") + self.data_total: Optional[int] = payload.get("data_total") + self.data_total_billed: Optional[float] = deserialize.decimal( + payload.get("data_total_billed") + ) + self.billed_unit: Optional[str] = payload.get("billed_unit") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class UsageRecordPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UsageRecordInstance: + """ + Build an instance of UsageRecordInstance + + :param payload: Payload response from the API + """ + return UsageRecordInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class UsageRecordList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the UsageRecordList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/UsageRecords" + + def stream( + self, + sim: Union[str, object] = values.unset, + fleet: Union[str, object] = values.unset, + network: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + group: Union["UsageRecordInstance.Group", object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UsageRecordInstance]: + """ + Streams UsageRecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sim: SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. + :param str fleet: SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. + :param str network: SID of a Network resource. Only show UsageRecords representing usage on this network. + :param str iso_country: Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. + :param "UsageRecordInstance.Group" group: Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. + :param "UsageRecordInstance.Granularity" granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. + :param datetime start_time: Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. + :param datetime end_time: Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + sim=sim, + fleet=fleet, + network=network, + iso_country=iso_country, + group=group, + granularity=granularity, + start_time=start_time, + end_time=end_time, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + sim: Union[str, object] = values.unset, + fleet: Union[str, object] = values.unset, + network: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + group: Union["UsageRecordInstance.Group", object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UsageRecordInstance]: + """ + Asynchronously streams UsageRecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sim: SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. + :param str fleet: SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. + :param str network: SID of a Network resource. Only show UsageRecords representing usage on this network. + :param str iso_country: Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. + :param "UsageRecordInstance.Group" group: Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. + :param "UsageRecordInstance.Granularity" granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. + :param datetime start_time: Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. + :param datetime end_time: Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + sim=sim, + fleet=fleet, + network=network, + iso_country=iso_country, + group=group, + granularity=granularity, + start_time=start_time, + end_time=end_time, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + sim: Union[str, object] = values.unset, + fleet: Union[str, object] = values.unset, + network: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + group: Union["UsageRecordInstance.Group", object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UsageRecordInstance]: + """ + Lists UsageRecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sim: SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. + :param str fleet: SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. + :param str network: SID of a Network resource. Only show UsageRecords representing usage on this network. + :param str iso_country: Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. + :param "UsageRecordInstance.Group" group: Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. + :param "UsageRecordInstance.Granularity" granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. + :param datetime start_time: Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. + :param datetime end_time: Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + sim=sim, + fleet=fleet, + network=network, + iso_country=iso_country, + group=group, + granularity=granularity, + start_time=start_time, + end_time=end_time, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + sim: Union[str, object] = values.unset, + fleet: Union[str, object] = values.unset, + network: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + group: Union["UsageRecordInstance.Group", object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UsageRecordInstance]: + """ + Asynchronously lists UsageRecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sim: SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. + :param str fleet: SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. + :param str network: SID of a Network resource. Only show UsageRecords representing usage on this network. + :param str iso_country: Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. + :param "UsageRecordInstance.Group" group: Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. + :param "UsageRecordInstance.Granularity" granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. + :param datetime start_time: Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. + :param datetime end_time: Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + sim=sim, + fleet=fleet, + network=network, + iso_country=iso_country, + group=group, + granularity=granularity, + start_time=start_time, + end_time=end_time, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + sim: Union[str, object] = values.unset, + fleet: Union[str, object] = values.unset, + network: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + group: Union["UsageRecordInstance.Group", object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UsageRecordPage: + """ + Retrieve a single page of UsageRecordInstance records from the API. + Request is executed immediately + + :param sim: SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. + :param fleet: SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. + :param network: SID of a Network resource. Only show UsageRecords representing usage on this network. + :param iso_country: Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. + :param group: Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. + :param granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. + :param start_time: Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. + :param end_time: Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UsageRecordInstance + """ + data = values.of( + { + "Sim": sim, + "Fleet": fleet, + "Network": network, + "IsoCountry": iso_country, + "Group": group, + "Granularity": granularity, + "StartTime": serialize.iso8601_datetime(start_time), + "EndTime": serialize.iso8601_datetime(end_time), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsageRecordPage(self._version, response) + + async def page_async( + self, + sim: Union[str, object] = values.unset, + fleet: Union[str, object] = values.unset, + network: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + group: Union["UsageRecordInstance.Group", object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UsageRecordPage: + """ + Asynchronously retrieve a single page of UsageRecordInstance records from the API. + Request is executed immediately + + :param sim: SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. + :param fleet: SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. + :param network: SID of a Network resource. Only show UsageRecords representing usage on this network. + :param iso_country: Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. + :param group: Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. + :param granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. + :param start_time: Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. + :param end_time: Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UsageRecordInstance + """ + data = values.of( + { + "Sim": sim, + "Fleet": fleet, + "Network": network, + "IsoCountry": iso_country, + "Group": group, + "Granularity": granularity, + "StartTime": serialize.iso8601_datetime(start_time), + "EndTime": serialize.iso8601_datetime(end_time), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsageRecordPage(self._version, response) + + def get_page(self, target_url: str) -> UsageRecordPage: + """ + Retrieve a specific page of UsageRecordInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UsageRecordInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UsageRecordPage(self._version, response) + + async def get_page_async(self, target_url: str) -> UsageRecordPage: + """ + Asynchronously retrieve a specific page of UsageRecordInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UsageRecordInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UsageRecordPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/sync/SyncBase.py b/venv/Lib/site-packages/twilio/rest/sync/SyncBase.py new file mode 100644 index 00000000..113cac03 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/sync/SyncBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.sync.v1 import V1 + + +class SyncBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Sync Domain + + :returns: Domain for Sync + """ + super().__init__(twilio, "https://sync.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Sync + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/sync/__init__.py b/venv/Lib/site-packages/twilio/rest/sync/__init__.py new file mode 100644 index 00000000..37b9ce03 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/sync/__init__.py @@ -0,0 +1,15 @@ +from warnings import warn + +from twilio.rest.sync.SyncBase import SyncBase +from twilio.rest.sync.v1.service import ServiceList + + +class Sync(SyncBase): + @property + def services(self) -> ServiceList: + warn( + "services is deprecated. Use v1.services instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.services diff --git a/venv/Lib/site-packages/twilio/rest/sync/__pycache__/SyncBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/sync/__pycache__/SyncBase.cpython-312.pyc new file mode 100644 index 00000000..c87da7da Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/sync/__pycache__/SyncBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/sync/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/sync/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..bb5b0a49 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/sync/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/sync/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/sync/v1/__init__.py new file mode 100644 index 00000000..e98201bd --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/sync/v1/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Sync + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.sync.v1.service import ServiceList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Sync + + :param domain: The Twilio.sync domain + """ + super().__init__(domain, "v1") + self._services: Optional[ServiceList] = None + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/sync/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/sync/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..d230ed15 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/sync/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/sync/v1/service/__init__.py b/venv/Lib/site-packages/twilio/rest/sync/v1/service/__init__.py new file mode 100644 index 00000000..d17491d3 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/sync/v1/service/__init__.py @@ -0,0 +1,846 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Sync + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.sync.v1.service.document import DocumentList +from twilio.rest.sync.v1.service.sync_list import SyncListList +from twilio.rest.sync.v1.service.sync_map import SyncMapList +from twilio.rest.sync.v1.service.sync_stream import SyncStreamList + + +class ServiceInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Service resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. It is a read-only property, it cannot be assigned using REST API. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Service resource. + :ivar webhook_url: The URL we call when Sync objects are manipulated. + :ivar webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + :ivar reachability_webhooks_enabled: Whether the service instance calls `webhook_url` when client endpoints connect to Sync. The default is `false`. + :ivar acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. It is disabled (false) by default. + :ivar reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :ivar reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before `webhook_url` is called, if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the reachability event from occurring. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.webhook_url: Optional[str] = payload.get("webhook_url") + self.webhooks_from_rest_enabled: Optional[bool] = payload.get( + "webhooks_from_rest_enabled" + ) + self.reachability_webhooks_enabled: Optional[bool] = payload.get( + "reachability_webhooks_enabled" + ) + self.acl_enabled: Optional[bool] = payload.get("acl_enabled") + self.reachability_debouncing_enabled: Optional[bool] = payload.get( + "reachability_debouncing_enabled" + ) + self.reachability_debouncing_window: Optional[int] = deserialize.integer( + payload.get("reachability_debouncing_window") + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + webhook_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param friendly_name: A string that you assign to describe the resource. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the webhook is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the webhook from being called. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + webhook_url=webhook_url, + friendly_name=friendly_name, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) + + async def update_async( + self, + webhook_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param friendly_name: A string that you assign to describe the resource. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the webhook is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the webhook from being called. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + webhook_url=webhook_url, + friendly_name=friendly_name, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) + + @property + def documents(self) -> DocumentList: + """ + Access the documents + """ + return self._proxy.documents + + @property + def sync_lists(self) -> SyncListList: + """ + Access the sync_lists + """ + return self._proxy.sync_lists + + @property + def sync_maps(self) -> SyncMapList: + """ + Access the sync_maps + """ + return self._proxy.sync_maps + + @property + def sync_streams(self) -> SyncStreamList: + """ + Access the sync_streams + """ + return self._proxy.sync_streams + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: The SID of the Service resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._documents: Optional[DocumentList] = None + self._sync_lists: Optional[SyncListList] = None + self._sync_maps: Optional[SyncMapList] = None + self._sync_streams: Optional[SyncStreamList] = None + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + webhook_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param friendly_name: A string that you assign to describe the resource. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the webhook is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the webhook from being called. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "WebhookUrl": webhook_url, + "FriendlyName": friendly_name, + "ReachabilityWebhooksEnabled": serialize.boolean_to_string( + reachability_webhooks_enabled + ), + "AclEnabled": serialize.boolean_to_string(acl_enabled), + "ReachabilityDebouncingEnabled": serialize.boolean_to_string( + reachability_debouncing_enabled + ), + "ReachabilityDebouncingWindow": reachability_debouncing_window, + "WebhooksFromRestEnabled": serialize.boolean_to_string( + webhooks_from_rest_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + webhook_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param friendly_name: A string that you assign to describe the resource. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the webhook is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the webhook from being called. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "WebhookUrl": webhook_url, + "FriendlyName": friendly_name, + "ReachabilityWebhooksEnabled": serialize.boolean_to_string( + reachability_webhooks_enabled + ), + "AclEnabled": serialize.boolean_to_string(acl_enabled), + "ReachabilityDebouncingEnabled": serialize.boolean_to_string( + reachability_debouncing_enabled + ), + "ReachabilityDebouncingWindow": reachability_debouncing_window, + "WebhooksFromRestEnabled": serialize.boolean_to_string( + webhooks_from_rest_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def documents(self) -> DocumentList: + """ + Access the documents + """ + if self._documents is None: + self._documents = DocumentList( + self._version, + self._solution["sid"], + ) + return self._documents + + @property + def sync_lists(self) -> SyncListList: + """ + Access the sync_lists + """ + if self._sync_lists is None: + self._sync_lists = SyncListList( + self._version, + self._solution["sid"], + ) + return self._sync_lists + + @property + def sync_maps(self) -> SyncMapList: + """ + Access the sync_maps + """ + if self._sync_maps is None: + self._sync_maps = SyncMapList( + self._version, + self._solution["sid"], + ) + return self._sync_maps + + @property + def sync_streams(self) -> SyncStreamList: + """ + Access the sync_streams + """ + if self._sync_streams is None: + self._sync_streams = SyncStreamList( + self._version, + self._solution["sid"], + ) + return self._sync_streams + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def create( + self, + friendly_name: Union[str, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: A string that you assign to describe the resource. + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the `webhook_url` is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the call to `webhook_url`. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "WebhookUrl": webhook_url, + "ReachabilityWebhooksEnabled": serialize.boolean_to_string( + reachability_webhooks_enabled + ), + "AclEnabled": serialize.boolean_to_string(acl_enabled), + "ReachabilityDebouncingEnabled": serialize.boolean_to_string( + reachability_debouncing_enabled + ), + "ReachabilityDebouncingWindow": reachability_debouncing_window, + "WebhooksFromRestEnabled": serialize.boolean_to_string( + webhooks_from_rest_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async( + self, + friendly_name: Union[str, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: A string that you assign to describe the resource. + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the `webhook_url` is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the call to `webhook_url`. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "WebhookUrl": webhook_url, + "ReachabilityWebhooksEnabled": serialize.boolean_to_string( + reachability_webhooks_enabled + ), + "AclEnabled": serialize.boolean_to_string(acl_enabled), + "ReachabilityDebouncingEnabled": serialize.boolean_to_string( + reachability_debouncing_enabled + ), + "ReachabilityDebouncingWindow": reachability_debouncing_window, + "WebhooksFromRestEnabled": serialize.boolean_to_string( + webhooks_from_rest_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The SID of the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The SID of the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/sync/v1/service/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/sync/v1/service/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..a5b51432 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/sync/v1/service/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/sync/v1/service/document/__init__.py b/venv/Lib/site-packages/twilio/rest/sync/v1/service/document/__init__.py new file mode 100644 index 00000000..fe64f629 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/sync/v1/service/document/__init__.py @@ -0,0 +1,723 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Sync + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.sync.v1.service.document.document_permission import ( + DocumentPermissionList, +) + + +class DocumentInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Document resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource and can be up to 320 characters long. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Document resource. + :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + :ivar url: The absolute URL of the Document resource. + :ivar links: The URLs of resources related to the Sync Document. + :ivar revision: The current revision of the Sync Document, represented as a string. The `revision` property is used with conditional updates to ensure data consistency. + :ivar data: An arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :ivar date_expires: The date and time in GMT when the Sync Document expires and will be deleted, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. If the Sync Document does not expire, this value is `null`. The Document resource might not be deleted immediately after it expires. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar created_by: The identity of the Sync Document's creator. If the Sync Document is created from the client SDK, the value matches the Access Token's `identity` field. If the Sync Document was created from the REST API, the value is `system`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.revision: Optional[str] = payload.get("revision") + self.data: Optional[Dict[str, object]] = payload.get("data") + self.date_expires: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_expires") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[DocumentContext] = None + + @property + def _proxy(self) -> "DocumentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DocumentContext for this DocumentInstance + """ + if self._context is None: + self._context = DocumentContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the DocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "DocumentInstance": + """ + Fetch the DocumentInstance + + + :returns: The fetched DocumentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DocumentInstance": + """ + Asynchronous coroutine to fetch the DocumentInstance + + + :returns: The fetched DocumentInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> "DocumentInstance": + """ + Update the DocumentInstance + + :param if_match: The If-Match HTTP request header + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (time-to-live). + + :returns: The updated DocumentInstance + """ + return self._proxy.update( + if_match=if_match, + data=data, + ttl=ttl, + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> "DocumentInstance": + """ + Asynchronous coroutine to update the DocumentInstance + + :param if_match: The If-Match HTTP request header + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (time-to-live). + + :returns: The updated DocumentInstance + """ + return await self._proxy.update_async( + if_match=if_match, + data=data, + ttl=ttl, + ) + + @property + def document_permissions(self) -> DocumentPermissionList: + """ + Access the document_permissions + """ + return self._proxy.document_permissions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DocumentContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the DocumentContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Document resource to update. + :param sid: The SID of the Document resource to update. Can be the Document resource's `sid` or its `unique_name`. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Documents/{sid}".format(**self._solution) + + self._document_permissions: Optional[DocumentPermissionList] = None + + def delete(self) -> bool: + """ + Deletes the DocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> DocumentInstance: + """ + Fetch the DocumentInstance + + + :returns: The fetched DocumentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DocumentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> DocumentInstance: + """ + Asynchronous coroutine to fetch the DocumentInstance + + + :returns: The fetched DocumentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DocumentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> DocumentInstance: + """ + Update the DocumentInstance + + :param if_match: The If-Match HTTP request header + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (time-to-live). + + :returns: The updated DocumentInstance + """ + + data = values.of( + { + "Data": serialize.object(data), + "Ttl": ttl, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DocumentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> DocumentInstance: + """ + Asynchronous coroutine to update the DocumentInstance + + :param if_match: The If-Match HTTP request header + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (time-to-live). + + :returns: The updated DocumentInstance + """ + + data = values.of( + { + "Data": serialize.object(data), + "Ttl": ttl, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DocumentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def document_permissions(self) -> DocumentPermissionList: + """ + Access the document_permissions + """ + if self._document_permissions is None: + self._document_permissions = DocumentPermissionList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._document_permissions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DocumentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DocumentInstance: + """ + Build an instance of DocumentInstance + + :param payload: Payload response from the API + """ + return DocumentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class DocumentList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the DocumentList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Document resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Documents".format(**self._solution) + + def create( + self, + unique_name: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> DocumentInstance: + """ + Create the DocumentInstance + + :param unique_name: An application-defined string that uniquely identifies the Sync Document + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (the Sync Document's time-to-live). + + :returns: The created DocumentInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Data": serialize.object(data), + "Ttl": ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DocumentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> DocumentInstance: + """ + Asynchronously create the DocumentInstance + + :param unique_name: An application-defined string that uniquely identifies the Sync Document + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (the Sync Document's time-to-live). + + :returns: The created DocumentInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Data": serialize.object(data), + "Ttl": ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DocumentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DocumentInstance]: + """ + Streams DocumentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DocumentInstance]: + """ + Asynchronously streams DocumentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DocumentInstance]: + """ + Lists DocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DocumentInstance]: + """ + Asynchronously lists DocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DocumentPage: + """ + Retrieve a single page of DocumentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DocumentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DocumentPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DocumentPage: + """ + Asynchronously retrieve a single page of DocumentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DocumentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DocumentPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DocumentPage: + """ + Retrieve a specific page of DocumentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DocumentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DocumentPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DocumentPage: + """ + Asynchronously retrieve a specific page of DocumentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DocumentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DocumentPage(self._version, response, self._solution) + + def get(self, sid: str) -> DocumentContext: + """ + Constructs a DocumentContext + + :param sid: The SID of the Document resource to update. Can be the Document resource's `sid` or its `unique_name`. + """ + return DocumentContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> DocumentContext: + """ + Constructs a DocumentContext + + :param sid: The SID of the Document resource to update. Can be the Document resource's `sid` or its `unique_name`. + """ + return DocumentContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/sync/v1/service/document/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/sync/v1/service/document/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..c6489f9f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/sync/v1/service/document/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/sync/v1/service/document/__pycache__/document_permission.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/sync/v1/service/document/__pycache__/document_permission.cpython-312.pyc new file mode 100644 index 00000000..ebaee186 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/sync/v1/service/document/__pycache__/document_permission.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/sync/v1/service/document/document_permission.py b/venv/Lib/site-packages/twilio/rest/sync/v1/service/document/document_permission.py new file mode 100644 index 00000000..75a27c96 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/sync/v1/service/document/document_permission.py @@ -0,0 +1,617 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Sync + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DocumentPermissionInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Document Permission resource. + :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + :ivar document_sid: The SID of the Sync Document to which the Document Permission applies. + :ivar identity: The application-defined string that uniquely identifies the resource's User within the Service to an FPA token. + :ivar read: Whether the identity can read the Sync Document. + :ivar write: Whether the identity can update the Sync Document. + :ivar manage: Whether the identity can delete the Sync Document. + :ivar url: The absolute URL of the Sync Document Permission resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + document_sid: str, + identity: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.document_sid: Optional[str] = payload.get("document_sid") + self.identity: Optional[str] = payload.get("identity") + self.read: Optional[bool] = payload.get("read") + self.write: Optional[bool] = payload.get("write") + self.manage: Optional[bool] = payload.get("manage") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "document_sid": document_sid, + "identity": identity or self.identity, + } + self._context: Optional[DocumentPermissionContext] = None + + @property + def _proxy(self) -> "DocumentPermissionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DocumentPermissionContext for this DocumentPermissionInstance + """ + if self._context is None: + self._context = DocumentPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the DocumentPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DocumentPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "DocumentPermissionInstance": + """ + Fetch the DocumentPermissionInstance + + + :returns: The fetched DocumentPermissionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DocumentPermissionInstance": + """ + Asynchronous coroutine to fetch the DocumentPermissionInstance + + + :returns: The fetched DocumentPermissionInstance + """ + return await self._proxy.fetch_async() + + def update( + self, read: bool, write: bool, manage: bool + ) -> "DocumentPermissionInstance": + """ + Update the DocumentPermissionInstance + + :param read: Whether the identity can read the Sync Document. Default value is `false`. + :param write: Whether the identity can update the Sync Document. Default value is `false`. + :param manage: Whether the identity can delete the Sync Document. Default value is `false`. + + :returns: The updated DocumentPermissionInstance + """ + return self._proxy.update( + read=read, + write=write, + manage=manage, + ) + + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> "DocumentPermissionInstance": + """ + Asynchronous coroutine to update the DocumentPermissionInstance + + :param read: Whether the identity can read the Sync Document. Default value is `false`. + :param write: Whether the identity can update the Sync Document. Default value is `false`. + :param manage: Whether the identity can delete the Sync Document. Default value is `false`. + + :returns: The updated DocumentPermissionInstance + """ + return await self._proxy.update_async( + read=read, + write=write, + manage=manage, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DocumentPermissionContext(InstanceContext): + + def __init__( + self, version: Version, service_sid: str, document_sid: str, identity: str + ): + """ + Initialize the DocumentPermissionContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Document Permission resource to update. + :param document_sid: The SID of the Sync Document with the Document Permission resource to update. Can be the Document resource's `sid` or its `unique_name`. + :param identity: The application-defined string that uniquely identifies the User's Document Permission resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "document_sid": document_sid, + "identity": identity, + } + self._uri = "/Services/{service_sid}/Documents/{document_sid}/Permissions/{identity}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the DocumentPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DocumentPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> DocumentPermissionInstance: + """ + Fetch the DocumentPermissionInstance + + + :returns: The fetched DocumentPermissionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + + async def fetch_async(self) -> DocumentPermissionInstance: + """ + Asynchronous coroutine to fetch the DocumentPermissionInstance + + + :returns: The fetched DocumentPermissionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + + def update( + self, read: bool, write: bool, manage: bool + ) -> DocumentPermissionInstance: + """ + Update the DocumentPermissionInstance + + :param read: Whether the identity can read the Sync Document. Default value is `false`. + :param write: Whether the identity can update the Sync Document. Default value is `false`. + :param manage: Whether the identity can delete the Sync Document. Default value is `false`. + + :returns: The updated DocumentPermissionInstance + """ + + data = values.of( + { + "Read": serialize.boolean_to_string(read), + "Write": serialize.boolean_to_string(write), + "Manage": serialize.boolean_to_string(manage), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> DocumentPermissionInstance: + """ + Asynchronous coroutine to update the DocumentPermissionInstance + + :param read: Whether the identity can read the Sync Document. Default value is `false`. + :param write: Whether the identity can update the Sync Document. Default value is `false`. + :param manage: Whether the identity can delete the Sync Document. Default value is `false`. + + :returns: The updated DocumentPermissionInstance + """ + + data = values.of( + { + "Read": serialize.boolean_to_string(read), + "Write": serialize.boolean_to_string(write), + "Manage": serialize.boolean_to_string(manage), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DocumentPermissionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DocumentPermissionInstance: + """ + Build an instance of DocumentPermissionInstance + + :param payload: Payload response from the API + """ + return DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class DocumentPermissionList(ListResource): + + def __init__(self, version: Version, service_sid: str, document_sid: str): + """ + Initialize the DocumentPermissionList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Document Permission resources to read. + :param document_sid: The SID of the Sync Document with the Document Permission resources to read. Can be the Document resource's `sid` or its `unique_name`. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "document_sid": document_sid, + } + self._uri = ( + "/Services/{service_sid}/Documents/{document_sid}/Permissions".format( + **self._solution + ) + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DocumentPermissionInstance]: + """ + Streams DocumentPermissionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DocumentPermissionInstance]: + """ + Asynchronously streams DocumentPermissionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DocumentPermissionInstance]: + """ + Lists DocumentPermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DocumentPermissionInstance]: + """ + Asynchronously lists DocumentPermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DocumentPermissionPage: + """ + Retrieve a single page of DocumentPermissionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DocumentPermissionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DocumentPermissionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DocumentPermissionPage: + """ + Asynchronously retrieve a single page of DocumentPermissionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DocumentPermissionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DocumentPermissionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DocumentPermissionPage: + """ + Retrieve a specific page of DocumentPermissionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DocumentPermissionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DocumentPermissionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DocumentPermissionPage: + """ + Asynchronously retrieve a specific page of DocumentPermissionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DocumentPermissionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DocumentPermissionPage(self._version, response, self._solution) + + def get(self, identity: str) -> DocumentPermissionContext: + """ + Constructs a DocumentPermissionContext + + :param identity: The application-defined string that uniquely identifies the User's Document Permission resource to update. + """ + return DocumentPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=identity, + ) + + def __call__(self, identity: str) -> DocumentPermissionContext: + """ + Constructs a DocumentPermissionContext + + :param identity: The application-defined string that uniquely identifies the User's Document Permission resource to update. + """ + return DocumentPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=identity, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_list/__init__.py b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_list/__init__.py new file mode 100644 index 00000000..1b8e54af --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_list/__init__.py @@ -0,0 +1,723 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Sync + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.sync.v1.service.sync_list.sync_list_item import SyncListItemList +from twilio.rest.sync.v1.service.sync_list.sync_list_permission import ( + SyncListPermissionList, +) + + +class SyncListInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Sync List resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Sync List resource. + :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + :ivar url: The absolute URL of the Sync List resource. + :ivar links: The URLs of the Sync List's nested resources. + :ivar revision: The current revision of the Sync List, represented as a string. + :ivar date_expires: The date and time in GMT when the Sync List expires and will be deleted, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. If the Sync List does not expire, this value is `null`. The Sync List might not be deleted immediately after it expires. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar created_by: The identity of the Sync List's creator. If the Sync List is created from the client SDK, the value matches the Access Token's `identity` field. If the Sync List was created from the REST API, the value is `system`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.revision: Optional[str] = payload.get("revision") + self.date_expires: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_expires") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[SyncListContext] = None + + @property + def _proxy(self) -> "SyncListContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SyncListContext for this SyncListInstance + """ + if self._context is None: + self._context = SyncListContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SyncListInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncListInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SyncListInstance": + """ + Fetch the SyncListInstance + + + :returns: The fetched SyncListInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SyncListInstance": + """ + Asynchronous coroutine to fetch the SyncListInstance + + + :returns: The fetched SyncListInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncListInstance": + """ + Update the SyncListInstance + + :param ttl: An alias for `collection_ttl`. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: The updated SyncListInstance + """ + return self._proxy.update( + ttl=ttl, + collection_ttl=collection_ttl, + ) + + async def update_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncListInstance": + """ + Asynchronous coroutine to update the SyncListInstance + + :param ttl: An alias for `collection_ttl`. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: The updated SyncListInstance + """ + return await self._proxy.update_async( + ttl=ttl, + collection_ttl=collection_ttl, + ) + + @property + def sync_list_items(self) -> SyncListItemList: + """ + Access the sync_list_items + """ + return self._proxy.sync_list_items + + @property + def sync_list_permissions(self) -> SyncListPermissionList: + """ + Access the sync_list_permissions + """ + return self._proxy.sync_list_permissions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SyncListContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the SyncListContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync List resource to update. + :param sid: The SID of the Sync List resource to update. Can be the Sync List resource's `sid` or its `unique_name`. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Lists/{sid}".format(**self._solution) + + self._sync_list_items: Optional[SyncListItemList] = None + self._sync_list_permissions: Optional[SyncListPermissionList] = None + + def delete(self) -> bool: + """ + Deletes the SyncListInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncListInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SyncListInstance: + """ + Fetch the SyncListInstance + + + :returns: The fetched SyncListInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SyncListInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SyncListInstance: + """ + Asynchronous coroutine to fetch the SyncListInstance + + + :returns: The fetched SyncListInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SyncListInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListInstance: + """ + Update the SyncListInstance + + :param ttl: An alias for `collection_ttl`. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: The updated SyncListInstance + """ + + data = values.of( + { + "Ttl": ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncListInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListInstance: + """ + Asynchronous coroutine to update the SyncListInstance + + :param ttl: An alias for `collection_ttl`. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: The updated SyncListInstance + """ + + data = values.of( + { + "Ttl": ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncListInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def sync_list_items(self) -> SyncListItemList: + """ + Access the sync_list_items + """ + if self._sync_list_items is None: + self._sync_list_items = SyncListItemList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._sync_list_items + + @property + def sync_list_permissions(self) -> SyncListPermissionList: + """ + Access the sync_list_permissions + """ + if self._sync_list_permissions is None: + self._sync_list_permissions = SyncListPermissionList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._sync_list_permissions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SyncListPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SyncListInstance: + """ + Build an instance of SyncListInstance + + :param payload: Payload response from the API + """ + return SyncListInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SyncListList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the SyncListList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync List resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Lists".format(**self._solution) + + def create( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListInstance: + """ + Create the SyncListInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: Alias for collection_ttl. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: The created SyncListInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Ttl": ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncListInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListInstance: + """ + Asynchronously create the SyncListInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: Alias for collection_ttl. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: The created SyncListInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Ttl": ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncListInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SyncListInstance]: + """ + Streams SyncListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SyncListInstance]: + """ + Asynchronously streams SyncListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncListInstance]: + """ + Lists SyncListInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncListInstance]: + """ + Asynchronously lists SyncListInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncListPage: + """ + Retrieve a single page of SyncListInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncListInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncListPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncListPage: + """ + Asynchronously retrieve a single page of SyncListInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncListInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncListPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SyncListPage: + """ + Retrieve a specific page of SyncListInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncListInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SyncListPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SyncListPage: + """ + Asynchronously retrieve a specific page of SyncListInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncListInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncListPage(self._version, response, self._solution) + + def get(self, sid: str) -> SyncListContext: + """ + Constructs a SyncListContext + + :param sid: The SID of the Sync List resource to update. Can be the Sync List resource's `sid` or its `unique_name`. + """ + return SyncListContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> SyncListContext: + """ + Constructs a SyncListContext + + :param sid: The SID of the Sync List resource to update. Can be the Sync List resource's `sid` or its `unique_name`. + """ + return SyncListContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_list/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_list/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..7cb3abcb Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_list/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_list/__pycache__/sync_list_item.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_list/__pycache__/sync_list_item.cpython-312.pyc new file mode 100644 index 00000000..fcdeff7d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_list/__pycache__/sync_list_item.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_list/__pycache__/sync_list_permission.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_list/__pycache__/sync_list_permission.cpython-312.pyc new file mode 100644 index 00000000..e2f2b22f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_list/__pycache__/sync_list_permission.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_list/sync_list_item.py b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_list/sync_list_item.py new file mode 100644 index 00000000..61783aa5 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_list/sync_list_item.py @@ -0,0 +1,835 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Sync + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SyncListItemInstance(InstanceResource): + + class QueryFromBoundType(object): + INCLUSIVE = "inclusive" + EXCLUSIVE = "exclusive" + + class QueryResultOrder(object): + ASC = "asc" + DESC = "desc" + + """ + :ivar index: The automatically generated index of the List Item. The `index` values of the List Items in a Sync List can have gaps in their sequence. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the List Item resource. + :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + :ivar list_sid: The SID of the Sync List that contains the List Item. + :ivar url: The absolute URL of the List Item resource. + :ivar revision: The current revision of the item, represented as a string. + :ivar data: An arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :ivar date_expires: The date and time in GMT when the List Item expires and will be deleted, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. If the List Item does not expire, this value is `null`. The List Item resource might not be deleted immediately after it expires. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar created_by: The identity of the List Item's creator. If the item is created from the client SDK, the value matches the Access Token's `identity` field. If the item was created from the REST API, the value is `system`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + list_sid: str, + index: Optional[int] = None, + ): + super().__init__(version) + + self.index: Optional[int] = deserialize.integer(payload.get("index")) + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.list_sid: Optional[str] = payload.get("list_sid") + self.url: Optional[str] = payload.get("url") + self.revision: Optional[str] = payload.get("revision") + self.data: Optional[Dict[str, object]] = payload.get("data") + self.date_expires: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_expires") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + + self._solution = { + "service_sid": service_sid, + "list_sid": list_sid, + "index": index or self.index, + } + self._context: Optional[SyncListItemContext] = None + + @property + def _proxy(self) -> "SyncListItemContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SyncListItemContext for this SyncListItemInstance + """ + if self._context is None: + self._context = SyncListItemContext( + self._version, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], + ) + return self._context + + def delete(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Deletes the SyncListItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + if_match=if_match, + ) + + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Asynchronous coroutine that deletes the SyncListItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + if_match=if_match, + ) + + def fetch(self) -> "SyncListItemInstance": + """ + Fetch the SyncListItemInstance + + + :returns: The fetched SyncListItemInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SyncListItemInstance": + """ + Asynchronous coroutine to fetch the SyncListItemInstance + + + :returns: The fetched SyncListItemInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncListItemInstance": + """ + Update the SyncListItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. This parameter can only be used when the List Item's `data` or `ttl` is updated in the same request. + + :returns: The updated SyncListItemInstance + """ + return self._proxy.update( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncListItemInstance": + """ + Asynchronous coroutine to update the SyncListItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. This parameter can only be used when the List Item's `data` or `ttl` is updated in the same request. + + :returns: The updated SyncListItemInstance + """ + return await self._proxy.update_async( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SyncListItemContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, list_sid: str, index: int): + """ + Initialize the SyncListItemContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync List Item resource to update. + :param list_sid: The SID of the Sync List with the Sync List Item resource to update. Can be the Sync List resource's `sid` or its `unique_name`. + :param index: The index of the Sync List Item resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "list_sid": list_sid, + "index": index, + } + self._uri = "/Services/{service_sid}/Lists/{list_sid}/Items/{index}".format( + **self._solution + ) + + def delete(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Deletes the SyncListItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "If-Match": if_match, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Asynchronous coroutine that deletes the SyncListItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "If-Match": if_match, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SyncListItemInstance: + """ + Fetch the SyncListItemInstance + + + :returns: The fetched SyncListItemInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], + ) + + async def fetch_async(self) -> SyncListItemInstance: + """ + Asynchronous coroutine to fetch the SyncListItemInstance + + + :returns: The fetched SyncListItemInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], + ) + + def update( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListItemInstance: + """ + Update the SyncListItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. This parameter can only be used when the List Item's `data` or `ttl` is updated in the same request. + + :returns: The updated SyncListItemInstance + """ + + data = values.of( + { + "Data": serialize.object(data), + "Ttl": ttl, + "ItemTtl": item_ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListItemInstance: + """ + Asynchronous coroutine to update the SyncListItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. This parameter can only be used when the List Item's `data` or `ttl` is updated in the same request. + + :returns: The updated SyncListItemInstance + """ + + data = values.of( + { + "Data": serialize.object(data), + "Ttl": ttl, + "ItemTtl": item_ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SyncListItemPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SyncListItemInstance: + """ + Build an instance of SyncListItemInstance + + :param payload: Payload response from the API + """ + return SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SyncListItemList(ListResource): + + def __init__(self, version: Version, service_sid: str, list_sid: str): + """ + Initialize the SyncListItemList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the List Item resources to read. + :param list_sid: The SID of the Sync List with the List Items to read. Can be the Sync List resource's `sid` or its `unique_name`. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "list_sid": list_sid, + } + self._uri = "/Services/{service_sid}/Lists/{list_sid}/Items".format( + **self._solution + ) + + def create( + self, + data: object, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListItemInstance: + """ + Create the SyncListItemInstance + + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. + + :returns: The created SyncListItemInstance + """ + + data = values.of( + { + "Data": serialize.object(data), + "Ttl": ttl, + "ItemTtl": item_ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + ) + + async def create_async( + self, + data: object, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListItemInstance: + """ + Asynchronously create the SyncListItemInstance + + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. + + :returns: The created SyncListItemInstance + """ + + data = values.of( + { + "Data": serialize.object(data), + "Ttl": ttl, + "ItemTtl": item_ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + ) + + def stream( + self, + order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SyncListItemInstance]: + """ + Streams SyncListItemInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "SyncListItemInstance.QueryResultOrder" order: How to order the List Items returned by their `index` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. + :param str from_: The `index` of the first Sync List Item resource to read. See also `bounds`. + :param "SyncListItemInstance.QueryFromBoundType" bounds: Whether to include the List Item referenced by the `from` parameter. Can be: `inclusive` to include the List Item referenced by the `from` parameter or `exclusive` to start with the next List Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SyncListItemInstance]: + """ + Asynchronously streams SyncListItemInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "SyncListItemInstance.QueryResultOrder" order: How to order the List Items returned by their `index` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. + :param str from_: The `index` of the first Sync List Item resource to read. See also `bounds`. + :param "SyncListItemInstance.QueryFromBoundType" bounds: Whether to include the List Item referenced by the `from` parameter. Can be: `inclusive` to include the List Item referenced by the `from` parameter or `exclusive` to start with the next List Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncListItemInstance]: + """ + Lists SyncListItemInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "SyncListItemInstance.QueryResultOrder" order: How to order the List Items returned by their `index` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. + :param str from_: The `index` of the first Sync List Item resource to read. See also `bounds`. + :param "SyncListItemInstance.QueryFromBoundType" bounds: Whether to include the List Item referenced by the `from` parameter. Can be: `inclusive` to include the List Item referenced by the `from` parameter or `exclusive` to start with the next List Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + order=order, + from_=from_, + bounds=bounds, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncListItemInstance]: + """ + Asynchronously lists SyncListItemInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "SyncListItemInstance.QueryResultOrder" order: How to order the List Items returned by their `index` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. + :param str from_: The `index` of the first Sync List Item resource to read. See also `bounds`. + :param "SyncListItemInstance.QueryFromBoundType" bounds: Whether to include the List Item referenced by the `from` parameter. Can be: `inclusive` to include the List Item referenced by the `from` parameter or `exclusive` to start with the next List Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + order=order, + from_=from_, + bounds=bounds, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncListItemPage: + """ + Retrieve a single page of SyncListItemInstance records from the API. + Request is executed immediately + + :param order: How to order the List Items returned by their `index` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. + :param from_: The `index` of the first Sync List Item resource to read. See also `bounds`. + :param bounds: Whether to include the List Item referenced by the `from` parameter. Can be: `inclusive` to include the List Item referenced by the `from` parameter or `exclusive` to start with the next List Item. The default value is `inclusive`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncListItemInstance + """ + data = values.of( + { + "Order": order, + "From": from_, + "Bounds": bounds, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncListItemPage(self._version, response, self._solution) + + async def page_async( + self, + order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncListItemPage: + """ + Asynchronously retrieve a single page of SyncListItemInstance records from the API. + Request is executed immediately + + :param order: How to order the List Items returned by their `index` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. + :param from_: The `index` of the first Sync List Item resource to read. See also `bounds`. + :param bounds: Whether to include the List Item referenced by the `from` parameter. Can be: `inclusive` to include the List Item referenced by the `from` parameter or `exclusive` to start with the next List Item. The default value is `inclusive`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncListItemInstance + """ + data = values.of( + { + "Order": order, + "From": from_, + "Bounds": bounds, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncListItemPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SyncListItemPage: + """ + Retrieve a specific page of SyncListItemInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncListItemInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SyncListItemPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SyncListItemPage: + """ + Asynchronously retrieve a specific page of SyncListItemInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncListItemInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncListItemPage(self._version, response, self._solution) + + def get(self, index: int) -> SyncListItemContext: + """ + Constructs a SyncListItemContext + + :param index: The index of the Sync List Item resource to update. + """ + return SyncListItemContext( + self._version, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=index, + ) + + def __call__(self, index: int) -> SyncListItemContext: + """ + Constructs a SyncListItemContext + + :param index: The index of the Sync List Item resource to update. + """ + return SyncListItemContext( + self._version, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=index, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_list/sync_list_permission.py b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_list/sync_list_permission.py new file mode 100644 index 00000000..f1eb8534 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_list/sync_list_permission.py @@ -0,0 +1,617 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Sync + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SyncListPermissionInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Sync List Permission resource. + :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + :ivar list_sid: The SID of the Sync List to which the Permission applies. + :ivar identity: The application-defined string that uniquely identifies the resource's User within the Service to an FPA token. + :ivar read: Whether the identity can read the Sync List and its Items. + :ivar write: Whether the identity can create, update, and delete Items in the Sync List. + :ivar manage: Whether the identity can delete the Sync List. + :ivar url: The absolute URL of the Sync List Permission resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + list_sid: str, + identity: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.list_sid: Optional[str] = payload.get("list_sid") + self.identity: Optional[str] = payload.get("identity") + self.read: Optional[bool] = payload.get("read") + self.write: Optional[bool] = payload.get("write") + self.manage: Optional[bool] = payload.get("manage") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "list_sid": list_sid, + "identity": identity or self.identity, + } + self._context: Optional[SyncListPermissionContext] = None + + @property + def _proxy(self) -> "SyncListPermissionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SyncListPermissionContext for this SyncListPermissionInstance + """ + if self._context is None: + self._context = SyncListPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SyncListPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncListPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SyncListPermissionInstance": + """ + Fetch the SyncListPermissionInstance + + + :returns: The fetched SyncListPermissionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SyncListPermissionInstance": + """ + Asynchronous coroutine to fetch the SyncListPermissionInstance + + + :returns: The fetched SyncListPermissionInstance + """ + return await self._proxy.fetch_async() + + def update( + self, read: bool, write: bool, manage: bool + ) -> "SyncListPermissionInstance": + """ + Update the SyncListPermissionInstance + + :param read: Whether the identity can read the Sync List and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. + :param manage: Whether the identity can delete the Sync List. Default value is `false`. + + :returns: The updated SyncListPermissionInstance + """ + return self._proxy.update( + read=read, + write=write, + manage=manage, + ) + + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> "SyncListPermissionInstance": + """ + Asynchronous coroutine to update the SyncListPermissionInstance + + :param read: Whether the identity can read the Sync List and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. + :param manage: Whether the identity can delete the Sync List. Default value is `false`. + + :returns: The updated SyncListPermissionInstance + """ + return await self._proxy.update_async( + read=read, + write=write, + manage=manage, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SyncListPermissionContext(InstanceContext): + + def __init__( + self, version: Version, service_sid: str, list_sid: str, identity: str + ): + """ + Initialize the SyncListPermissionContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync List Permission resource to update. + :param list_sid: The SID of the Sync List with the Sync List Permission resource to update. Can be the Sync List resource's `sid` or its `unique_name`. + :param identity: The application-defined string that uniquely identifies the User's Sync List Permission resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "list_sid": list_sid, + "identity": identity, + } + self._uri = ( + "/Services/{service_sid}/Lists/{list_sid}/Permissions/{identity}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the SyncListPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncListPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SyncListPermissionInstance: + """ + Fetch the SyncListPermissionInstance + + + :returns: The fetched SyncListPermissionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + + async def fetch_async(self) -> SyncListPermissionInstance: + """ + Asynchronous coroutine to fetch the SyncListPermissionInstance + + + :returns: The fetched SyncListPermissionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + + def update( + self, read: bool, write: bool, manage: bool + ) -> SyncListPermissionInstance: + """ + Update the SyncListPermissionInstance + + :param read: Whether the identity can read the Sync List and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. + :param manage: Whether the identity can delete the Sync List. Default value is `false`. + + :returns: The updated SyncListPermissionInstance + """ + + data = values.of( + { + "Read": serialize.boolean_to_string(read), + "Write": serialize.boolean_to_string(write), + "Manage": serialize.boolean_to_string(manage), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> SyncListPermissionInstance: + """ + Asynchronous coroutine to update the SyncListPermissionInstance + + :param read: Whether the identity can read the Sync List and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. + :param manage: Whether the identity can delete the Sync List. Default value is `false`. + + :returns: The updated SyncListPermissionInstance + """ + + data = values.of( + { + "Read": serialize.boolean_to_string(read), + "Write": serialize.boolean_to_string(write), + "Manage": serialize.boolean_to_string(manage), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SyncListPermissionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SyncListPermissionInstance: + """ + Build an instance of SyncListPermissionInstance + + :param payload: Payload response from the API + """ + return SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SyncListPermissionList(ListResource): + + def __init__(self, version: Version, service_sid: str, list_sid: str): + """ + Initialize the SyncListPermissionList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync List Permission resources to read. + :param list_sid: The SID of the Sync List with the Sync List Permission resources to read. Can be the Sync List resource's `sid` or its `unique_name`. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "list_sid": list_sid, + } + self._uri = "/Services/{service_sid}/Lists/{list_sid}/Permissions".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SyncListPermissionInstance]: + """ + Streams SyncListPermissionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SyncListPermissionInstance]: + """ + Asynchronously streams SyncListPermissionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncListPermissionInstance]: + """ + Lists SyncListPermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncListPermissionInstance]: + """ + Asynchronously lists SyncListPermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncListPermissionPage: + """ + Retrieve a single page of SyncListPermissionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncListPermissionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncListPermissionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncListPermissionPage: + """ + Asynchronously retrieve a single page of SyncListPermissionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncListPermissionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncListPermissionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SyncListPermissionPage: + """ + Retrieve a specific page of SyncListPermissionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncListPermissionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SyncListPermissionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SyncListPermissionPage: + """ + Asynchronously retrieve a specific page of SyncListPermissionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncListPermissionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncListPermissionPage(self._version, response, self._solution) + + def get(self, identity: str) -> SyncListPermissionContext: + """ + Constructs a SyncListPermissionContext + + :param identity: The application-defined string that uniquely identifies the User's Sync List Permission resource to update. + """ + return SyncListPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=identity, + ) + + def __call__(self, identity: str) -> SyncListPermissionContext: + """ + Constructs a SyncListPermissionContext + + :param identity: The application-defined string that uniquely identifies the User's Sync List Permission resource to update. + """ + return SyncListPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=identity, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_map/__init__.py b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_map/__init__.py new file mode 100644 index 00000000..c6bb1ce5 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_map/__init__.py @@ -0,0 +1,723 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Sync + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.sync.v1.service.sync_map.sync_map_item import SyncMapItemList +from twilio.rest.sync.v1.service.sync_map.sync_map_permission import ( + SyncMapPermissionList, +) + + +class SyncMapInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Sync Map resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Sync Map resource. + :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + :ivar url: The absolute URL of the Sync Map resource. + :ivar links: The URLs of the Sync Map's nested resources. + :ivar revision: The current revision of the Sync Map, represented as a string. + :ivar date_expires: The date and time in GMT when the Sync Map expires and will be deleted, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. If the Sync Map does not expire, this value is `null`. The Sync Map might not be deleted immediately after it expires. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar created_by: The identity of the Sync Map's creator. If the Sync Map is created from the client SDK, the value matches the Access Token's `identity` field. If the Sync Map was created from the REST API, the value is `system`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.revision: Optional[str] = payload.get("revision") + self.date_expires: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_expires") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[SyncMapContext] = None + + @property + def _proxy(self) -> "SyncMapContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SyncMapContext for this SyncMapInstance + """ + if self._context is None: + self._context = SyncMapContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SyncMapInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncMapInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SyncMapInstance": + """ + Fetch the SyncMapInstance + + + :returns: The fetched SyncMapInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SyncMapInstance": + """ + Asynchronous coroutine to fetch the SyncMapInstance + + + :returns: The fetched SyncMapInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncMapInstance": + """ + Update the SyncMapInstance + + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: The updated SyncMapInstance + """ + return self._proxy.update( + ttl=ttl, + collection_ttl=collection_ttl, + ) + + async def update_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncMapInstance": + """ + Asynchronous coroutine to update the SyncMapInstance + + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: The updated SyncMapInstance + """ + return await self._proxy.update_async( + ttl=ttl, + collection_ttl=collection_ttl, + ) + + @property + def sync_map_items(self) -> SyncMapItemList: + """ + Access the sync_map_items + """ + return self._proxy.sync_map_items + + @property + def sync_map_permissions(self) -> SyncMapPermissionList: + """ + Access the sync_map_permissions + """ + return self._proxy.sync_map_permissions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SyncMapContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the SyncMapContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync Map resource to update. + :param sid: The SID of the Sync Map resource to update. Can be the Sync Map's `sid` or its `unique_name`. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Maps/{sid}".format(**self._solution) + + self._sync_map_items: Optional[SyncMapItemList] = None + self._sync_map_permissions: Optional[SyncMapPermissionList] = None + + def delete(self) -> bool: + """ + Deletes the SyncMapInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncMapInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SyncMapInstance: + """ + Fetch the SyncMapInstance + + + :returns: The fetched SyncMapInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SyncMapInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SyncMapInstance: + """ + Asynchronous coroutine to fetch the SyncMapInstance + + + :returns: The fetched SyncMapInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SyncMapInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapInstance: + """ + Update the SyncMapInstance + + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: The updated SyncMapInstance + """ + + data = values.of( + { + "Ttl": ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncMapInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapInstance: + """ + Asynchronous coroutine to update the SyncMapInstance + + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: The updated SyncMapInstance + """ + + data = values.of( + { + "Ttl": ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncMapInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def sync_map_items(self) -> SyncMapItemList: + """ + Access the sync_map_items + """ + if self._sync_map_items is None: + self._sync_map_items = SyncMapItemList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._sync_map_items + + @property + def sync_map_permissions(self) -> SyncMapPermissionList: + """ + Access the sync_map_permissions + """ + if self._sync_map_permissions is None: + self._sync_map_permissions = SyncMapPermissionList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._sync_map_permissions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SyncMapPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SyncMapInstance: + """ + Build an instance of SyncMapInstance + + :param payload: Payload response from the API + """ + return SyncMapInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SyncMapList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the SyncMapList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync Map resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Maps".format(**self._solution) + + def create( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapInstance: + """ + Create the SyncMapInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: The created SyncMapInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Ttl": ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncMapInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapInstance: + """ + Asynchronously create the SyncMapInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: The created SyncMapInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Ttl": ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncMapInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SyncMapInstance]: + """ + Streams SyncMapInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SyncMapInstance]: + """ + Asynchronously streams SyncMapInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncMapInstance]: + """ + Lists SyncMapInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncMapInstance]: + """ + Asynchronously lists SyncMapInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncMapPage: + """ + Retrieve a single page of SyncMapInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncMapInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncMapPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncMapPage: + """ + Asynchronously retrieve a single page of SyncMapInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncMapInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncMapPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SyncMapPage: + """ + Retrieve a specific page of SyncMapInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncMapInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SyncMapPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SyncMapPage: + """ + Asynchronously retrieve a specific page of SyncMapInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncMapInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncMapPage(self._version, response, self._solution) + + def get(self, sid: str) -> SyncMapContext: + """ + Constructs a SyncMapContext + + :param sid: The SID of the Sync Map resource to update. Can be the Sync Map's `sid` or its `unique_name`. + """ + return SyncMapContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> SyncMapContext: + """ + Constructs a SyncMapContext + + :param sid: The SID of the Sync Map resource to update. Can be the Sync Map's `sid` or its `unique_name`. + """ + return SyncMapContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_map/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_map/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..412d1dd4 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_map/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_map/__pycache__/sync_map_item.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_map/__pycache__/sync_map_item.cpython-312.pyc new file mode 100644 index 00000000..383c029a Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_map/__pycache__/sync_map_item.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_map/__pycache__/sync_map_permission.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_map/__pycache__/sync_map_permission.cpython-312.pyc new file mode 100644 index 00000000..0149d4ea Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_map/__pycache__/sync_map_permission.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_map/sync_map_item.py b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_map/sync_map_item.py new file mode 100644 index 00000000..49396940 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_map/sync_map_item.py @@ -0,0 +1,841 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Sync + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SyncMapItemInstance(InstanceResource): + + class QueryFromBoundType(object): + INCLUSIVE = "inclusive" + EXCLUSIVE = "exclusive" + + class QueryResultOrder(object): + ASC = "asc" + DESC = "desc" + + """ + :ivar key: The unique, user-defined key for the Map Item. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Map Item resource. + :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + :ivar map_sid: The SID of the Sync Map that contains the Map Item. + :ivar url: The absolute URL of the Map Item resource. + :ivar revision: The current revision of the Map Item, represented as a string. + :ivar data: An arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :ivar date_expires: The date and time in GMT when the Map Item expires and will be deleted, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. If the Map Item does not expire, this value is `null`. The Map Item might not be deleted immediately after it expires. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar created_by: The identity of the Map Item's creator. If the Map Item is created from the client SDK, the value matches the Access Token's `identity` field. If the Map Item was created from the REST API, the value is `system`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + map_sid: str, + key: Optional[str] = None, + ): + super().__init__(version) + + self.key: Optional[str] = payload.get("key") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.map_sid: Optional[str] = payload.get("map_sid") + self.url: Optional[str] = payload.get("url") + self.revision: Optional[str] = payload.get("revision") + self.data: Optional[Dict[str, object]] = payload.get("data") + self.date_expires: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_expires") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + + self._solution = { + "service_sid": service_sid, + "map_sid": map_sid, + "key": key or self.key, + } + self._context: Optional[SyncMapItemContext] = None + + @property + def _proxy(self) -> "SyncMapItemContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SyncMapItemContext for this SyncMapItemInstance + """ + if self._context is None: + self._context = SyncMapItemContext( + self._version, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], + ) + return self._context + + def delete(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Deletes the SyncMapItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + if_match=if_match, + ) + + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Asynchronous coroutine that deletes the SyncMapItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + if_match=if_match, + ) + + def fetch(self) -> "SyncMapItemInstance": + """ + Fetch the SyncMapItemInstance + + + :returns: The fetched SyncMapItemInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SyncMapItemInstance": + """ + Asynchronous coroutine to fetch the SyncMapItemInstance + + + :returns: The fetched SyncMapItemInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncMapItemInstance": + """ + Update the SyncMapItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. This parameter can only be used when the Map Item's `data` or `ttl` is updated in the same request. + + :returns: The updated SyncMapItemInstance + """ + return self._proxy.update( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncMapItemInstance": + """ + Asynchronous coroutine to update the SyncMapItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. This parameter can only be used when the Map Item's `data` or `ttl` is updated in the same request. + + :returns: The updated SyncMapItemInstance + """ + return await self._proxy.update_async( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SyncMapItemContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, map_sid: str, key: str): + """ + Initialize the SyncMapItemContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync Map Item resource to update. + :param map_sid: The SID of the Sync Map with the Sync Map Item resource to update. Can be the Sync Map resource's `sid` or its `unique_name`. + :param key: The `key` value of the Sync Map Item resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "map_sid": map_sid, + "key": key, + } + self._uri = "/Services/{service_sid}/Maps/{map_sid}/Items/{key}".format( + **self._solution + ) + + def delete(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Deletes the SyncMapItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "If-Match": if_match, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Asynchronous coroutine that deletes the SyncMapItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "If-Match": if_match, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SyncMapItemInstance: + """ + Fetch the SyncMapItemInstance + + + :returns: The fetched SyncMapItemInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], + ) + + async def fetch_async(self) -> SyncMapItemInstance: + """ + Asynchronous coroutine to fetch the SyncMapItemInstance + + + :returns: The fetched SyncMapItemInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], + ) + + def update( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapItemInstance: + """ + Update the SyncMapItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. This parameter can only be used when the Map Item's `data` or `ttl` is updated in the same request. + + :returns: The updated SyncMapItemInstance + """ + + data = values.of( + { + "Data": serialize.object(data), + "Ttl": ttl, + "ItemTtl": item_ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapItemInstance: + """ + Asynchronous coroutine to update the SyncMapItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. This parameter can only be used when the Map Item's `data` or `ttl` is updated in the same request. + + :returns: The updated SyncMapItemInstance + """ + + data = values.of( + { + "Data": serialize.object(data), + "Ttl": ttl, + "ItemTtl": item_ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SyncMapItemPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SyncMapItemInstance: + """ + Build an instance of SyncMapItemInstance + + :param payload: Payload response from the API + """ + return SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SyncMapItemList(ListResource): + + def __init__(self, version: Version, service_sid: str, map_sid: str): + """ + Initialize the SyncMapItemList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Map Item resources to read. + :param map_sid: The SID of the Sync Map with the Sync Map Item resource to fetch. Can be the Sync Map resource's `sid` or its `unique_name`. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "map_sid": map_sid, + } + self._uri = "/Services/{service_sid}/Maps/{map_sid}/Items".format( + **self._solution + ) + + def create( + self, + key: str, + data: object, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapItemInstance: + """ + Create the SyncMapItemInstance + + :param key: The unique, user-defined key for the Map Item. Can be up to 320 characters long. + :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. + + :returns: The created SyncMapItemInstance + """ + + data = values.of( + { + "Key": key, + "Data": serialize.object(data), + "Ttl": ttl, + "ItemTtl": item_ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + ) + + async def create_async( + self, + key: str, + data: object, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapItemInstance: + """ + Asynchronously create the SyncMapItemInstance + + :param key: The unique, user-defined key for the Map Item. Can be up to 320 characters long. + :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. + + :returns: The created SyncMapItemInstance + """ + + data = values.of( + { + "Key": key, + "Data": serialize.object(data), + "Ttl": ttl, + "ItemTtl": item_ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + ) + + def stream( + self, + order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SyncMapItemInstance]: + """ + Streams SyncMapItemInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "SyncMapItemInstance.QueryResultOrder" order: How to order the Map Items returned by their `key` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. Map Items are [ordered lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) by Item key. + :param str from_: The `key` of the first Sync Map Item resource to read. See also `bounds`. + :param "SyncMapItemInstance.QueryFromBoundType" bounds: Whether to include the Map Item referenced by the `from` parameter. Can be: `inclusive` to include the Map Item referenced by the `from` parameter or `exclusive` to start with the next Map Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SyncMapItemInstance]: + """ + Asynchronously streams SyncMapItemInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "SyncMapItemInstance.QueryResultOrder" order: How to order the Map Items returned by their `key` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. Map Items are [ordered lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) by Item key. + :param str from_: The `key` of the first Sync Map Item resource to read. See also `bounds`. + :param "SyncMapItemInstance.QueryFromBoundType" bounds: Whether to include the Map Item referenced by the `from` parameter. Can be: `inclusive` to include the Map Item referenced by the `from` parameter or `exclusive` to start with the next Map Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncMapItemInstance]: + """ + Lists SyncMapItemInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "SyncMapItemInstance.QueryResultOrder" order: How to order the Map Items returned by their `key` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. Map Items are [ordered lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) by Item key. + :param str from_: The `key` of the first Sync Map Item resource to read. See also `bounds`. + :param "SyncMapItemInstance.QueryFromBoundType" bounds: Whether to include the Map Item referenced by the `from` parameter. Can be: `inclusive` to include the Map Item referenced by the `from` parameter or `exclusive` to start with the next Map Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + order=order, + from_=from_, + bounds=bounds, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncMapItemInstance]: + """ + Asynchronously lists SyncMapItemInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "SyncMapItemInstance.QueryResultOrder" order: How to order the Map Items returned by their `key` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. Map Items are [ordered lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) by Item key. + :param str from_: The `key` of the first Sync Map Item resource to read. See also `bounds`. + :param "SyncMapItemInstance.QueryFromBoundType" bounds: Whether to include the Map Item referenced by the `from` parameter. Can be: `inclusive` to include the Map Item referenced by the `from` parameter or `exclusive` to start with the next Map Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + order=order, + from_=from_, + bounds=bounds, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncMapItemPage: + """ + Retrieve a single page of SyncMapItemInstance records from the API. + Request is executed immediately + + :param order: How to order the Map Items returned by their `key` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. Map Items are [ordered lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) by Item key. + :param from_: The `key` of the first Sync Map Item resource to read. See also `bounds`. + :param bounds: Whether to include the Map Item referenced by the `from` parameter. Can be: `inclusive` to include the Map Item referenced by the `from` parameter or `exclusive` to start with the next Map Item. The default value is `inclusive`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncMapItemInstance + """ + data = values.of( + { + "Order": order, + "From": from_, + "Bounds": bounds, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncMapItemPage(self._version, response, self._solution) + + async def page_async( + self, + order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncMapItemPage: + """ + Asynchronously retrieve a single page of SyncMapItemInstance records from the API. + Request is executed immediately + + :param order: How to order the Map Items returned by their `key` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. Map Items are [ordered lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) by Item key. + :param from_: The `key` of the first Sync Map Item resource to read. See also `bounds`. + :param bounds: Whether to include the Map Item referenced by the `from` parameter. Can be: `inclusive` to include the Map Item referenced by the `from` parameter or `exclusive` to start with the next Map Item. The default value is `inclusive`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncMapItemInstance + """ + data = values.of( + { + "Order": order, + "From": from_, + "Bounds": bounds, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncMapItemPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SyncMapItemPage: + """ + Retrieve a specific page of SyncMapItemInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncMapItemInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SyncMapItemPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SyncMapItemPage: + """ + Asynchronously retrieve a specific page of SyncMapItemInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncMapItemInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncMapItemPage(self._version, response, self._solution) + + def get(self, key: str) -> SyncMapItemContext: + """ + Constructs a SyncMapItemContext + + :param key: The `key` value of the Sync Map Item resource to update. + """ + return SyncMapItemContext( + self._version, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=key, + ) + + def __call__(self, key: str) -> SyncMapItemContext: + """ + Constructs a SyncMapItemContext + + :param key: The `key` value of the Sync Map Item resource to update. + """ + return SyncMapItemContext( + self._version, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=key, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_map/sync_map_permission.py b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_map/sync_map_permission.py new file mode 100644 index 00000000..910560ad --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_map/sync_map_permission.py @@ -0,0 +1,615 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Sync + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SyncMapPermissionInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Sync Map Permission resource. + :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + :ivar map_sid: The SID of the Sync Map to which the Permission applies. + :ivar identity: The application-defined string that uniquely identifies the resource's User within the Service to an FPA token. + :ivar read: Whether the identity can read the Sync Map and its Items. + :ivar write: Whether the identity can create, update, and delete Items in the Sync Map. + :ivar manage: Whether the identity can delete the Sync Map. + :ivar url: The absolute URL of the Sync Map Permission resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + map_sid: str, + identity: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.map_sid: Optional[str] = payload.get("map_sid") + self.identity: Optional[str] = payload.get("identity") + self.read: Optional[bool] = payload.get("read") + self.write: Optional[bool] = payload.get("write") + self.manage: Optional[bool] = payload.get("manage") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "map_sid": map_sid, + "identity": identity or self.identity, + } + self._context: Optional[SyncMapPermissionContext] = None + + @property + def _proxy(self) -> "SyncMapPermissionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SyncMapPermissionContext for this SyncMapPermissionInstance + """ + if self._context is None: + self._context = SyncMapPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SyncMapPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncMapPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SyncMapPermissionInstance": + """ + Fetch the SyncMapPermissionInstance + + + :returns: The fetched SyncMapPermissionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SyncMapPermissionInstance": + """ + Asynchronous coroutine to fetch the SyncMapPermissionInstance + + + :returns: The fetched SyncMapPermissionInstance + """ + return await self._proxy.fetch_async() + + def update( + self, read: bool, write: bool, manage: bool + ) -> "SyncMapPermissionInstance": + """ + Update the SyncMapPermissionInstance + + :param read: Whether the identity can read the Sync Map and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. + :param manage: Whether the identity can delete the Sync Map. Default value is `false`. + + :returns: The updated SyncMapPermissionInstance + """ + return self._proxy.update( + read=read, + write=write, + manage=manage, + ) + + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> "SyncMapPermissionInstance": + """ + Asynchronous coroutine to update the SyncMapPermissionInstance + + :param read: Whether the identity can read the Sync Map and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. + :param manage: Whether the identity can delete the Sync Map. Default value is `false`. + + :returns: The updated SyncMapPermissionInstance + """ + return await self._proxy.update_async( + read=read, + write=write, + manage=manage, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SyncMapPermissionContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, map_sid: str, identity: str): + """ + Initialize the SyncMapPermissionContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync Map Permission resource to update. Can be the Service's `sid` value or `default`. + :param map_sid: The SID of the Sync Map with the Sync Map Permission resource to update. Can be the Sync Map resource's `sid` or its `unique_name`. + :param identity: The application-defined string that uniquely identifies the User's Sync Map Permission resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "map_sid": map_sid, + "identity": identity, + } + self._uri = ( + "/Services/{service_sid}/Maps/{map_sid}/Permissions/{identity}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the SyncMapPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncMapPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SyncMapPermissionInstance: + """ + Fetch the SyncMapPermissionInstance + + + :returns: The fetched SyncMapPermissionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + + async def fetch_async(self) -> SyncMapPermissionInstance: + """ + Asynchronous coroutine to fetch the SyncMapPermissionInstance + + + :returns: The fetched SyncMapPermissionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + + def update( + self, read: bool, write: bool, manage: bool + ) -> SyncMapPermissionInstance: + """ + Update the SyncMapPermissionInstance + + :param read: Whether the identity can read the Sync Map and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. + :param manage: Whether the identity can delete the Sync Map. Default value is `false`. + + :returns: The updated SyncMapPermissionInstance + """ + + data = values.of( + { + "Read": serialize.boolean_to_string(read), + "Write": serialize.boolean_to_string(write), + "Manage": serialize.boolean_to_string(manage), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> SyncMapPermissionInstance: + """ + Asynchronous coroutine to update the SyncMapPermissionInstance + + :param read: Whether the identity can read the Sync Map and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. + :param manage: Whether the identity can delete the Sync Map. Default value is `false`. + + :returns: The updated SyncMapPermissionInstance + """ + + data = values.of( + { + "Read": serialize.boolean_to_string(read), + "Write": serialize.boolean_to_string(write), + "Manage": serialize.boolean_to_string(manage), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SyncMapPermissionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SyncMapPermissionInstance: + """ + Build an instance of SyncMapPermissionInstance + + :param payload: Payload response from the API + """ + return SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SyncMapPermissionList(ListResource): + + def __init__(self, version: Version, service_sid: str, map_sid: str): + """ + Initialize the SyncMapPermissionList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync Map Permission resources to read. Can be the Service's `sid` value or `default`. + :param map_sid: The SID of the Sync Map with the Permission resources to read. Can be the Sync Map resource's `sid` or its `unique_name`. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "map_sid": map_sid, + } + self._uri = "/Services/{service_sid}/Maps/{map_sid}/Permissions".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SyncMapPermissionInstance]: + """ + Streams SyncMapPermissionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SyncMapPermissionInstance]: + """ + Asynchronously streams SyncMapPermissionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncMapPermissionInstance]: + """ + Lists SyncMapPermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncMapPermissionInstance]: + """ + Asynchronously lists SyncMapPermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncMapPermissionPage: + """ + Retrieve a single page of SyncMapPermissionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncMapPermissionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncMapPermissionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncMapPermissionPage: + """ + Asynchronously retrieve a single page of SyncMapPermissionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncMapPermissionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncMapPermissionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SyncMapPermissionPage: + """ + Retrieve a specific page of SyncMapPermissionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncMapPermissionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SyncMapPermissionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SyncMapPermissionPage: + """ + Asynchronously retrieve a specific page of SyncMapPermissionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncMapPermissionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncMapPermissionPage(self._version, response, self._solution) + + def get(self, identity: str) -> SyncMapPermissionContext: + """ + Constructs a SyncMapPermissionContext + + :param identity: The application-defined string that uniquely identifies the User's Sync Map Permission resource to update. + """ + return SyncMapPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=identity, + ) + + def __call__(self, identity: str) -> SyncMapPermissionContext: + """ + Constructs a SyncMapPermissionContext + + :param identity: The application-defined string that uniquely identifies the User's Sync Map Permission resource to update. + """ + return SyncMapPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=identity, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_stream/__init__.py b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_stream/__init__.py new file mode 100644 index 00000000..a7f4128e --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_stream/__init__.py @@ -0,0 +1,671 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Sync + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.sync.v1.service.sync_stream.stream_message import StreamMessageList + + +class SyncStreamInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Sync Stream resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Sync Stream resource. + :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + :ivar url: The absolute URL of the Message Stream resource. + :ivar links: The URLs of the Stream's nested resources. + :ivar date_expires: The date and time in GMT when the Message Stream expires and will be deleted, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. If the Message Stream does not expire, this value is `null`. The Stream might not be deleted immediately after it expires. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar created_by: The identity of the Stream's creator. If the Stream is created from the client SDK, the value matches the Access Token's `identity` field. If the Stream was created from the REST API, the value is 'system'. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.date_expires: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_expires") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[SyncStreamContext] = None + + @property + def _proxy(self) -> "SyncStreamContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SyncStreamContext for this SyncStreamInstance + """ + if self._context is None: + self._context = SyncStreamContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SyncStreamInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncStreamInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SyncStreamInstance": + """ + Fetch the SyncStreamInstance + + + :returns: The fetched SyncStreamInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SyncStreamInstance": + """ + Asynchronous coroutine to fetch the SyncStreamInstance + + + :returns: The fetched SyncStreamInstance + """ + return await self._proxy.fetch_async() + + def update(self, ttl: Union[int, object] = values.unset) -> "SyncStreamInstance": + """ + Update the SyncStreamInstance + + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: The updated SyncStreamInstance + """ + return self._proxy.update( + ttl=ttl, + ) + + async def update_async( + self, ttl: Union[int, object] = values.unset + ) -> "SyncStreamInstance": + """ + Asynchronous coroutine to update the SyncStreamInstance + + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: The updated SyncStreamInstance + """ + return await self._proxy.update_async( + ttl=ttl, + ) + + @property + def stream_messages(self) -> StreamMessageList: + """ + Access the stream_messages + """ + return self._proxy.stream_messages + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SyncStreamContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the SyncStreamContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync Stream resource to update. + :param sid: The SID of the Stream resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Streams/{sid}".format(**self._solution) + + self._stream_messages: Optional[StreamMessageList] = None + + def delete(self) -> bool: + """ + Deletes the SyncStreamInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncStreamInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SyncStreamInstance: + """ + Fetch the SyncStreamInstance + + + :returns: The fetched SyncStreamInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SyncStreamInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SyncStreamInstance: + """ + Asynchronous coroutine to fetch the SyncStreamInstance + + + :returns: The fetched SyncStreamInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SyncStreamInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update(self, ttl: Union[int, object] = values.unset) -> SyncStreamInstance: + """ + Update the SyncStreamInstance + + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: The updated SyncStreamInstance + """ + + data = values.of( + { + "Ttl": ttl, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncStreamInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, ttl: Union[int, object] = values.unset + ) -> SyncStreamInstance: + """ + Asynchronous coroutine to update the SyncStreamInstance + + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: The updated SyncStreamInstance + """ + + data = values.of( + { + "Ttl": ttl, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncStreamInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def stream_messages(self) -> StreamMessageList: + """ + Access the stream_messages + """ + if self._stream_messages is None: + self._stream_messages = StreamMessageList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._stream_messages + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SyncStreamPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SyncStreamInstance: + """ + Build an instance of SyncStreamInstance + + :param payload: Payload response from the API + """ + return SyncStreamInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SyncStreamList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the SyncStreamList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Stream resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Streams".format(**self._solution) + + def create( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> SyncStreamInstance: + """ + Create the SyncStreamInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: The created SyncStreamInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Ttl": ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncStreamInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> SyncStreamInstance: + """ + Asynchronously create the SyncStreamInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: The created SyncStreamInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Ttl": ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncStreamInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SyncStreamInstance]: + """ + Streams SyncStreamInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SyncStreamInstance]: + """ + Asynchronously streams SyncStreamInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncStreamInstance]: + """ + Lists SyncStreamInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncStreamInstance]: + """ + Asynchronously lists SyncStreamInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncStreamPage: + """ + Retrieve a single page of SyncStreamInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncStreamInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncStreamPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncStreamPage: + """ + Asynchronously retrieve a single page of SyncStreamInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncStreamInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncStreamPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SyncStreamPage: + """ + Retrieve a specific page of SyncStreamInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncStreamInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SyncStreamPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SyncStreamPage: + """ + Asynchronously retrieve a specific page of SyncStreamInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncStreamInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncStreamPage(self._version, response, self._solution) + + def get(self, sid: str) -> SyncStreamContext: + """ + Constructs a SyncStreamContext + + :param sid: The SID of the Stream resource to update. + """ + return SyncStreamContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> SyncStreamContext: + """ + Constructs a SyncStreamContext + + :param sid: The SID of the Stream resource to update. + """ + return SyncStreamContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_stream/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_stream/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..43531778 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_stream/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_stream/__pycache__/stream_message.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_stream/__pycache__/stream_message.cpython-312.pyc new file mode 100644 index 00000000..169548e9 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_stream/__pycache__/stream_message.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_stream/stream_message.py b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_stream/stream_message.py new file mode 100644 index 00000000..bcce2399 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/sync/v1/service/sync_stream/stream_message.py @@ -0,0 +1,146 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Sync + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class StreamMessageInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Stream Message resource. + :ivar data: An arbitrary, schema-less object that contains the Stream Message body. Can be up to 4 KiB in length. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + stream_sid: str, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.data: Optional[Dict[str, object]] = payload.get("data") + + self._solution = { + "service_sid": service_sid, + "stream_sid": stream_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class StreamMessageList(ListResource): + + def __init__(self, version: Version, service_sid: str, stream_sid: str): + """ + Initialize the StreamMessageList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) to create the new Stream Message in. + :param stream_sid: The SID of the Sync Stream to create the new Stream Message resource for. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "stream_sid": stream_sid, + } + self._uri = "/Services/{service_sid}/Streams/{stream_sid}/Messages".format( + **self._solution + ) + + def create(self, data: object) -> StreamMessageInstance: + """ + Create the StreamMessageInstance + + :param data: A JSON string that represents an arbitrary, schema-less object that makes up the Stream Message body. Can be up to 4 KiB in length. + + :returns: The created StreamMessageInstance + """ + + data = values.of( + { + "Data": serialize.object(data), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return StreamMessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + stream_sid=self._solution["stream_sid"], + ) + + async def create_async(self, data: object) -> StreamMessageInstance: + """ + Asynchronously create the StreamMessageInstance + + :param data: A JSON string that represents an arbitrary, schema-less object that makes up the Stream Message body. Can be up to 4 KiB in length. + + :returns: The created StreamMessageInstance + """ + + data = values.of( + { + "Data": serialize.object(data), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return StreamMessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + stream_sid=self._solution["stream_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/TaskrouterBase.py b/venv/Lib/site-packages/twilio/rest/taskrouter/TaskrouterBase.py new file mode 100644 index 00000000..4bbbdb60 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/TaskrouterBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.taskrouter.v1 import V1 + + +class TaskrouterBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Taskrouter Domain + + :returns: Domain for Taskrouter + """ + super().__init__(twilio, "https://taskrouter.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Taskrouter + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/__init__.py b/venv/Lib/site-packages/twilio/rest/taskrouter/__init__.py new file mode 100644 index 00000000..73d3ee82 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/__init__.py @@ -0,0 +1,15 @@ +from warnings import warn + +from twilio.rest.taskrouter.TaskrouterBase import TaskrouterBase +from twilio.rest.taskrouter.v1.workspace import WorkspaceList + + +class Taskrouter(TaskrouterBase): + @property + def workspaces(self) -> WorkspaceList: + warn( + "workspaces is deprecated. Use v1.workspaces instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.workspaces diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/__pycache__/TaskrouterBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/__pycache__/TaskrouterBase.cpython-312.pyc new file mode 100644 index 00000000..bd629e5b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/__pycache__/TaskrouterBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..9d7356ba Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/__init__.py new file mode 100644 index 00000000..a17eeccc --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.taskrouter.v1.workspace import WorkspaceList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Taskrouter + + :param domain: The Twilio.taskrouter domain + """ + super().__init__(domain, "v1") + self._workspaces: Optional[WorkspaceList] = None + + @property + def workspaces(self) -> WorkspaceList: + if self._workspaces is None: + self._workspaces = WorkspaceList(self) + return self._workspaces + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..048d985b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/__init__.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/__init__.py new file mode 100644 index 00000000..086e3e17 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/__init__.py @@ -0,0 +1,979 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.taskrouter.v1.workspace.activity import ActivityList +from twilio.rest.taskrouter.v1.workspace.event import EventList +from twilio.rest.taskrouter.v1.workspace.task import TaskList +from twilio.rest.taskrouter.v1.workspace.task_channel import TaskChannelList +from twilio.rest.taskrouter.v1.workspace.task_queue import TaskQueueList +from twilio.rest.taskrouter.v1.workspace.worker import WorkerList +from twilio.rest.taskrouter.v1.workspace.workflow import WorkflowList +from twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics import ( + WorkspaceCumulativeStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics import ( + WorkspaceRealTimeStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.workspace_statistics import ( + WorkspaceStatisticsList, +) + + +class WorkspaceInstance(InstanceResource): + + class QueueOrder(object): + FIFO = "FIFO" + LIFO = "LIFO" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workspace resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar default_activity_name: The name of the default activity. + :ivar default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. + :ivar event_callback_url: The URL we call when an event occurs. If provided, the Workspace will publish events to this URL, for example, to collect data for reporting. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :ivar events_filter: The list of Workspace events for which to call `event_callback_url`. For example, if `EventsFilter=task.created, task.canceled, worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :ivar friendly_name: The string that you assigned to describe the Workspace resource. For example `Customer Support` or `2014 Election Campaign`. + :ivar multi_task_enabled: Whether multi-tasking is enabled. The default is `true`, which enables multi-tasking. Multi-tasking allows Workers to handle multiple Tasks simultaneously. When enabled (`true`), each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking each Worker would only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :ivar sid: The unique string that we created to identify the Workspace resource. + :ivar timeout_activity_name: The name of the timeout activity. + :ivar timeout_activity_sid: The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. + :ivar prioritize_queue_order: + :ivar url: The absolute URL of the Workspace resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.default_activity_name: Optional[str] = payload.get("default_activity_name") + self.default_activity_sid: Optional[str] = payload.get("default_activity_sid") + self.event_callback_url: Optional[str] = payload.get("event_callback_url") + self.events_filter: Optional[str] = payload.get("events_filter") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.multi_task_enabled: Optional[bool] = payload.get("multi_task_enabled") + self.sid: Optional[str] = payload.get("sid") + self.timeout_activity_name: Optional[str] = payload.get("timeout_activity_name") + self.timeout_activity_sid: Optional[str] = payload.get("timeout_activity_sid") + self.prioritize_queue_order: Optional["WorkspaceInstance.QueueOrder"] = ( + payload.get("prioritize_queue_order") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[WorkspaceContext] = None + + @property + def _proxy(self) -> "WorkspaceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkspaceContext for this WorkspaceInstance + """ + if self._context is None: + self._context = WorkspaceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the WorkspaceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WorkspaceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "WorkspaceInstance": + """ + Fetch the WorkspaceInstance + + + :returns: The fetched WorkspaceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "WorkspaceInstance": + """ + Asynchronous coroutine to fetch the WorkspaceInstance + + + :returns: The fetched WorkspaceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + default_activity_sid: Union[str, object] = values.unset, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + timeout_activity_sid: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> "WorkspaceInstance": + """ + Update the WorkspaceInstance + + :param default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. + :param event_callback_url: The URL we should call when an event occurs. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example if `EventsFilter=task.created,task.canceled,worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param friendly_name: A descriptive string that you create to describe the Workspace resource. For example: `Sales Call Center` or `Customer Support Team`. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be maintained as multi-tasking. There is no default when omitting this parameter. A multi-tasking Workspace can't be updated to single-tasking unless it is not a Flex Project and another (legacy) single-tasking Workspace exists. Multi-tasking allows Workers to handle multiple Tasks simultaneously. In multi-tasking mode, each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param timeout_activity_sid: The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. + :param prioritize_queue_order: + + :returns: The updated WorkspaceInstance + """ + return self._proxy.update( + default_activity_sid=default_activity_sid, + event_callback_url=event_callback_url, + events_filter=events_filter, + friendly_name=friendly_name, + multi_task_enabled=multi_task_enabled, + timeout_activity_sid=timeout_activity_sid, + prioritize_queue_order=prioritize_queue_order, + ) + + async def update_async( + self, + default_activity_sid: Union[str, object] = values.unset, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + timeout_activity_sid: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> "WorkspaceInstance": + """ + Asynchronous coroutine to update the WorkspaceInstance + + :param default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. + :param event_callback_url: The URL we should call when an event occurs. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example if `EventsFilter=task.created,task.canceled,worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param friendly_name: A descriptive string that you create to describe the Workspace resource. For example: `Sales Call Center` or `Customer Support Team`. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be maintained as multi-tasking. There is no default when omitting this parameter. A multi-tasking Workspace can't be updated to single-tasking unless it is not a Flex Project and another (legacy) single-tasking Workspace exists. Multi-tasking allows Workers to handle multiple Tasks simultaneously. In multi-tasking mode, each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param timeout_activity_sid: The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. + :param prioritize_queue_order: + + :returns: The updated WorkspaceInstance + """ + return await self._proxy.update_async( + default_activity_sid=default_activity_sid, + event_callback_url=event_callback_url, + events_filter=events_filter, + friendly_name=friendly_name, + multi_task_enabled=multi_task_enabled, + timeout_activity_sid=timeout_activity_sid, + prioritize_queue_order=prioritize_queue_order, + ) + + @property + def activities(self) -> ActivityList: + """ + Access the activities + """ + return self._proxy.activities + + @property + def events(self) -> EventList: + """ + Access the events + """ + return self._proxy.events + + @property + def tasks(self) -> TaskList: + """ + Access the tasks + """ + return self._proxy.tasks + + @property + def task_channels(self) -> TaskChannelList: + """ + Access the task_channels + """ + return self._proxy.task_channels + + @property + def task_queues(self) -> TaskQueueList: + """ + Access the task_queues + """ + return self._proxy.task_queues + + @property + def workers(self) -> WorkerList: + """ + Access the workers + """ + return self._proxy.workers + + @property + def workflows(self) -> WorkflowList: + """ + Access the workflows + """ + return self._proxy.workflows + + @property + def cumulative_statistics(self) -> WorkspaceCumulativeStatisticsList: + """ + Access the cumulative_statistics + """ + return self._proxy.cumulative_statistics + + @property + def real_time_statistics(self) -> WorkspaceRealTimeStatisticsList: + """ + Access the real_time_statistics + """ + return self._proxy.real_time_statistics + + @property + def statistics(self) -> WorkspaceStatisticsList: + """ + Access the statistics + """ + return self._proxy.statistics + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WorkspaceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the WorkspaceContext + + :param version: Version that contains the resource + :param sid: The SID of the Workspace resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Workspaces/{sid}".format(**self._solution) + + self._activities: Optional[ActivityList] = None + self._events: Optional[EventList] = None + self._tasks: Optional[TaskList] = None + self._task_channels: Optional[TaskChannelList] = None + self._task_queues: Optional[TaskQueueList] = None + self._workers: Optional[WorkerList] = None + self._workflows: Optional[WorkflowList] = None + self._cumulative_statistics: Optional[WorkspaceCumulativeStatisticsList] = None + self._real_time_statistics: Optional[WorkspaceRealTimeStatisticsList] = None + self._statistics: Optional[WorkspaceStatisticsList] = None + + def delete(self) -> bool: + """ + Deletes the WorkspaceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WorkspaceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> WorkspaceInstance: + """ + Fetch the WorkspaceInstance + + + :returns: The fetched WorkspaceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WorkspaceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> WorkspaceInstance: + """ + Asynchronous coroutine to fetch the WorkspaceInstance + + + :returns: The fetched WorkspaceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WorkspaceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + default_activity_sid: Union[str, object] = values.unset, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + timeout_activity_sid: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> WorkspaceInstance: + """ + Update the WorkspaceInstance + + :param default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. + :param event_callback_url: The URL we should call when an event occurs. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example if `EventsFilter=task.created,task.canceled,worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param friendly_name: A descriptive string that you create to describe the Workspace resource. For example: `Sales Call Center` or `Customer Support Team`. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be maintained as multi-tasking. There is no default when omitting this parameter. A multi-tasking Workspace can't be updated to single-tasking unless it is not a Flex Project and another (legacy) single-tasking Workspace exists. Multi-tasking allows Workers to handle multiple Tasks simultaneously. In multi-tasking mode, each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param timeout_activity_sid: The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. + :param prioritize_queue_order: + + :returns: The updated WorkspaceInstance + """ + + data = values.of( + { + "DefaultActivitySid": default_activity_sid, + "EventCallbackUrl": event_callback_url, + "EventsFilter": events_filter, + "FriendlyName": friendly_name, + "MultiTaskEnabled": serialize.boolean_to_string(multi_task_enabled), + "TimeoutActivitySid": timeout_activity_sid, + "PrioritizeQueueOrder": prioritize_queue_order, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkspaceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + default_activity_sid: Union[str, object] = values.unset, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + timeout_activity_sid: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> WorkspaceInstance: + """ + Asynchronous coroutine to update the WorkspaceInstance + + :param default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. + :param event_callback_url: The URL we should call when an event occurs. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example if `EventsFilter=task.created,task.canceled,worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param friendly_name: A descriptive string that you create to describe the Workspace resource. For example: `Sales Call Center` or `Customer Support Team`. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be maintained as multi-tasking. There is no default when omitting this parameter. A multi-tasking Workspace can't be updated to single-tasking unless it is not a Flex Project and another (legacy) single-tasking Workspace exists. Multi-tasking allows Workers to handle multiple Tasks simultaneously. In multi-tasking mode, each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param timeout_activity_sid: The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. + :param prioritize_queue_order: + + :returns: The updated WorkspaceInstance + """ + + data = values.of( + { + "DefaultActivitySid": default_activity_sid, + "EventCallbackUrl": event_callback_url, + "EventsFilter": events_filter, + "FriendlyName": friendly_name, + "MultiTaskEnabled": serialize.boolean_to_string(multi_task_enabled), + "TimeoutActivitySid": timeout_activity_sid, + "PrioritizeQueueOrder": prioritize_queue_order, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkspaceInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def activities(self) -> ActivityList: + """ + Access the activities + """ + if self._activities is None: + self._activities = ActivityList( + self._version, + self._solution["sid"], + ) + return self._activities + + @property + def events(self) -> EventList: + """ + Access the events + """ + if self._events is None: + self._events = EventList( + self._version, + self._solution["sid"], + ) + return self._events + + @property + def tasks(self) -> TaskList: + """ + Access the tasks + """ + if self._tasks is None: + self._tasks = TaskList( + self._version, + self._solution["sid"], + ) + return self._tasks + + @property + def task_channels(self) -> TaskChannelList: + """ + Access the task_channels + """ + if self._task_channels is None: + self._task_channels = TaskChannelList( + self._version, + self._solution["sid"], + ) + return self._task_channels + + @property + def task_queues(self) -> TaskQueueList: + """ + Access the task_queues + """ + if self._task_queues is None: + self._task_queues = TaskQueueList( + self._version, + self._solution["sid"], + ) + return self._task_queues + + @property + def workers(self) -> WorkerList: + """ + Access the workers + """ + if self._workers is None: + self._workers = WorkerList( + self._version, + self._solution["sid"], + ) + return self._workers + + @property + def workflows(self) -> WorkflowList: + """ + Access the workflows + """ + if self._workflows is None: + self._workflows = WorkflowList( + self._version, + self._solution["sid"], + ) + return self._workflows + + @property + def cumulative_statistics(self) -> WorkspaceCumulativeStatisticsList: + """ + Access the cumulative_statistics + """ + if self._cumulative_statistics is None: + self._cumulative_statistics = WorkspaceCumulativeStatisticsList( + self._version, + self._solution["sid"], + ) + return self._cumulative_statistics + + @property + def real_time_statistics(self) -> WorkspaceRealTimeStatisticsList: + """ + Access the real_time_statistics + """ + if self._real_time_statistics is None: + self._real_time_statistics = WorkspaceRealTimeStatisticsList( + self._version, + self._solution["sid"], + ) + return self._real_time_statistics + + @property + def statistics(self) -> WorkspaceStatisticsList: + """ + Access the statistics + """ + if self._statistics is None: + self._statistics = WorkspaceStatisticsList( + self._version, + self._solution["sid"], + ) + return self._statistics + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WorkspacePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WorkspaceInstance: + """ + Build an instance of WorkspaceInstance + + :param payload: Payload response from the API + """ + return WorkspaceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class WorkspaceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the WorkspaceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Workspaces" + + def create( + self, + friendly_name: str, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + template: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> WorkspaceInstance: + """ + Create the WorkspaceInstance + + :param friendly_name: A descriptive string that you create to describe the Workspace resource. It can be up to 64 characters long. For example: `Customer Support` or `2014 Election Campaign`. + :param event_callback_url: The URL we should call when an event occurs. If provided, the Workspace will publish events to this URL, for example, to collect data for reporting. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example, if `EventsFilter=task.created, task.canceled, worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be created as multi-tasking. The default is `true`. Multi-tasking allows Workers to handle multiple Tasks simultaneously. When enabled (`true`), each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param template: An available template name. Can be: `NONE` or `FIFO` and the default is `NONE`. Pre-configures the Workspace with the Workflow and Activities specified in the template. `NONE` will create a Workspace with only a set of default activities. `FIFO` will configure TaskRouter with a set of default activities and a single TaskQueue for first-in, first-out distribution, which can be useful when you are getting started with TaskRouter. + :param prioritize_queue_order: + + :returns: The created WorkspaceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "EventCallbackUrl": event_callback_url, + "EventsFilter": events_filter, + "MultiTaskEnabled": serialize.boolean_to_string(multi_task_enabled), + "Template": template, + "PrioritizeQueueOrder": prioritize_queue_order, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkspaceInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + template: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> WorkspaceInstance: + """ + Asynchronously create the WorkspaceInstance + + :param friendly_name: A descriptive string that you create to describe the Workspace resource. It can be up to 64 characters long. For example: `Customer Support` or `2014 Election Campaign`. + :param event_callback_url: The URL we should call when an event occurs. If provided, the Workspace will publish events to this URL, for example, to collect data for reporting. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example, if `EventsFilter=task.created, task.canceled, worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be created as multi-tasking. The default is `true`. Multi-tasking allows Workers to handle multiple Tasks simultaneously. When enabled (`true`), each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param template: An available template name. Can be: `NONE` or `FIFO` and the default is `NONE`. Pre-configures the Workspace with the Workflow and Activities specified in the template. `NONE` will create a Workspace with only a set of default activities. `FIFO` will configure TaskRouter with a set of default activities and a single TaskQueue for first-in, first-out distribution, which can be useful when you are getting started with TaskRouter. + :param prioritize_queue_order: + + :returns: The created WorkspaceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "EventCallbackUrl": event_callback_url, + "EventsFilter": events_filter, + "MultiTaskEnabled": serialize.boolean_to_string(multi_task_enabled), + "Template": template, + "PrioritizeQueueOrder": prioritize_queue_order, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkspaceInstance(self._version, payload) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WorkspaceInstance]: + """ + Streams WorkspaceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(friendly_name=friendly_name, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WorkspaceInstance]: + """ + Asynchronously streams WorkspaceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkspaceInstance]: + """ + Lists WorkspaceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkspaceInstance]: + """ + Asynchronously lists WorkspaceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WorkspacePage: + """ + Retrieve a single page of WorkspaceInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WorkspaceInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkspacePage(self._version, response) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WorkspacePage: + """ + Asynchronously retrieve a single page of WorkspaceInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WorkspaceInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkspacePage(self._version, response) + + def get_page(self, target_url: str) -> WorkspacePage: + """ + Retrieve a specific page of WorkspaceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkspaceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return WorkspacePage(self._version, response) + + async def get_page_async(self, target_url: str) -> WorkspacePage: + """ + Asynchronously retrieve a specific page of WorkspaceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkspaceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return WorkspacePage(self._version, response) + + def get(self, sid: str) -> WorkspaceContext: + """ + Constructs a WorkspaceContext + + :param sid: The SID of the Workspace resource to update. + """ + return WorkspaceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> WorkspaceContext: + """ + Constructs a WorkspaceContext + + :param sid: The SID of the Workspace resource to update. + """ + return WorkspaceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..7bb865e0 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/__pycache__/activity.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/__pycache__/activity.cpython-312.pyc new file mode 100644 index 00000000..df55fde4 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/__pycache__/activity.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/__pycache__/event.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/__pycache__/event.cpython-312.pyc new file mode 100644 index 00000000..9f79ce34 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/__pycache__/event.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/__pycache__/task_channel.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/__pycache__/task_channel.cpython-312.pyc new file mode 100644 index 00000000..b56b9647 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/__pycache__/task_channel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/__pycache__/workspace_cumulative_statistics.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/__pycache__/workspace_cumulative_statistics.cpython-312.pyc new file mode 100644 index 00000000..79eb1c26 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/__pycache__/workspace_cumulative_statistics.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/__pycache__/workspace_real_time_statistics.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/__pycache__/workspace_real_time_statistics.cpython-312.pyc new file mode 100644 index 00000000..1718457f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/__pycache__/workspace_real_time_statistics.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/__pycache__/workspace_statistics.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/__pycache__/workspace_statistics.cpython-312.pyc new file mode 100644 index 00000000..8ea7bac1 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/__pycache__/workspace_statistics.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/activity.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/activity.py new file mode 100644 index 00000000..4e3e416a --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/activity.py @@ -0,0 +1,686 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ActivityInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Activity resource. + :ivar available: Whether the Worker is eligible to receive a Task when it occupies the Activity. A value of `true`, `1`, or `yes` indicates the Activity is available. All other values indicate that it is not. The value cannot be changed after the Activity is created. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar friendly_name: The string that you assigned to describe the Activity resource. + :ivar sid: The unique string that we created to identify the Activity resource. + :ivar workspace_sid: The SID of the Workspace that contains the Activity. + :ivar url: The absolute URL of the Activity resource. + :ivar links: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.available: Optional[bool] = payload.get("available") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.sid: Optional[str] = payload.get("sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid or self.sid, + } + self._context: Optional[ActivityContext] = None + + @property + def _proxy(self) -> "ActivityContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ActivityContext for this ActivityInstance + """ + if self._context is None: + self._context = ActivityContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ActivityInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ActivityInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ActivityInstance": + """ + Fetch the ActivityInstance + + + :returns: The fetched ActivityInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ActivityInstance": + """ + Asynchronous coroutine to fetch the ActivityInstance + + + :returns: The fetched ActivityInstance + """ + return await self._proxy.fetch_async() + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> "ActivityInstance": + """ + Update the ActivityInstance + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + + :returns: The updated ActivityInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "ActivityInstance": + """ + Asynchronous coroutine to update the ActivityInstance + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + + :returns: The updated ActivityInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ActivityContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, sid: str): + """ + Initialize the ActivityContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Activity resources to update. + :param sid: The SID of the Activity resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/Activities/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the ActivityInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ActivityInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ActivityInstance: + """ + Fetch the ActivityInstance + + + :returns: The fetched ActivityInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ActivityInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ActivityInstance: + """ + Asynchronous coroutine to fetch the ActivityInstance + + + :returns: The fetched ActivityInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ActivityInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> ActivityInstance: + """ + Update the ActivityInstance + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + + :returns: The updated ActivityInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ActivityInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ActivityInstance: + """ + Asynchronous coroutine to update the ActivityInstance + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + + :returns: The updated ActivityInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ActivityInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ActivityPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ActivityInstance: + """ + Build an instance of ActivityInstance + + :param payload: Payload response from the API + """ + return ActivityInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ActivityList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the ActivityList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Activity resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Activities".format(**self._solution) + + def create( + self, friendly_name: str, available: Union[bool, object] = values.unset + ) -> ActivityInstance: + """ + Create the ActivityInstance + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + :param available: Whether the Worker should be eligible to receive a Task when it occupies the Activity. A value of `true`, `1`, or `yes` specifies the Activity is available. All other values specify that it is not. The value cannot be changed after the Activity is created. + + :returns: The created ActivityInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Available": serialize.boolean_to_string(available), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ActivityInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_async( + self, friendly_name: str, available: Union[bool, object] = values.unset + ) -> ActivityInstance: + """ + Asynchronously create the ActivityInstance + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + :param available: Whether the Worker should be eligible to receive a Task when it occupies the Activity. A value of `true`, `1`, or `yes` specifies the Activity is available. All other values specify that it is not. The value cannot be changed after the Activity is created. + + :returns: The created ActivityInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Available": serialize.boolean_to_string(available), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ActivityInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ActivityInstance]: + """ + Streams ActivityInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the Activity resources to read. + :param str available: Whether return only Activity resources that are available or unavailable. A value of `true` returns only available activities. Values of '1' or `yes` also indicate `true`. All other values represent `false` and return activities that are unavailable. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + friendly_name=friendly_name, + available=available, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ActivityInstance]: + """ + Asynchronously streams ActivityInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the Activity resources to read. + :param str available: Whether return only Activity resources that are available or unavailable. A value of `true` returns only available activities. Values of '1' or `yes` also indicate `true`. All other values represent `false` and return activities that are unavailable. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, + available=available, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ActivityInstance]: + """ + Lists ActivityInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the Activity resources to read. + :param str available: Whether return only Activity resources that are available or unavailable. A value of `true` returns only available activities. Values of '1' or `yes` also indicate `true`. All other values represent `false` and return activities that are unavailable. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + friendly_name=friendly_name, + available=available, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ActivityInstance]: + """ + Asynchronously lists ActivityInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the Activity resources to read. + :param str available: Whether return only Activity resources that are available or unavailable. A value of `true` returns only available activities. Values of '1' or `yes` also indicate `true`. All other values represent `false` and return activities that are unavailable. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + available=available, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + friendly_name: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ActivityPage: + """ + Retrieve a single page of ActivityInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the Activity resources to read. + :param available: Whether return only Activity resources that are available or unavailable. A value of `true` returns only available activities. Values of '1' or `yes` also indicate `true`. All other values represent `false` and return activities that are unavailable. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ActivityInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "Available": available, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ActivityPage(self._version, response, self._solution) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ActivityPage: + """ + Asynchronously retrieve a single page of ActivityInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the Activity resources to read. + :param available: Whether return only Activity resources that are available or unavailable. A value of `true` returns only available activities. Values of '1' or `yes` also indicate `true`. All other values represent `false` and return activities that are unavailable. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ActivityInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "Available": available, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ActivityPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ActivityPage: + """ + Retrieve a specific page of ActivityInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ActivityInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ActivityPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ActivityPage: + """ + Asynchronously retrieve a specific page of ActivityInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ActivityInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ActivityPage(self._version, response, self._solution) + + def get(self, sid: str) -> ActivityContext: + """ + Constructs a ActivityContext + + :param sid: The SID of the Activity resource to update. + """ + return ActivityContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ActivityContext: + """ + Constructs a ActivityContext + + :param sid: The SID of the Activity resource to update. + """ + return ActivityContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/event.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/event.py new file mode 100644 index 00000000..1b7f289e --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/event.py @@ -0,0 +1,658 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class EventInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Event resource. + :ivar actor_sid: The SID of the resource that triggered the event. + :ivar actor_type: The type of resource that triggered the event. + :ivar actor_url: The absolute URL of the resource that triggered the event. + :ivar description: A description of the event. + :ivar event_data: Data about the event. For more information, see [Event types](https://www.twilio.com/docs/taskrouter/api/event#event-types). + :ivar event_date: The time the event was sent, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar event_date_ms: The time the event was sent in milliseconds. + :ivar event_type: The identifier for the event. + :ivar resource_sid: The SID of the object the event is most relevant to, such as a TaskSid, ReservationSid, or a WorkerSid. + :ivar resource_type: The type of object the event is most relevant to, such as a Task, Reservation, or a Worker). + :ivar resource_url: The URL of the resource the event is most relevant to. + :ivar sid: The unique string that we created to identify the Event resource. + :ivar source: Where the Event originated. + :ivar source_ip_address: The IP from which the Event originated. + :ivar url: The absolute URL of the Event resource. + :ivar workspace_sid: The SID of the Workspace that contains the Event. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.actor_sid: Optional[str] = payload.get("actor_sid") + self.actor_type: Optional[str] = payload.get("actor_type") + self.actor_url: Optional[str] = payload.get("actor_url") + self.description: Optional[str] = payload.get("description") + self.event_data: Optional[Dict[str, object]] = payload.get("event_data") + self.event_date: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("event_date") + ) + self.event_date_ms: Optional[int] = payload.get("event_date_ms") + self.event_type: Optional[str] = payload.get("event_type") + self.resource_sid: Optional[str] = payload.get("resource_sid") + self.resource_type: Optional[str] = payload.get("resource_type") + self.resource_url: Optional[str] = payload.get("resource_url") + self.sid: Optional[str] = payload.get("sid") + self.source: Optional[str] = payload.get("source") + self.source_ip_address: Optional[str] = payload.get("source_ip_address") + self.url: Optional[str] = payload.get("url") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid or self.sid, + } + self._context: Optional[EventContext] = None + + @property + def _proxy(self) -> "EventContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EventContext for this EventInstance + """ + if self._context is None: + self._context = EventContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "EventInstance": + """ + Fetch the EventInstance + + + :returns: The fetched EventInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EventInstance": + """ + Asynchronous coroutine to fetch the EventInstance + + + :returns: The fetched EventInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EventContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, sid: str): + """ + Initialize the EventContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Event to fetch. + :param sid: The SID of the Event resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/Events/{sid}".format(**self._solution) + + def fetch(self) -> EventInstance: + """ + Fetch the EventInstance + + + :returns: The fetched EventInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EventInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> EventInstance: + """ + Asynchronous coroutine to fetch the EventInstance + + + :returns: The fetched EventInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EventInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EventPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EventInstance: + """ + Build an instance of EventInstance + + :param payload: Payload response from the API + """ + return EventInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class EventList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the EventList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Events to read. Returns only the Events that pertain to the specified Workspace. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Events".format(**self._solution) + + def stream( + self, + end_date: Union[datetime, object] = values.unset, + event_type: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + reservation_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EventInstance]: + """ + Streams EventInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str event_type: The type of Events to read. Returns only Events of the type specified. + :param int minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param str reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param datetime start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param str task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param str task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param str worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param str workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param str task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param str sid: The SID of the Event resource to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + end_date=end_date, + event_type=event_type, + minutes=minutes, + reservation_sid=reservation_sid, + start_date=start_date, + task_queue_sid=task_queue_sid, + task_sid=task_sid, + worker_sid=worker_sid, + workflow_sid=workflow_sid, + task_channel=task_channel, + sid=sid, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + end_date: Union[datetime, object] = values.unset, + event_type: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + reservation_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EventInstance]: + """ + Asynchronously streams EventInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str event_type: The type of Events to read. Returns only Events of the type specified. + :param int minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param str reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param datetime start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param str task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param str task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param str worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param str workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param str task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param str sid: The SID of the Event resource to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + end_date=end_date, + event_type=event_type, + minutes=minutes, + reservation_sid=reservation_sid, + start_date=start_date, + task_queue_sid=task_queue_sid, + task_sid=task_sid, + worker_sid=worker_sid, + workflow_sid=workflow_sid, + task_channel=task_channel, + sid=sid, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + end_date: Union[datetime, object] = values.unset, + event_type: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + reservation_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventInstance]: + """ + Lists EventInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str event_type: The type of Events to read. Returns only Events of the type specified. + :param int minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param str reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param datetime start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param str task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param str task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param str worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param str workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param str task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param str sid: The SID of the Event resource to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + end_date=end_date, + event_type=event_type, + minutes=minutes, + reservation_sid=reservation_sid, + start_date=start_date, + task_queue_sid=task_queue_sid, + task_sid=task_sid, + worker_sid=worker_sid, + workflow_sid=workflow_sid, + task_channel=task_channel, + sid=sid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + end_date: Union[datetime, object] = values.unset, + event_type: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + reservation_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventInstance]: + """ + Asynchronously lists EventInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str event_type: The type of Events to read. Returns only Events of the type specified. + :param int minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param str reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param datetime start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param str task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param str task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param str worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param str workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param str task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param str sid: The SID of the Event resource to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + end_date=end_date, + event_type=event_type, + minutes=minutes, + reservation_sid=reservation_sid, + start_date=start_date, + task_queue_sid=task_queue_sid, + task_sid=task_sid, + worker_sid=worker_sid, + workflow_sid=workflow_sid, + task_channel=task_channel, + sid=sid, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + end_date: Union[datetime, object] = values.unset, + event_type: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + reservation_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EventPage: + """ + Retrieve a single page of EventInstance records from the API. + Request is executed immediately + + :param end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param event_type: The type of Events to read. Returns only Events of the type specified. + :param minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param sid: The SID of the Event resource to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EventInstance + """ + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "EventType": event_type, + "Minutes": minutes, + "ReservationSid": reservation_sid, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskQueueSid": task_queue_sid, + "TaskSid": task_sid, + "WorkerSid": worker_sid, + "WorkflowSid": workflow_sid, + "TaskChannel": task_channel, + "Sid": sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response, self._solution) + + async def page_async( + self, + end_date: Union[datetime, object] = values.unset, + event_type: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + reservation_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EventPage: + """ + Asynchronously retrieve a single page of EventInstance records from the API. + Request is executed immediately + + :param end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param event_type: The type of Events to read. Returns only Events of the type specified. + :param minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param sid: The SID of the Event resource to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EventInstance + """ + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "EventType": event_type, + "Minutes": minutes, + "ReservationSid": reservation_sid, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskQueueSid": task_queue_sid, + "TaskSid": task_sid, + "WorkerSid": worker_sid, + "WorkflowSid": workflow_sid, + "TaskChannel": task_channel, + "Sid": sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> EventPage: + """ + Retrieve a specific page of EventInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EventInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EventPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> EventPage: + """ + Asynchronously retrieve a specific page of EventInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EventInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EventPage(self._version, response, self._solution) + + def get(self, sid: str) -> EventContext: + """ + Constructs a EventContext + + :param sid: The SID of the Event resource to fetch. + """ + return EventContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __call__(self, sid: str) -> EventContext: + """ + Constructs a EventContext + + :param sid: The SID of the Event resource to fetch. + """ + return EventContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task/__init__.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task/__init__.py new file mode 100644 index 00000000..2c4516df --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task/__init__.py @@ -0,0 +1,1050 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.taskrouter.v1.workspace.task.reservation import ReservationList + + +class TaskInstance(InstanceResource): + + class Status(object): + PENDING = "pending" + RESERVED = "reserved" + ASSIGNED = "assigned" + CANCELED = "canceled" + COMPLETED = "completed" + WRAPPING = "wrapping" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Task resource. + :ivar age: The number of seconds since the Task was created. + :ivar assignment_status: + :ivar attributes: The JSON string with custom attributes of the work. **Note** If this property has been assigned a value, it will only be displayed in FETCH action that returns a single resource. Otherwise, it will be null. + :ivar addons: An object that contains the [Add-on](https://www.twilio.com/docs/add-ons) data for all installed Add-ons. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar task_queue_entered_date: The date and time in GMT when the Task entered the TaskQueue, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar priority: The current priority score of the Task as assigned to a Worker by the workflow. Tasks with higher priority values will be assigned before Tasks with lower values. + :ivar reason: The reason the Task was canceled or completed, if applicable. + :ivar sid: The unique string that we created to identify the Task resource. + :ivar task_queue_sid: The SID of the TaskQueue. + :ivar task_queue_friendly_name: The friendly name of the TaskQueue. + :ivar task_channel_sid: The SID of the TaskChannel. + :ivar task_channel_unique_name: The unique name of the TaskChannel. + :ivar timeout: The amount of time in seconds that the Task can live before being assigned. + :ivar workflow_sid: The SID of the Workflow that is controlling the Task. + :ivar workflow_friendly_name: The friendly name of the Workflow that is controlling the Task. + :ivar workspace_sid: The SID of the Workspace that contains the Task. + :ivar url: The absolute URL of the Task resource. + :ivar links: The URLs of related resources. + :ivar virtual_start_time: The date and time in GMT indicating the ordering for routing of the Task specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar ignore_capacity: A boolean that indicates if the Task should respect a Worker's capacity and availability during assignment. This field can only be used when the `RoutingTarget` field is set to a Worker SID. By setting `IgnoreCapacity` to a value of `true`, `1`, or `yes`, the Task will be routed to the Worker without respecting their capacity and availability. Any other value will enforce the Worker's capacity and availability. The default value of `IgnoreCapacity` is `true` when the `RoutingTarget` is set to a Worker SID. + :ivar routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.age: Optional[int] = deserialize.integer(payload.get("age")) + self.assignment_status: Optional["TaskInstance.Status"] = payload.get( + "assignment_status" + ) + self.attributes: Optional[str] = payload.get("attributes") + self.addons: Optional[str] = payload.get("addons") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.task_queue_entered_date: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("task_queue_entered_date") + ) + self.priority: Optional[int] = deserialize.integer(payload.get("priority")) + self.reason: Optional[str] = payload.get("reason") + self.sid: Optional[str] = payload.get("sid") + self.task_queue_sid: Optional[str] = payload.get("task_queue_sid") + self.task_queue_friendly_name: Optional[str] = payload.get( + "task_queue_friendly_name" + ) + self.task_channel_sid: Optional[str] = payload.get("task_channel_sid") + self.task_channel_unique_name: Optional[str] = payload.get( + "task_channel_unique_name" + ) + self.timeout: Optional[int] = deserialize.integer(payload.get("timeout")) + self.workflow_sid: Optional[str] = payload.get("workflow_sid") + self.workflow_friendly_name: Optional[str] = payload.get( + "workflow_friendly_name" + ) + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.virtual_start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("virtual_start_time") + ) + self.ignore_capacity: Optional[bool] = payload.get("ignore_capacity") + self.routing_target: Optional[str] = payload.get("routing_target") + + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid or self.sid, + } + self._context: Optional[TaskContext] = None + + @property + def _proxy(self) -> "TaskContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TaskContext for this TaskInstance + """ + if self._context is None: + self._context = TaskContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Deletes the TaskInstance + + :param if_match: If provided, deletes this Task if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + if_match=if_match, + ) + + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Asynchronous coroutine that deletes the TaskInstance + + :param if_match: If provided, deletes this Task if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + if_match=if_match, + ) + + def fetch(self) -> "TaskInstance": + """ + Fetch the TaskInstance + + + :returns: The fetched TaskInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TaskInstance": + """ + Asynchronous coroutine to fetch the TaskInstance + + + :returns: The fetched TaskInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + if_match: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + assignment_status: Union["TaskInstance.Status", object] = values.unset, + reason: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + ) -> "TaskInstance": + """ + Update the TaskInstance + + :param if_match: If provided, applies this mutation if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param attributes: The JSON string that describes the custom attributes of the task. + :param assignment_status: + :param reason: The reason that the Task was canceled or completed. This parameter is required only if the Task is canceled or completed. Setting this value queues the task for deletion and logs the reason. + :param priority: The Task's new priority value. When supplied, the Task takes on the specified priority unless it matches a Workflow Target with a Priority set. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel with the task to update. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param virtual_start_time: The task's new virtual start time value. When supplied, the Task takes on the specified virtual start time. Value can't be in the future or before the year of 1900. + + :returns: The updated TaskInstance + """ + return self._proxy.update( + if_match=if_match, + attributes=attributes, + assignment_status=assignment_status, + reason=reason, + priority=priority, + task_channel=task_channel, + virtual_start_time=virtual_start_time, + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + assignment_status: Union["TaskInstance.Status", object] = values.unset, + reason: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + ) -> "TaskInstance": + """ + Asynchronous coroutine to update the TaskInstance + + :param if_match: If provided, applies this mutation if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param attributes: The JSON string that describes the custom attributes of the task. + :param assignment_status: + :param reason: The reason that the Task was canceled or completed. This parameter is required only if the Task is canceled or completed. Setting this value queues the task for deletion and logs the reason. + :param priority: The Task's new priority value. When supplied, the Task takes on the specified priority unless it matches a Workflow Target with a Priority set. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel with the task to update. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param virtual_start_time: The task's new virtual start time value. When supplied, the Task takes on the specified virtual start time. Value can't be in the future or before the year of 1900. + + :returns: The updated TaskInstance + """ + return await self._proxy.update_async( + if_match=if_match, + attributes=attributes, + assignment_status=assignment_status, + reason=reason, + priority=priority, + task_channel=task_channel, + virtual_start_time=virtual_start_time, + ) + + @property + def reservations(self) -> ReservationList: + """ + Access the reservations + """ + return self._proxy.reservations + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TaskContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, sid: str): + """ + Initialize the TaskContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Task to update. + :param sid: The SID of the Task resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/Tasks/{sid}".format(**self._solution) + + self._reservations: Optional[ReservationList] = None + + def delete(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Deletes the TaskInstance + + :param if_match: If provided, deletes this Task if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "If-Match": if_match, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Asynchronous coroutine that deletes the TaskInstance + + :param if_match: If provided, deletes this Task if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "If-Match": if_match, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TaskInstance: + """ + Fetch the TaskInstance + + + :returns: The fetched TaskInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TaskInstance: + """ + Asynchronous coroutine to fetch the TaskInstance + + + :returns: The fetched TaskInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + if_match: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + assignment_status: Union["TaskInstance.Status", object] = values.unset, + reason: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + ) -> TaskInstance: + """ + Update the TaskInstance + + :param if_match: If provided, applies this mutation if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param attributes: The JSON string that describes the custom attributes of the task. + :param assignment_status: + :param reason: The reason that the Task was canceled or completed. This parameter is required only if the Task is canceled or completed. Setting this value queues the task for deletion and logs the reason. + :param priority: The Task's new priority value. When supplied, the Task takes on the specified priority unless it matches a Workflow Target with a Priority set. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel with the task to update. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param virtual_start_time: The task's new virtual start time value. When supplied, the Task takes on the specified virtual start time. Value can't be in the future or before the year of 1900. + + :returns: The updated TaskInstance + """ + + data = values.of( + { + "Attributes": attributes, + "AssignmentStatus": assignment_status, + "Reason": reason, + "Priority": priority, + "TaskChannel": task_channel, + "VirtualStartTime": serialize.iso8601_datetime(virtual_start_time), + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + assignment_status: Union["TaskInstance.Status", object] = values.unset, + reason: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + ) -> TaskInstance: + """ + Asynchronous coroutine to update the TaskInstance + + :param if_match: If provided, applies this mutation if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param attributes: The JSON string that describes the custom attributes of the task. + :param assignment_status: + :param reason: The reason that the Task was canceled or completed. This parameter is required only if the Task is canceled or completed. Setting this value queues the task for deletion and logs the reason. + :param priority: The Task's new priority value. When supplied, the Task takes on the specified priority unless it matches a Workflow Target with a Priority set. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel with the task to update. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param virtual_start_time: The task's new virtual start time value. When supplied, the Task takes on the specified virtual start time. Value can't be in the future or before the year of 1900. + + :returns: The updated TaskInstance + """ + + data = values.of( + { + "Attributes": attributes, + "AssignmentStatus": assignment_status, + "Reason": reason, + "Priority": priority, + "TaskChannel": task_channel, + "VirtualStartTime": serialize.iso8601_datetime(virtual_start_time), + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + @property + def reservations(self) -> ReservationList: + """ + Access the reservations + """ + if self._reservations is None: + self._reservations = ReservationList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._reservations + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TaskPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TaskInstance: + """ + Build an instance of TaskInstance + + :param payload: Payload response from the API + """ + return TaskInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TaskList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the TaskList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Tasks to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Tasks".format(**self._solution) + + def create( + self, + timeout: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ignore_capacity: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ) -> TaskInstance: + """ + Create the TaskInstance + + :param timeout: The amount of time in seconds the new task can live before being assigned. Can be up to a maximum of 2 weeks (1,209,600 seconds). The default value is 24 hours (86,400 seconds). On timeout, the `task.canceled` event will fire with description `Task TTL Exceeded`. + :param priority: The priority to assign the new task and override the default. When supplied, the new Task will have this priority unless it matches a Workflow Target with a Priority set. When not supplied, the new Task will have the priority of the matching Workflow Target. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel by passing either its `unique_name` or `sid`. Default value is `default`. + :param workflow_sid: The SID of the Workflow that you would like to handle routing for the new Task. If there is only one Workflow defined for the Workspace that you are posting the new task to, this parameter is optional. + :param attributes: A URL-encoded JSON string with the attributes of the new task. This value is passed to the Workflow's `assignment_callback_url` when the Task is assigned to a Worker. For example: `{ \\\"task_type\\\": \\\"call\\\", \\\"twilio_call_sid\\\": \\\"CAxxx\\\", \\\"customer_ticket_number\\\": \\\"12345\\\" }`. + :param virtual_start_time: The virtual start time to assign the new task and override the default. When supplied, the new task will have this virtual start time. When not supplied, the new task will have the virtual start time equal to `date_created`. Value can't be in the future or before the year of 1900. + :param routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param ignore_capacity: A boolean that indicates if the Task should respect a Worker's capacity and availability during assignment. This field can only be used when the `RoutingTarget` field is set to a Worker SID. By setting `IgnoreCapacity` to a value of `true`, `1`, or `yes`, the Task will be routed to the Worker without respecting their capacity and availability. Any other value will enforce the Worker's capacity and availability. The default value of `IgnoreCapacity` is `true` when the `RoutingTarget` is set to a Worker SID. + :param task_queue_sid: The SID of the TaskQueue in which the Task belongs + + :returns: The created TaskInstance + """ + + data = values.of( + { + "Timeout": timeout, + "Priority": priority, + "TaskChannel": task_channel, + "WorkflowSid": workflow_sid, + "Attributes": attributes, + "VirtualStartTime": serialize.iso8601_datetime(virtual_start_time), + "RoutingTarget": routing_target, + "IgnoreCapacity": ignore_capacity, + "TaskQueueSid": task_queue_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_async( + self, + timeout: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ignore_capacity: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ) -> TaskInstance: + """ + Asynchronously create the TaskInstance + + :param timeout: The amount of time in seconds the new task can live before being assigned. Can be up to a maximum of 2 weeks (1,209,600 seconds). The default value is 24 hours (86,400 seconds). On timeout, the `task.canceled` event will fire with description `Task TTL Exceeded`. + :param priority: The priority to assign the new task and override the default. When supplied, the new Task will have this priority unless it matches a Workflow Target with a Priority set. When not supplied, the new Task will have the priority of the matching Workflow Target. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel by passing either its `unique_name` or `sid`. Default value is `default`. + :param workflow_sid: The SID of the Workflow that you would like to handle routing for the new Task. If there is only one Workflow defined for the Workspace that you are posting the new task to, this parameter is optional. + :param attributes: A URL-encoded JSON string with the attributes of the new task. This value is passed to the Workflow's `assignment_callback_url` when the Task is assigned to a Worker. For example: `{ \\\"task_type\\\": \\\"call\\\", \\\"twilio_call_sid\\\": \\\"CAxxx\\\", \\\"customer_ticket_number\\\": \\\"12345\\\" }`. + :param virtual_start_time: The virtual start time to assign the new task and override the default. When supplied, the new task will have this virtual start time. When not supplied, the new task will have the virtual start time equal to `date_created`. Value can't be in the future or before the year of 1900. + :param routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param ignore_capacity: A boolean that indicates if the Task should respect a Worker's capacity and availability during assignment. This field can only be used when the `RoutingTarget` field is set to a Worker SID. By setting `IgnoreCapacity` to a value of `true`, `1`, or `yes`, the Task will be routed to the Worker without respecting their capacity and availability. Any other value will enforce the Worker's capacity and availability. The default value of `IgnoreCapacity` is `true` when the `RoutingTarget` is set to a Worker SID. + :param task_queue_sid: The SID of the TaskQueue in which the Task belongs + + :returns: The created TaskInstance + """ + + data = values.of( + { + "Timeout": timeout, + "Priority": priority, + "TaskChannel": task_channel, + "WorkflowSid": workflow_sid, + "Attributes": attributes, + "VirtualStartTime": serialize.iso8601_datetime(virtual_start_time), + "RoutingTarget": routing_target, + "IgnoreCapacity": ignore_capacity, + "TaskQueueSid": task_queue_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def stream( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TaskInstance]: + """ + Streams TaskInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param List[str] assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param str workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param str workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param str task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param str task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param str evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param str routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param str ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param bool has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + priority=priority, + assignment_status=assignment_status, + workflow_sid=workflow_sid, + workflow_name=workflow_name, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + evaluate_task_attributes=evaluate_task_attributes, + routing_target=routing_target, + ordering=ordering, + has_addons=has_addons, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TaskInstance]: + """ + Asynchronously streams TaskInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param List[str] assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param str workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param str workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param str task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param str task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param str evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param str routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param str ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param bool has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + priority=priority, + assignment_status=assignment_status, + workflow_sid=workflow_sid, + workflow_name=workflow_name, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + evaluate_task_attributes=evaluate_task_attributes, + routing_target=routing_target, + ordering=ordering, + has_addons=has_addons, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TaskInstance]: + """ + Lists TaskInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param List[str] assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param str workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param str workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param str task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param str task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param str evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param str routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param str ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param bool has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + priority=priority, + assignment_status=assignment_status, + workflow_sid=workflow_sid, + workflow_name=workflow_name, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + evaluate_task_attributes=evaluate_task_attributes, + routing_target=routing_target, + ordering=ordering, + has_addons=has_addons, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TaskInstance]: + """ + Asynchronously lists TaskInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param List[str] assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param str workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param str workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param str task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param str task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param str evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param str routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param str ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param bool has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + priority=priority, + assignment_status=assignment_status, + workflow_sid=workflow_sid, + workflow_name=workflow_name, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + evaluate_task_attributes=evaluate_task_attributes, + routing_target=routing_target, + ordering=ordering, + has_addons=has_addons, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TaskPage: + """ + Retrieve a single page of TaskInstance records from the API. + Request is executed immediately + + :param priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TaskInstance + """ + data = values.of( + { + "Priority": priority, + "AssignmentStatus": serialize.map(assignment_status, lambda e: e), + "WorkflowSid": workflow_sid, + "WorkflowName": workflow_name, + "TaskQueueSid": task_queue_sid, + "TaskQueueName": task_queue_name, + "EvaluateTaskAttributes": evaluate_task_attributes, + "RoutingTarget": routing_target, + "Ordering": ordering, + "HasAddons": serialize.boolean_to_string(has_addons), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskPage(self._version, response, self._solution) + + async def page_async( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TaskPage: + """ + Asynchronously retrieve a single page of TaskInstance records from the API. + Request is executed immediately + + :param priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TaskInstance + """ + data = values.of( + { + "Priority": priority, + "AssignmentStatus": serialize.map(assignment_status, lambda e: e), + "WorkflowSid": workflow_sid, + "WorkflowName": workflow_name, + "TaskQueueSid": task_queue_sid, + "TaskQueueName": task_queue_name, + "EvaluateTaskAttributes": evaluate_task_attributes, + "RoutingTarget": routing_target, + "Ordering": ordering, + "HasAddons": serialize.boolean_to_string(has_addons), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> TaskPage: + """ + Retrieve a specific page of TaskInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TaskInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TaskPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> TaskPage: + """ + Asynchronously retrieve a specific page of TaskInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TaskInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TaskPage(self._version, response, self._solution) + + def get(self, sid: str) -> TaskContext: + """ + Constructs a TaskContext + + :param sid: The SID of the Task resource to update. + """ + return TaskContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __call__(self, sid: str) -> TaskContext: + """ + Constructs a TaskContext + + :param sid: The SID of the Task resource to update. + """ + return TaskContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..8d8c21dd Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task/__pycache__/reservation.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task/__pycache__/reservation.cpython-312.pyc new file mode 100644 index 00000000..e5cbc20b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task/__pycache__/reservation.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task/reservation.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task/reservation.py new file mode 100644 index 00000000..28cb0333 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task/reservation.py @@ -0,0 +1,1351 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ReservationInstance(InstanceResource): + + class CallStatus(object): + INITIATED = "initiated" + RINGING = "ringing" + ANSWERED = "answered" + COMPLETED = "completed" + + class ConferenceEvent(object): + START = "start" + END = "end" + JOIN = "join" + LEAVE = "leave" + MUTE = "mute" + HOLD = "hold" + SPEAKER = "speaker" + + class Status(object): + PENDING = "pending" + ACCEPTED = "accepted" + REJECTED = "rejected" + TIMEOUT = "timeout" + CANCELED = "canceled" + RESCINDED = "rescinded" + WRAPPING = "wrapping" + COMPLETED = "completed" + + class SupervisorMode(object): + MONITOR = "monitor" + WHISPER = "whisper" + BARGE = "barge" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskReservation resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar reservation_status: + :ivar sid: The unique string that we created to identify the TaskReservation resource. + :ivar task_sid: The SID of the reserved Task resource. + :ivar worker_name: The `friendly_name` of the Worker that is reserved. + :ivar worker_sid: The SID of the reserved Worker resource. + :ivar workspace_sid: The SID of the Workspace that this task is contained within. + :ivar url: The absolute URL of the TaskReservation reservation. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + task_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.reservation_status: Optional["ReservationInstance.Status"] = payload.get( + "reservation_status" + ) + self.sid: Optional[str] = payload.get("sid") + self.task_sid: Optional[str] = payload.get("task_sid") + self.worker_name: Optional[str] = payload.get("worker_name") + self.worker_sid: Optional[str] = payload.get("worker_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "workspace_sid": workspace_sid, + "task_sid": task_sid, + "sid": sid or self.sid, + } + self._context: Optional[ReservationContext] = None + + @property + def _proxy(self) -> "ReservationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ReservationContext for this ReservationInstance + """ + if self._context is None: + self._context = ReservationContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "ReservationInstance": + """ + Fetch the ReservationInstance + + + :returns: The fetched ReservationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ReservationInstance": + """ + Asynchronous coroutine to fetch the ReservationInstance + + + :returns: The fetched ReservationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + supervisor_mode: Union[ + "ReservationInstance.SupervisorMode", object + ] = values.unset, + supervisor: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> "ReservationInstance": + """ + Update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The Caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: Timeout for call when executing a Dequeue instruction. + :param dequeue_to: The Contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The Callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction or which leg to record. + :param call_timeout: Timeout for call when executing a Call instruction. + :param call_to: The Contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The Caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: Timeout for call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. The default is `false`. + :param muted: Whether the agent is muted in the conference. The default is `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. The default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: How to trim the leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param supervisor_mode: + :param supervisor: The Supervisor SID/URI when executing the Supervise instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + return self._proxy.update( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + supervisor_mode=supervisor_mode, + supervisor=supervisor, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + supervisor_mode: Union[ + "ReservationInstance.SupervisorMode", object + ] = values.unset, + supervisor: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> "ReservationInstance": + """ + Asynchronous coroutine to update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The Caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: Timeout for call when executing a Dequeue instruction. + :param dequeue_to: The Contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The Callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction or which leg to record. + :param call_timeout: Timeout for call when executing a Call instruction. + :param call_to: The Contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The Caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: Timeout for call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. The default is `false`. + :param muted: Whether the agent is muted in the conference. The default is `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. The default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: How to trim the leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param supervisor_mode: + :param supervisor: The Supervisor SID/URI when executing the Supervise instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + return await self._proxy.update_async( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + supervisor_mode=supervisor_mode, + supervisor=supervisor, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ReservationContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, task_sid: str, sid: str): + """ + Initialize the ReservationContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskReservation resources to update. + :param task_sid: The SID of the reserved Task resource with the TaskReservation resources to update. + :param sid: The SID of the TaskReservation resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_sid": task_sid, + "sid": sid, + } + self._uri = ( + "/Workspaces/{workspace_sid}/Tasks/{task_sid}/Reservations/{sid}".format( + **self._solution + ) + ) + + def fetch(self) -> ReservationInstance: + """ + Fetch the ReservationInstance + + + :returns: The fetched ReservationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ReservationInstance: + """ + Asynchronous coroutine to fetch the ReservationInstance + + + :returns: The fetched ReservationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + supervisor_mode: Union[ + "ReservationInstance.SupervisorMode", object + ] = values.unset, + supervisor: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ReservationInstance: + """ + Update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The Caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: Timeout for call when executing a Dequeue instruction. + :param dequeue_to: The Contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The Callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction or which leg to record. + :param call_timeout: Timeout for call when executing a Call instruction. + :param call_to: The Contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The Caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: Timeout for call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. The default is `false`. + :param muted: Whether the agent is muted in the conference. The default is `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. The default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: How to trim the leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param supervisor_mode: + :param supervisor: The Supervisor SID/URI when executing the Supervise instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerActivitySid": worker_activity_sid, + "Instruction": instruction, + "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, + "DequeueFrom": dequeue_from, + "DequeueRecord": dequeue_record, + "DequeueTimeout": dequeue_timeout, + "DequeueTo": dequeue_to, + "DequeueStatusCallbackUrl": dequeue_status_callback_url, + "CallFrom": call_from, + "CallRecord": call_record, + "CallTimeout": call_timeout, + "CallTo": call_to, + "CallUrl": call_url, + "CallStatusCallbackUrl": call_status_callback_url, + "CallAccept": serialize.boolean_to_string(call_accept), + "RedirectCallSid": redirect_call_sid, + "RedirectAccept": serialize.boolean_to_string(redirect_accept), + "RedirectUrl": redirect_url, + "To": to, + "From": from_, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "Muted": serialize.boolean_to_string(muted), + "Beep": beep, + "StartConferenceOnEnter": serialize.boolean_to_string( + start_conference_on_enter + ), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "EarlyMedia": serialize.boolean_to_string(early_media), + "MaxParticipants": max_participants, + "ConferenceStatusCallback": conference_status_callback, + "ConferenceStatusCallbackMethod": conference_status_callback_method, + "ConferenceStatusCallbackEvent": serialize.map( + conference_status_callback_event, lambda e: e + ), + "ConferenceRecord": conference_record, + "ConferenceTrim": conference_trim, + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "ConferenceRecordingStatusCallback": conference_recording_status_callback, + "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, + "Region": region, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "DequeueStatusCallbackEvent": serialize.map( + dequeue_status_callback_event, lambda e: e + ), + "PostWorkActivitySid": post_work_activity_sid, + "SupervisorMode": supervisor_mode, + "Supervisor": supervisor, + "EndConferenceOnCustomerExit": serialize.boolean_to_string( + end_conference_on_customer_exit + ), + "BeepOnCustomerEntrance": serialize.boolean_to_string( + beep_on_customer_entrance + ), + "JitterBufferSize": jitter_buffer_size, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + supervisor_mode: Union[ + "ReservationInstance.SupervisorMode", object + ] = values.unset, + supervisor: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ReservationInstance: + """ + Asynchronous coroutine to update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The Caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: Timeout for call when executing a Dequeue instruction. + :param dequeue_to: The Contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The Callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction or which leg to record. + :param call_timeout: Timeout for call when executing a Call instruction. + :param call_to: The Contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The Caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: Timeout for call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. The default is `false`. + :param muted: Whether the agent is muted in the conference. The default is `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. The default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: How to trim the leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param supervisor_mode: + :param supervisor: The Supervisor SID/URI when executing the Supervise instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerActivitySid": worker_activity_sid, + "Instruction": instruction, + "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, + "DequeueFrom": dequeue_from, + "DequeueRecord": dequeue_record, + "DequeueTimeout": dequeue_timeout, + "DequeueTo": dequeue_to, + "DequeueStatusCallbackUrl": dequeue_status_callback_url, + "CallFrom": call_from, + "CallRecord": call_record, + "CallTimeout": call_timeout, + "CallTo": call_to, + "CallUrl": call_url, + "CallStatusCallbackUrl": call_status_callback_url, + "CallAccept": serialize.boolean_to_string(call_accept), + "RedirectCallSid": redirect_call_sid, + "RedirectAccept": serialize.boolean_to_string(redirect_accept), + "RedirectUrl": redirect_url, + "To": to, + "From": from_, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "Muted": serialize.boolean_to_string(muted), + "Beep": beep, + "StartConferenceOnEnter": serialize.boolean_to_string( + start_conference_on_enter + ), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "EarlyMedia": serialize.boolean_to_string(early_media), + "MaxParticipants": max_participants, + "ConferenceStatusCallback": conference_status_callback, + "ConferenceStatusCallbackMethod": conference_status_callback_method, + "ConferenceStatusCallbackEvent": serialize.map( + conference_status_callback_event, lambda e: e + ), + "ConferenceRecord": conference_record, + "ConferenceTrim": conference_trim, + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "ConferenceRecordingStatusCallback": conference_recording_status_callback, + "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, + "Region": region, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "DequeueStatusCallbackEvent": serialize.map( + dequeue_status_callback_event, lambda e: e + ), + "PostWorkActivitySid": post_work_activity_sid, + "SupervisorMode": supervisor_mode, + "Supervisor": supervisor, + "EndConferenceOnCustomerExit": serialize.boolean_to_string( + end_conference_on_customer_exit + ), + "BeepOnCustomerEntrance": serialize.boolean_to_string( + beep_on_customer_entrance + ), + "JitterBufferSize": jitter_buffer_size, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ReservationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ReservationInstance: + """ + Build an instance of ReservationInstance + + :param payload: Payload response from the API + """ + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ReservationList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, task_sid: str): + """ + Initialize the ReservationList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskReservation resources to read. + :param task_sid: The SID of the reserved Task resource with the TaskReservation resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_sid": task_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Tasks/{task_sid}/Reservations".format( + **self._solution + ) + + def stream( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ReservationInstance]: + """ + Streams ReservationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param str worker_sid: The SID of the reserved Worker resource to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + reservation_status=reservation_status, + worker_sid=worker_sid, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ReservationInstance]: + """ + Asynchronously streams ReservationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param str worker_sid: The SID of the reserved Worker resource to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + reservation_status=reservation_status, + worker_sid=worker_sid, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ReservationInstance]: + """ + Lists ReservationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param str worker_sid: The SID of the reserved Worker resource to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + reservation_status=reservation_status, + worker_sid=worker_sid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ReservationInstance]: + """ + Asynchronously lists ReservationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param str worker_sid: The SID of the reserved Worker resource to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + reservation_status=reservation_status, + worker_sid=worker_sid, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ReservationPage: + """ + Retrieve a single page of ReservationInstance records from the API. + Request is executed immediately + + :param reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param worker_sid: The SID of the reserved Worker resource to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ReservationInstance + """ + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerSid": worker_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ReservationPage(self._version, response, self._solution) + + async def page_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ReservationPage: + """ + Asynchronously retrieve a single page of ReservationInstance records from the API. + Request is executed immediately + + :param reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param worker_sid: The SID of the reserved Worker resource to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ReservationInstance + """ + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerSid": worker_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ReservationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ReservationPage: + """ + Retrieve a specific page of ReservationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ReservationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ReservationPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ReservationPage: + """ + Asynchronously retrieve a specific page of ReservationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ReservationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ReservationPage(self._version, response, self._solution) + + def get(self, sid: str) -> ReservationContext: + """ + Constructs a ReservationContext + + :param sid: The SID of the TaskReservation resource to update. + """ + return ReservationContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> ReservationContext: + """ + Constructs a ReservationContext + + :param sid: The SID of the TaskReservation resource to update. + """ + return ReservationContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_channel.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_channel.py new file mode 100644 index 00000000..3a4b0a6b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_channel.py @@ -0,0 +1,684 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TaskChannelInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Task Channel resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar sid: The unique string that we created to identify the Task Channel resource. + :ivar unique_name: An application-defined string that uniquely identifies the Task Channel, such as `voice` or `sms`. + :ivar workspace_sid: The SID of the Workspace that contains the Task Channel. + :ivar channel_optimized_routing: Whether the Task Channel will prioritize Workers that have been idle. When `true`, Workers that have been idle the longest are prioritized. + :ivar url: The absolute URL of the Task Channel resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.channel_optimized_routing: Optional[bool] = payload.get( + "channel_optimized_routing" + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid or self.sid, + } + self._context: Optional[TaskChannelContext] = None + + @property + def _proxy(self) -> "TaskChannelContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TaskChannelContext for this TaskChannelInstance + """ + if self._context is None: + self._context = TaskChannelContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TaskChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TaskChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "TaskChannelInstance": + """ + Fetch the TaskChannelInstance + + + :returns: The fetched TaskChannelInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TaskChannelInstance": + """ + Asynchronous coroutine to fetch the TaskChannelInstance + + + :returns: The fetched TaskChannelInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> "TaskChannelInstance": + """ + Update the TaskChannelInstance + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: The updated TaskChannelInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + channel_optimized_routing=channel_optimized_routing, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> "TaskChannelInstance": + """ + Asynchronous coroutine to update the TaskChannelInstance + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: The updated TaskChannelInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + channel_optimized_routing=channel_optimized_routing, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TaskChannelContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, sid: str): + """ + Initialize the TaskChannelContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Task Channel to update. + :param sid: The SID of the Task Channel resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/TaskChannels/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the TaskChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TaskChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TaskChannelInstance: + """ + Fetch the TaskChannelInstance + + + :returns: The fetched TaskChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TaskChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TaskChannelInstance: + """ + Asynchronous coroutine to fetch the TaskChannelInstance + + + :returns: The fetched TaskChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TaskChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> TaskChannelInstance: + """ + Update the TaskChannelInstance + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: The updated TaskChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ChannelOptimizedRouting": serialize.boolean_to_string( + channel_optimized_routing + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> TaskChannelInstance: + """ + Asynchronous coroutine to update the TaskChannelInstance + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: The updated TaskChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ChannelOptimizedRouting": serialize.boolean_to_string( + channel_optimized_routing + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TaskChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TaskChannelInstance: + """ + Build an instance of TaskChannelInstance + + :param payload: Payload response from the API + """ + return TaskChannelInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TaskChannelList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the TaskChannelList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Task Channel to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/TaskChannels".format(**self._solution) + + def create( + self, + friendly_name: str, + unique_name: str, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> TaskChannelInstance: + """ + Create the TaskChannelInstance + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the Task Channel, such as `voice` or `sms`. + :param channel_optimized_routing: Whether the Task Channel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: The created TaskChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "ChannelOptimizedRouting": serialize.boolean_to_string( + channel_optimized_routing + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskChannelInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_async( + self, + friendly_name: str, + unique_name: str, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> TaskChannelInstance: + """ + Asynchronously create the TaskChannelInstance + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the Task Channel, such as `voice` or `sms`. + :param channel_optimized_routing: Whether the Task Channel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: The created TaskChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "ChannelOptimizedRouting": serialize.boolean_to_string( + channel_optimized_routing + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskChannelInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TaskChannelInstance]: + """ + Streams TaskChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TaskChannelInstance]: + """ + Asynchronously streams TaskChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TaskChannelInstance]: + """ + Lists TaskChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TaskChannelInstance]: + """ + Asynchronously lists TaskChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TaskChannelPage: + """ + Retrieve a single page of TaskChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TaskChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskChannelPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TaskChannelPage: + """ + Asynchronously retrieve a single page of TaskChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TaskChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskChannelPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> TaskChannelPage: + """ + Retrieve a specific page of TaskChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TaskChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TaskChannelPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> TaskChannelPage: + """ + Asynchronously retrieve a specific page of TaskChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TaskChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TaskChannelPage(self._version, response, self._solution) + + def get(self, sid: str) -> TaskChannelContext: + """ + Constructs a TaskChannelContext + + :param sid: The SID of the Task Channel resource to update. + """ + return TaskChannelContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __call__(self, sid: str) -> TaskChannelContext: + """ + Constructs a TaskChannelContext + + :param sid: The SID of the Task Channel resource to update. + """ + return TaskChannelContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py new file mode 100644 index 00000000..4511a553 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py @@ -0,0 +1,949 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_bulk_real_time_statistics import ( + TaskQueueBulkRealTimeStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics import ( + TaskQueueCumulativeStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics import ( + TaskQueueRealTimeStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics import ( + TaskQueueStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.task_queue.task_queues_statistics import ( + TaskQueuesStatisticsList, +) + + +class TaskQueueInstance(InstanceResource): + + class TaskOrder(object): + FIFO = "FIFO" + LIFO = "LIFO" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. + :ivar assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned for them. + :ivar assignment_activity_name: The name of the Activity to assign Workers when a task is assigned for them. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar max_reserved_workers: The maximum number of Workers to reserve for the assignment of a task in the queue. Can be an integer between 1 and 50, inclusive and defaults to 1. + :ivar reservation_activity_sid: The SID of the Activity to assign Workers once a task is reserved for them. + :ivar reservation_activity_name: The name of the Activity to assign Workers once a task is reserved for them. + :ivar sid: The unique string that we created to identify the TaskQueue resource. + :ivar target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example `'\"language\" == \"spanish\"'` If no TargetWorkers parameter is provided, Tasks will wait in the TaskQueue until they are either deleted or moved to another TaskQueue. Additional examples on how to describing Worker selection criteria below. Defaults to 1==1. + :ivar task_order: + :ivar url: The absolute URL of the TaskQueue resource. + :ivar workspace_sid: The SID of the Workspace that contains the TaskQueue. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.assignment_activity_sid: Optional[str] = payload.get( + "assignment_activity_sid" + ) + self.assignment_activity_name: Optional[str] = payload.get( + "assignment_activity_name" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.max_reserved_workers: Optional[int] = deserialize.integer( + payload.get("max_reserved_workers") + ) + self.reservation_activity_sid: Optional[str] = payload.get( + "reservation_activity_sid" + ) + self.reservation_activity_name: Optional[str] = payload.get( + "reservation_activity_name" + ) + self.sid: Optional[str] = payload.get("sid") + self.target_workers: Optional[str] = payload.get("target_workers") + self.task_order: Optional["TaskQueueInstance.TaskOrder"] = payload.get( + "task_order" + ) + self.url: Optional[str] = payload.get("url") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid or self.sid, + } + self._context: Optional[TaskQueueContext] = None + + @property + def _proxy(self) -> "TaskQueueContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TaskQueueContext for this TaskQueueInstance + """ + if self._context is None: + self._context = TaskQueueContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TaskQueueInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TaskQueueInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "TaskQueueInstance": + """ + Fetch the TaskQueueInstance + + + :returns: The fetched TaskQueueInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TaskQueueInstance": + """ + Asynchronous coroutine to fetch the TaskQueueInstance + + + :returns: The fetched TaskQueueInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + target_workers: Union[str, object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + ) -> "TaskQueueInstance": + """ + Update the TaskQueueInstance + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example '\\\"language\\\" == \\\"spanish\\\"' If no TargetWorkers parameter is provided, Tasks will wait in the queue until they are either deleted or moved to another queue. Additional examples on how to describing Worker selection criteria below. + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned for them. + :param max_reserved_workers: The maximum number of Workers to create reservations for the assignment of a task while in the queue. Maximum of 50. + :param task_order: + + :returns: The updated TaskQueueInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + target_workers=target_workers, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + target_workers: Union[str, object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + ) -> "TaskQueueInstance": + """ + Asynchronous coroutine to update the TaskQueueInstance + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example '\\\"language\\\" == \\\"spanish\\\"' If no TargetWorkers parameter is provided, Tasks will wait in the queue until they are either deleted or moved to another queue. Additional examples on how to describing Worker selection criteria below. + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned for them. + :param max_reserved_workers: The maximum number of Workers to create reservations for the assignment of a task while in the queue. Maximum of 50. + :param task_order: + + :returns: The updated TaskQueueInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + target_workers=target_workers, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + ) + + @property + def cumulative_statistics(self) -> TaskQueueCumulativeStatisticsList: + """ + Access the cumulative_statistics + """ + return self._proxy.cumulative_statistics + + @property + def real_time_statistics(self) -> TaskQueueRealTimeStatisticsList: + """ + Access the real_time_statistics + """ + return self._proxy.real_time_statistics + + @property + def statistics(self) -> TaskQueueStatisticsList: + """ + Access the statistics + """ + return self._proxy.statistics + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TaskQueueContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, sid: str): + """ + Initialize the TaskQueueContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskQueue to update. + :param sid: The SID of the TaskQueue resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/TaskQueues/{sid}".format( + **self._solution + ) + + self._cumulative_statistics: Optional[TaskQueueCumulativeStatisticsList] = None + self._real_time_statistics: Optional[TaskQueueRealTimeStatisticsList] = None + self._statistics: Optional[TaskQueueStatisticsList] = None + + def delete(self) -> bool: + """ + Deletes the TaskQueueInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TaskQueueInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TaskQueueInstance: + """ + Fetch the TaskQueueInstance + + + :returns: The fetched TaskQueueInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TaskQueueInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TaskQueueInstance: + """ + Asynchronous coroutine to fetch the TaskQueueInstance + + + :returns: The fetched TaskQueueInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TaskQueueInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + target_workers: Union[str, object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + ) -> TaskQueueInstance: + """ + Update the TaskQueueInstance + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example '\\\"language\\\" == \\\"spanish\\\"' If no TargetWorkers parameter is provided, Tasks will wait in the queue until they are either deleted or moved to another queue. Additional examples on how to describing Worker selection criteria below. + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned for them. + :param max_reserved_workers: The maximum number of Workers to create reservations for the assignment of a task while in the queue. Maximum of 50. + :param task_order: + + :returns: The updated TaskQueueInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "TargetWorkers": target_workers, + "ReservationActivitySid": reservation_activity_sid, + "AssignmentActivitySid": assignment_activity_sid, + "MaxReservedWorkers": max_reserved_workers, + "TaskOrder": task_order, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskQueueInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + target_workers: Union[str, object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + ) -> TaskQueueInstance: + """ + Asynchronous coroutine to update the TaskQueueInstance + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example '\\\"language\\\" == \\\"spanish\\\"' If no TargetWorkers parameter is provided, Tasks will wait in the queue until they are either deleted or moved to another queue. Additional examples on how to describing Worker selection criteria below. + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned for them. + :param max_reserved_workers: The maximum number of Workers to create reservations for the assignment of a task while in the queue. Maximum of 50. + :param task_order: + + :returns: The updated TaskQueueInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "TargetWorkers": target_workers, + "ReservationActivitySid": reservation_activity_sid, + "AssignmentActivitySid": assignment_activity_sid, + "MaxReservedWorkers": max_reserved_workers, + "TaskOrder": task_order, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskQueueInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + @property + def cumulative_statistics(self) -> TaskQueueCumulativeStatisticsList: + """ + Access the cumulative_statistics + """ + if self._cumulative_statistics is None: + self._cumulative_statistics = TaskQueueCumulativeStatisticsList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._cumulative_statistics + + @property + def real_time_statistics(self) -> TaskQueueRealTimeStatisticsList: + """ + Access the real_time_statistics + """ + if self._real_time_statistics is None: + self._real_time_statistics = TaskQueueRealTimeStatisticsList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._real_time_statistics + + @property + def statistics(self) -> TaskQueueStatisticsList: + """ + Access the statistics + """ + if self._statistics is None: + self._statistics = TaskQueueStatisticsList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._statistics + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TaskQueuePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TaskQueueInstance: + """ + Build an instance of TaskQueueInstance + + :param payload: Payload response from the API + """ + return TaskQueueInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TaskQueueList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the TaskQueueList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskQueue to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/TaskQueues".format(**self._solution) + + self._bulk_real_time_statistics: Optional[ + TaskQueueBulkRealTimeStatisticsList + ] = None + self._statistics: Optional[TaskQueuesStatisticsList] = None + + def create( + self, + friendly_name: str, + target_workers: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + ) -> TaskQueueInstance: + """ + Create the TaskQueueInstance + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string that describes the Worker selection criteria for any Tasks that enter the TaskQueue. For example, `'\\\"language\\\" == \\\"spanish\\\"'`. The default value is `1==1`. If this value is empty, Tasks will wait in the TaskQueue until they are deleted or moved to another TaskQueue. For more information about Worker selection, see [Describing Worker selection criteria](https://www.twilio.com/docs/taskrouter/api/taskqueues#target-workers). + :param max_reserved_workers: The maximum number of Workers to reserve for the assignment of a Task in the queue. Can be an integer between 1 and 50, inclusive and defaults to 1. + :param task_order: + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned to them. + + :returns: The created TaskQueueInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "TargetWorkers": target_workers, + "MaxReservedWorkers": max_reserved_workers, + "TaskOrder": task_order, + "ReservationActivitySid": reservation_activity_sid, + "AssignmentActivitySid": assignment_activity_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskQueueInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_async( + self, + friendly_name: str, + target_workers: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + ) -> TaskQueueInstance: + """ + Asynchronously create the TaskQueueInstance + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string that describes the Worker selection criteria for any Tasks that enter the TaskQueue. For example, `'\\\"language\\\" == \\\"spanish\\\"'`. The default value is `1==1`. If this value is empty, Tasks will wait in the TaskQueue until they are deleted or moved to another TaskQueue. For more information about Worker selection, see [Describing Worker selection criteria](https://www.twilio.com/docs/taskrouter/api/taskqueues#target-workers). + :param max_reserved_workers: The maximum number of Workers to reserve for the assignment of a Task in the queue. Can be an integer between 1 and 50, inclusive and defaults to 1. + :param task_order: + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned to them. + + :returns: The created TaskQueueInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "TargetWorkers": target_workers, + "MaxReservedWorkers": max_reserved_workers, + "TaskOrder": task_order, + "ReservationActivitySid": reservation_activity_sid, + "AssignmentActivitySid": assignment_activity_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskQueueInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + evaluate_worker_attributes: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TaskQueueInstance]: + """ + Streams TaskQueueInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the TaskQueue resources to read. + :param str evaluate_worker_attributes: The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. + :param str worker_sid: The SID of the Worker with the TaskQueue resources to read. + :param str ordering: Sorting parameter for TaskQueues + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + friendly_name=friendly_name, + evaluate_worker_attributes=evaluate_worker_attributes, + worker_sid=worker_sid, + ordering=ordering, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + evaluate_worker_attributes: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TaskQueueInstance]: + """ + Asynchronously streams TaskQueueInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the TaskQueue resources to read. + :param str evaluate_worker_attributes: The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. + :param str worker_sid: The SID of the Worker with the TaskQueue resources to read. + :param str ordering: Sorting parameter for TaskQueues + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, + evaluate_worker_attributes=evaluate_worker_attributes, + worker_sid=worker_sid, + ordering=ordering, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + evaluate_worker_attributes: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TaskQueueInstance]: + """ + Lists TaskQueueInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the TaskQueue resources to read. + :param str evaluate_worker_attributes: The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. + :param str worker_sid: The SID of the Worker with the TaskQueue resources to read. + :param str ordering: Sorting parameter for TaskQueues + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + friendly_name=friendly_name, + evaluate_worker_attributes=evaluate_worker_attributes, + worker_sid=worker_sid, + ordering=ordering, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + evaluate_worker_attributes: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TaskQueueInstance]: + """ + Asynchronously lists TaskQueueInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the TaskQueue resources to read. + :param str evaluate_worker_attributes: The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. + :param str worker_sid: The SID of the Worker with the TaskQueue resources to read. + :param str ordering: Sorting parameter for TaskQueues + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + evaluate_worker_attributes=evaluate_worker_attributes, + worker_sid=worker_sid, + ordering=ordering, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + friendly_name: Union[str, object] = values.unset, + evaluate_worker_attributes: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TaskQueuePage: + """ + Retrieve a single page of TaskQueueInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the TaskQueue resources to read. + :param evaluate_worker_attributes: The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. + :param worker_sid: The SID of the Worker with the TaskQueue resources to read. + :param ordering: Sorting parameter for TaskQueues + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TaskQueueInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "EvaluateWorkerAttributes": evaluate_worker_attributes, + "WorkerSid": worker_sid, + "Ordering": ordering, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskQueuePage(self._version, response, self._solution) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + evaluate_worker_attributes: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TaskQueuePage: + """ + Asynchronously retrieve a single page of TaskQueueInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the TaskQueue resources to read. + :param evaluate_worker_attributes: The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. + :param worker_sid: The SID of the Worker with the TaskQueue resources to read. + :param ordering: Sorting parameter for TaskQueues + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TaskQueueInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "EvaluateWorkerAttributes": evaluate_worker_attributes, + "WorkerSid": worker_sid, + "Ordering": ordering, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskQueuePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> TaskQueuePage: + """ + Retrieve a specific page of TaskQueueInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TaskQueueInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TaskQueuePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> TaskQueuePage: + """ + Asynchronously retrieve a specific page of TaskQueueInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TaskQueueInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TaskQueuePage(self._version, response, self._solution) + + @property + def bulk_real_time_statistics(self) -> TaskQueueBulkRealTimeStatisticsList: + """ + Access the bulk_real_time_statistics + """ + if self._bulk_real_time_statistics is None: + self._bulk_real_time_statistics = TaskQueueBulkRealTimeStatisticsList( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + return self._bulk_real_time_statistics + + @property + def statistics(self) -> TaskQueuesStatisticsList: + """ + Access the statistics + """ + if self._statistics is None: + self._statistics = TaskQueuesStatisticsList( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + return self._statistics + + def get(self, sid: str) -> TaskQueueContext: + """ + Constructs a TaskQueueContext + + :param sid: The SID of the TaskQueue resource to update. + """ + return TaskQueueContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __call__(self, sid: str) -> TaskQueueContext: + """ + Constructs a TaskQueueContext + + :param sid: The SID of the TaskQueue resource to update. + """ + return TaskQueueContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..14596aba Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/__pycache__/task_queue_bulk_real_time_statistics.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/__pycache__/task_queue_bulk_real_time_statistics.cpython-312.pyc new file mode 100644 index 00000000..0c8b5169 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/__pycache__/task_queue_bulk_real_time_statistics.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/__pycache__/task_queue_cumulative_statistics.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/__pycache__/task_queue_cumulative_statistics.cpython-312.pyc new file mode 100644 index 00000000..29a1d8d3 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/__pycache__/task_queue_cumulative_statistics.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/__pycache__/task_queue_real_time_statistics.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/__pycache__/task_queue_real_time_statistics.cpython-312.pyc new file mode 100644 index 00000000..44a407f1 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/__pycache__/task_queue_real_time_statistics.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/__pycache__/task_queue_statistics.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/__pycache__/task_queue_statistics.cpython-312.pyc new file mode 100644 index 00000000..3fdbe252 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/__pycache__/task_queue_statistics.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/__pycache__/task_queues_statistics.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/__pycache__/task_queues_statistics.cpython-312.pyc new file mode 100644 index 00000000..fbc03660 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/__pycache__/task_queues_statistics.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_bulk_real_time_statistics.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_bulk_real_time_statistics.py new file mode 100644 index 00000000..90400c79 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_bulk_real_time_statistics.py @@ -0,0 +1,141 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TaskQueueBulkRealTimeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. + :ivar workspace_sid: The SID of the Workspace that contains the TaskQueue. + :ivar task_queue_data: The real-time statistics for each requested TaskQueue SID. `task_queue_data` returns the following attributes: `task_queue_sid`: The SID of the TaskQueue from which these statistics were calculated. `total_available_workers`: The total number of Workers available for Tasks in the TaskQueue. `total_eligible_workers`: The total number of Workers eligible for Tasks in the TaskQueue, regardless of their Activity state. `total_tasks`: The total number of Tasks. `longest_task_waiting_age`: The age of the longest waiting Task. `longest_task_waiting_sid`: The SID of the longest waiting Task. `tasks_by_status`: The number of Tasks grouped by their current status. `tasks_by_priority`: The number of Tasks grouped by priority. `activity_statistics`: The number of current Workers grouped by Activity. + :ivar task_queue_response_count: The number of TaskQueue statistics received in task_queue_data. + :ivar url: The absolute URL of the TaskQueue statistics resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.task_queue_data: Optional[List[Dict[str, object]]] = payload.get( + "task_queue_data" + ) + self.task_queue_response_count: Optional[int] = deserialize.integer( + payload.get("task_queue_response_count") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return ( + "".format( + context + ) + ) + + +class TaskQueueBulkRealTimeStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the TaskQueueBulkRealTimeStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The unique SID identifier of the Workspace. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/TaskQueues/RealTimeStatistics".format( + **self._solution + ) + + def create( + self, body: Union[object, object] = values.unset + ) -> TaskQueueBulkRealTimeStatisticsInstance: + """ + Create the TaskQueueBulkRealTimeStatisticsInstance + + :param body: + + :returns: The created TaskQueueBulkRealTimeStatisticsInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskQueueBulkRealTimeStatisticsInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> TaskQueueBulkRealTimeStatisticsInstance: + """ + Asynchronously create the TaskQueueBulkRealTimeStatisticsInstance + + :param body: + + :returns: The created TaskQueueBulkRealTimeStatisticsInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskQueueBulkRealTimeStatisticsInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_cumulative_statistics.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_cumulative_statistics.py new file mode 100644 index 00000000..ef851c75 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_cumulative_statistics.py @@ -0,0 +1,376 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TaskQueueCumulativeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. + :ivar avg_task_acceptance_time: The average time in seconds between Task creation and acceptance. + :ivar start_time: The beginning of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar end_time: The end of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar reservations_created: The total number of Reservations created for Tasks in the TaskQueue. + :ivar reservations_accepted: The total number of Reservations accepted for Tasks in the TaskQueue. + :ivar reservations_rejected: The total number of Reservations rejected for Tasks in the TaskQueue. + :ivar reservations_timed_out: The total number of Reservations that timed out for Tasks in the TaskQueue. + :ivar reservations_canceled: The total number of Reservations canceled for Tasks in the TaskQueue. + :ivar reservations_rescinded: The total number of Reservations rescinded. + :ivar split_by_wait_time: A list of objects that describe the number of Tasks canceled and reservations accepted above and below the thresholds specified in seconds. + :ivar task_queue_sid: The SID of the TaskQueue from which these statistics were calculated. + :ivar wait_duration_until_accepted: The wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks accepted while in the TaskQueue. Calculation is based on the time when the Tasks were created. For transfers, the wait duration is counted from the moment ***the Task was created***, and not from when the transfer was initiated. + :ivar wait_duration_until_canceled: The wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks canceled while in the TaskQueue. + :ivar wait_duration_in_queue_until_accepted: The relative wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks accepted while in the TaskQueue. Calculation is based on the time when the Tasks entered the TaskQueue. + :ivar tasks_canceled: The total number of Tasks canceled in the TaskQueue. + :ivar tasks_completed: The total number of Tasks completed in the TaskQueue. + :ivar tasks_deleted: The total number of Tasks deleted in the TaskQueue. + :ivar tasks_entered: The total number of Tasks entered into the TaskQueue. + :ivar tasks_moved: The total number of Tasks that were moved from one queue to another. + :ivar workspace_sid: The SID of the Workspace that contains the TaskQueue. + :ivar url: The absolute URL of the TaskQueue statistics resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + task_queue_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.avg_task_acceptance_time: Optional[int] = deserialize.integer( + payload.get("avg_task_acceptance_time") + ) + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.reservations_created: Optional[int] = deserialize.integer( + payload.get("reservations_created") + ) + self.reservations_accepted: Optional[int] = deserialize.integer( + payload.get("reservations_accepted") + ) + self.reservations_rejected: Optional[int] = deserialize.integer( + payload.get("reservations_rejected") + ) + self.reservations_timed_out: Optional[int] = deserialize.integer( + payload.get("reservations_timed_out") + ) + self.reservations_canceled: Optional[int] = deserialize.integer( + payload.get("reservations_canceled") + ) + self.reservations_rescinded: Optional[int] = deserialize.integer( + payload.get("reservations_rescinded") + ) + self.split_by_wait_time: Optional[Dict[str, object]] = payload.get( + "split_by_wait_time" + ) + self.task_queue_sid: Optional[str] = payload.get("task_queue_sid") + self.wait_duration_until_accepted: Optional[Dict[str, object]] = payload.get( + "wait_duration_until_accepted" + ) + self.wait_duration_until_canceled: Optional[Dict[str, object]] = payload.get( + "wait_duration_until_canceled" + ) + self.wait_duration_in_queue_until_accepted: Optional[Dict[str, object]] = ( + payload.get("wait_duration_in_queue_until_accepted") + ) + self.tasks_canceled: Optional[int] = deserialize.integer( + payload.get("tasks_canceled") + ) + self.tasks_completed: Optional[int] = deserialize.integer( + payload.get("tasks_completed") + ) + self.tasks_deleted: Optional[int] = deserialize.integer( + payload.get("tasks_deleted") + ) + self.tasks_entered: Optional[int] = deserialize.integer( + payload.get("tasks_entered") + ) + self.tasks_moved: Optional[int] = deserialize.integer( + payload.get("tasks_moved") + ) + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } + self._context: Optional[TaskQueueCumulativeStatisticsContext] = None + + @property + def _proxy(self) -> "TaskQueueCumulativeStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TaskQueueCumulativeStatisticsContext for this TaskQueueCumulativeStatisticsInstance + """ + if self._context is None: + self._context = TaskQueueCumulativeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + return self._context + + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "TaskQueueCumulativeStatisticsInstance": + """ + Fetch the TaskQueueCumulativeStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. TaskRouter will calculate statistics on up to 10,000 Tasks/Reservations for any given threshold. + + :returns: The fetched TaskQueueCumulativeStatisticsInstance + """ + return self._proxy.fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "TaskQueueCumulativeStatisticsInstance": + """ + Asynchronous coroutine to fetch the TaskQueueCumulativeStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. TaskRouter will calculate statistics on up to 10,000 Tasks/Reservations for any given threshold. + + :returns: The fetched TaskQueueCumulativeStatisticsInstance + """ + return await self._proxy.fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class TaskQueueCumulativeStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): + """ + Initialize the TaskQueueCumulativeStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskQueue to fetch. + :param task_queue_sid: The SID of the TaskQueue for which to fetch statistics. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } + self._uri = "/Workspaces/{workspace_sid}/TaskQueues/{task_queue_sid}/CumulativeStatistics".format( + **self._solution + ) + + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> TaskQueueCumulativeStatisticsInstance: + """ + Fetch the TaskQueueCumulativeStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. TaskRouter will calculate statistics on up to 10,000 Tasks/Reservations for any given threshold. + + :returns: The fetched TaskQueueCumulativeStatisticsInstance + """ + + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return TaskQueueCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> TaskQueueCumulativeStatisticsInstance: + """ + Asynchronous coroutine to fetch the TaskQueueCumulativeStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. TaskRouter will calculate statistics on up to 10,000 Tasks/Reservations for any given threshold. + + :returns: The fetched TaskQueueCumulativeStatisticsInstance + """ + + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return TaskQueueCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class TaskQueueCumulativeStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): + """ + Initialize the TaskQueueCumulativeStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskQueue to fetch. + :param task_queue_sid: The SID of the TaskQueue for which to fetch statistics. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } + + def get(self) -> TaskQueueCumulativeStatisticsContext: + """ + Constructs a TaskQueueCumulativeStatisticsContext + + """ + return TaskQueueCumulativeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + def __call__(self) -> TaskQueueCumulativeStatisticsContext: + """ + Constructs a TaskQueueCumulativeStatisticsContext + + """ + return TaskQueueCumulativeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_real_time_statistics.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_real_time_statistics.py new file mode 100644 index 00000000..c4eb30dd --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_real_time_statistics.py @@ -0,0 +1,291 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TaskQueueRealTimeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. + :ivar activity_statistics: The number of current Workers by Activity. + :ivar longest_task_waiting_age: The age of the longest waiting Task. + :ivar longest_task_waiting_sid: The SID of the longest waiting Task. + :ivar longest_relative_task_age_in_queue: The relative age in the TaskQueue for the longest waiting Task. Calculation is based on the time when the Task entered the TaskQueue. + :ivar longest_relative_task_sid_in_queue: The Task SID of the Task waiting in the TaskQueue the longest. Calculation is based on the time when the Task entered the TaskQueue. + :ivar task_queue_sid: The SID of the TaskQueue from which these statistics were calculated. + :ivar tasks_by_priority: The number of Tasks by priority. For example: `{\"0\": \"10\", \"99\": \"5\"}` shows 10 Tasks at priority 0 and 5 at priority 99. + :ivar tasks_by_status: The number of Tasks by their current status. For example: `{\"pending\": \"1\", \"reserved\": \"3\", \"assigned\": \"2\", \"completed\": \"5\"}`. + :ivar total_available_workers: The total number of Workers in the TaskQueue with an `available` status. Workers with an `available` status may already have active interactions or may have none. + :ivar total_eligible_workers: The total number of Workers eligible for Tasks in the TaskQueue, independent of their Activity state. + :ivar total_tasks: The total number of Tasks. + :ivar workspace_sid: The SID of the Workspace that contains the TaskQueue. + :ivar url: The absolute URL of the TaskQueue statistics resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + task_queue_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.activity_statistics: Optional[List[Dict[str, object]]] = payload.get( + "activity_statistics" + ) + self.longest_task_waiting_age: Optional[int] = deserialize.integer( + payload.get("longest_task_waiting_age") + ) + self.longest_task_waiting_sid: Optional[str] = payload.get( + "longest_task_waiting_sid" + ) + self.longest_relative_task_age_in_queue: Optional[int] = deserialize.integer( + payload.get("longest_relative_task_age_in_queue") + ) + self.longest_relative_task_sid_in_queue: Optional[str] = payload.get( + "longest_relative_task_sid_in_queue" + ) + self.task_queue_sid: Optional[str] = payload.get("task_queue_sid") + self.tasks_by_priority: Optional[Dict[str, object]] = payload.get( + "tasks_by_priority" + ) + self.tasks_by_status: Optional[Dict[str, object]] = payload.get( + "tasks_by_status" + ) + self.total_available_workers: Optional[int] = deserialize.integer( + payload.get("total_available_workers") + ) + self.total_eligible_workers: Optional[int] = deserialize.integer( + payload.get("total_eligible_workers") + ) + self.total_tasks: Optional[int] = deserialize.integer( + payload.get("total_tasks") + ) + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } + self._context: Optional[TaskQueueRealTimeStatisticsContext] = None + + @property + def _proxy(self) -> "TaskQueueRealTimeStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TaskQueueRealTimeStatisticsContext for this TaskQueueRealTimeStatisticsInstance + """ + if self._context is None: + self._context = TaskQueueRealTimeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + return self._context + + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> "TaskQueueRealTimeStatisticsInstance": + """ + Fetch the TaskQueueRealTimeStatisticsInstance + + :param task_channel: The TaskChannel for which to fetch statistics. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched TaskQueueRealTimeStatisticsInstance + """ + return self._proxy.fetch( + task_channel=task_channel, + ) + + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> "TaskQueueRealTimeStatisticsInstance": + """ + Asynchronous coroutine to fetch the TaskQueueRealTimeStatisticsInstance + + :param task_channel: The TaskChannel for which to fetch statistics. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched TaskQueueRealTimeStatisticsInstance + """ + return await self._proxy.fetch_async( + task_channel=task_channel, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class TaskQueueRealTimeStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): + """ + Initialize the TaskQueueRealTimeStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskQueue to fetch. + :param task_queue_sid: The SID of the TaskQueue for which to fetch statistics. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } + self._uri = "/Workspaces/{workspace_sid}/TaskQueues/{task_queue_sid}/RealTimeStatistics".format( + **self._solution + ) + + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> TaskQueueRealTimeStatisticsInstance: + """ + Fetch the TaskQueueRealTimeStatisticsInstance + + :param task_channel: The TaskChannel for which to fetch statistics. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched TaskQueueRealTimeStatisticsInstance + """ + + data = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return TaskQueueRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> TaskQueueRealTimeStatisticsInstance: + """ + Asynchronous coroutine to fetch the TaskQueueRealTimeStatisticsInstance + + :param task_channel: The TaskChannel for which to fetch statistics. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched TaskQueueRealTimeStatisticsInstance + """ + + data = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return TaskQueueRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class TaskQueueRealTimeStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): + """ + Initialize the TaskQueueRealTimeStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskQueue to fetch. + :param task_queue_sid: The SID of the TaskQueue for which to fetch statistics. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } + + def get(self) -> TaskQueueRealTimeStatisticsContext: + """ + Constructs a TaskQueueRealTimeStatisticsContext + + """ + return TaskQueueRealTimeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + def __call__(self) -> TaskQueueRealTimeStatisticsContext: + """ + Constructs a TaskQueueRealTimeStatisticsContext + + """ + return TaskQueueRealTimeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_statistics.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_statistics.py new file mode 100644 index 00000000..2d5d6310 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_statistics.py @@ -0,0 +1,306 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TaskQueueStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. + :ivar cumulative: An object that contains the cumulative statistics for the TaskQueue. + :ivar realtime: An object that contains the real-time statistics for the TaskQueue. + :ivar task_queue_sid: The SID of the TaskQueue from which these statistics were calculated. + :ivar workspace_sid: The SID of the Workspace that contains the TaskQueue. + :ivar url: The absolute URL of the TaskQueue statistics resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + task_queue_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.cumulative: Optional[Dict[str, object]] = payload.get("cumulative") + self.realtime: Optional[Dict[str, object]] = payload.get("realtime") + self.task_queue_sid: Optional[str] = payload.get("task_queue_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } + self._context: Optional[TaskQueueStatisticsContext] = None + + @property + def _proxy(self) -> "TaskQueueStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TaskQueueStatisticsContext for this TaskQueueStatisticsInstance + """ + if self._context is None: + self._context = TaskQueueStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + return self._context + + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "TaskQueueStatisticsInstance": + """ + Fetch the TaskQueueStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate real-time and cumulative statistics for the specified TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + + :returns: The fetched TaskQueueStatisticsInstance + """ + return self._proxy.fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "TaskQueueStatisticsInstance": + """ + Asynchronous coroutine to fetch the TaskQueueStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate real-time and cumulative statistics for the specified TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + + :returns: The fetched TaskQueueStatisticsInstance + """ + return await self._proxy.fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TaskQueueStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): + """ + Initialize the TaskQueueStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskQueue to fetch. + :param task_queue_sid: The SID of the TaskQueue for which to fetch statistics. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } + self._uri = ( + "/Workspaces/{workspace_sid}/TaskQueues/{task_queue_sid}/Statistics".format( + **self._solution + ) + ) + + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> TaskQueueStatisticsInstance: + """ + Fetch the TaskQueueStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate real-time and cumulative statistics for the specified TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + + :returns: The fetched TaskQueueStatisticsInstance + """ + + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return TaskQueueStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> TaskQueueStatisticsInstance: + """ + Asynchronous coroutine to fetch the TaskQueueStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate real-time and cumulative statistics for the specified TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + + :returns: The fetched TaskQueueStatisticsInstance + """ + + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return TaskQueueStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TaskQueueStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): + """ + Initialize the TaskQueueStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskQueue to fetch. + :param task_queue_sid: The SID of the TaskQueue for which to fetch statistics. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } + + def get(self) -> TaskQueueStatisticsContext: + """ + Constructs a TaskQueueStatisticsContext + + """ + return TaskQueueStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + def __call__(self) -> TaskQueueStatisticsContext: + """ + Constructs a TaskQueueStatisticsContext + + """ + return TaskQueueStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/task_queues_statistics.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/task_queues_statistics.py new file mode 100644 index 00000000..036f6ad9 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/task_queue/task_queues_statistics.py @@ -0,0 +1,409 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TaskQueuesStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. + :ivar cumulative: An object that contains the cumulative statistics for the TaskQueues. + :ivar realtime: An object that contains the real-time statistics for the TaskQueues. + :ivar task_queue_sid: The SID of the TaskQueue from which these statistics were calculated. + :ivar workspace_sid: The SID of the Workspace that contains the TaskQueues. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.cumulative: Optional[Dict[str, object]] = payload.get("cumulative") + self.realtime: Optional[Dict[str, object]] = payload.get("realtime") + self.task_queue_sid: Optional[str] = payload.get("task_queue_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + + self._solution = { + "workspace_sid": workspace_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TaskQueuesStatisticsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TaskQueuesStatisticsInstance: + """ + Build an instance of TaskQueuesStatisticsInstance + + :param payload: Payload response from the API + """ + return TaskQueuesStatisticsInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TaskQueuesStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the TaskQueuesStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskQueues to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/TaskQueues/Statistics".format( + **self._solution + ) + + def stream( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TaskQueuesStatisticsInstance]: + """ + Streams TaskQueuesStatisticsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param int minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param datetime start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param str task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param str split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + end_date=end_date, + friendly_name=friendly_name, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TaskQueuesStatisticsInstance]: + """ + Asynchronously streams TaskQueuesStatisticsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param int minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param datetime start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param str task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param str split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + end_date=end_date, + friendly_name=friendly_name, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TaskQueuesStatisticsInstance]: + """ + Lists TaskQueuesStatisticsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param int minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param datetime start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param str task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param str split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + end_date=end_date, + friendly_name=friendly_name, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TaskQueuesStatisticsInstance]: + """ + Asynchronously lists TaskQueuesStatisticsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param int minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param datetime start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param str task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param str split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + end_date=end_date, + friendly_name=friendly_name, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TaskQueuesStatisticsPage: + """ + Retrieve a single page of TaskQueuesStatisticsInstance records from the API. + Request is executed immediately + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TaskQueuesStatisticsInstance + """ + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "FriendlyName": friendly_name, + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskQueuesStatisticsPage(self._version, response, self._solution) + + async def page_async( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TaskQueuesStatisticsPage: + """ + Asynchronously retrieve a single page of TaskQueuesStatisticsInstance records from the API. + Request is executed immediately + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TaskQueuesStatisticsInstance + """ + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "FriendlyName": friendly_name, + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskQueuesStatisticsPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> TaskQueuesStatisticsPage: + """ + Retrieve a specific page of TaskQueuesStatisticsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TaskQueuesStatisticsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TaskQueuesStatisticsPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> TaskQueuesStatisticsPage: + """ + Asynchronously retrieve a specific page of TaskQueuesStatisticsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TaskQueuesStatisticsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TaskQueuesStatisticsPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/__init__.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/__init__.py new file mode 100644 index 00000000..38aede84 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/__init__.py @@ -0,0 +1,1009 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.taskrouter.v1.workspace.worker.reservation import ReservationList +from twilio.rest.taskrouter.v1.workspace.worker.worker_channel import WorkerChannelList +from twilio.rest.taskrouter.v1.workspace.worker.worker_statistics import ( + WorkerStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics import ( + WorkersCumulativeStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics import ( + WorkersRealTimeStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.worker.workers_statistics import ( + WorkersStatisticsList, +) + + +class WorkerInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Worker resource. + :ivar activity_name: The `friendly_name` of the Worker's current Activity. + :ivar activity_sid: The SID of the Worker's current Activity. + :ivar attributes: The JSON string that describes the Worker. For example: `{ \"email\": \"Bob@example.com\", \"phone\": \"+5095551234\" }`. **Note** If this property has been assigned a value, it will only be displayed in FETCH actions that return a single resource. Otherwise, this property will be null, even if it has a value. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. + :ivar available: Whether the Worker is available to perform tasks. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_status_changed: The date and time in GMT of the last change to the Worker's activity specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Used to calculate Workflow statistics. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar friendly_name: The string that you assigned to describe the resource. Friendly names are case insensitive, and unique within the TaskRouter Workspace. + :ivar sid: The unique string that we created to identify the Worker resource. + :ivar workspace_sid: The SID of the Workspace that contains the Worker. + :ivar url: The absolute URL of the Worker resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.activity_name: Optional[str] = payload.get("activity_name") + self.activity_sid: Optional[str] = payload.get("activity_sid") + self.attributes: Optional[str] = payload.get("attributes") + self.available: Optional[bool] = payload.get("available") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_status_changed: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_status_changed") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.sid: Optional[str] = payload.get("sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid or self.sid, + } + self._context: Optional[WorkerContext] = None + + @property + def _proxy(self) -> "WorkerContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkerContext for this WorkerInstance + """ + if self._context is None: + self._context = WorkerContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Deletes the WorkerInstance + + :param if_match: The If-Match HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + if_match=if_match, + ) + + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Asynchronous coroutine that deletes the WorkerInstance + + :param if_match: The If-Match HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + if_match=if_match, + ) + + def fetch(self) -> "WorkerInstance": + """ + Fetch the WorkerInstance + + + :returns: The fetched WorkerInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "WorkerInstance": + """ + Asynchronous coroutine to fetch the WorkerInstance + + + :returns: The fetched WorkerInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + if_match: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reject_pending_reservations: Union[bool, object] = values.unset, + ) -> "WorkerInstance": + """ + Update the WorkerInstance + + :param if_match: The If-Match HTTP request header + :param activity_sid: The SID of a valid Activity that will describe the Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. + :param attributes: The JSON string that describes the Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + :param friendly_name: A descriptive string that you create to describe the Worker. It can be up to 64 characters long. + :param reject_pending_reservations: Whether to reject the Worker's pending reservations. This option is only valid if the Worker's new [Activity](https://www.twilio.com/docs/taskrouter/api/activity) resource has its `availability` property set to `False`. + + :returns: The updated WorkerInstance + """ + return self._proxy.update( + if_match=if_match, + activity_sid=activity_sid, + attributes=attributes, + friendly_name=friendly_name, + reject_pending_reservations=reject_pending_reservations, + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reject_pending_reservations: Union[bool, object] = values.unset, + ) -> "WorkerInstance": + """ + Asynchronous coroutine to update the WorkerInstance + + :param if_match: The If-Match HTTP request header + :param activity_sid: The SID of a valid Activity that will describe the Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. + :param attributes: The JSON string that describes the Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + :param friendly_name: A descriptive string that you create to describe the Worker. It can be up to 64 characters long. + :param reject_pending_reservations: Whether to reject the Worker's pending reservations. This option is only valid if the Worker's new [Activity](https://www.twilio.com/docs/taskrouter/api/activity) resource has its `availability` property set to `False`. + + :returns: The updated WorkerInstance + """ + return await self._proxy.update_async( + if_match=if_match, + activity_sid=activity_sid, + attributes=attributes, + friendly_name=friendly_name, + reject_pending_reservations=reject_pending_reservations, + ) + + @property + def reservations(self) -> ReservationList: + """ + Access the reservations + """ + return self._proxy.reservations + + @property + def worker_channels(self) -> WorkerChannelList: + """ + Access the worker_channels + """ + return self._proxy.worker_channels + + @property + def statistics(self) -> WorkerStatisticsList: + """ + Access the statistics + """ + return self._proxy.statistics + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WorkerContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, sid: str): + """ + Initialize the WorkerContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Worker to update. + :param sid: The SID of the Worker resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers/{sid}".format(**self._solution) + + self._reservations: Optional[ReservationList] = None + self._worker_channels: Optional[WorkerChannelList] = None + self._statistics: Optional[WorkerStatisticsList] = None + + def delete(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Deletes the WorkerInstance + + :param if_match: The If-Match HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "If-Match": if_match, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Asynchronous coroutine that deletes the WorkerInstance + + :param if_match: The If-Match HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "If-Match": if_match, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> WorkerInstance: + """ + Fetch the WorkerInstance + + + :returns: The fetched WorkerInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WorkerInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> WorkerInstance: + """ + Asynchronous coroutine to fetch the WorkerInstance + + + :returns: The fetched WorkerInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WorkerInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + if_match: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reject_pending_reservations: Union[bool, object] = values.unset, + ) -> WorkerInstance: + """ + Update the WorkerInstance + + :param if_match: The If-Match HTTP request header + :param activity_sid: The SID of a valid Activity that will describe the Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. + :param attributes: The JSON string that describes the Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + :param friendly_name: A descriptive string that you create to describe the Worker. It can be up to 64 characters long. + :param reject_pending_reservations: Whether to reject the Worker's pending reservations. This option is only valid if the Worker's new [Activity](https://www.twilio.com/docs/taskrouter/api/activity) resource has its `availability` property set to `False`. + + :returns: The updated WorkerInstance + """ + + data = values.of( + { + "ActivitySid": activity_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + "RejectPendingReservations": serialize.boolean_to_string( + reject_pending_reservations + ), + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkerInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reject_pending_reservations: Union[bool, object] = values.unset, + ) -> WorkerInstance: + """ + Asynchronous coroutine to update the WorkerInstance + + :param if_match: The If-Match HTTP request header + :param activity_sid: The SID of a valid Activity that will describe the Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. + :param attributes: The JSON string that describes the Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + :param friendly_name: A descriptive string that you create to describe the Worker. It can be up to 64 characters long. + :param reject_pending_reservations: Whether to reject the Worker's pending reservations. This option is only valid if the Worker's new [Activity](https://www.twilio.com/docs/taskrouter/api/activity) resource has its `availability` property set to `False`. + + :returns: The updated WorkerInstance + """ + + data = values.of( + { + "ActivitySid": activity_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + "RejectPendingReservations": serialize.boolean_to_string( + reject_pending_reservations + ), + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkerInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + @property + def reservations(self) -> ReservationList: + """ + Access the reservations + """ + if self._reservations is None: + self._reservations = ReservationList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._reservations + + @property + def worker_channels(self) -> WorkerChannelList: + """ + Access the worker_channels + """ + if self._worker_channels is None: + self._worker_channels = WorkerChannelList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._worker_channels + + @property + def statistics(self) -> WorkerStatisticsList: + """ + Access the statistics + """ + if self._statistics is None: + self._statistics = WorkerStatisticsList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._statistics + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WorkerPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WorkerInstance: + """ + Build an instance of WorkerInstance + + :param payload: Payload response from the API + """ + return WorkerInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class WorkerList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkerList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Workers to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers".format(**self._solution) + + self._cumulative_statistics: Optional[WorkersCumulativeStatisticsList] = None + self._real_time_statistics: Optional[WorkersRealTimeStatisticsList] = None + self._statistics: Optional[WorkersStatisticsList] = None + + def create( + self, + friendly_name: str, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> WorkerInstance: + """ + Create the WorkerInstance + + :param friendly_name: A descriptive string that you create to describe the new Worker. It can be up to 64 characters long. + :param activity_sid: The SID of a valid Activity that will describe the new Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. If not provided, the new Worker's initial state is the `default_activity_sid` configured on the Workspace. + :param attributes: A valid JSON string that describes the new Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + + :returns: The created WorkerInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ActivitySid": activity_sid, + "Attributes": attributes, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkerInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_async( + self, + friendly_name: str, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> WorkerInstance: + """ + Asynchronously create the WorkerInstance + + :param friendly_name: A descriptive string that you create to describe the new Worker. It can be up to 64 characters long. + :param activity_sid: The SID of a valid Activity that will describe the new Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. If not provided, the new Worker's initial state is the `default_activity_sid` configured on the Workspace. + :param attributes: A valid JSON string that describes the new Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + + :returns: The created WorkerInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ActivitySid": activity_sid, + "Attributes": attributes, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkerInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def stream( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WorkerInstance]: + """ + Streams WorkerInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str activity_name: The `activity_name` of the Worker resources to read. + :param str activity_sid: The `activity_sid` of the Worker resources to read. + :param str available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param str friendly_name: The `friendly_name` of the Worker resources to read. + :param str target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param str task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param str task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param str ordering: Sorting parameter for Workers + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + activity_name=activity_name, + activity_sid=activity_sid, + available=available, + friendly_name=friendly_name, + target_workers_expression=target_workers_expression, + task_queue_name=task_queue_name, + task_queue_sid=task_queue_sid, + ordering=ordering, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WorkerInstance]: + """ + Asynchronously streams WorkerInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str activity_name: The `activity_name` of the Worker resources to read. + :param str activity_sid: The `activity_sid` of the Worker resources to read. + :param str available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param str friendly_name: The `friendly_name` of the Worker resources to read. + :param str target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param str task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param str task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param str ordering: Sorting parameter for Workers + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + activity_name=activity_name, + activity_sid=activity_sid, + available=available, + friendly_name=friendly_name, + target_workers_expression=target_workers_expression, + task_queue_name=task_queue_name, + task_queue_sid=task_queue_sid, + ordering=ordering, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkerInstance]: + """ + Lists WorkerInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str activity_name: The `activity_name` of the Worker resources to read. + :param str activity_sid: The `activity_sid` of the Worker resources to read. + :param str available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param str friendly_name: The `friendly_name` of the Worker resources to read. + :param str target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param str task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param str task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param str ordering: Sorting parameter for Workers + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + activity_name=activity_name, + activity_sid=activity_sid, + available=available, + friendly_name=friendly_name, + target_workers_expression=target_workers_expression, + task_queue_name=task_queue_name, + task_queue_sid=task_queue_sid, + ordering=ordering, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkerInstance]: + """ + Asynchronously lists WorkerInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str activity_name: The `activity_name` of the Worker resources to read. + :param str activity_sid: The `activity_sid` of the Worker resources to read. + :param str available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param str friendly_name: The `friendly_name` of the Worker resources to read. + :param str target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param str task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param str task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param str ordering: Sorting parameter for Workers + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + activity_name=activity_name, + activity_sid=activity_sid, + available=available, + friendly_name=friendly_name, + target_workers_expression=target_workers_expression, + task_queue_name=task_queue_name, + task_queue_sid=task_queue_sid, + ordering=ordering, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WorkerPage: + """ + Retrieve a single page of WorkerInstance records from the API. + Request is executed immediately + + :param activity_name: The `activity_name` of the Worker resources to read. + :param activity_sid: The `activity_sid` of the Worker resources to read. + :param available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param friendly_name: The `friendly_name` of the Worker resources to read. + :param target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param ordering: Sorting parameter for Workers + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WorkerInstance + """ + data = values.of( + { + "ActivityName": activity_name, + "ActivitySid": activity_sid, + "Available": available, + "FriendlyName": friendly_name, + "TargetWorkersExpression": target_workers_expression, + "TaskQueueName": task_queue_name, + "TaskQueueSid": task_queue_sid, + "Ordering": ordering, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkerPage(self._version, response, self._solution) + + async def page_async( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WorkerPage: + """ + Asynchronously retrieve a single page of WorkerInstance records from the API. + Request is executed immediately + + :param activity_name: The `activity_name` of the Worker resources to read. + :param activity_sid: The `activity_sid` of the Worker resources to read. + :param available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param friendly_name: The `friendly_name` of the Worker resources to read. + :param target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param ordering: Sorting parameter for Workers + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WorkerInstance + """ + data = values.of( + { + "ActivityName": activity_name, + "ActivitySid": activity_sid, + "Available": available, + "FriendlyName": friendly_name, + "TargetWorkersExpression": target_workers_expression, + "TaskQueueName": task_queue_name, + "TaskQueueSid": task_queue_sid, + "Ordering": ordering, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkerPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> WorkerPage: + """ + Retrieve a specific page of WorkerInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkerInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return WorkerPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> WorkerPage: + """ + Asynchronously retrieve a specific page of WorkerInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkerInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return WorkerPage(self._version, response, self._solution) + + @property + def cumulative_statistics(self) -> WorkersCumulativeStatisticsList: + """ + Access the cumulative_statistics + """ + if self._cumulative_statistics is None: + self._cumulative_statistics = WorkersCumulativeStatisticsList( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + return self._cumulative_statistics + + @property + def real_time_statistics(self) -> WorkersRealTimeStatisticsList: + """ + Access the real_time_statistics + """ + if self._real_time_statistics is None: + self._real_time_statistics = WorkersRealTimeStatisticsList( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + return self._real_time_statistics + + @property + def statistics(self) -> WorkersStatisticsList: + """ + Access the statistics + """ + if self._statistics is None: + self._statistics = WorkersStatisticsList( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + return self._statistics + + def get(self, sid: str) -> WorkerContext: + """ + Constructs a WorkerContext + + :param sid: The SID of the Worker resource to update. + """ + return WorkerContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __call__(self, sid: str) -> WorkerContext: + """ + Constructs a WorkerContext + + :param sid: The SID of the Worker resource to update. + """ + return WorkerContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..63e7b0e5 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/__pycache__/reservation.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/__pycache__/reservation.cpython-312.pyc new file mode 100644 index 00000000..a10baa13 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/__pycache__/reservation.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/__pycache__/worker_channel.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/__pycache__/worker_channel.cpython-312.pyc new file mode 100644 index 00000000..c7cbc7d5 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/__pycache__/worker_channel.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/__pycache__/worker_statistics.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/__pycache__/worker_statistics.cpython-312.pyc new file mode 100644 index 00000000..16120120 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/__pycache__/worker_statistics.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/__pycache__/workers_cumulative_statistics.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/__pycache__/workers_cumulative_statistics.cpython-312.pyc new file mode 100644 index 00000000..461644ad Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/__pycache__/workers_cumulative_statistics.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/__pycache__/workers_real_time_statistics.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/__pycache__/workers_real_time_statistics.cpython-312.pyc new file mode 100644 index 00000000..8e70e9c9 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/__pycache__/workers_real_time_statistics.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/__pycache__/workers_statistics.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/__pycache__/workers_statistics.cpython-312.pyc new file mode 100644 index 00000000..eb512bf4 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/__pycache__/workers_statistics.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/reservation.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/reservation.py new file mode 100644 index 00000000..7f240578 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/reservation.py @@ -0,0 +1,1294 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ReservationInstance(InstanceResource): + + class CallStatus(object): + INITIATED = "initiated" + RINGING = "ringing" + ANSWERED = "answered" + COMPLETED = "completed" + + class ConferenceEvent(object): + START = "start" + END = "end" + JOIN = "join" + LEAVE = "leave" + MUTE = "mute" + HOLD = "hold" + SPEAKER = "speaker" + + class Status(object): + PENDING = "pending" + ACCEPTED = "accepted" + REJECTED = "rejected" + TIMEOUT = "timeout" + CANCELED = "canceled" + RESCINDED = "rescinded" + WRAPPING = "wrapping" + COMPLETED = "completed" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the WorkerReservation resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar reservation_status: + :ivar sid: The unique string that we created to identify the WorkerReservation resource. + :ivar task_sid: The SID of the reserved Task resource. + :ivar worker_name: The `friendly_name` of the Worker that is reserved. + :ivar worker_sid: The SID of the reserved Worker resource. + :ivar workspace_sid: The SID of the Workspace that this worker is contained within. + :ivar url: The absolute URL of the WorkerReservation resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + worker_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.reservation_status: Optional["ReservationInstance.Status"] = payload.get( + "reservation_status" + ) + self.sid: Optional[str] = payload.get("sid") + self.task_sid: Optional[str] = payload.get("task_sid") + self.worker_name: Optional[str] = payload.get("worker_name") + self.worker_sid: Optional[str] = payload.get("worker_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + "sid": sid or self.sid, + } + self._context: Optional[ReservationContext] = None + + @property + def _proxy(self) -> "ReservationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ReservationContext for this ReservationInstance + """ + if self._context is None: + self._context = ReservationContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "ReservationInstance": + """ + Fetch the ReservationInstance + + + :returns: The fetched ReservationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ReservationInstance": + """ + Asynchronous coroutine to fetch the ReservationInstance + + + :returns: The fetched ReservationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> "ReservationInstance": + """ + Update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for the reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: The timeout for call when executing a Dequeue instruction. + :param dequeue_to: The contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction. + :param call_timeout: The timeout for a call when executing a Call instruction. + :param call_to: The contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: The timeout for a call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. + :param muted: Whether the agent is muted in the conference. Defaults to `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants allowed in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: Whether to trim leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + return self._proxy.update( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> "ReservationInstance": + """ + Asynchronous coroutine to update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for the reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: The timeout for call when executing a Dequeue instruction. + :param dequeue_to: The contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction. + :param call_timeout: The timeout for a call when executing a Call instruction. + :param call_to: The contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: The timeout for a call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. + :param muted: Whether the agent is muted in the conference. Defaults to `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants allowed in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: Whether to trim leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + return await self._proxy.update_async( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ReservationContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, worker_sid: str, sid: str): + """ + Initialize the ReservationContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the WorkerReservation resources to update. + :param worker_sid: The SID of the reserved Worker resource with the WorkerReservation resources to update. + :param sid: The SID of the WorkerReservation resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers/{worker_sid}/Reservations/{sid}".format( + **self._solution + ) + + def fetch(self) -> ReservationInstance: + """ + Fetch the ReservationInstance + + + :returns: The fetched ReservationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ReservationInstance: + """ + Asynchronous coroutine to fetch the ReservationInstance + + + :returns: The fetched ReservationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ReservationInstance: + """ + Update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for the reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: The timeout for call when executing a Dequeue instruction. + :param dequeue_to: The contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction. + :param call_timeout: The timeout for a call when executing a Call instruction. + :param call_to: The contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: The timeout for a call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. + :param muted: Whether the agent is muted in the conference. Defaults to `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants allowed in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: Whether to trim leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerActivitySid": worker_activity_sid, + "Instruction": instruction, + "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, + "DequeueFrom": dequeue_from, + "DequeueRecord": dequeue_record, + "DequeueTimeout": dequeue_timeout, + "DequeueTo": dequeue_to, + "DequeueStatusCallbackUrl": dequeue_status_callback_url, + "CallFrom": call_from, + "CallRecord": call_record, + "CallTimeout": call_timeout, + "CallTo": call_to, + "CallUrl": call_url, + "CallStatusCallbackUrl": call_status_callback_url, + "CallAccept": serialize.boolean_to_string(call_accept), + "RedirectCallSid": redirect_call_sid, + "RedirectAccept": serialize.boolean_to_string(redirect_accept), + "RedirectUrl": redirect_url, + "To": to, + "From": from_, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "Muted": serialize.boolean_to_string(muted), + "Beep": beep, + "StartConferenceOnEnter": serialize.boolean_to_string( + start_conference_on_enter + ), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "EarlyMedia": serialize.boolean_to_string(early_media), + "MaxParticipants": max_participants, + "ConferenceStatusCallback": conference_status_callback, + "ConferenceStatusCallbackMethod": conference_status_callback_method, + "ConferenceStatusCallbackEvent": serialize.map( + conference_status_callback_event, lambda e: e + ), + "ConferenceRecord": conference_record, + "ConferenceTrim": conference_trim, + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "ConferenceRecordingStatusCallback": conference_recording_status_callback, + "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, + "Region": region, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "DequeueStatusCallbackEvent": serialize.map( + dequeue_status_callback_event, lambda e: e + ), + "PostWorkActivitySid": post_work_activity_sid, + "EndConferenceOnCustomerExit": serialize.boolean_to_string( + end_conference_on_customer_exit + ), + "BeepOnCustomerEntrance": serialize.boolean_to_string( + beep_on_customer_entrance + ), + "JitterBufferSize": jitter_buffer_size, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ReservationInstance: + """ + Asynchronous coroutine to update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for the reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: The timeout for call when executing a Dequeue instruction. + :param dequeue_to: The contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction. + :param call_timeout: The timeout for a call when executing a Call instruction. + :param call_to: The contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: The timeout for a call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. + :param muted: Whether the agent is muted in the conference. Defaults to `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants allowed in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: Whether to trim leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerActivitySid": worker_activity_sid, + "Instruction": instruction, + "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, + "DequeueFrom": dequeue_from, + "DequeueRecord": dequeue_record, + "DequeueTimeout": dequeue_timeout, + "DequeueTo": dequeue_to, + "DequeueStatusCallbackUrl": dequeue_status_callback_url, + "CallFrom": call_from, + "CallRecord": call_record, + "CallTimeout": call_timeout, + "CallTo": call_to, + "CallUrl": call_url, + "CallStatusCallbackUrl": call_status_callback_url, + "CallAccept": serialize.boolean_to_string(call_accept), + "RedirectCallSid": redirect_call_sid, + "RedirectAccept": serialize.boolean_to_string(redirect_accept), + "RedirectUrl": redirect_url, + "To": to, + "From": from_, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "Muted": serialize.boolean_to_string(muted), + "Beep": beep, + "StartConferenceOnEnter": serialize.boolean_to_string( + start_conference_on_enter + ), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "EarlyMedia": serialize.boolean_to_string(early_media), + "MaxParticipants": max_participants, + "ConferenceStatusCallback": conference_status_callback, + "ConferenceStatusCallbackMethod": conference_status_callback_method, + "ConferenceStatusCallbackEvent": serialize.map( + conference_status_callback_event, lambda e: e + ), + "ConferenceRecord": conference_record, + "ConferenceTrim": conference_trim, + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "ConferenceRecordingStatusCallback": conference_recording_status_callback, + "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, + "Region": region, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "DequeueStatusCallbackEvent": serialize.map( + dequeue_status_callback_event, lambda e: e + ), + "PostWorkActivitySid": post_work_activity_sid, + "EndConferenceOnCustomerExit": serialize.boolean_to_string( + end_conference_on_customer_exit + ), + "BeepOnCustomerEntrance": serialize.boolean_to_string( + beep_on_customer_entrance + ), + "JitterBufferSize": jitter_buffer_size, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ReservationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ReservationInstance: + """ + Build an instance of ReservationInstance + + :param payload: Payload response from the API + """ + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ReservationList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, worker_sid: str): + """ + Initialize the ReservationList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the WorkerReservation resources to read. + :param worker_sid: The SID of the reserved Worker resource with the WorkerReservation resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + } + self._uri = ( + "/Workspaces/{workspace_sid}/Workers/{worker_sid}/Reservations".format( + **self._solution + ) + ) + + def stream( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ReservationInstance]: + """ + Streams ReservationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + reservation_status=reservation_status, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ReservationInstance]: + """ + Asynchronously streams ReservationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + reservation_status=reservation_status, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ReservationInstance]: + """ + Lists ReservationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + reservation_status=reservation_status, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ReservationInstance]: + """ + Asynchronously lists ReservationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + reservation_status=reservation_status, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ReservationPage: + """ + Retrieve a single page of ReservationInstance records from the API. + Request is executed immediately + + :param reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ReservationInstance + """ + data = values.of( + { + "ReservationStatus": reservation_status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ReservationPage(self._version, response, self._solution) + + async def page_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ReservationPage: + """ + Asynchronously retrieve a single page of ReservationInstance records from the API. + Request is executed immediately + + :param reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ReservationInstance + """ + data = values.of( + { + "ReservationStatus": reservation_status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ReservationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ReservationPage: + """ + Retrieve a specific page of ReservationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ReservationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ReservationPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ReservationPage: + """ + Asynchronously retrieve a specific page of ReservationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ReservationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ReservationPage(self._version, response, self._solution) + + def get(self, sid: str) -> ReservationContext: + """ + Constructs a ReservationContext + + :param sid: The SID of the WorkerReservation resource to update. + """ + return ReservationContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> ReservationContext: + """ + Constructs a ReservationContext + + :param sid: The SID of the WorkerReservation resource to update. + """ + return ReservationContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py new file mode 100644 index 00000000..6e3cc9c1 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py @@ -0,0 +1,594 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class WorkerChannelInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Worker resource. + :ivar assigned_tasks: The total number of Tasks assigned to Worker for the TaskChannel type. + :ivar available: Whether the Worker should receive Tasks of the TaskChannel type. + :ivar available_capacity_percentage: The current percentage of capacity the TaskChannel has available. Can be a number between `0` and `100`. A value of `0` indicates that TaskChannel has no capacity available and a value of `100` means the Worker is available to receive any Tasks of this TaskChannel type. + :ivar configured_capacity: The current configured capacity for the WorkerChannel. TaskRouter will not create any reservations after the assigned Tasks for the Worker reaches the value. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar sid: The unique string that we created to identify the WorkerChannel resource. + :ivar task_channel_sid: The SID of the TaskChannel. + :ivar task_channel_unique_name: The unique name of the TaskChannel, such as `voice` or `sms`. + :ivar worker_sid: The SID of the Worker that contains the WorkerChannel. + :ivar workspace_sid: The SID of the Workspace that contains the WorkerChannel. + :ivar url: The absolute URL of the WorkerChannel resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + worker_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.assigned_tasks: Optional[int] = deserialize.integer( + payload.get("assigned_tasks") + ) + self.available: Optional[bool] = payload.get("available") + self.available_capacity_percentage: Optional[int] = deserialize.integer( + payload.get("available_capacity_percentage") + ) + self.configured_capacity: Optional[int] = deserialize.integer( + payload.get("configured_capacity") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.sid: Optional[str] = payload.get("sid") + self.task_channel_sid: Optional[str] = payload.get("task_channel_sid") + self.task_channel_unique_name: Optional[str] = payload.get( + "task_channel_unique_name" + ) + self.worker_sid: Optional[str] = payload.get("worker_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + "sid": sid or self.sid, + } + self._context: Optional[WorkerChannelContext] = None + + @property + def _proxy(self) -> "WorkerChannelContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkerChannelContext for this WorkerChannelInstance + """ + if self._context is None: + self._context = WorkerChannelContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "WorkerChannelInstance": + """ + Fetch the WorkerChannelInstance + + + :returns: The fetched WorkerChannelInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "WorkerChannelInstance": + """ + Asynchronous coroutine to fetch the WorkerChannelInstance + + + :returns: The fetched WorkerChannelInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> "WorkerChannelInstance": + """ + Update the WorkerChannelInstance + + :param capacity: The total number of Tasks that the Worker should handle for the TaskChannel type. TaskRouter creates reservations for Tasks of this TaskChannel type up to the specified capacity. If the capacity is 0, no new reservations will be created. + :param available: Whether the WorkerChannel is available. Set to `false` to prevent the Worker from receiving any new Tasks of this TaskChannel type. + + :returns: The updated WorkerChannelInstance + """ + return self._proxy.update( + capacity=capacity, + available=available, + ) + + async def update_async( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> "WorkerChannelInstance": + """ + Asynchronous coroutine to update the WorkerChannelInstance + + :param capacity: The total number of Tasks that the Worker should handle for the TaskChannel type. TaskRouter creates reservations for Tasks of this TaskChannel type up to the specified capacity. If the capacity is 0, no new reservations will be created. + :param available: Whether the WorkerChannel is available. Set to `false` to prevent the Worker from receiving any new Tasks of this TaskChannel type. + + :returns: The updated WorkerChannelInstance + """ + return await self._proxy.update_async( + capacity=capacity, + available=available, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WorkerChannelContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, worker_sid: str, sid: str): + """ + Initialize the WorkerChannelContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the WorkerChannel to update. + :param worker_sid: The SID of the Worker with the WorkerChannel to update. + :param sid: The SID of the WorkerChannel to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + "sid": sid, + } + self._uri = ( + "/Workspaces/{workspace_sid}/Workers/{worker_sid}/Channels/{sid}".format( + **self._solution + ) + ) + + def fetch(self) -> WorkerChannelInstance: + """ + Fetch the WorkerChannelInstance + + + :returns: The fetched WorkerChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WorkerChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> WorkerChannelInstance: + """ + Asynchronous coroutine to fetch the WorkerChannelInstance + + + :returns: The fetched WorkerChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WorkerChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> WorkerChannelInstance: + """ + Update the WorkerChannelInstance + + :param capacity: The total number of Tasks that the Worker should handle for the TaskChannel type. TaskRouter creates reservations for Tasks of this TaskChannel type up to the specified capacity. If the capacity is 0, no new reservations will be created. + :param available: Whether the WorkerChannel is available. Set to `false` to prevent the Worker from receiving any new Tasks of this TaskChannel type. + + :returns: The updated WorkerChannelInstance + """ + + data = values.of( + { + "Capacity": capacity, + "Available": serialize.boolean_to_string(available), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkerChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> WorkerChannelInstance: + """ + Asynchronous coroutine to update the WorkerChannelInstance + + :param capacity: The total number of Tasks that the Worker should handle for the TaskChannel type. TaskRouter creates reservations for Tasks of this TaskChannel type up to the specified capacity. If the capacity is 0, no new reservations will be created. + :param available: Whether the WorkerChannel is available. Set to `false` to prevent the Worker from receiving any new Tasks of this TaskChannel type. + + :returns: The updated WorkerChannelInstance + """ + + data = values.of( + { + "Capacity": capacity, + "Available": serialize.boolean_to_string(available), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkerChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WorkerChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WorkerChannelInstance: + """ + Build an instance of WorkerChannelInstance + + :param payload: Payload response from the API + """ + return WorkerChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class WorkerChannelList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, worker_sid: str): + """ + Initialize the WorkerChannelList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the WorkerChannels to read. + :param worker_sid: The SID of the Worker with the WorkerChannels to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers/{worker_sid}/Channels".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WorkerChannelInstance]: + """ + Streams WorkerChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WorkerChannelInstance]: + """ + Asynchronously streams WorkerChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkerChannelInstance]: + """ + Lists WorkerChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkerChannelInstance]: + """ + Asynchronously lists WorkerChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WorkerChannelPage: + """ + Retrieve a single page of WorkerChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WorkerChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkerChannelPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WorkerChannelPage: + """ + Asynchronously retrieve a single page of WorkerChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WorkerChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkerChannelPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> WorkerChannelPage: + """ + Retrieve a specific page of WorkerChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkerChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return WorkerChannelPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> WorkerChannelPage: + """ + Asynchronously retrieve a specific page of WorkerChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkerChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return WorkerChannelPage(self._version, response, self._solution) + + def get(self, sid: str) -> WorkerChannelContext: + """ + Constructs a WorkerChannelContext + + :param sid: The SID of the WorkerChannel to update. + """ + return WorkerChannelContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> WorkerChannelContext: + """ + Constructs a WorkerChannelContext + + :param sid: The SID of the WorkerChannel to update. + """ + return WorkerChannelContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/worker_statistics.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/worker_statistics.py new file mode 100644 index 00000000..eea670aa --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/worker_statistics.py @@ -0,0 +1,292 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WorkerStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Worker resource. + :ivar cumulative: An object that contains the cumulative statistics for the Worker. + :ivar worker_sid: The SID of the Worker that contains the WorkerChannel. + :ivar workspace_sid: The SID of the Workspace that contains the WorkerChannel. + :ivar url: The absolute URL of the WorkerChannel statistics resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + worker_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.cumulative: Optional[Dict[str, object]] = payload.get("cumulative") + self.worker_sid: Optional[str] = payload.get("worker_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + } + self._context: Optional[WorkerStatisticsContext] = None + + @property + def _proxy(self) -> "WorkerStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkerStatisticsContext for this WorkerStatisticsInstance + """ + if self._context is None: + self._context = WorkerStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) + return self._context + + def fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> "WorkerStatisticsInstance": + """ + Fetch the WorkerStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkerStatisticsInstance + """ + return self._proxy.fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + ) + + async def fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> "WorkerStatisticsInstance": + """ + Asynchronous coroutine to fetch the WorkerStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkerStatisticsInstance + """ + return await self._proxy.fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WorkerStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, worker_sid: str): + """ + Initialize the WorkerStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the WorkerChannel to fetch. + :param worker_sid: The SID of the Worker with the WorkerChannel to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + } + self._uri = ( + "/Workspaces/{workspace_sid}/Workers/{worker_sid}/Statistics".format( + **self._solution + ) + ) + + def fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> WorkerStatisticsInstance: + """ + Fetch the WorkerStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkerStatisticsInstance + """ + + data = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkerStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) + + async def fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> WorkerStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkerStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkerStatisticsInstance + """ + + data = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkerStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WorkerStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, worker_sid: str): + """ + Initialize the WorkerStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the WorkerChannel to fetch. + :param worker_sid: The SID of the Worker with the WorkerChannel to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + } + + def get(self) -> WorkerStatisticsContext: + """ + Constructs a WorkerStatisticsContext + + """ + return WorkerStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) + + def __call__(self) -> WorkerStatisticsContext: + """ + Constructs a WorkerStatisticsContext + + """ + return WorkerStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py new file mode 100644 index 00000000..48a78710 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py @@ -0,0 +1,308 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WorkersCumulativeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Worker resource. + :ivar start_time: The beginning of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar end_time: The end of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar activity_durations: The minimum, average, maximum, and total time (in seconds) that Workers spent in each Activity. + :ivar reservations_created: The total number of Reservations that were created. + :ivar reservations_accepted: The total number of Reservations that were accepted. + :ivar reservations_rejected: The total number of Reservations that were rejected. + :ivar reservations_timed_out: The total number of Reservations that were timed out. + :ivar reservations_canceled: The total number of Reservations that were canceled. + :ivar reservations_rescinded: The total number of Reservations that were rescinded. + :ivar workspace_sid: The SID of the Workspace that contains the Workers. + :ivar url: The absolute URL of the Workers statistics resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.activity_durations: Optional[List[Dict[str, object]]] = payload.get( + "activity_durations" + ) + self.reservations_created: Optional[int] = deserialize.integer( + payload.get("reservations_created") + ) + self.reservations_accepted: Optional[int] = deserialize.integer( + payload.get("reservations_accepted") + ) + self.reservations_rejected: Optional[int] = deserialize.integer( + payload.get("reservations_rejected") + ) + self.reservations_timed_out: Optional[int] = deserialize.integer( + payload.get("reservations_timed_out") + ) + self.reservations_canceled: Optional[int] = deserialize.integer( + payload.get("reservations_canceled") + ) + self.reservations_rescinded: Optional[int] = deserialize.integer( + payload.get("reservations_rescinded") + ) + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + } + self._context: Optional[WorkersCumulativeStatisticsContext] = None + + @property + def _proxy(self) -> "WorkersCumulativeStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkersCumulativeStatisticsContext for this WorkersCumulativeStatisticsInstance + """ + if self._context is None: + self._context = WorkersCumulativeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + ) + return self._context + + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> "WorkersCumulativeStatisticsInstance": + """ + Fetch the WorkersCumulativeStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersCumulativeStatisticsInstance + """ + return self._proxy.fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + ) + + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> "WorkersCumulativeStatisticsInstance": + """ + Asynchronous coroutine to fetch the WorkersCumulativeStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersCumulativeStatisticsInstance + """ + return await self._proxy.fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class WorkersCumulativeStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkersCumulativeStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers/CumulativeStatistics".format( + **self._solution + ) + + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> WorkersCumulativeStatisticsInstance: + """ + Fetch the WorkersCumulativeStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersCumulativeStatisticsInstance + """ + + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkersCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> WorkersCumulativeStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkersCumulativeStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersCumulativeStatisticsInstance + """ + + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkersCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class WorkersCumulativeStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkersCumulativeStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the resource to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + + def get(self) -> WorkersCumulativeStatisticsContext: + """ + Constructs a WorkersCumulativeStatisticsContext + + """ + return WorkersCumulativeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + + def __call__(self) -> WorkersCumulativeStatisticsContext: + """ + Constructs a WorkersCumulativeStatisticsContext + + """ + return WorkersCumulativeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/workers_real_time_statistics.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/workers_real_time_statistics.py new file mode 100644 index 00000000..2e997047 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/workers_real_time_statistics.py @@ -0,0 +1,239 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WorkersRealTimeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Worker resource. + :ivar activity_statistics: The number of current Workers by Activity. + :ivar total_workers: The total number of Workers. + :ivar workspace_sid: The SID of the Workspace that contains the Workers. + :ivar url: The absolute URL of the Workers statistics resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.activity_statistics: Optional[List[Dict[str, object]]] = payload.get( + "activity_statistics" + ) + self.total_workers: Optional[int] = deserialize.integer( + payload.get("total_workers") + ) + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + } + self._context: Optional[WorkersRealTimeStatisticsContext] = None + + @property + def _proxy(self) -> "WorkersRealTimeStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkersRealTimeStatisticsContext for this WorkersRealTimeStatisticsInstance + """ + if self._context is None: + self._context = WorkersRealTimeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + ) + return self._context + + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> "WorkersRealTimeStatisticsInstance": + """ + Fetch the WorkersRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersRealTimeStatisticsInstance + """ + return self._proxy.fetch( + task_channel=task_channel, + ) + + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> "WorkersRealTimeStatisticsInstance": + """ + Asynchronous coroutine to fetch the WorkersRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersRealTimeStatisticsInstance + """ + return await self._proxy.fetch_async( + task_channel=task_channel, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class WorkersRealTimeStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkersRealTimeStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers/RealTimeStatistics".format( + **self._solution + ) + + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> WorkersRealTimeStatisticsInstance: + """ + Fetch the WorkersRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersRealTimeStatisticsInstance + """ + + data = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkersRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> WorkersRealTimeStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkersRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersRealTimeStatisticsInstance + """ + + data = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkersRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class WorkersRealTimeStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkersRealTimeStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the resource to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + + def get(self) -> WorkersRealTimeStatisticsContext: + """ + Constructs a WorkersRealTimeStatisticsContext + + """ + return WorkersRealTimeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + + def __call__(self) -> WorkersRealTimeStatisticsContext: + """ + Constructs a WorkersRealTimeStatisticsContext + + """ + return WorkersRealTimeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py new file mode 100644 index 00000000..31c79ee6 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py @@ -0,0 +1,308 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WorkersStatisticsInstance(InstanceResource): + """ + :ivar realtime: An object that contains the real-time statistics for the Worker. + :ivar cumulative: An object that contains the cumulative statistics for the Worker. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Worker resource. + :ivar workspace_sid: The SID of the Workspace that contains the Worker. + :ivar url: The absolute URL of the Worker statistics resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str): + super().__init__(version) + + self.realtime: Optional[Dict[str, object]] = payload.get("realtime") + self.cumulative: Optional[Dict[str, object]] = payload.get("cumulative") + self.account_sid: Optional[str] = payload.get("account_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + } + self._context: Optional[WorkersStatisticsContext] = None + + @property + def _proxy(self) -> "WorkersStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkersStatisticsContext for this WorkersStatisticsInstance + """ + if self._context is None: + self._context = WorkersStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + ) + return self._context + + def fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> "WorkersStatisticsInstance": + """ + Fetch the WorkersStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_queue_sid: The SID of the TaskQueue for which to fetch Worker statistics. + :param task_queue_name: The `friendly_name` of the TaskQueue for which to fetch Worker statistics. + :param friendly_name: Only include Workers with `friendly_name` values that match this parameter. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersStatisticsInstance + """ + return self._proxy.fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + friendly_name=friendly_name, + task_channel=task_channel, + ) + + async def fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> "WorkersStatisticsInstance": + """ + Asynchronous coroutine to fetch the WorkersStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_queue_sid: The SID of the TaskQueue for which to fetch Worker statistics. + :param task_queue_name: The `friendly_name` of the TaskQueue for which to fetch Worker statistics. + :param friendly_name: Only include Workers with `friendly_name` values that match this parameter. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersStatisticsInstance + """ + return await self._proxy.fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + friendly_name=friendly_name, + task_channel=task_channel, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WorkersStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkersStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Worker to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers/Statistics".format( + **self._solution + ) + + def fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> WorkersStatisticsInstance: + """ + Fetch the WorkersStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_queue_sid: The SID of the TaskQueue for which to fetch Worker statistics. + :param task_queue_name: The `friendly_name` of the TaskQueue for which to fetch Worker statistics. + :param friendly_name: Only include Workers with `friendly_name` values that match this parameter. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersStatisticsInstance + """ + + data = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskQueueSid": task_queue_sid, + "TaskQueueName": task_queue_name, + "FriendlyName": friendly_name, + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkersStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + async def fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> WorkersStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkersStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_queue_sid: The SID of the TaskQueue for which to fetch Worker statistics. + :param task_queue_name: The `friendly_name` of the TaskQueue for which to fetch Worker statistics. + :param friendly_name: Only include Workers with `friendly_name` values that match this parameter. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersStatisticsInstance + """ + + data = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskQueueSid": task_queue_sid, + "TaskQueueName": task_queue_name, + "FriendlyName": friendly_name, + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkersStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WorkersStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkersStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Worker to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + + def get(self) -> WorkersStatisticsContext: + """ + Constructs a WorkersStatisticsContext + + """ + return WorkersStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + + def __call__(self) -> WorkersStatisticsContext: + """ + Constructs a WorkersStatisticsContext + + """ + return WorkersStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py new file mode 100644 index 00000000..619ae1bc --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py @@ -0,0 +1,837 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics import ( + WorkflowCumulativeStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics import ( + WorkflowRealTimeStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics import ( + WorkflowStatisticsList, +) + + +class WorkflowInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workflow resource. + :ivar assignment_callback_url: The URL that we call when a task managed by the Workflow is assigned to a Worker. See Assignment Callback URL for more information. + :ivar configuration: A JSON string that contains the Workflow's configuration. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar document_content_type: The MIME type of the document. + :ivar fallback_assignment_callback_url: The URL that we call when a call to the `assignment_callback_url` fails. + :ivar friendly_name: The string that you assigned to describe the Workflow resource. For example, `Customer Support` or `2014 Election Campaign`. + :ivar sid: The unique string that we created to identify the Workflow resource. + :ivar task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + :ivar workspace_sid: The SID of the Workspace that contains the Workflow. + :ivar url: The absolute URL of the Workflow resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.assignment_callback_url: Optional[str] = payload.get( + "assignment_callback_url" + ) + self.configuration: Optional[str] = payload.get("configuration") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.document_content_type: Optional[str] = payload.get("document_content_type") + self.fallback_assignment_callback_url: Optional[str] = payload.get( + "fallback_assignment_callback_url" + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.sid: Optional[str] = payload.get("sid") + self.task_reservation_timeout: Optional[int] = deserialize.integer( + payload.get("task_reservation_timeout") + ) + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid or self.sid, + } + self._context: Optional[WorkflowContext] = None + + @property + def _proxy(self) -> "WorkflowContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkflowContext for this WorkflowInstance + """ + if self._context is None: + self._context = WorkflowContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the WorkflowInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WorkflowInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "WorkflowInstance": + """ + Fetch the WorkflowInstance + + + :returns: The fetched WorkflowInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "WorkflowInstance": + """ + Asynchronous coroutine to fetch the WorkflowInstance + + + :returns: The fetched WorkflowInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + re_evaluate_tasks: Union[str, object] = values.unset, + ) -> "WorkflowInstance": + """ + Update the WorkflowInstance + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + :param re_evaluate_tasks: Whether or not to re-evaluate Tasks. The default is `false`, which means Tasks in the Workflow will not be processed through the assignment loop again. + + :returns: The updated WorkflowInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + configuration=configuration, + task_reservation_timeout=task_reservation_timeout, + re_evaluate_tasks=re_evaluate_tasks, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + re_evaluate_tasks: Union[str, object] = values.unset, + ) -> "WorkflowInstance": + """ + Asynchronous coroutine to update the WorkflowInstance + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + :param re_evaluate_tasks: Whether or not to re-evaluate Tasks. The default is `false`, which means Tasks in the Workflow will not be processed through the assignment loop again. + + :returns: The updated WorkflowInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + configuration=configuration, + task_reservation_timeout=task_reservation_timeout, + re_evaluate_tasks=re_evaluate_tasks, + ) + + @property + def cumulative_statistics(self) -> WorkflowCumulativeStatisticsList: + """ + Access the cumulative_statistics + """ + return self._proxy.cumulative_statistics + + @property + def real_time_statistics(self) -> WorkflowRealTimeStatisticsList: + """ + Access the real_time_statistics + """ + return self._proxy.real_time_statistics + + @property + def statistics(self) -> WorkflowStatisticsList: + """ + Access the statistics + """ + return self._proxy.statistics + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WorkflowContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, sid: str): + """ + Initialize the WorkflowContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Workflow to update. + :param sid: The SID of the Workflow resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workflows/{sid}".format( + **self._solution + ) + + self._cumulative_statistics: Optional[WorkflowCumulativeStatisticsList] = None + self._real_time_statistics: Optional[WorkflowRealTimeStatisticsList] = None + self._statistics: Optional[WorkflowStatisticsList] = None + + def delete(self) -> bool: + """ + Deletes the WorkflowInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WorkflowInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> WorkflowInstance: + """ + Fetch the WorkflowInstance + + + :returns: The fetched WorkflowInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WorkflowInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> WorkflowInstance: + """ + Asynchronous coroutine to fetch the WorkflowInstance + + + :returns: The fetched WorkflowInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WorkflowInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + re_evaluate_tasks: Union[str, object] = values.unset, + ) -> WorkflowInstance: + """ + Update the WorkflowInstance + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + :param re_evaluate_tasks: Whether or not to re-evaluate Tasks. The default is `false`, which means Tasks in the Workflow will not be processed through the assignment loop again. + + :returns: The updated WorkflowInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "AssignmentCallbackUrl": assignment_callback_url, + "FallbackAssignmentCallbackUrl": fallback_assignment_callback_url, + "Configuration": configuration, + "TaskReservationTimeout": task_reservation_timeout, + "ReEvaluateTasks": re_evaluate_tasks, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkflowInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + re_evaluate_tasks: Union[str, object] = values.unset, + ) -> WorkflowInstance: + """ + Asynchronous coroutine to update the WorkflowInstance + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + :param re_evaluate_tasks: Whether or not to re-evaluate Tasks. The default is `false`, which means Tasks in the Workflow will not be processed through the assignment loop again. + + :returns: The updated WorkflowInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "AssignmentCallbackUrl": assignment_callback_url, + "FallbackAssignmentCallbackUrl": fallback_assignment_callback_url, + "Configuration": configuration, + "TaskReservationTimeout": task_reservation_timeout, + "ReEvaluateTasks": re_evaluate_tasks, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkflowInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + @property + def cumulative_statistics(self) -> WorkflowCumulativeStatisticsList: + """ + Access the cumulative_statistics + """ + if self._cumulative_statistics is None: + self._cumulative_statistics = WorkflowCumulativeStatisticsList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._cumulative_statistics + + @property + def real_time_statistics(self) -> WorkflowRealTimeStatisticsList: + """ + Access the real_time_statistics + """ + if self._real_time_statistics is None: + self._real_time_statistics = WorkflowRealTimeStatisticsList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._real_time_statistics + + @property + def statistics(self) -> WorkflowStatisticsList: + """ + Access the statistics + """ + if self._statistics is None: + self._statistics = WorkflowStatisticsList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._statistics + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WorkflowPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WorkflowInstance: + """ + Build an instance of WorkflowInstance + + :param payload: Payload response from the API + """ + return WorkflowInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class WorkflowList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkflowList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Workflow to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workflows".format(**self._solution) + + def create( + self, + friendly_name: str, + configuration: str, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + ) -> WorkflowInstance: + """ + Create the WorkflowInstance + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + + :returns: The created WorkflowInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Configuration": configuration, + "AssignmentCallbackUrl": assignment_callback_url, + "FallbackAssignmentCallbackUrl": fallback_assignment_callback_url, + "TaskReservationTimeout": task_reservation_timeout, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkflowInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_async( + self, + friendly_name: str, + configuration: str, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + ) -> WorkflowInstance: + """ + Asynchronously create the WorkflowInstance + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + + :returns: The created WorkflowInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Configuration": configuration, + "AssignmentCallbackUrl": assignment_callback_url, + "FallbackAssignmentCallbackUrl": fallback_assignment_callback_url, + "TaskReservationTimeout": task_reservation_timeout, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkflowInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WorkflowInstance]: + """ + Streams WorkflowInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the Workflow resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(friendly_name=friendly_name, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WorkflowInstance]: + """ + Asynchronously streams WorkflowInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the Workflow resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkflowInstance]: + """ + Lists WorkflowInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the Workflow resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkflowInstance]: + """ + Asynchronously lists WorkflowInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the Workflow resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WorkflowPage: + """ + Retrieve a single page of WorkflowInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the Workflow resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WorkflowInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkflowPage(self._version, response, self._solution) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WorkflowPage: + """ + Asynchronously retrieve a single page of WorkflowInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the Workflow resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WorkflowInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkflowPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> WorkflowPage: + """ + Retrieve a specific page of WorkflowInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkflowInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return WorkflowPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> WorkflowPage: + """ + Asynchronously retrieve a specific page of WorkflowInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkflowInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return WorkflowPage(self._version, response, self._solution) + + def get(self, sid: str) -> WorkflowContext: + """ + Constructs a WorkflowContext + + :param sid: The SID of the Workflow resource to update. + """ + return WorkflowContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __call__(self, sid: str) -> WorkflowContext: + """ + Constructs a WorkflowContext + + :param sid: The SID of the Workflow resource to update. + """ + return WorkflowContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workflow/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workflow/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..22fde69f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workflow/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workflow/__pycache__/workflow_cumulative_statistics.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workflow/__pycache__/workflow_cumulative_statistics.cpython-312.pyc new file mode 100644 index 00000000..1332a2b2 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workflow/__pycache__/workflow_cumulative_statistics.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workflow/__pycache__/workflow_real_time_statistics.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workflow/__pycache__/workflow_real_time_statistics.cpython-312.pyc new file mode 100644 index 00000000..9363897b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workflow/__pycache__/workflow_real_time_statistics.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workflow/__pycache__/workflow_statistics.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workflow/__pycache__/workflow_statistics.cpython-312.pyc new file mode 100644 index 00000000..6eef3793 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workflow/__pycache__/workflow_statistics.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workflow/workflow_cumulative_statistics.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workflow/workflow_cumulative_statistics.py new file mode 100644 index 00000000..d6d7c094 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workflow/workflow_cumulative_statistics.py @@ -0,0 +1,376 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WorkflowCumulativeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workflow resource. + :ivar avg_task_acceptance_time: The average time in seconds between Task creation and acceptance. + :ivar start_time: The beginning of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar end_time: The end of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar reservations_created: The total number of Reservations that were created for Workers. + :ivar reservations_accepted: The total number of Reservations accepted by Workers. + :ivar reservations_rejected: The total number of Reservations that were rejected. + :ivar reservations_timed_out: The total number of Reservations that were timed out. + :ivar reservations_canceled: The total number of Reservations that were canceled. + :ivar reservations_rescinded: The total number of Reservations that were rescinded. + :ivar split_by_wait_time: A list of objects that describe the number of Tasks canceled and reservations accepted above and below the thresholds specified in seconds. + :ivar wait_duration_until_accepted: The wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks that were accepted. + :ivar wait_duration_until_canceled: The wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks that were canceled. + :ivar tasks_canceled: The total number of Tasks that were canceled. + :ivar tasks_completed: The total number of Tasks that were completed. + :ivar tasks_entered: The total number of Tasks that entered the Workflow. + :ivar tasks_deleted: The total number of Tasks that were deleted. + :ivar tasks_moved: The total number of Tasks that were moved from one queue to another. + :ivar tasks_timed_out_in_workflow: The total number of Tasks that were timed out of their Workflows (and deleted). + :ivar workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified Sid value. + :ivar workspace_sid: The SID of the Workspace that contains the Workflow. + :ivar url: The absolute URL of the Workflow statistics resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + workflow_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.avg_task_acceptance_time: Optional[int] = deserialize.integer( + payload.get("avg_task_acceptance_time") + ) + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.reservations_created: Optional[int] = deserialize.integer( + payload.get("reservations_created") + ) + self.reservations_accepted: Optional[int] = deserialize.integer( + payload.get("reservations_accepted") + ) + self.reservations_rejected: Optional[int] = deserialize.integer( + payload.get("reservations_rejected") + ) + self.reservations_timed_out: Optional[int] = deserialize.integer( + payload.get("reservations_timed_out") + ) + self.reservations_canceled: Optional[int] = deserialize.integer( + payload.get("reservations_canceled") + ) + self.reservations_rescinded: Optional[int] = deserialize.integer( + payload.get("reservations_rescinded") + ) + self.split_by_wait_time: Optional[Dict[str, object]] = payload.get( + "split_by_wait_time" + ) + self.wait_duration_until_accepted: Optional[Dict[str, object]] = payload.get( + "wait_duration_until_accepted" + ) + self.wait_duration_until_canceled: Optional[Dict[str, object]] = payload.get( + "wait_duration_until_canceled" + ) + self.tasks_canceled: Optional[int] = deserialize.integer( + payload.get("tasks_canceled") + ) + self.tasks_completed: Optional[int] = deserialize.integer( + payload.get("tasks_completed") + ) + self.tasks_entered: Optional[int] = deserialize.integer( + payload.get("tasks_entered") + ) + self.tasks_deleted: Optional[int] = deserialize.integer( + payload.get("tasks_deleted") + ) + self.tasks_moved: Optional[int] = deserialize.integer( + payload.get("tasks_moved") + ) + self.tasks_timed_out_in_workflow: Optional[int] = deserialize.integer( + payload.get("tasks_timed_out_in_workflow") + ) + self.workflow_sid: Optional[str] = payload.get("workflow_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } + self._context: Optional[WorkflowCumulativeStatisticsContext] = None + + @property + def _proxy(self) -> "WorkflowCumulativeStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkflowCumulativeStatisticsContext for this WorkflowCumulativeStatisticsInstance + """ + if self._context is None: + self._context = WorkflowCumulativeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return self._context + + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "WorkflowCumulativeStatisticsInstance": + """ + Fetch the WorkflowCumulativeStatisticsInstance + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: The fetched WorkflowCumulativeStatisticsInstance + """ + return self._proxy.fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "WorkflowCumulativeStatisticsInstance": + """ + Asynchronous coroutine to fetch the WorkflowCumulativeStatisticsInstance + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: The fetched WorkflowCumulativeStatisticsInstance + """ + return await self._proxy.fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class WorkflowCumulativeStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): + """ + Initialize the WorkflowCumulativeStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the resource to fetch. + :param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified Sid value. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workflows/{workflow_sid}/CumulativeStatistics".format( + **self._solution + ) + + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkflowCumulativeStatisticsInstance: + """ + Fetch the WorkflowCumulativeStatisticsInstance + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: The fetched WorkflowCumulativeStatisticsInstance + """ + + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkflowCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkflowCumulativeStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkflowCumulativeStatisticsInstance + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: The fetched WorkflowCumulativeStatisticsInstance + """ + + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkflowCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class WorkflowCumulativeStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): + """ + Initialize the WorkflowCumulativeStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the resource to fetch. + :param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified Sid value. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } + + def get(self) -> WorkflowCumulativeStatisticsContext: + """ + Constructs a WorkflowCumulativeStatisticsContext + + """ + return WorkflowCumulativeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + + def __call__(self) -> WorkflowCumulativeStatisticsContext: + """ + Constructs a WorkflowCumulativeStatisticsContext + + """ + return WorkflowCumulativeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workflow/workflow_real_time_statistics.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workflow/workflow_real_time_statistics.py new file mode 100644 index 00000000..93876225 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workflow/workflow_real_time_statistics.py @@ -0,0 +1,271 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WorkflowRealTimeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workflow resource. + :ivar longest_task_waiting_age: The age of the longest waiting Task. + :ivar longest_task_waiting_sid: The SID of the longest waiting Task. + :ivar tasks_by_priority: The number of Tasks by priority. For example: `{\"0\": \"10\", \"99\": \"5\"}` shows 10 Tasks at priority 0 and 5 at priority 99. + :ivar tasks_by_status: The number of Tasks by their current status. For example: `{\"pending\": \"1\", \"reserved\": \"3\", \"assigned\": \"2\", \"completed\": \"5\"}`. + :ivar total_tasks: The total number of Tasks. + :ivar workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value. + :ivar workspace_sid: The SID of the Workspace that contains the Workflow. + :ivar url: The absolute URL of the Workflow statistics resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + workflow_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.longest_task_waiting_age: Optional[int] = deserialize.integer( + payload.get("longest_task_waiting_age") + ) + self.longest_task_waiting_sid: Optional[str] = payload.get( + "longest_task_waiting_sid" + ) + self.tasks_by_priority: Optional[Dict[str, object]] = payload.get( + "tasks_by_priority" + ) + self.tasks_by_status: Optional[Dict[str, object]] = payload.get( + "tasks_by_status" + ) + self.total_tasks: Optional[int] = deserialize.integer( + payload.get("total_tasks") + ) + self.workflow_sid: Optional[str] = payload.get("workflow_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } + self._context: Optional[WorkflowRealTimeStatisticsContext] = None + + @property + def _proxy(self) -> "WorkflowRealTimeStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkflowRealTimeStatisticsContext for this WorkflowRealTimeStatisticsInstance + """ + if self._context is None: + self._context = WorkflowRealTimeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return self._context + + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> "WorkflowRealTimeStatisticsInstance": + """ + Fetch the WorkflowRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkflowRealTimeStatisticsInstance + """ + return self._proxy.fetch( + task_channel=task_channel, + ) + + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> "WorkflowRealTimeStatisticsInstance": + """ + Asynchronous coroutine to fetch the WorkflowRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkflowRealTimeStatisticsInstance + """ + return await self._proxy.fetch_async( + task_channel=task_channel, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class WorkflowRealTimeStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): + """ + Initialize the WorkflowRealTimeStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Workflow to fetch. + :param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workflows/{workflow_sid}/RealTimeStatistics".format( + **self._solution + ) + + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> WorkflowRealTimeStatisticsInstance: + """ + Fetch the WorkflowRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkflowRealTimeStatisticsInstance + """ + + data = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkflowRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> WorkflowRealTimeStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkflowRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkflowRealTimeStatisticsInstance + """ + + data = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkflowRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class WorkflowRealTimeStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): + """ + Initialize the WorkflowRealTimeStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Workflow to fetch. + :param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } + + def get(self) -> WorkflowRealTimeStatisticsContext: + """ + Constructs a WorkflowRealTimeStatisticsContext + + """ + return WorkflowRealTimeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + + def __call__(self) -> WorkflowRealTimeStatisticsContext: + """ + Constructs a WorkflowRealTimeStatisticsContext + + """ + return WorkflowRealTimeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py new file mode 100644 index 00000000..e49bd32d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py @@ -0,0 +1,306 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WorkflowStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workflow resource. + :ivar cumulative: An object that contains the cumulative statistics for the Workflow. + :ivar realtime: An object that contains the real-time statistics for the Workflow. + :ivar workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value. + :ivar workspace_sid: The SID of the Workspace that contains the Workflow. + :ivar url: The absolute URL of the Workflow statistics resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + workflow_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.cumulative: Optional[Dict[str, object]] = payload.get("cumulative") + self.realtime: Optional[Dict[str, object]] = payload.get("realtime") + self.workflow_sid: Optional[str] = payload.get("workflow_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } + self._context: Optional[WorkflowStatisticsContext] = None + + @property + def _proxy(self) -> "WorkflowStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkflowStatisticsContext for this WorkflowStatisticsInstance + """ + if self._context is None: + self._context = WorkflowStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return self._context + + def fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "WorkflowStatisticsInstance": + """ + Fetch the WorkflowStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: The fetched WorkflowStatisticsInstance + """ + return self._proxy.fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + async def fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "WorkflowStatisticsInstance": + """ + Asynchronous coroutine to fetch the WorkflowStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: The fetched WorkflowStatisticsInstance + """ + return await self._proxy.fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WorkflowStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): + """ + Initialize the WorkflowStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Workflow to fetch. + :param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } + self._uri = ( + "/Workspaces/{workspace_sid}/Workflows/{workflow_sid}/Statistics".format( + **self._solution + ) + ) + + def fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkflowStatisticsInstance: + """ + Fetch the WorkflowStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: The fetched WorkflowStatisticsInstance + """ + + data = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkflowStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + + async def fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkflowStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkflowStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: The fetched WorkflowStatisticsInstance + """ + + data = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkflowStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WorkflowStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): + """ + Initialize the WorkflowStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Workflow to fetch. + :param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } + + def get(self) -> WorkflowStatisticsContext: + """ + Constructs a WorkflowStatisticsContext + + """ + return WorkflowStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + + def __call__(self) -> WorkflowStatisticsContext: + """ + Constructs a WorkflowStatisticsContext + + """ + return WorkflowStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py new file mode 100644 index 00000000..3747b395 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py @@ -0,0 +1,356 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WorkspaceCumulativeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workspace resource. + :ivar avg_task_acceptance_time: The average time in seconds between Task creation and acceptance. + :ivar start_time: The beginning of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar end_time: The end of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar reservations_created: The total number of Reservations that were created for Workers. + :ivar reservations_accepted: The total number of Reservations accepted by Workers. + :ivar reservations_rejected: The total number of Reservations that were rejected. + :ivar reservations_timed_out: The total number of Reservations that were timed out. + :ivar reservations_canceled: The total number of Reservations that were canceled. + :ivar reservations_rescinded: The total number of Reservations that were rescinded. + :ivar split_by_wait_time: A list of objects that describe the number of Tasks canceled and reservations accepted above and below the thresholds specified in seconds. + :ivar wait_duration_until_accepted: The wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks that were accepted. + :ivar wait_duration_until_canceled: The wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks that were canceled. + :ivar tasks_canceled: The total number of Tasks that were canceled. + :ivar tasks_completed: The total number of Tasks that were completed. + :ivar tasks_created: The total number of Tasks created. + :ivar tasks_deleted: The total number of Tasks that were deleted. + :ivar tasks_moved: The total number of Tasks that were moved from one queue to another. + :ivar tasks_timed_out_in_workflow: The total number of Tasks that were timed out of their Workflows (and deleted). + :ivar workspace_sid: The SID of the Workspace. + :ivar url: The absolute URL of the Workspace statistics resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.avg_task_acceptance_time: Optional[int] = deserialize.integer( + payload.get("avg_task_acceptance_time") + ) + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.reservations_created: Optional[int] = deserialize.integer( + payload.get("reservations_created") + ) + self.reservations_accepted: Optional[int] = deserialize.integer( + payload.get("reservations_accepted") + ) + self.reservations_rejected: Optional[int] = deserialize.integer( + payload.get("reservations_rejected") + ) + self.reservations_timed_out: Optional[int] = deserialize.integer( + payload.get("reservations_timed_out") + ) + self.reservations_canceled: Optional[int] = deserialize.integer( + payload.get("reservations_canceled") + ) + self.reservations_rescinded: Optional[int] = deserialize.integer( + payload.get("reservations_rescinded") + ) + self.split_by_wait_time: Optional[Dict[str, object]] = payload.get( + "split_by_wait_time" + ) + self.wait_duration_until_accepted: Optional[Dict[str, object]] = payload.get( + "wait_duration_until_accepted" + ) + self.wait_duration_until_canceled: Optional[Dict[str, object]] = payload.get( + "wait_duration_until_canceled" + ) + self.tasks_canceled: Optional[int] = deserialize.integer( + payload.get("tasks_canceled") + ) + self.tasks_completed: Optional[int] = deserialize.integer( + payload.get("tasks_completed") + ) + self.tasks_created: Optional[int] = deserialize.integer( + payload.get("tasks_created") + ) + self.tasks_deleted: Optional[int] = deserialize.integer( + payload.get("tasks_deleted") + ) + self.tasks_moved: Optional[int] = deserialize.integer( + payload.get("tasks_moved") + ) + self.tasks_timed_out_in_workflow: Optional[int] = deserialize.integer( + payload.get("tasks_timed_out_in_workflow") + ) + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + } + self._context: Optional[WorkspaceCumulativeStatisticsContext] = None + + @property + def _proxy(self) -> "WorkspaceCumulativeStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkspaceCumulativeStatisticsContext for this WorkspaceCumulativeStatisticsInstance + """ + if self._context is None: + self._context = WorkspaceCumulativeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + ) + return self._context + + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "WorkspaceCumulativeStatisticsInstance": + """ + Fetch the WorkspaceCumulativeStatisticsInstance + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: The fetched WorkspaceCumulativeStatisticsInstance + """ + return self._proxy.fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "WorkspaceCumulativeStatisticsInstance": + """ + Asynchronous coroutine to fetch the WorkspaceCumulativeStatisticsInstance + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: The fetched WorkspaceCumulativeStatisticsInstance + """ + return await self._proxy.fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class WorkspaceCumulativeStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkspaceCumulativeStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/CumulativeStatistics".format( + **self._solution + ) + + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkspaceCumulativeStatisticsInstance: + """ + Fetch the WorkspaceCumulativeStatisticsInstance + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: The fetched WorkspaceCumulativeStatisticsInstance + """ + + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkspaceCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkspaceCumulativeStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkspaceCumulativeStatisticsInstance + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: The fetched WorkspaceCumulativeStatisticsInstance + """ + + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkspaceCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class WorkspaceCumulativeStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkspaceCumulativeStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + + def get(self) -> WorkspaceCumulativeStatisticsContext: + """ + Constructs a WorkspaceCumulativeStatisticsContext + + """ + return WorkspaceCumulativeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + + def __call__(self) -> WorkspaceCumulativeStatisticsContext: + """ + Constructs a WorkspaceCumulativeStatisticsContext + + """ + return WorkspaceCumulativeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workspace_real_time_statistics.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workspace_real_time_statistics.py new file mode 100644 index 00000000..923a94bf --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workspace_real_time_statistics.py @@ -0,0 +1,259 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WorkspaceRealTimeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workspace resource. + :ivar activity_statistics: The number of current Workers by Activity. + :ivar longest_task_waiting_age: The age of the longest waiting Task. + :ivar longest_task_waiting_sid: The SID of the longest waiting Task. + :ivar tasks_by_priority: The number of Tasks by priority. For example: `{\"0\": \"10\", \"99\": \"5\"}` shows 10 Tasks at priority 0 and 5 at priority 99. + :ivar tasks_by_status: The number of Tasks by their current status. For example: `{\"pending\": \"1\", \"reserved\": \"3\", \"assigned\": \"2\", \"completed\": \"5\"}`. + :ivar total_tasks: The total number of Tasks. + :ivar total_workers: The total number of Workers in the Workspace. + :ivar workspace_sid: The SID of the Workspace. + :ivar url: The absolute URL of the Workspace statistics resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.activity_statistics: Optional[List[Dict[str, object]]] = payload.get( + "activity_statistics" + ) + self.longest_task_waiting_age: Optional[int] = deserialize.integer( + payload.get("longest_task_waiting_age") + ) + self.longest_task_waiting_sid: Optional[str] = payload.get( + "longest_task_waiting_sid" + ) + self.tasks_by_priority: Optional[Dict[str, object]] = payload.get( + "tasks_by_priority" + ) + self.tasks_by_status: Optional[Dict[str, object]] = payload.get( + "tasks_by_status" + ) + self.total_tasks: Optional[int] = deserialize.integer( + payload.get("total_tasks") + ) + self.total_workers: Optional[int] = deserialize.integer( + payload.get("total_workers") + ) + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + } + self._context: Optional[WorkspaceRealTimeStatisticsContext] = None + + @property + def _proxy(self) -> "WorkspaceRealTimeStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkspaceRealTimeStatisticsContext for this WorkspaceRealTimeStatisticsInstance + """ + if self._context is None: + self._context = WorkspaceRealTimeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + ) + return self._context + + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> "WorkspaceRealTimeStatisticsInstance": + """ + Fetch the WorkspaceRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkspaceRealTimeStatisticsInstance + """ + return self._proxy.fetch( + task_channel=task_channel, + ) + + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> "WorkspaceRealTimeStatisticsInstance": + """ + Asynchronous coroutine to fetch the WorkspaceRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkspaceRealTimeStatisticsInstance + """ + return await self._proxy.fetch_async( + task_channel=task_channel, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class WorkspaceRealTimeStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkspaceRealTimeStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/RealTimeStatistics".format( + **self._solution + ) + + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> WorkspaceRealTimeStatisticsInstance: + """ + Fetch the WorkspaceRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkspaceRealTimeStatisticsInstance + """ + + data = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkspaceRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> WorkspaceRealTimeStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkspaceRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkspaceRealTimeStatisticsInstance + """ + + data = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkspaceRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class WorkspaceRealTimeStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkspaceRealTimeStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + + def get(self) -> WorkspaceRealTimeStatisticsContext: + """ + Constructs a WorkspaceRealTimeStatisticsContext + + """ + return WorkspaceRealTimeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + + def __call__(self) -> WorkspaceRealTimeStatisticsContext: + """ + Constructs a WorkspaceRealTimeStatisticsContext + + """ + return WorkspaceRealTimeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py new file mode 100644 index 00000000..b8414a5c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py @@ -0,0 +1,282 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WorkspaceStatisticsInstance(InstanceResource): + """ + :ivar realtime: An object that contains the real-time statistics for the Workspace. + :ivar cumulative: An object that contains the cumulative statistics for the Workspace. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workspace resource. + :ivar workspace_sid: The SID of the Workspace. + :ivar url: The absolute URL of the Workspace statistics resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str): + super().__init__(version) + + self.realtime: Optional[Dict[str, object]] = payload.get("realtime") + self.cumulative: Optional[Dict[str, object]] = payload.get("cumulative") + self.account_sid: Optional[str] = payload.get("account_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + } + self._context: Optional[WorkspaceStatisticsContext] = None + + @property + def _proxy(self) -> "WorkspaceStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkspaceStatisticsContext for this WorkspaceStatisticsInstance + """ + if self._context is None: + self._context = WorkspaceStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + ) + return self._context + + def fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "WorkspaceStatisticsInstance": + """ + Fetch the WorkspaceStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: The fetched WorkspaceStatisticsInstance + """ + return self._proxy.fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + async def fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "WorkspaceStatisticsInstance": + """ + Asynchronous coroutine to fetch the WorkspaceStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: The fetched WorkspaceStatisticsInstance + """ + return await self._proxy.fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WorkspaceStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkspaceStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Statistics".format(**self._solution) + + def fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkspaceStatisticsInstance: + """ + Fetch the WorkspaceStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: The fetched WorkspaceStatisticsInstance + """ + + data = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkspaceStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + async def fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkspaceStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkspaceStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: The fetched WorkspaceStatisticsInstance + """ + + data = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkspaceStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WorkspaceStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkspaceStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + + def get(self) -> WorkspaceStatisticsContext: + """ + Constructs a WorkspaceStatisticsContext + + """ + return WorkspaceStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + + def __call__(self) -> WorkspaceStatisticsContext: + """ + Constructs a WorkspaceStatisticsContext + + """ + return WorkspaceStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trunking/TrunkingBase.py b/venv/Lib/site-packages/twilio/rest/trunking/TrunkingBase.py new file mode 100644 index 00000000..bed8f9a2 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trunking/TrunkingBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.trunking.v1 import V1 + + +class TrunkingBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Trunking Domain + + :returns: Domain for Trunking + """ + super().__init__(twilio, "https://trunking.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Trunking + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trunking/__init__.py b/venv/Lib/site-packages/twilio/rest/trunking/__init__.py new file mode 100644 index 00000000..14bd6be6 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trunking/__init__.py @@ -0,0 +1,15 @@ +from warnings import warn + +from twilio.rest.trunking.TrunkingBase import TrunkingBase +from twilio.rest.trunking.v1.trunk import TrunkList + + +class Trunking(TrunkingBase): + @property + def trunks(self) -> TrunkList: + warn( + "trunks is deprecated. Use v1.trunks instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.trunks diff --git a/venv/Lib/site-packages/twilio/rest/trunking/__pycache__/TrunkingBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trunking/__pycache__/TrunkingBase.cpython-312.pyc new file mode 100644 index 00000000..f0b43abb Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trunking/__pycache__/TrunkingBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trunking/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trunking/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..fd43e40e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trunking/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trunking/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/trunking/v1/__init__.py new file mode 100644 index 00000000..af530b97 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trunking/v1/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trunking + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.trunking.v1.trunk import TrunkList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Trunking + + :param domain: The Twilio.trunking domain + """ + super().__init__(domain, "v1") + self._trunks: Optional[TrunkList] = None + + @property + def trunks(self) -> TrunkList: + if self._trunks is None: + self._trunks = TrunkList(self) + return self._trunks + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trunking/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trunking/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..4f410c24 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trunking/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/__init__.py b/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/__init__.py new file mode 100644 index 00000000..6a93a832 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/__init__.py @@ -0,0 +1,887 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trunking + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.trunking.v1.trunk.credential_list import CredentialListList +from twilio.rest.trunking.v1.trunk.ip_access_control_list import IpAccessControlListList +from twilio.rest.trunking.v1.trunk.origination_url import OriginationUrlList +from twilio.rest.trunking.v1.trunk.phone_number import PhoneNumberList +from twilio.rest.trunking.v1.trunk.recording import RecordingList + + +class TrunkInstance(InstanceResource): + + class TransferCallerId(object): + FROM_TRANSFEREE = "from-transferee" + FROM_TRANSFEROR = "from-transferor" + + class TransferSetting(object): + DISABLE_ALL = "disable-all" + ENABLE_ALL = "enable-all" + SIP_ONLY = "sip-only" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Trunk resource. + :ivar domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :ivar disaster_recovery_method: The HTTP method we use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :ivar disaster_recovery_url: The URL we call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from this URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :ivar recording: The recording settings for the trunk. Can be: `do-not-record`, `record-from-ringing`, `record-from-answer`. If set to `record-from-ringing` or `record-from-answer`, all calls going through the trunk will be recorded. The only way to change recording parameters is on a sub-resource of a Trunk after it has been created. e.g.`/Trunks/[Trunk_SID]/Recording -XPOST -d'Mode=record-from-answer'`. See [Recording](https://www.twilio.com/docs/sip-trunking#recording) for more information. + :ivar transfer_mode: + :ivar transfer_caller_id: + :ivar cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :ivar auth_type: The types of authentication mapped to the domain. Can be: `IP_ACL` and `CREDENTIAL_LIST`. If both are mapped, the values are returned in a comma delimited list. If empty, the domain will not receive any traffic. + :ivar auth_type_set: Reserved. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar sid: The unique string that we created to identify the Trunk resource. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.domain_name: Optional[str] = payload.get("domain_name") + self.disaster_recovery_method: Optional[str] = payload.get( + "disaster_recovery_method" + ) + self.disaster_recovery_url: Optional[str] = payload.get("disaster_recovery_url") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.secure: Optional[bool] = payload.get("secure") + self.recording: Optional[Dict[str, object]] = payload.get("recording") + self.transfer_mode: Optional["TrunkInstance.TransferSetting"] = payload.get( + "transfer_mode" + ) + self.transfer_caller_id: Optional["TrunkInstance.TransferCallerId"] = ( + payload.get("transfer_caller_id") + ) + self.cnam_lookup_enabled: Optional[bool] = payload.get("cnam_lookup_enabled") + self.auth_type: Optional[str] = payload.get("auth_type") + self.auth_type_set: Optional[List[str]] = payload.get("auth_type_set") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.sid: Optional[str] = payload.get("sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[TrunkContext] = None + + @property + def _proxy(self) -> "TrunkContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TrunkContext for this TrunkInstance + """ + if self._context is None: + self._context = TrunkContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TrunkInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TrunkInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "TrunkInstance": + """ + Fetch the TrunkInstance + + + :returns: The fetched TrunkInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TrunkInstance": + """ + Asynchronous coroutine to fetch the TrunkInstance + + + :returns: The fetched TrunkInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> "TrunkInstance": + """ + Update the TrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: The updated TrunkInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + domain_name=domain_name, + disaster_recovery_url=disaster_recovery_url, + disaster_recovery_method=disaster_recovery_method, + transfer_mode=transfer_mode, + secure=secure, + cnam_lookup_enabled=cnam_lookup_enabled, + transfer_caller_id=transfer_caller_id, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> "TrunkInstance": + """ + Asynchronous coroutine to update the TrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: The updated TrunkInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + domain_name=domain_name, + disaster_recovery_url=disaster_recovery_url, + disaster_recovery_method=disaster_recovery_method, + transfer_mode=transfer_mode, + secure=secure, + cnam_lookup_enabled=cnam_lookup_enabled, + transfer_caller_id=transfer_caller_id, + ) + + @property + def credentials_lists(self) -> CredentialListList: + """ + Access the credentials_lists + """ + return self._proxy.credentials_lists + + @property + def ip_access_control_lists(self) -> IpAccessControlListList: + """ + Access the ip_access_control_lists + """ + return self._proxy.ip_access_control_lists + + @property + def origination_urls(self) -> OriginationUrlList: + """ + Access the origination_urls + """ + return self._proxy.origination_urls + + @property + def phone_numbers(self) -> PhoneNumberList: + """ + Access the phone_numbers + """ + return self._proxy.phone_numbers + + @property + def recordings(self) -> RecordingList: + """ + Access the recordings + """ + return self._proxy.recordings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TrunkContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the TrunkContext + + :param version: Version that contains the resource + :param sid: The unique string that we created to identify the OriginationUrl resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Trunks/{sid}".format(**self._solution) + + self._credentials_lists: Optional[CredentialListList] = None + self._ip_access_control_lists: Optional[IpAccessControlListList] = None + self._origination_urls: Optional[OriginationUrlList] = None + self._phone_numbers: Optional[PhoneNumberList] = None + self._recordings: Optional[RecordingList] = None + + def delete(self) -> bool: + """ + Deletes the TrunkInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TrunkInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TrunkInstance: + """ + Fetch the TrunkInstance + + + :returns: The fetched TrunkInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TrunkInstance: + """ + Asynchronous coroutine to fetch the TrunkInstance + + + :returns: The fetched TrunkInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> TrunkInstance: + """ + Update the TrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: The updated TrunkInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DomainName": domain_name, + "DisasterRecoveryUrl": disaster_recovery_url, + "DisasterRecoveryMethod": disaster_recovery_method, + "TransferMode": transfer_mode, + "Secure": serialize.boolean_to_string(secure), + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), + "TransferCallerId": transfer_caller_id, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrunkInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> TrunkInstance: + """ + Asynchronous coroutine to update the TrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: The updated TrunkInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DomainName": domain_name, + "DisasterRecoveryUrl": disaster_recovery_url, + "DisasterRecoveryMethod": disaster_recovery_method, + "TransferMode": transfer_mode, + "Secure": serialize.boolean_to_string(secure), + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), + "TransferCallerId": transfer_caller_id, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrunkInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def credentials_lists(self) -> CredentialListList: + """ + Access the credentials_lists + """ + if self._credentials_lists is None: + self._credentials_lists = CredentialListList( + self._version, + self._solution["sid"], + ) + return self._credentials_lists + + @property + def ip_access_control_lists(self) -> IpAccessControlListList: + """ + Access the ip_access_control_lists + """ + if self._ip_access_control_lists is None: + self._ip_access_control_lists = IpAccessControlListList( + self._version, + self._solution["sid"], + ) + return self._ip_access_control_lists + + @property + def origination_urls(self) -> OriginationUrlList: + """ + Access the origination_urls + """ + if self._origination_urls is None: + self._origination_urls = OriginationUrlList( + self._version, + self._solution["sid"], + ) + return self._origination_urls + + @property + def phone_numbers(self) -> PhoneNumberList: + """ + Access the phone_numbers + """ + if self._phone_numbers is None: + self._phone_numbers = PhoneNumberList( + self._version, + self._solution["sid"], + ) + return self._phone_numbers + + @property + def recordings(self) -> RecordingList: + """ + Access the recordings + """ + if self._recordings is None: + self._recordings = RecordingList( + self._version, + self._solution["sid"], + ) + return self._recordings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TrunkPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TrunkInstance: + """ + Build an instance of TrunkInstance + + :param payload: Payload response from the API + """ + return TrunkInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TrunkList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TrunkList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Trunks" + + def create( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> TrunkInstance: + """ + Create the TrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: The created TrunkInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DomainName": domain_name, + "DisasterRecoveryUrl": disaster_recovery_url, + "DisasterRecoveryMethod": disaster_recovery_method, + "TransferMode": transfer_mode, + "Secure": serialize.boolean_to_string(secure), + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), + "TransferCallerId": transfer_caller_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrunkInstance(self._version, payload) + + async def create_async( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> TrunkInstance: + """ + Asynchronously create the TrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: The created TrunkInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DomainName": domain_name, + "DisasterRecoveryUrl": disaster_recovery_url, + "DisasterRecoveryMethod": disaster_recovery_method, + "TransferMode": transfer_mode, + "Secure": serialize.boolean_to_string(secure), + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), + "TransferCallerId": transfer_caller_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrunkInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TrunkInstance]: + """ + Streams TrunkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TrunkInstance]: + """ + Asynchronously streams TrunkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TrunkInstance]: + """ + Lists TrunkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TrunkInstance]: + """ + Asynchronously lists TrunkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TrunkPage: + """ + Retrieve a single page of TrunkInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TrunkInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TrunkPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TrunkPage: + """ + Asynchronously retrieve a single page of TrunkInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TrunkInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TrunkPage(self._version, response) + + def get_page(self, target_url: str) -> TrunkPage: + """ + Retrieve a specific page of TrunkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TrunkInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TrunkPage(self._version, response) + + async def get_page_async(self, target_url: str) -> TrunkPage: + """ + Asynchronously retrieve a specific page of TrunkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TrunkInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TrunkPage(self._version, response) + + def get(self, sid: str) -> TrunkContext: + """ + Constructs a TrunkContext + + :param sid: The unique string that we created to identify the OriginationUrl resource to update. + """ + return TrunkContext(self._version, sid=sid) + + def __call__(self, sid: str) -> TrunkContext: + """ + Constructs a TrunkContext + + :param sid: The unique string that we created to identify the OriginationUrl resource to update. + """ + return TrunkContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..c8b3747f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/__pycache__/credential_list.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/__pycache__/credential_list.cpython-312.pyc new file mode 100644 index 00000000..64b8ec91 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/__pycache__/credential_list.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/__pycache__/ip_access_control_list.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/__pycache__/ip_access_control_list.cpython-312.pyc new file mode 100644 index 00000000..85c7f7af Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/__pycache__/ip_access_control_list.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/__pycache__/origination_url.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/__pycache__/origination_url.cpython-312.pyc new file mode 100644 index 00000000..3b4fb36d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/__pycache__/origination_url.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/__pycache__/phone_number.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/__pycache__/phone_number.cpython-312.pyc new file mode 100644 index 00000000..e1e414e8 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/__pycache__/phone_number.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/__pycache__/recording.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/__pycache__/recording.cpython-312.pyc new file mode 100644 index 00000000..2e3eb24c Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/__pycache__/recording.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/credential_list.py b/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/credential_list.py new file mode 100644 index 00000000..09ffc992 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/credential_list.py @@ -0,0 +1,538 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trunking + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CredentialListInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialList resource. + :ivar sid: The unique string that we created to identify the CredentialList resource. + :ivar trunk_sid: The SID of the Trunk the credential list in associated with. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + trunk_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.trunk_sid: Optional[str] = payload.get("trunk_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid or self.sid, + } + self._context: Optional[CredentialListContext] = None + + @property + def _proxy(self) -> "CredentialListContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CredentialListContext for this CredentialListInstance + """ + if self._context is None: + self._context = CredentialListContext( + self._version, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CredentialListInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialListInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CredentialListInstance": + """ + Fetch the CredentialListInstance + + + :returns: The fetched CredentialListInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CredentialListInstance": + """ + Asynchronous coroutine to fetch the CredentialListInstance + + + :returns: The fetched CredentialListInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialListContext(InstanceContext): + + def __init__(self, version: Version, trunk_sid: str, sid: str): + """ + Initialize the CredentialListContext + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to fetch the credential list. + :param sid: The unique string that we created to identify the CredentialList resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid, + } + self._uri = "/Trunks/{trunk_sid}/CredentialLists/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the CredentialListInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialListInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialListInstance: + """ + Fetch the CredentialListInstance + + + :returns: The fetched CredentialListInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CredentialListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialListInstance: + """ + Asynchronous coroutine to fetch the CredentialListInstance + + + :returns: The fetched CredentialListInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CredentialListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialListPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialListInstance: + """ + Build an instance of CredentialListInstance + + :param payload: Payload response from the API + """ + return CredentialListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CredentialListList(ListResource): + + def __init__(self, version: Version, trunk_sid: str): + """ + Initialize the CredentialListList + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to read the credential lists. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + } + self._uri = "/Trunks/{trunk_sid}/CredentialLists".format(**self._solution) + + def create(self, credential_list_sid: str) -> CredentialListInstance: + """ + Create the CredentialListInstance + + :param credential_list_sid: The SID of the [Credential List](https://www.twilio.com/docs/voice/sip/api/sip-credentiallist-resource) that you want to associate with the trunk. Once associated, we will authenticate access to the trunk against this list. + + :returns: The created CredentialListInstance + """ + + data = values.of( + { + "CredentialListSid": credential_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + async def create_async(self, credential_list_sid: str) -> CredentialListInstance: + """ + Asynchronously create the CredentialListInstance + + :param credential_list_sid: The SID of the [Credential List](https://www.twilio.com/docs/voice/sip/api/sip-credentiallist-resource) that you want to associate with the trunk. Once associated, we will authenticate access to the trunk against this list. + + :returns: The created CredentialListInstance + """ + + data = values.of( + { + "CredentialListSid": credential_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialListInstance]: + """ + Streams CredentialListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialListInstance]: + """ + Asynchronously streams CredentialListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialListInstance]: + """ + Lists CredentialListInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialListInstance]: + """ + Asynchronously lists CredentialListInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialListPage: + """ + Retrieve a single page of CredentialListInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialListInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialListPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialListPage: + """ + Asynchronously retrieve a single page of CredentialListInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialListInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialListPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> CredentialListPage: + """ + Retrieve a specific page of CredentialListInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialListInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialListPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> CredentialListPage: + """ + Asynchronously retrieve a specific page of CredentialListInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialListInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialListPage(self._version, response, self._solution) + + def get(self, sid: str) -> CredentialListContext: + """ + Constructs a CredentialListContext + + :param sid: The unique string that we created to identify the CredentialList resource to fetch. + """ + return CredentialListContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) + + def __call__(self, sid: str) -> CredentialListContext: + """ + Constructs a CredentialListContext + + :param sid: The unique string that we created to identify the CredentialList resource to fetch. + """ + return CredentialListContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/ip_access_control_list.py b/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/ip_access_control_list.py new file mode 100644 index 00000000..ec5a59de --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/ip_access_control_list.py @@ -0,0 +1,542 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trunking + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class IpAccessControlListInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IpAccessControlList resource. + :ivar sid: The unique string that we created to identify the IpAccessControlList resource. + :ivar trunk_sid: The SID of the Trunk the resource is associated with. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + trunk_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.trunk_sid: Optional[str] = payload.get("trunk_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid or self.sid, + } + self._context: Optional[IpAccessControlListContext] = None + + @property + def _proxy(self) -> "IpAccessControlListContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: IpAccessControlListContext for this IpAccessControlListInstance + """ + if self._context is None: + self._context = IpAccessControlListContext( + self._version, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the IpAccessControlListInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpAccessControlListInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "IpAccessControlListInstance": + """ + Fetch the IpAccessControlListInstance + + + :returns: The fetched IpAccessControlListInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "IpAccessControlListInstance": + """ + Asynchronous coroutine to fetch the IpAccessControlListInstance + + + :returns: The fetched IpAccessControlListInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class IpAccessControlListContext(InstanceContext): + + def __init__(self, version: Version, trunk_sid: str, sid: str): + """ + Initialize the IpAccessControlListContext + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to fetch the IP Access Control List. + :param sid: The unique string that we created to identify the IpAccessControlList resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid, + } + self._uri = "/Trunks/{trunk_sid}/IpAccessControlLists/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the IpAccessControlListInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpAccessControlListInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> IpAccessControlListInstance: + """ + Fetch the IpAccessControlListInstance + + + :returns: The fetched IpAccessControlListInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return IpAccessControlListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> IpAccessControlListInstance: + """ + Asynchronous coroutine to fetch the IpAccessControlListInstance + + + :returns: The fetched IpAccessControlListInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return IpAccessControlListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class IpAccessControlListPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> IpAccessControlListInstance: + """ + Build an instance of IpAccessControlListInstance + + :param payload: Payload response from the API + """ + return IpAccessControlListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class IpAccessControlListList(ListResource): + + def __init__(self, version: Version, trunk_sid: str): + """ + Initialize the IpAccessControlListList + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to read the IP Access Control Lists. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + } + self._uri = "/Trunks/{trunk_sid}/IpAccessControlLists".format(**self._solution) + + def create(self, ip_access_control_list_sid: str) -> IpAccessControlListInstance: + """ + Create the IpAccessControlListInstance + + :param ip_access_control_list_sid: The SID of the [IP Access Control List](https://www.twilio.com/docs/voice/sip/api/sip-ipaccesscontrollist-resource) that you want to associate with the trunk. + + :returns: The created IpAccessControlListInstance + """ + + data = values.of( + { + "IpAccessControlListSid": ip_access_control_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpAccessControlListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + async def create_async( + self, ip_access_control_list_sid: str + ) -> IpAccessControlListInstance: + """ + Asynchronously create the IpAccessControlListInstance + + :param ip_access_control_list_sid: The SID of the [IP Access Control List](https://www.twilio.com/docs/voice/sip/api/sip-ipaccesscontrollist-resource) that you want to associate with the trunk. + + :returns: The created IpAccessControlListInstance + """ + + data = values.of( + { + "IpAccessControlListSid": ip_access_control_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpAccessControlListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[IpAccessControlListInstance]: + """ + Streams IpAccessControlListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IpAccessControlListInstance]: + """ + Asynchronously streams IpAccessControlListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAccessControlListInstance]: + """ + Lists IpAccessControlListInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAccessControlListInstance]: + """ + Asynchronously lists IpAccessControlListInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpAccessControlListPage: + """ + Retrieve a single page of IpAccessControlListInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpAccessControlListInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpAccessControlListPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpAccessControlListPage: + """ + Asynchronously retrieve a single page of IpAccessControlListInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpAccessControlListInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpAccessControlListPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> IpAccessControlListPage: + """ + Retrieve a specific page of IpAccessControlListInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpAccessControlListInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return IpAccessControlListPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> IpAccessControlListPage: + """ + Asynchronously retrieve a specific page of IpAccessControlListInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpAccessControlListInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return IpAccessControlListPage(self._version, response, self._solution) + + def get(self, sid: str) -> IpAccessControlListContext: + """ + Constructs a IpAccessControlListContext + + :param sid: The unique string that we created to identify the IpAccessControlList resource to fetch. + """ + return IpAccessControlListContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) + + def __call__(self, sid: str) -> IpAccessControlListContext: + """ + Constructs a IpAccessControlListContext + + :param sid: The unique string that we created to identify the IpAccessControlList resource to fetch. + """ + return IpAccessControlListContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/origination_url.py b/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/origination_url.py new file mode 100644 index 00000000..082fa34b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/origination_url.py @@ -0,0 +1,722 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trunking + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class OriginationUrlInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the OriginationUrl resource. + :ivar sid: The unique string that we created to identify the OriginationUrl resource. + :ivar trunk_sid: The SID of the Trunk that owns the Origination URL. + :ivar weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :ivar enabled: Whether the URL is enabled. The default is `true`. + :ivar sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + trunk_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.trunk_sid: Optional[str] = payload.get("trunk_sid") + self.weight: Optional[int] = deserialize.integer(payload.get("weight")) + self.enabled: Optional[bool] = payload.get("enabled") + self.sip_url: Optional[str] = payload.get("sip_url") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.priority: Optional[int] = deserialize.integer(payload.get("priority")) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid or self.sid, + } + self._context: Optional[OriginationUrlContext] = None + + @property + def _proxy(self) -> "OriginationUrlContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OriginationUrlContext for this OriginationUrlInstance + """ + if self._context is None: + self._context = OriginationUrlContext( + self._version, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the OriginationUrlInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OriginationUrlInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "OriginationUrlInstance": + """ + Fetch the OriginationUrlInstance + + + :returns: The fetched OriginationUrlInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "OriginationUrlInstance": + """ + Asynchronous coroutine to fetch the OriginationUrlInstance + + + :returns: The fetched OriginationUrlInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + weight: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sip_url: Union[str, object] = values.unset, + ) -> "OriginationUrlInstance": + """ + Update the OriginationUrlInstance + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. `sips` is NOT supported. + + :returns: The updated OriginationUrlInstance + """ + return self._proxy.update( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) + + async def update_async( + self, + weight: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sip_url: Union[str, object] = values.unset, + ) -> "OriginationUrlInstance": + """ + Asynchronous coroutine to update the OriginationUrlInstance + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. `sips` is NOT supported. + + :returns: The updated OriginationUrlInstance + """ + return await self._proxy.update_async( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OriginationUrlContext(InstanceContext): + + def __init__(self, version: Version, trunk_sid: str, sid: str): + """ + Initialize the OriginationUrlContext + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to update the OriginationUrl. + :param sid: The unique string that we created to identify the OriginationUrl resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid, + } + self._uri = "/Trunks/{trunk_sid}/OriginationUrls/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the OriginationUrlInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OriginationUrlInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> OriginationUrlInstance: + """ + Fetch the OriginationUrlInstance + + + :returns: The fetched OriginationUrlInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return OriginationUrlInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> OriginationUrlInstance: + """ + Asynchronous coroutine to fetch the OriginationUrlInstance + + + :returns: The fetched OriginationUrlInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return OriginationUrlInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + weight: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sip_url: Union[str, object] = values.unset, + ) -> OriginationUrlInstance: + """ + Update the OriginationUrlInstance + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. `sips` is NOT supported. + + :returns: The updated OriginationUrlInstance + """ + + data = values.of( + { + "Weight": weight, + "Priority": priority, + "Enabled": serialize.boolean_to_string(enabled), + "FriendlyName": friendly_name, + "SipUrl": sip_url, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return OriginationUrlInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + weight: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sip_url: Union[str, object] = values.unset, + ) -> OriginationUrlInstance: + """ + Asynchronous coroutine to update the OriginationUrlInstance + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. `sips` is NOT supported. + + :returns: The updated OriginationUrlInstance + """ + + data = values.of( + { + "Weight": weight, + "Priority": priority, + "Enabled": serialize.boolean_to_string(enabled), + "FriendlyName": friendly_name, + "SipUrl": sip_url, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return OriginationUrlInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OriginationUrlPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> OriginationUrlInstance: + """ + Build an instance of OriginationUrlInstance + + :param payload: Payload response from the API + """ + return OriginationUrlInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class OriginationUrlList(ListResource): + + def __init__(self, version: Version, trunk_sid: str): + """ + Initialize the OriginationUrlList + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to read the OriginationUrl. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + } + self._uri = "/Trunks/{trunk_sid}/OriginationUrls".format(**self._solution) + + def create( + self, + weight: int, + priority: int, + enabled: bool, + friendly_name: str, + sip_url: str, + ) -> OriginationUrlInstance: + """ + Create the OriginationUrlInstance + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. + + :returns: The created OriginationUrlInstance + """ + + data = values.of( + { + "Weight": weight, + "Priority": priority, + "Enabled": serialize.boolean_to_string(enabled), + "FriendlyName": friendly_name, + "SipUrl": sip_url, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return OriginationUrlInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + async def create_async( + self, + weight: int, + priority: int, + enabled: bool, + friendly_name: str, + sip_url: str, + ) -> OriginationUrlInstance: + """ + Asynchronously create the OriginationUrlInstance + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. + + :returns: The created OriginationUrlInstance + """ + + data = values.of( + { + "Weight": weight, + "Priority": priority, + "Enabled": serialize.boolean_to_string(enabled), + "FriendlyName": friendly_name, + "SipUrl": sip_url, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return OriginationUrlInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[OriginationUrlInstance]: + """ + Streams OriginationUrlInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[OriginationUrlInstance]: + """ + Asynchronously streams OriginationUrlInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OriginationUrlInstance]: + """ + Lists OriginationUrlInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OriginationUrlInstance]: + """ + Asynchronously lists OriginationUrlInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OriginationUrlPage: + """ + Retrieve a single page of OriginationUrlInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of OriginationUrlInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OriginationUrlPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OriginationUrlPage: + """ + Asynchronously retrieve a single page of OriginationUrlInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of OriginationUrlInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OriginationUrlPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> OriginationUrlPage: + """ + Retrieve a specific page of OriginationUrlInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OriginationUrlInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return OriginationUrlPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> OriginationUrlPage: + """ + Asynchronously retrieve a specific page of OriginationUrlInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OriginationUrlInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return OriginationUrlPage(self._version, response, self._solution) + + def get(self, sid: str) -> OriginationUrlContext: + """ + Constructs a OriginationUrlContext + + :param sid: The unique string that we created to identify the OriginationUrl resource to update. + """ + return OriginationUrlContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) + + def __call__(self, sid: str) -> OriginationUrlContext: + """ + Constructs a OriginationUrlContext + + :param sid: The unique string that we created to identify the OriginationUrl resource to update. + """ + return OriginationUrlContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/phone_number.py b/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/phone_number.py new file mode 100644 index 00000000..a7c3dbe2 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/phone_number.py @@ -0,0 +1,589 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trunking + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class PhoneNumberInstance(InstanceResource): + + class AddressRequirement(object): + NONE = "none" + ANY = "any" + LOCAL = "local" + FOREIGN = "foreign" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the PhoneNumber resource. + :ivar address_requirements: + :ivar api_version: The API version used to start a new TwiML session. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: The set of Boolean properties that indicate whether a phone number can receive calls or messages. Capabilities are `Voice`, `SMS`, and `MMS` and each capability can be: `true` or `false`. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar links: The URLs of related resources. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar sid: The unique string that we created to identify the PhoneNumber resource. + :ivar sms_application_sid: The SID of the application that handles SMS messages sent to the phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :ivar sms_fallback_method: The HTTP method we use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :ivar sms_fallback_url: The URL that we call using the `sms_fallback_method` when an error occurs while retrieving or executing the TwiML from `sms_url`. + :ivar sms_method: The HTTP method we use to call `sms_url`. Can be: `GET` or `POST`. + :ivar sms_url: The URL we call using the `sms_method` when the phone number receives an incoming SMS message. + :ivar status_callback: The URL we call using the `status_callback_method` to send status information to your application. + :ivar status_callback_method: The HTTP method we use to call `status_callback`. Can be: `GET` or `POST`. + :ivar trunk_sid: The SID of the Trunk that handles calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice URLs and voice applications and use those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :ivar url: The absolute URL of the resource. + :ivar voice_application_sid: The SID of the application that handles calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice URLs and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :ivar voice_caller_id_lookup: Whether we look up the caller's caller-ID name from the CNAM database ($0.01 per look up). Can be: `true` or `false`. + :ivar voice_fallback_method: The HTTP method that we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_url: The URL that we call using the `voice_fallback_method` when an error occurs retrieving or executing the TwiML requested by `url`. + :ivar voice_method: The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + :ivar voice_url: The URL we call using the `voice_method` when the phone number receives a call. The `voice_url` is not be used if a `voice_application_sid` or a `trunk_sid` is set. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + trunk_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.address_requirements: Optional[ + "PhoneNumberInstance.AddressRequirement" + ] = payload.get("address_requirements") + self.api_version: Optional[str] = payload.get("api_version") + self.beta: Optional[bool] = payload.get("beta") + self.capabilities: Optional[Dict[str, object]] = payload.get("capabilities") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.phone_number: Optional[str] = payload.get("phone_number") + self.sid: Optional[str] = payload.get("sid") + self.sms_application_sid: Optional[str] = payload.get("sms_application_sid") + self.sms_fallback_method: Optional[str] = payload.get("sms_fallback_method") + self.sms_fallback_url: Optional[str] = payload.get("sms_fallback_url") + self.sms_method: Optional[str] = payload.get("sms_method") + self.sms_url: Optional[str] = payload.get("sms_url") + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.trunk_sid: Optional[str] = payload.get("trunk_sid") + self.url: Optional[str] = payload.get("url") + self.voice_application_sid: Optional[str] = payload.get("voice_application_sid") + self.voice_caller_id_lookup: Optional[bool] = payload.get( + "voice_caller_id_lookup" + ) + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_url: Optional[str] = payload.get("voice_url") + + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid or self.sid, + } + self._context: Optional[PhoneNumberContext] = None + + @property + def _proxy(self) -> "PhoneNumberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PhoneNumberContext for this PhoneNumberInstance + """ + if self._context is None: + self._context = PhoneNumberContext( + self._version, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the PhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "PhoneNumberInstance": + """ + Fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PhoneNumberInstance": + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PhoneNumberContext(InstanceContext): + + def __init__(self, version: Version, trunk_sid: str, sid: str): + """ + Initialize the PhoneNumberContext + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to fetch the PhoneNumber resource. + :param sid: The unique string that we created to identify the PhoneNumber resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid, + } + self._uri = "/Trunks/{trunk_sid}/PhoneNumbers/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the PhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> PhoneNumberInstance: + """ + Fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PhoneNumberInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> PhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PhoneNumberInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PhoneNumberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PhoneNumberInstance: + """ + Build an instance of PhoneNumberInstance + + :param payload: Payload response from the API + """ + return PhoneNumberInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class PhoneNumberList(ListResource): + + def __init__(self, version: Version, trunk_sid: str): + """ + Initialize the PhoneNumberList + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to read the PhoneNumber resources. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + } + self._uri = "/Trunks/{trunk_sid}/PhoneNumbers".format(**self._solution) + + def create(self, phone_number_sid: str) -> PhoneNumberInstance: + """ + Create the PhoneNumberInstance + + :param phone_number_sid: The SID of the [Incoming Phone Number](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) that you want to associate with the trunk. + + :returns: The created PhoneNumberInstance + """ + + data = values.of( + { + "PhoneNumberSid": phone_number_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + async def create_async(self, phone_number_sid: str) -> PhoneNumberInstance: + """ + Asynchronously create the PhoneNumberInstance + + :param phone_number_sid: The SID of the [Incoming Phone Number](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) that you want to associate with the trunk. + + :returns: The created PhoneNumberInstance + """ + + data = values.of( + { + "PhoneNumberSid": phone_number_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PhoneNumberInstance]: + """ + Streams PhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PhoneNumberInstance]: + """ + Asynchronously streams PhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PhoneNumberInstance]: + """ + Lists PhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PhoneNumberInstance]: + """ + Asynchronously lists PhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PhoneNumberPage: + """ + Retrieve a single page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PhoneNumberInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PhoneNumberPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PhoneNumberPage: + """ + Asynchronously retrieve a single page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PhoneNumberInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PhoneNumberPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> PhoneNumberPage: + """ + Retrieve a specific page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PhoneNumberInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PhoneNumberPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> PhoneNumberPage: + """ + Asynchronously retrieve a specific page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PhoneNumberInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PhoneNumberPage(self._version, response, self._solution) + + def get(self, sid: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param sid: The unique string that we created to identify the PhoneNumber resource to fetch. + """ + return PhoneNumberContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) + + def __call__(self, sid: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param sid: The unique string that we created to identify the PhoneNumber resource to fetch. + """ + return PhoneNumberContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/recording.py b/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/recording.py new file mode 100644 index 00000000..0507662f --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trunking/v1/trunk/recording.py @@ -0,0 +1,305 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trunking + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class RecordingInstance(InstanceResource): + + class RecordingMode(object): + DO_NOT_RECORD = "do-not-record" + RECORD_FROM_RINGING = "record-from-ringing" + RECORD_FROM_ANSWER = "record-from-answer" + RECORD_FROM_RINGING_DUAL = "record-from-ringing-dual" + RECORD_FROM_ANSWER_DUAL = "record-from-answer-dual" + + class RecordingTrim(object): + TRIM_SILENCE = "trim-silence" + DO_NOT_TRIM = "do-not-trim" + + """ + :ivar mode: + :ivar trim: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], trunk_sid: str): + super().__init__(version) + + self.mode: Optional["RecordingInstance.RecordingMode"] = payload.get("mode") + self.trim: Optional["RecordingInstance.RecordingTrim"] = payload.get("trim") + + self._solution = { + "trunk_sid": trunk_sid, + } + self._context: Optional[RecordingContext] = None + + @property + def _proxy(self) -> "RecordingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RecordingContext for this RecordingInstance + """ + if self._context is None: + self._context = RecordingContext( + self._version, + trunk_sid=self._solution["trunk_sid"], + ) + return self._context + + def fetch(self) -> "RecordingInstance": + """ + Fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RecordingInstance": + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + mode: Union["RecordingInstance.RecordingMode", object] = values.unset, + trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, + ) -> "RecordingInstance": + """ + Update the RecordingInstance + + :param mode: + :param trim: + + :returns: The updated RecordingInstance + """ + return self._proxy.update( + mode=mode, + trim=trim, + ) + + async def update_async( + self, + mode: Union["RecordingInstance.RecordingMode", object] = values.unset, + trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, + ) -> "RecordingInstance": + """ + Asynchronous coroutine to update the RecordingInstance + + :param mode: + :param trim: + + :returns: The updated RecordingInstance + """ + return await self._proxy.update_async( + mode=mode, + trim=trim, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RecordingContext(InstanceContext): + + def __init__(self, version: Version, trunk_sid: str): + """ + Initialize the RecordingContext + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk that will have its recording settings updated. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + } + self._uri = "/Trunks/{trunk_sid}/Recording".format(**self._solution) + + def fetch(self) -> RecordingInstance: + """ + Fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RecordingInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + ) + + async def fetch_async(self) -> RecordingInstance: + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + ) + + def update( + self, + mode: Union["RecordingInstance.RecordingMode", object] = values.unset, + trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, + ) -> RecordingInstance: + """ + Update the RecordingInstance + + :param mode: + :param trim: + + :returns: The updated RecordingInstance + """ + + data = values.of( + { + "Mode": mode, + "Trim": trim, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RecordingInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + async def update_async( + self, + mode: Union["RecordingInstance.RecordingMode", object] = values.unset, + trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, + ) -> RecordingInstance: + """ + Asynchronous coroutine to update the RecordingInstance + + :param mode: + :param trim: + + :returns: The updated RecordingInstance + """ + + data = values.of( + { + "Mode": mode, + "Trim": trim, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RecordingInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RecordingList(ListResource): + + def __init__(self, version: Version, trunk_sid: str): + """ + Initialize the RecordingList + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to fetch the recording settings. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + } + + def get(self) -> RecordingContext: + """ + Constructs a RecordingContext + + """ + return RecordingContext(self._version, trunk_sid=self._solution["trunk_sid"]) + + def __call__(self) -> RecordingContext: + """ + Constructs a RecordingContext + + """ + return RecordingContext(self._version, trunk_sid=self._solution["trunk_sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/TrusthubBase.py b/venv/Lib/site-packages/twilio/rest/trusthub/TrusthubBase.py new file mode 100644 index 00000000..97fd32f9 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trusthub/TrusthubBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.trusthub.v1 import V1 + + +class TrusthubBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Trusthub Domain + + :returns: Domain for Trusthub + """ + super().__init__(twilio, "https://trusthub.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Trusthub + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/__init__.py b/venv/Lib/site-packages/twilio/rest/trusthub/__init__.py new file mode 100644 index 00000000..3da2fcfd --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trusthub/__init__.py @@ -0,0 +1,75 @@ +from warnings import warn + +from twilio.rest.trusthub.TrusthubBase import TrusthubBase +from twilio.rest.trusthub.v1.customer_profiles import CustomerProfilesList +from twilio.rest.trusthub.v1.end_user import EndUserList +from twilio.rest.trusthub.v1.end_user_type import EndUserTypeList +from twilio.rest.trusthub.v1.policies import PoliciesList +from twilio.rest.trusthub.v1.supporting_document import SupportingDocumentList +from twilio.rest.trusthub.v1.supporting_document_type import SupportingDocumentTypeList +from twilio.rest.trusthub.v1.trust_products import TrustProductsList + + +class Trusthub(TrusthubBase): + @property + def customer_profiles(self) -> CustomerProfilesList: + warn( + "customer_profiles is deprecated. Use v1.customer_profiles instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.customer_profiles + + @property + def end_users(self) -> EndUserList: + warn( + "end_users is deprecated. Use v1.end_users instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.end_users + + @property + def end_user_types(self) -> EndUserTypeList: + warn( + "end_user_types is deprecated. Use v1.end_user_types instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.end_user_types + + @property + def policies(self) -> PoliciesList: + warn( + "policies is deprecated. Use v1.policies instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.policies + + @property + def supporting_documents(self) -> SupportingDocumentList: + warn( + "supporting_documents is deprecated. Use v1.supporting_documents instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.supporting_documents + + @property + def supporting_document_types(self) -> SupportingDocumentTypeList: + warn( + "supporting_document_types is deprecated. Use v1.supporting_document_types instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.supporting_document_types + + @property + def trust_products(self) -> TrustProductsList: + warn( + "trust_products is deprecated. Use v1.trust_products instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.trust_products diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/__pycache__/TrusthubBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trusthub/__pycache__/TrusthubBase.cpython-312.pyc new file mode 100644 index 00000000..2806ae9d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trusthub/__pycache__/TrusthubBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trusthub/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..e11a12da Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trusthub/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/trusthub/v1/__init__.py new file mode 100644 index 00000000..596c5ea7 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trusthub/v1/__init__.py @@ -0,0 +1,125 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.trusthub.v1.compliance_inquiries import ComplianceInquiriesList +from twilio.rest.trusthub.v1.compliance_registration_inquiries import ( + ComplianceRegistrationInquiriesList, +) +from twilio.rest.trusthub.v1.compliance_tollfree_inquiries import ( + ComplianceTollfreeInquiriesList, +) +from twilio.rest.trusthub.v1.customer_profiles import CustomerProfilesList +from twilio.rest.trusthub.v1.end_user import EndUserList +from twilio.rest.trusthub.v1.end_user_type import EndUserTypeList +from twilio.rest.trusthub.v1.policies import PoliciesList +from twilio.rest.trusthub.v1.supporting_document import SupportingDocumentList +from twilio.rest.trusthub.v1.supporting_document_type import SupportingDocumentTypeList +from twilio.rest.trusthub.v1.trust_products import TrustProductsList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Trusthub + + :param domain: The Twilio.trusthub domain + """ + super().__init__(domain, "v1") + self._compliance_inquiries: Optional[ComplianceInquiriesList] = None + self._compliance_registration_inquiries: Optional[ + ComplianceRegistrationInquiriesList + ] = None + self._compliance_tollfree_inquiries: Optional[ + ComplianceTollfreeInquiriesList + ] = None + self._customer_profiles: Optional[CustomerProfilesList] = None + self._end_users: Optional[EndUserList] = None + self._end_user_types: Optional[EndUserTypeList] = None + self._policies: Optional[PoliciesList] = None + self._supporting_documents: Optional[SupportingDocumentList] = None + self._supporting_document_types: Optional[SupportingDocumentTypeList] = None + self._trust_products: Optional[TrustProductsList] = None + + @property + def compliance_inquiries(self) -> ComplianceInquiriesList: + if self._compliance_inquiries is None: + self._compliance_inquiries = ComplianceInquiriesList(self) + return self._compliance_inquiries + + @property + def compliance_registration_inquiries(self) -> ComplianceRegistrationInquiriesList: + if self._compliance_registration_inquiries is None: + self._compliance_registration_inquiries = ( + ComplianceRegistrationInquiriesList(self) + ) + return self._compliance_registration_inquiries + + @property + def compliance_tollfree_inquiries(self) -> ComplianceTollfreeInquiriesList: + if self._compliance_tollfree_inquiries is None: + self._compliance_tollfree_inquiries = ComplianceTollfreeInquiriesList(self) + return self._compliance_tollfree_inquiries + + @property + def customer_profiles(self) -> CustomerProfilesList: + if self._customer_profiles is None: + self._customer_profiles = CustomerProfilesList(self) + return self._customer_profiles + + @property + def end_users(self) -> EndUserList: + if self._end_users is None: + self._end_users = EndUserList(self) + return self._end_users + + @property + def end_user_types(self) -> EndUserTypeList: + if self._end_user_types is None: + self._end_user_types = EndUserTypeList(self) + return self._end_user_types + + @property + def policies(self) -> PoliciesList: + if self._policies is None: + self._policies = PoliciesList(self) + return self._policies + + @property + def supporting_documents(self) -> SupportingDocumentList: + if self._supporting_documents is None: + self._supporting_documents = SupportingDocumentList(self) + return self._supporting_documents + + @property + def supporting_document_types(self) -> SupportingDocumentTypeList: + if self._supporting_document_types is None: + self._supporting_document_types = SupportingDocumentTypeList(self) + return self._supporting_document_types + + @property + def trust_products(self) -> TrustProductsList: + if self._trust_products is None: + self._trust_products = TrustProductsList(self) + return self._trust_products + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..e6c010cc Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/compliance_inquiries.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/compliance_inquiries.cpython-312.pyc new file mode 100644 index 00000000..564a93d3 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/compliance_inquiries.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/compliance_registration_inquiries.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/compliance_registration_inquiries.cpython-312.pyc new file mode 100644 index 00000000..516225a4 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/compliance_registration_inquiries.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/compliance_tollfree_inquiries.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/compliance_tollfree_inquiries.cpython-312.pyc new file mode 100644 index 00000000..40d2623b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/compliance_tollfree_inquiries.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/end_user.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/end_user.cpython-312.pyc new file mode 100644 index 00000000..feec87f7 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/end_user.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/end_user_type.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/end_user_type.cpython-312.pyc new file mode 100644 index 00000000..cb3203b3 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/end_user_type.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/policies.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/policies.cpython-312.pyc new file mode 100644 index 00000000..f24009bd Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/policies.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/supporting_document.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/supporting_document.cpython-312.pyc new file mode 100644 index 00000000..a00e4493 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/supporting_document.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/supporting_document_type.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/supporting_document_type.cpython-312.pyc new file mode 100644 index 00000000..99720cca Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trusthub/v1/__pycache__/supporting_document_type.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/compliance_inquiries.py b/venv/Lib/site-packages/twilio/rest/trusthub/v1/compliance_inquiries.py new file mode 100644 index 00000000..3c1abd59 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trusthub/v1/compliance_inquiries.py @@ -0,0 +1,304 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ComplianceInquiriesInstance(InstanceResource): + """ + :ivar inquiry_id: The unique ID used to start an embedded compliance registration session. + :ivar inquiry_session_token: The session token used to start an embedded compliance registration session. + :ivar customer_id: The CustomerID matching the Customer Profile that should be resumed or resubmitted for editing. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + customer_id: Optional[str] = None, + ): + super().__init__(version) + + self.inquiry_id: Optional[str] = payload.get("inquiry_id") + self.inquiry_session_token: Optional[str] = payload.get("inquiry_session_token") + self.customer_id: Optional[str] = payload.get("customer_id") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "customer_id": customer_id or self.customer_id, + } + self._context: Optional[ComplianceInquiriesContext] = None + + @property + def _proxy(self) -> "ComplianceInquiriesContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ComplianceInquiriesContext for this ComplianceInquiriesInstance + """ + if self._context is None: + self._context = ComplianceInquiriesContext( + self._version, + customer_id=self._solution["customer_id"], + ) + return self._context + + def update( + self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> "ComplianceInquiriesInstance": + """ + Update the ComplianceInquiriesInstance + + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The updated ComplianceInquiriesInstance + """ + return self._proxy.update( + primary_profile_sid=primary_profile_sid, + theme_set_id=theme_set_id, + ) + + async def update_async( + self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> "ComplianceInquiriesInstance": + """ + Asynchronous coroutine to update the ComplianceInquiriesInstance + + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The updated ComplianceInquiriesInstance + """ + return await self._proxy.update_async( + primary_profile_sid=primary_profile_sid, + theme_set_id=theme_set_id, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ComplianceInquiriesContext(InstanceContext): + + def __init__(self, version: Version, customer_id: str): + """ + Initialize the ComplianceInquiriesContext + + :param version: Version that contains the resource + :param customer_id: The unique CustomerId matching the Customer Profile/Compliance Inquiry that should be resumed or resubmitted. This value will have been returned by the initial Compliance Inquiry creation call. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "customer_id": customer_id, + } + self._uri = "/ComplianceInquiries/Customers/{customer_id}/Initialize".format( + **self._solution + ) + + def update( + self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> ComplianceInquiriesInstance: + """ + Update the ComplianceInquiriesInstance + + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The updated ComplianceInquiriesInstance + """ + + data = values.of( + { + "PrimaryProfileSid": primary_profile_sid, + "ThemeSetId": theme_set_id, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ComplianceInquiriesInstance( + self._version, payload, customer_id=self._solution["customer_id"] + ) + + async def update_async( + self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> ComplianceInquiriesInstance: + """ + Asynchronous coroutine to update the ComplianceInquiriesInstance + + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The updated ComplianceInquiriesInstance + """ + + data = values.of( + { + "PrimaryProfileSid": primary_profile_sid, + "ThemeSetId": theme_set_id, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ComplianceInquiriesInstance( + self._version, payload, customer_id=self._solution["customer_id"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ComplianceInquiriesList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ComplianceInquiriesList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ComplianceInquiries/Customers/Initialize" + + def create( + self, + primary_profile_sid: str, + notification_email: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ComplianceInquiriesInstance: + """ + Create the ComplianceInquiriesInstance + + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + :param notification_email: The email address that approval status updates will be sent to. If not specified, the email address associated with your primary customer profile will be used. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The created ComplianceInquiriesInstance + """ + + data = values.of( + { + "PrimaryProfileSid": primary_profile_sid, + "NotificationEmail": notification_email, + "ThemeSetId": theme_set_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ComplianceInquiriesInstance(self._version, payload) + + async def create_async( + self, + primary_profile_sid: str, + notification_email: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ComplianceInquiriesInstance: + """ + Asynchronously create the ComplianceInquiriesInstance + + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + :param notification_email: The email address that approval status updates will be sent to. If not specified, the email address associated with your primary customer profile will be used. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The created ComplianceInquiriesInstance + """ + + data = values.of( + { + "PrimaryProfileSid": primary_profile_sid, + "NotificationEmail": notification_email, + "ThemeSetId": theme_set_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ComplianceInquiriesInstance(self._version, payload) + + def get(self, customer_id: str) -> ComplianceInquiriesContext: + """ + Constructs a ComplianceInquiriesContext + + :param customer_id: The unique CustomerId matching the Customer Profile/Compliance Inquiry that should be resumed or resubmitted. This value will have been returned by the initial Compliance Inquiry creation call. + """ + return ComplianceInquiriesContext(self._version, customer_id=customer_id) + + def __call__(self, customer_id: str) -> ComplianceInquiriesContext: + """ + Constructs a ComplianceInquiriesContext + + :param customer_id: The unique CustomerId matching the Customer Profile/Compliance Inquiry that should be resumed or resubmitted. This value will have been returned by the initial Compliance Inquiry creation call. + """ + return ComplianceInquiriesContext(self._version, customer_id=customer_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/compliance_registration_inquiries.py b/venv/Lib/site-packages/twilio/rest/trusthub/v1/compliance_registration_inquiries.py new file mode 100644 index 00000000..eccd1ac8 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trusthub/v1/compliance_registration_inquiries.py @@ -0,0 +1,579 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ComplianceRegistrationInquiriesInstance(InstanceResource): + + class BusinessIdentityType(object): + DIRECT_CUSTOMER = "direct_customer" + ISV_RESELLER_OR_PARTNER = "isv_reseller_or_partner" + UNKNOWN = "unknown" + + class BusinessRegistrationAuthority(object): + UK_CRN = "UK:CRN" + US_EIN = "US:EIN" + CA_CBN = "CA:CBN" + AU_ACN = "AU:ACN" + OTHER = "Other" + + class EndUserType(object): + INDIVIDUAL = "Individual" + BUSINESS = "Business" + + class PhoneNumberType(object): + LOCAL = "local" + NATIONAL = "national" + MOBILE = "mobile" + TOLL_FREE = "toll-free" + + """ + :ivar inquiry_id: The unique ID used to start an embedded compliance registration session. + :ivar inquiry_session_token: The session token used to start an embedded compliance registration session. + :ivar registration_id: The RegistrationId matching the Registration Profile that should be resumed or resubmitted for editing. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + registration_id: Optional[str] = None, + ): + super().__init__(version) + + self.inquiry_id: Optional[str] = payload.get("inquiry_id") + self.inquiry_session_token: Optional[str] = payload.get("inquiry_session_token") + self.registration_id: Optional[str] = payload.get("registration_id") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "registration_id": registration_id or self.registration_id, + } + self._context: Optional[ComplianceRegistrationInquiriesContext] = None + + @property + def _proxy(self) -> "ComplianceRegistrationInquiriesContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ComplianceRegistrationInquiriesContext for this ComplianceRegistrationInquiriesInstance + """ + if self._context is None: + self._context = ComplianceRegistrationInquiriesContext( + self._version, + registration_id=self._solution["registration_id"], + ) + return self._context + + def update( + self, + is_isv_embed: Union[bool, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> "ComplianceRegistrationInquiriesInstance": + """ + Update the ComplianceRegistrationInquiriesInstance + + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The updated ComplianceRegistrationInquiriesInstance + """ + return self._proxy.update( + is_isv_embed=is_isv_embed, + theme_set_id=theme_set_id, + ) + + async def update_async( + self, + is_isv_embed: Union[bool, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> "ComplianceRegistrationInquiriesInstance": + """ + Asynchronous coroutine to update the ComplianceRegistrationInquiriesInstance + + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The updated ComplianceRegistrationInquiriesInstance + """ + return await self._proxy.update_async( + is_isv_embed=is_isv_embed, + theme_set_id=theme_set_id, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class ComplianceRegistrationInquiriesContext(InstanceContext): + + def __init__(self, version: Version, registration_id: str): + """ + Initialize the ComplianceRegistrationInquiriesContext + + :param version: Version that contains the resource + :param registration_id: The unique RegistrationId matching the Regulatory Compliance Inquiry that should be resumed or resubmitted. This value will have been returned by the initial Regulatory Compliance Inquiry creation call. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "registration_id": registration_id, + } + self._uri = "/ComplianceInquiries/Registration/{registration_id}/RegulatoryCompliance/GB/Initialize".format( + **self._solution + ) + + def update( + self, + is_isv_embed: Union[bool, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ComplianceRegistrationInquiriesInstance: + """ + Update the ComplianceRegistrationInquiriesInstance + + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The updated ComplianceRegistrationInquiriesInstance + """ + + data = values.of( + { + "IsIsvEmbed": serialize.boolean_to_string(is_isv_embed), + "ThemeSetId": theme_set_id, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ComplianceRegistrationInquiriesInstance( + self._version, payload, registration_id=self._solution["registration_id"] + ) + + async def update_async( + self, + is_isv_embed: Union[bool, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ComplianceRegistrationInquiriesInstance: + """ + Asynchronous coroutine to update the ComplianceRegistrationInquiriesInstance + + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The updated ComplianceRegistrationInquiriesInstance + """ + + data = values.of( + { + "IsIsvEmbed": serialize.boolean_to_string(is_isv_embed), + "ThemeSetId": theme_set_id, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ComplianceRegistrationInquiriesInstance( + self._version, payload, registration_id=self._solution["registration_id"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class ComplianceRegistrationInquiriesList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ComplianceRegistrationInquiriesList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = ( + "/ComplianceInquiries/Registration/RegulatoryCompliance/GB/Initialize" + ) + + def create( + self, + end_user_type: "ComplianceRegistrationInquiriesInstance.EndUserType", + phone_number_type: "ComplianceRegistrationInquiriesInstance.PhoneNumberType", + business_identity_type: Union[ + "ComplianceRegistrationInquiriesInstance.BusinessIdentityType", object + ] = values.unset, + business_registration_authority: Union[ + "ComplianceRegistrationInquiriesInstance.BusinessRegistrationAuthority", + object, + ] = values.unset, + business_legal_name: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + accepted_notification_receipt: Union[bool, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_website_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + authorized_representative1_first_name: Union[str, object] = values.unset, + authorized_representative1_last_name: Union[str, object] = values.unset, + authorized_representative1_phone: Union[str, object] = values.unset, + authorized_representative1_email: Union[str, object] = values.unset, + authorized_representative1_date_of_birth: Union[str, object] = values.unset, + address_street: Union[str, object] = values.unset, + address_street_secondary: Union[str, object] = values.unset, + address_city: Union[str, object] = values.unset, + address_subdivision: Union[str, object] = values.unset, + address_postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + emergency_address_street: Union[str, object] = values.unset, + emergency_address_street_secondary: Union[str, object] = values.unset, + emergency_address_city: Union[str, object] = values.unset, + emergency_address_subdivision: Union[str, object] = values.unset, + emergency_address_postal_code: Union[str, object] = values.unset, + emergency_address_country_code: Union[str, object] = values.unset, + use_address_as_emergency_address: Union[bool, object] = values.unset, + file_name: Union[str, object] = values.unset, + file: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + individual_email: Union[str, object] = values.unset, + individual_phone: Union[str, object] = values.unset, + is_isv_embed: Union[bool, object] = values.unset, + isv_registering_for_self_or_tenant: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ComplianceRegistrationInquiriesInstance: + """ + Create the ComplianceRegistrationInquiriesInstance + + :param end_user_type: + :param phone_number_type: + :param business_identity_type: + :param business_registration_authority: + :param business_legal_name: he name of the business or organization using the Tollfree number. + :param notification_email: he email address to receive the notification about the verification result. + :param accepted_notification_receipt: The email address to receive the notification about the verification result. + :param business_registration_number: Business registration number of the business + :param business_website_url: The URL of the business website + :param friendly_name: Friendly name for your business information + :param authorized_representative1_first_name: First name of the authorized representative + :param authorized_representative1_last_name: Last name of the authorized representative + :param authorized_representative1_phone: Phone number of the authorized representative + :param authorized_representative1_email: Email address of the authorized representative + :param authorized_representative1_date_of_birth: Birthdate of the authorized representative + :param address_street: Street address of the business + :param address_street_secondary: Street address of the business + :param address_city: City of the business + :param address_subdivision: State or province of the business + :param address_postal_code: Postal code of the business + :param address_country_code: Country code of the business + :param emergency_address_street: Street address of the business + :param emergency_address_street_secondary: Street address of the business + :param emergency_address_city: City of the business + :param emergency_address_subdivision: State or province of the business + :param emergency_address_postal_code: Postal code of the business + :param emergency_address_country_code: Country code of the business + :param use_address_as_emergency_address: Use the business address as the emergency address + :param file_name: The name of the verification document to upload + :param file: The verification document to upload + :param first_name: The first name of the Individual User. + :param last_name: The last name of the Individual User. + :param date_of_birth: The date of birth of the Individual User. + :param individual_email: The email address of the Individual User. + :param individual_phone: The phone number of the Individual User. + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param isv_registering_for_self_or_tenant: Indicates if the isv registering for self or tenant. + :param status_callback_url: The url we call to inform you of bundle changes. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The created ComplianceRegistrationInquiriesInstance + """ + + data = values.of( + { + "EndUserType": end_user_type, + "PhoneNumberType": phone_number_type, + "BusinessIdentityType": business_identity_type, + "BusinessRegistrationAuthority": business_registration_authority, + "BusinessLegalName": business_legal_name, + "NotificationEmail": notification_email, + "AcceptedNotificationReceipt": serialize.boolean_to_string( + accepted_notification_receipt + ), + "BusinessRegistrationNumber": business_registration_number, + "BusinessWebsiteUrl": business_website_url, + "FriendlyName": friendly_name, + "AuthorizedRepresentative1FirstName": authorized_representative1_first_name, + "AuthorizedRepresentative1LastName": authorized_representative1_last_name, + "AuthorizedRepresentative1Phone": authorized_representative1_phone, + "AuthorizedRepresentative1Email": authorized_representative1_email, + "AuthorizedRepresentative1DateOfBirth": authorized_representative1_date_of_birth, + "AddressStreet": address_street, + "AddressStreetSecondary": address_street_secondary, + "AddressCity": address_city, + "AddressSubdivision": address_subdivision, + "AddressPostalCode": address_postal_code, + "AddressCountryCode": address_country_code, + "EmergencyAddressStreet": emergency_address_street, + "EmergencyAddressStreetSecondary": emergency_address_street_secondary, + "EmergencyAddressCity": emergency_address_city, + "EmergencyAddressSubdivision": emergency_address_subdivision, + "EmergencyAddressPostalCode": emergency_address_postal_code, + "EmergencyAddressCountryCode": emergency_address_country_code, + "UseAddressAsEmergencyAddress": serialize.boolean_to_string( + use_address_as_emergency_address + ), + "FileName": file_name, + "File": file, + "FirstName": first_name, + "LastName": last_name, + "DateOfBirth": date_of_birth, + "IndividualEmail": individual_email, + "IndividualPhone": individual_phone, + "IsIsvEmbed": serialize.boolean_to_string(is_isv_embed), + "IsvRegisteringForSelfOrTenant": isv_registering_for_self_or_tenant, + "StatusCallbackUrl": status_callback_url, + "ThemeSetId": theme_set_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ComplianceRegistrationInquiriesInstance(self._version, payload) + + async def create_async( + self, + end_user_type: "ComplianceRegistrationInquiriesInstance.EndUserType", + phone_number_type: "ComplianceRegistrationInquiriesInstance.PhoneNumberType", + business_identity_type: Union[ + "ComplianceRegistrationInquiriesInstance.BusinessIdentityType", object + ] = values.unset, + business_registration_authority: Union[ + "ComplianceRegistrationInquiriesInstance.BusinessRegistrationAuthority", + object, + ] = values.unset, + business_legal_name: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + accepted_notification_receipt: Union[bool, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_website_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + authorized_representative1_first_name: Union[str, object] = values.unset, + authorized_representative1_last_name: Union[str, object] = values.unset, + authorized_representative1_phone: Union[str, object] = values.unset, + authorized_representative1_email: Union[str, object] = values.unset, + authorized_representative1_date_of_birth: Union[str, object] = values.unset, + address_street: Union[str, object] = values.unset, + address_street_secondary: Union[str, object] = values.unset, + address_city: Union[str, object] = values.unset, + address_subdivision: Union[str, object] = values.unset, + address_postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + emergency_address_street: Union[str, object] = values.unset, + emergency_address_street_secondary: Union[str, object] = values.unset, + emergency_address_city: Union[str, object] = values.unset, + emergency_address_subdivision: Union[str, object] = values.unset, + emergency_address_postal_code: Union[str, object] = values.unset, + emergency_address_country_code: Union[str, object] = values.unset, + use_address_as_emergency_address: Union[bool, object] = values.unset, + file_name: Union[str, object] = values.unset, + file: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + individual_email: Union[str, object] = values.unset, + individual_phone: Union[str, object] = values.unset, + is_isv_embed: Union[bool, object] = values.unset, + isv_registering_for_self_or_tenant: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ComplianceRegistrationInquiriesInstance: + """ + Asynchronously create the ComplianceRegistrationInquiriesInstance + + :param end_user_type: + :param phone_number_type: + :param business_identity_type: + :param business_registration_authority: + :param business_legal_name: he name of the business or organization using the Tollfree number. + :param notification_email: he email address to receive the notification about the verification result. + :param accepted_notification_receipt: The email address to receive the notification about the verification result. + :param business_registration_number: Business registration number of the business + :param business_website_url: The URL of the business website + :param friendly_name: Friendly name for your business information + :param authorized_representative1_first_name: First name of the authorized representative + :param authorized_representative1_last_name: Last name of the authorized representative + :param authorized_representative1_phone: Phone number of the authorized representative + :param authorized_representative1_email: Email address of the authorized representative + :param authorized_representative1_date_of_birth: Birthdate of the authorized representative + :param address_street: Street address of the business + :param address_street_secondary: Street address of the business + :param address_city: City of the business + :param address_subdivision: State or province of the business + :param address_postal_code: Postal code of the business + :param address_country_code: Country code of the business + :param emergency_address_street: Street address of the business + :param emergency_address_street_secondary: Street address of the business + :param emergency_address_city: City of the business + :param emergency_address_subdivision: State or province of the business + :param emergency_address_postal_code: Postal code of the business + :param emergency_address_country_code: Country code of the business + :param use_address_as_emergency_address: Use the business address as the emergency address + :param file_name: The name of the verification document to upload + :param file: The verification document to upload + :param first_name: The first name of the Individual User. + :param last_name: The last name of the Individual User. + :param date_of_birth: The date of birth of the Individual User. + :param individual_email: The email address of the Individual User. + :param individual_phone: The phone number of the Individual User. + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param isv_registering_for_self_or_tenant: Indicates if the isv registering for self or tenant. + :param status_callback_url: The url we call to inform you of bundle changes. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The created ComplianceRegistrationInquiriesInstance + """ + + data = values.of( + { + "EndUserType": end_user_type, + "PhoneNumberType": phone_number_type, + "BusinessIdentityType": business_identity_type, + "BusinessRegistrationAuthority": business_registration_authority, + "BusinessLegalName": business_legal_name, + "NotificationEmail": notification_email, + "AcceptedNotificationReceipt": serialize.boolean_to_string( + accepted_notification_receipt + ), + "BusinessRegistrationNumber": business_registration_number, + "BusinessWebsiteUrl": business_website_url, + "FriendlyName": friendly_name, + "AuthorizedRepresentative1FirstName": authorized_representative1_first_name, + "AuthorizedRepresentative1LastName": authorized_representative1_last_name, + "AuthorizedRepresentative1Phone": authorized_representative1_phone, + "AuthorizedRepresentative1Email": authorized_representative1_email, + "AuthorizedRepresentative1DateOfBirth": authorized_representative1_date_of_birth, + "AddressStreet": address_street, + "AddressStreetSecondary": address_street_secondary, + "AddressCity": address_city, + "AddressSubdivision": address_subdivision, + "AddressPostalCode": address_postal_code, + "AddressCountryCode": address_country_code, + "EmergencyAddressStreet": emergency_address_street, + "EmergencyAddressStreetSecondary": emergency_address_street_secondary, + "EmergencyAddressCity": emergency_address_city, + "EmergencyAddressSubdivision": emergency_address_subdivision, + "EmergencyAddressPostalCode": emergency_address_postal_code, + "EmergencyAddressCountryCode": emergency_address_country_code, + "UseAddressAsEmergencyAddress": serialize.boolean_to_string( + use_address_as_emergency_address + ), + "FileName": file_name, + "File": file, + "FirstName": first_name, + "LastName": last_name, + "DateOfBirth": date_of_birth, + "IndividualEmail": individual_email, + "IndividualPhone": individual_phone, + "IsIsvEmbed": serialize.boolean_to_string(is_isv_embed), + "IsvRegisteringForSelfOrTenant": isv_registering_for_self_or_tenant, + "StatusCallbackUrl": status_callback_url, + "ThemeSetId": theme_set_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ComplianceRegistrationInquiriesInstance(self._version, payload) + + def get(self, registration_id: str) -> ComplianceRegistrationInquiriesContext: + """ + Constructs a ComplianceRegistrationInquiriesContext + + :param registration_id: The unique RegistrationId matching the Regulatory Compliance Inquiry that should be resumed or resubmitted. This value will have been returned by the initial Regulatory Compliance Inquiry creation call. + """ + return ComplianceRegistrationInquiriesContext( + self._version, registration_id=registration_id + ) + + def __call__(self, registration_id: str) -> ComplianceRegistrationInquiriesContext: + """ + Constructs a ComplianceRegistrationInquiriesContext + + :param registration_id: The unique RegistrationId matching the Regulatory Compliance Inquiry that should be resumed or resubmitted. This value will have been returned by the initial Regulatory Compliance Inquiry creation call. + """ + return ComplianceRegistrationInquiriesContext( + self._version, registration_id=registration_id + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/compliance_tollfree_inquiries.py b/venv/Lib/site-packages/twilio/rest/trusthub/v1/compliance_tollfree_inquiries.py new file mode 100644 index 00000000..9cf259a3 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trusthub/v1/compliance_tollfree_inquiries.py @@ -0,0 +1,274 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ComplianceTollfreeInquiriesInstance(InstanceResource): + + class OptInType(object): + VERBAL = "VERBAL" + WEB_FORM = "WEB_FORM" + PAPER_FORM = "PAPER_FORM" + VIA_TEXT = "VIA_TEXT" + MOBILE_QR_CODE = "MOBILE_QR_CODE" + + """ + :ivar inquiry_id: The unique ID used to start an embedded compliance registration session. + :ivar inquiry_session_token: The session token used to start an embedded compliance registration session. + :ivar registration_id: The TolfreeId matching the Tollfree Profile that should be resumed or resubmitted for editing. + :ivar url: The URL of this resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.inquiry_id: Optional[str] = payload.get("inquiry_id") + self.inquiry_session_token: Optional[str] = payload.get("inquiry_session_token") + self.registration_id: Optional[str] = payload.get("registration_id") + self.url: Optional[str] = payload.get("url") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class ComplianceTollfreeInquiriesList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ComplianceTollfreeInquiriesList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ComplianceInquiries/Tollfree/Initialize" + + def create( + self, + tollfree_phone_number: str, + notification_email: str, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "ComplianceTollfreeInquiriesInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + skip_messaging_use_case: Union[bool, object] = values.unset, + ) -> ComplianceTollfreeInquiriesInstance: + """ + Create the ComplianceTollfreeInquiriesInstance + + :param tollfree_phone_number: The Tollfree phone number to be verified + :param notification_email: The email address to receive the notification about the verification result. + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The phone number of the contact for the business or organization using the Tollfree number. + :param theme_set_id: Theme id for styling the inquiry form. + :param skip_messaging_use_case: Skip the messaging use case screen of the inquiry form. + + :returns: The created ComplianceTollfreeInquiriesInstance + """ + + data = values.of( + { + "TollfreePhoneNumber": tollfree_phone_number, + "NotificationEmail": notification_email, + "BusinessName": business_name, + "BusinessWebsite": business_website, + "UseCaseCategories": serialize.map(use_case_categories, lambda e: e), + "UseCaseSummary": use_case_summary, + "ProductionMessageSample": production_message_sample, + "OptInImageUrls": serialize.map(opt_in_image_urls, lambda e: e), + "OptInType": opt_in_type, + "MessageVolume": message_volume, + "BusinessStreetAddress": business_street_address, + "BusinessStreetAddress2": business_street_address2, + "BusinessCity": business_city, + "BusinessStateProvinceRegion": business_state_province_region, + "BusinessPostalCode": business_postal_code, + "BusinessCountry": business_country, + "AdditionalInformation": additional_information, + "BusinessContactFirstName": business_contact_first_name, + "BusinessContactLastName": business_contact_last_name, + "BusinessContactEmail": business_contact_email, + "BusinessContactPhone": business_contact_phone, + "ThemeSetId": theme_set_id, + "SkipMessagingUseCase": serialize.boolean_to_string( + skip_messaging_use_case + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ComplianceTollfreeInquiriesInstance(self._version, payload) + + async def create_async( + self, + tollfree_phone_number: str, + notification_email: str, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "ComplianceTollfreeInquiriesInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + skip_messaging_use_case: Union[bool, object] = values.unset, + ) -> ComplianceTollfreeInquiriesInstance: + """ + Asynchronously create the ComplianceTollfreeInquiriesInstance + + :param tollfree_phone_number: The Tollfree phone number to be verified + :param notification_email: The email address to receive the notification about the verification result. + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The phone number of the contact for the business or organization using the Tollfree number. + :param theme_set_id: Theme id for styling the inquiry form. + :param skip_messaging_use_case: Skip the messaging use case screen of the inquiry form. + + :returns: The created ComplianceTollfreeInquiriesInstance + """ + + data = values.of( + { + "TollfreePhoneNumber": tollfree_phone_number, + "NotificationEmail": notification_email, + "BusinessName": business_name, + "BusinessWebsite": business_website, + "UseCaseCategories": serialize.map(use_case_categories, lambda e: e), + "UseCaseSummary": use_case_summary, + "ProductionMessageSample": production_message_sample, + "OptInImageUrls": serialize.map(opt_in_image_urls, lambda e: e), + "OptInType": opt_in_type, + "MessageVolume": message_volume, + "BusinessStreetAddress": business_street_address, + "BusinessStreetAddress2": business_street_address2, + "BusinessCity": business_city, + "BusinessStateProvinceRegion": business_state_province_region, + "BusinessPostalCode": business_postal_code, + "BusinessCountry": business_country, + "AdditionalInformation": additional_information, + "BusinessContactFirstName": business_contact_first_name, + "BusinessContactLastName": business_contact_last_name, + "BusinessContactEmail": business_contact_email, + "BusinessContactPhone": business_contact_phone, + "ThemeSetId": theme_set_id, + "SkipMessagingUseCase": serialize.boolean_to_string( + skip_messaging_use_case + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ComplianceTollfreeInquiriesInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/customer_profiles/__init__.py b/venv/Lib/site-packages/twilio/rest/trusthub/v1/customer_profiles/__init__.py new file mode 100644 index 00000000..bf5264e3 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trusthub/v1/customer_profiles/__init__.py @@ -0,0 +1,833 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.trusthub.v1.customer_profiles.customer_profiles_channel_endpoint_assignment import ( + CustomerProfilesChannelEndpointAssignmentList, +) +from twilio.rest.trusthub.v1.customer_profiles.customer_profiles_entity_assignments import ( + CustomerProfilesEntityAssignmentsList, +) +from twilio.rest.trusthub.v1.customer_profiles.customer_profiles_evaluations import ( + CustomerProfilesEvaluationsList, +) + + +class CustomerProfilesInstance(InstanceResource): + + class Status(object): + DRAFT = "draft" + PENDING_REVIEW = "pending-review" + IN_REVIEW = "in-review" + TWILIO_REJECTED = "twilio-rejected" + TWILIO_APPROVED = "twilio-approved" + + """ + :ivar sid: The unique string that we created to identify the Customer-Profile resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Customer-Profile resource. + :ivar policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar status: + :ivar valid_until: The date and time in GMT in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format when the resource will be valid until. + :ivar email: The email address that will receive updates when the Customer-Profile resource changes status. + :ivar status_callback: The URL we call to inform your application of status changes. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Customer-Profile resource. + :ivar links: The URLs of the Assigned Items of the Customer-Profile resource. + :ivar errors: The error codes associated with the rejection of the Customer-Profile. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.policy_sid: Optional[str] = payload.get("policy_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["CustomerProfilesInstance.Status"] = payload.get("status") + self.valid_until: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("valid_until") + ) + self.email: Optional[str] = payload.get("email") + self.status_callback: Optional[str] = payload.get("status_callback") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.errors: Optional[List[Dict[str, object]]] = payload.get("errors") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CustomerProfilesContext] = None + + @property + def _proxy(self) -> "CustomerProfilesContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CustomerProfilesContext for this CustomerProfilesInstance + """ + if self._context is None: + self._context = CustomerProfilesContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CustomerProfilesInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CustomerProfilesInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CustomerProfilesInstance": + """ + Fetch the CustomerProfilesInstance + + + :returns: The fetched CustomerProfilesInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CustomerProfilesInstance": + """ + Asynchronous coroutine to fetch the CustomerProfilesInstance + + + :returns: The fetched CustomerProfilesInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> "CustomerProfilesInstance": + """ + Update the CustomerProfilesInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + + :returns: The updated CustomerProfilesInstance + """ + return self._proxy.update( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + + async def update_async( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> "CustomerProfilesInstance": + """ + Asynchronous coroutine to update the CustomerProfilesInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + + :returns: The updated CustomerProfilesInstance + """ + return await self._proxy.update_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + + @property + def customer_profiles_channel_endpoint_assignment( + self, + ) -> CustomerProfilesChannelEndpointAssignmentList: + """ + Access the customer_profiles_channel_endpoint_assignment + """ + return self._proxy.customer_profiles_channel_endpoint_assignment + + @property + def customer_profiles_entity_assignments( + self, + ) -> CustomerProfilesEntityAssignmentsList: + """ + Access the customer_profiles_entity_assignments + """ + return self._proxy.customer_profiles_entity_assignments + + @property + def customer_profiles_evaluations(self) -> CustomerProfilesEvaluationsList: + """ + Access the customer_profiles_evaluations + """ + return self._proxy.customer_profiles_evaluations + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CustomerProfilesContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CustomerProfilesContext + + :param version: Version that contains the resource + :param sid: The unique string that we created to identify the Customer-Profile resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/CustomerProfiles/{sid}".format(**self._solution) + + self._customer_profiles_channel_endpoint_assignment: Optional[ + CustomerProfilesChannelEndpointAssignmentList + ] = None + self._customer_profiles_entity_assignments: Optional[ + CustomerProfilesEntityAssignmentsList + ] = None + self._customer_profiles_evaluations: Optional[ + CustomerProfilesEvaluationsList + ] = None + + def delete(self) -> bool: + """ + Deletes the CustomerProfilesInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CustomerProfilesInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CustomerProfilesInstance: + """ + Fetch the CustomerProfilesInstance + + + :returns: The fetched CustomerProfilesInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CustomerProfilesInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CustomerProfilesInstance: + """ + Asynchronous coroutine to fetch the CustomerProfilesInstance + + + :returns: The fetched CustomerProfilesInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CustomerProfilesInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> CustomerProfilesInstance: + """ + Update the CustomerProfilesInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + + :returns: The updated CustomerProfilesInstance + """ + + data = values.of( + { + "Status": status, + "StatusCallback": status_callback, + "FriendlyName": friendly_name, + "Email": email, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomerProfilesInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> CustomerProfilesInstance: + """ + Asynchronous coroutine to update the CustomerProfilesInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + + :returns: The updated CustomerProfilesInstance + """ + + data = values.of( + { + "Status": status, + "StatusCallback": status_callback, + "FriendlyName": friendly_name, + "Email": email, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomerProfilesInstance( + self._version, payload, sid=self._solution["sid"] + ) + + @property + def customer_profiles_channel_endpoint_assignment( + self, + ) -> CustomerProfilesChannelEndpointAssignmentList: + """ + Access the customer_profiles_channel_endpoint_assignment + """ + if self._customer_profiles_channel_endpoint_assignment is None: + self._customer_profiles_channel_endpoint_assignment = ( + CustomerProfilesChannelEndpointAssignmentList( + self._version, + self._solution["sid"], + ) + ) + return self._customer_profiles_channel_endpoint_assignment + + @property + def customer_profiles_entity_assignments( + self, + ) -> CustomerProfilesEntityAssignmentsList: + """ + Access the customer_profiles_entity_assignments + """ + if self._customer_profiles_entity_assignments is None: + self._customer_profiles_entity_assignments = ( + CustomerProfilesEntityAssignmentsList( + self._version, + self._solution["sid"], + ) + ) + return self._customer_profiles_entity_assignments + + @property + def customer_profiles_evaluations(self) -> CustomerProfilesEvaluationsList: + """ + Access the customer_profiles_evaluations + """ + if self._customer_profiles_evaluations is None: + self._customer_profiles_evaluations = CustomerProfilesEvaluationsList( + self._version, + self._solution["sid"], + ) + return self._customer_profiles_evaluations + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CustomerProfilesPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CustomerProfilesInstance: + """ + Build an instance of CustomerProfilesInstance + + :param payload: Payload response from the API + """ + return CustomerProfilesInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CustomerProfilesList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CustomerProfilesList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/CustomerProfiles" + + def create( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> CustomerProfilesInstance: + """ + Create the CustomerProfilesInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + :param policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param status_callback: The URL we call to inform your application of status changes. + + :returns: The created CustomerProfilesInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Email": email, + "PolicySid": policy_sid, + "StatusCallback": status_callback, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomerProfilesInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> CustomerProfilesInstance: + """ + Asynchronously create the CustomerProfilesInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + :param policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param status_callback: The URL we call to inform your application of status changes. + + :returns: The created CustomerProfilesInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Email": email, + "PolicySid": policy_sid, + "StatusCallback": status_callback, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomerProfilesInstance(self._version, payload) + + def stream( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CustomerProfilesInstance]: + """ + Streams CustomerProfilesInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "CustomerProfilesInstance.Status" status: The verification status of the Customer-Profile resource. + :param str friendly_name: The string that you assigned to describe the resource. + :param str policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CustomerProfilesInstance]: + """ + Asynchronously streams CustomerProfilesInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "CustomerProfilesInstance.Status" status: The verification status of the Customer-Profile resource. + :param str friendly_name: The string that you assigned to describe the resource. + :param str policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CustomerProfilesInstance]: + """ + Lists CustomerProfilesInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "CustomerProfilesInstance.Status" status: The verification status of the Customer-Profile resource. + :param str friendly_name: The string that you assigned to describe the resource. + :param str policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CustomerProfilesInstance]: + """ + Asynchronously lists CustomerProfilesInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "CustomerProfilesInstance.Status" status: The verification status of the Customer-Profile resource. + :param str friendly_name: The string that you assigned to describe the resource. + :param str policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CustomerProfilesPage: + """ + Retrieve a single page of CustomerProfilesInstance records from the API. + Request is executed immediately + + :param status: The verification status of the Customer-Profile resource. + :param friendly_name: The string that you assigned to describe the resource. + :param policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CustomerProfilesInstance + """ + data = values.of( + { + "Status": status, + "FriendlyName": friendly_name, + "PolicySid": policy_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CustomerProfilesPage(self._version, response) + + async def page_async( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CustomerProfilesPage: + """ + Asynchronously retrieve a single page of CustomerProfilesInstance records from the API. + Request is executed immediately + + :param status: The verification status of the Customer-Profile resource. + :param friendly_name: The string that you assigned to describe the resource. + :param policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CustomerProfilesInstance + """ + data = values.of( + { + "Status": status, + "FriendlyName": friendly_name, + "PolicySid": policy_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CustomerProfilesPage(self._version, response) + + def get_page(self, target_url: str) -> CustomerProfilesPage: + """ + Retrieve a specific page of CustomerProfilesInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CustomerProfilesInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CustomerProfilesPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CustomerProfilesPage: + """ + Asynchronously retrieve a specific page of CustomerProfilesInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CustomerProfilesInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CustomerProfilesPage(self._version, response) + + def get(self, sid: str) -> CustomerProfilesContext: + """ + Constructs a CustomerProfilesContext + + :param sid: The unique string that we created to identify the Customer-Profile resource. + """ + return CustomerProfilesContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CustomerProfilesContext: + """ + Constructs a CustomerProfilesContext + + :param sid: The unique string that we created to identify the Customer-Profile resource. + """ + return CustomerProfilesContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/customer_profiles/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trusthub/v1/customer_profiles/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..276706bb Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trusthub/v1/customer_profiles/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/customer_profiles/__pycache__/customer_profiles_channel_endpoint_assignment.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trusthub/v1/customer_profiles/__pycache__/customer_profiles_channel_endpoint_assignment.cpython-312.pyc new file mode 100644 index 00000000..3aa50fb9 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trusthub/v1/customer_profiles/__pycache__/customer_profiles_channel_endpoint_assignment.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/customer_profiles/__pycache__/customer_profiles_entity_assignments.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trusthub/v1/customer_profiles/__pycache__/customer_profiles_entity_assignments.cpython-312.pyc new file mode 100644 index 00000000..f1ceec91 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trusthub/v1/customer_profiles/__pycache__/customer_profiles_entity_assignments.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/customer_profiles/__pycache__/customer_profiles_evaluations.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trusthub/v1/customer_profiles/__pycache__/customer_profiles_evaluations.cpython-312.pyc new file mode 100644 index 00000000..58737db5 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trusthub/v1/customer_profiles/__pycache__/customer_profiles_evaluations.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_channel_endpoint_assignment.py b/venv/Lib/site-packages/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_channel_endpoint_assignment.py new file mode 100644 index 00000000..1adca541 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_channel_endpoint_assignment.py @@ -0,0 +1,616 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CustomerProfilesChannelEndpointAssignmentInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Item Assignment resource. + :ivar customer_profile_sid: The unique string that we created to identify the CustomerProfile resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Item Assignment resource. + :ivar channel_endpoint_type: The type of channel endpoint. eg: phone-number + :ivar channel_endpoint_sid: The SID of an channel endpoint + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Identity resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + customer_profile_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.customer_profile_sid: Optional[str] = payload.get("customer_profile_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.channel_endpoint_type: Optional[str] = payload.get("channel_endpoint_type") + self.channel_endpoint_sid: Optional[str] = payload.get("channel_endpoint_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "customer_profile_sid": customer_profile_sid, + "sid": sid or self.sid, + } + self._context: Optional[CustomerProfilesChannelEndpointAssignmentContext] = None + + @property + def _proxy(self) -> "CustomerProfilesChannelEndpointAssignmentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CustomerProfilesChannelEndpointAssignmentContext for this CustomerProfilesChannelEndpointAssignmentInstance + """ + if self._context is None: + self._context = CustomerProfilesChannelEndpointAssignmentContext( + self._version, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CustomerProfilesChannelEndpointAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CustomerProfilesChannelEndpointAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CustomerProfilesChannelEndpointAssignmentInstance": + """ + Fetch the CustomerProfilesChannelEndpointAssignmentInstance + + + :returns: The fetched CustomerProfilesChannelEndpointAssignmentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CustomerProfilesChannelEndpointAssignmentInstance": + """ + Asynchronous coroutine to fetch the CustomerProfilesChannelEndpointAssignmentInstance + + + :returns: The fetched CustomerProfilesChannelEndpointAssignmentInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class CustomerProfilesChannelEndpointAssignmentContext(InstanceContext): + + def __init__(self, version: Version, customer_profile_sid: str, sid: str): + """ + Initialize the CustomerProfilesChannelEndpointAssignmentContext + + :param version: Version that contains the resource + :param customer_profile_sid: The unique string that we created to identify the CustomerProfile resource. + :param sid: The unique string that we created to identify the resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "customer_profile_sid": customer_profile_sid, + "sid": sid, + } + self._uri = "/CustomerProfiles/{customer_profile_sid}/ChannelEndpointAssignments/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the CustomerProfilesChannelEndpointAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CustomerProfilesChannelEndpointAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CustomerProfilesChannelEndpointAssignmentInstance: + """ + Fetch the CustomerProfilesChannelEndpointAssignmentInstance + + + :returns: The fetched CustomerProfilesChannelEndpointAssignmentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CustomerProfilesChannelEndpointAssignmentInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CustomerProfilesChannelEndpointAssignmentInstance: + """ + Asynchronous coroutine to fetch the CustomerProfilesChannelEndpointAssignmentInstance + + + :returns: The fetched CustomerProfilesChannelEndpointAssignmentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CustomerProfilesChannelEndpointAssignmentInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class CustomerProfilesChannelEndpointAssignmentPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> CustomerProfilesChannelEndpointAssignmentInstance: + """ + Build an instance of CustomerProfilesChannelEndpointAssignmentInstance + + :param payload: Payload response from the API + """ + return CustomerProfilesChannelEndpointAssignmentInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CustomerProfilesChannelEndpointAssignmentList(ListResource): + + def __init__(self, version: Version, customer_profile_sid: str): + """ + Initialize the CustomerProfilesChannelEndpointAssignmentList + + :param version: Version that contains the resource + :param customer_profile_sid: The unique string that we created to identify the CustomerProfile resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "customer_profile_sid": customer_profile_sid, + } + self._uri = "/CustomerProfiles/{customer_profile_sid}/ChannelEndpointAssignments".format( + **self._solution + ) + + def create( + self, channel_endpoint_type: str, channel_endpoint_sid: str + ) -> CustomerProfilesChannelEndpointAssignmentInstance: + """ + Create the CustomerProfilesChannelEndpointAssignmentInstance + + :param channel_endpoint_type: The type of channel endpoint. eg: phone-number + :param channel_endpoint_sid: The SID of an channel endpoint + + :returns: The created CustomerProfilesChannelEndpointAssignmentInstance + """ + + data = values.of( + { + "ChannelEndpointType": channel_endpoint_type, + "ChannelEndpointSid": channel_endpoint_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomerProfilesChannelEndpointAssignmentInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + async def create_async( + self, channel_endpoint_type: str, channel_endpoint_sid: str + ) -> CustomerProfilesChannelEndpointAssignmentInstance: + """ + Asynchronously create the CustomerProfilesChannelEndpointAssignmentInstance + + :param channel_endpoint_type: The type of channel endpoint. eg: phone-number + :param channel_endpoint_sid: The SID of an channel endpoint + + :returns: The created CustomerProfilesChannelEndpointAssignmentInstance + """ + + data = values.of( + { + "ChannelEndpointType": channel_endpoint_type, + "ChannelEndpointSid": channel_endpoint_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomerProfilesChannelEndpointAssignmentInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + def stream( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CustomerProfilesChannelEndpointAssignmentInstance]: + """ + Streams CustomerProfilesChannelEndpointAssignmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str channel_endpoint_sid: The SID of an channel endpoint + :param str channel_endpoint_sids: comma separated list of channel endpoint sids + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CustomerProfilesChannelEndpointAssignmentInstance]: + """ + Asynchronously streams CustomerProfilesChannelEndpointAssignmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str channel_endpoint_sid: The SID of an channel endpoint + :param str channel_endpoint_sids: comma separated list of channel endpoint sids + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CustomerProfilesChannelEndpointAssignmentInstance]: + """ + Lists CustomerProfilesChannelEndpointAssignmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str channel_endpoint_sid: The SID of an channel endpoint + :param str channel_endpoint_sids: comma separated list of channel endpoint sids + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CustomerProfilesChannelEndpointAssignmentInstance]: + """ + Asynchronously lists CustomerProfilesChannelEndpointAssignmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str channel_endpoint_sid: The SID of an channel endpoint + :param str channel_endpoint_sids: comma separated list of channel endpoint sids + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CustomerProfilesChannelEndpointAssignmentPage: + """ + Retrieve a single page of CustomerProfilesChannelEndpointAssignmentInstance records from the API. + Request is executed immediately + + :param channel_endpoint_sid: The SID of an channel endpoint + :param channel_endpoint_sids: comma separated list of channel endpoint sids + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CustomerProfilesChannelEndpointAssignmentInstance + """ + data = values.of( + { + "ChannelEndpointSid": channel_endpoint_sid, + "ChannelEndpointSids": channel_endpoint_sids, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CustomerProfilesChannelEndpointAssignmentPage( + self._version, response, self._solution + ) + + async def page_async( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CustomerProfilesChannelEndpointAssignmentPage: + """ + Asynchronously retrieve a single page of CustomerProfilesChannelEndpointAssignmentInstance records from the API. + Request is executed immediately + + :param channel_endpoint_sid: The SID of an channel endpoint + :param channel_endpoint_sids: comma separated list of channel endpoint sids + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CustomerProfilesChannelEndpointAssignmentInstance + """ + data = values.of( + { + "ChannelEndpointSid": channel_endpoint_sid, + "ChannelEndpointSids": channel_endpoint_sids, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CustomerProfilesChannelEndpointAssignmentPage( + self._version, response, self._solution + ) + + def get_page( + self, target_url: str + ) -> CustomerProfilesChannelEndpointAssignmentPage: + """ + Retrieve a specific page of CustomerProfilesChannelEndpointAssignmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CustomerProfilesChannelEndpointAssignmentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CustomerProfilesChannelEndpointAssignmentPage( + self._version, response, self._solution + ) + + async def get_page_async( + self, target_url: str + ) -> CustomerProfilesChannelEndpointAssignmentPage: + """ + Asynchronously retrieve a specific page of CustomerProfilesChannelEndpointAssignmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CustomerProfilesChannelEndpointAssignmentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CustomerProfilesChannelEndpointAssignmentPage( + self._version, response, self._solution + ) + + def get(self, sid: str) -> CustomerProfilesChannelEndpointAssignmentContext: + """ + Constructs a CustomerProfilesChannelEndpointAssignmentContext + + :param sid: The unique string that we created to identify the resource. + """ + return CustomerProfilesChannelEndpointAssignmentContext( + self._version, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> CustomerProfilesChannelEndpointAssignmentContext: + """ + Constructs a CustomerProfilesChannelEndpointAssignmentContext + + :param sid: The unique string that we created to identify the resource. + """ + return CustomerProfilesChannelEndpointAssignmentContext( + self._version, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_entity_assignments.py b/venv/Lib/site-packages/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_entity_assignments.py new file mode 100644 index 00000000..f8710b9c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_entity_assignments.py @@ -0,0 +1,590 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CustomerProfilesEntityAssignmentsInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Item Assignment resource. + :ivar customer_profile_sid: The unique string that we created to identify the CustomerProfile resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Item Assignment resource. + :ivar object_sid: The SID of an object bag that holds information of the different items. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Identity resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + customer_profile_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.customer_profile_sid: Optional[str] = payload.get("customer_profile_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.object_sid: Optional[str] = payload.get("object_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "customer_profile_sid": customer_profile_sid, + "sid": sid or self.sid, + } + self._context: Optional[CustomerProfilesEntityAssignmentsContext] = None + + @property + def _proxy(self) -> "CustomerProfilesEntityAssignmentsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CustomerProfilesEntityAssignmentsContext for this CustomerProfilesEntityAssignmentsInstance + """ + if self._context is None: + self._context = CustomerProfilesEntityAssignmentsContext( + self._version, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CustomerProfilesEntityAssignmentsInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CustomerProfilesEntityAssignmentsInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CustomerProfilesEntityAssignmentsInstance": + """ + Fetch the CustomerProfilesEntityAssignmentsInstance + + + :returns: The fetched CustomerProfilesEntityAssignmentsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CustomerProfilesEntityAssignmentsInstance": + """ + Asynchronous coroutine to fetch the CustomerProfilesEntityAssignmentsInstance + + + :returns: The fetched CustomerProfilesEntityAssignmentsInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return ( + "".format( + context + ) + ) + + +class CustomerProfilesEntityAssignmentsContext(InstanceContext): + + def __init__(self, version: Version, customer_profile_sid: str, sid: str): + """ + Initialize the CustomerProfilesEntityAssignmentsContext + + :param version: Version that contains the resource + :param customer_profile_sid: The unique string that we created to identify the CustomerProfile resource. + :param sid: The unique string that we created to identify the Identity resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "customer_profile_sid": customer_profile_sid, + "sid": sid, + } + self._uri = ( + "/CustomerProfiles/{customer_profile_sid}/EntityAssignments/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the CustomerProfilesEntityAssignmentsInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CustomerProfilesEntityAssignmentsInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CustomerProfilesEntityAssignmentsInstance: + """ + Fetch the CustomerProfilesEntityAssignmentsInstance + + + :returns: The fetched CustomerProfilesEntityAssignmentsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CustomerProfilesEntityAssignmentsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CustomerProfilesEntityAssignmentsInstance: + """ + Asynchronous coroutine to fetch the CustomerProfilesEntityAssignmentsInstance + + + :returns: The fetched CustomerProfilesEntityAssignmentsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CustomerProfilesEntityAssignmentsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return ( + "".format( + context + ) + ) + + +class CustomerProfilesEntityAssignmentsPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> CustomerProfilesEntityAssignmentsInstance: + """ + Build an instance of CustomerProfilesEntityAssignmentsInstance + + :param payload: Payload response from the API + """ + return CustomerProfilesEntityAssignmentsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CustomerProfilesEntityAssignmentsList(ListResource): + + def __init__(self, version: Version, customer_profile_sid: str): + """ + Initialize the CustomerProfilesEntityAssignmentsList + + :param version: Version that contains the resource + :param customer_profile_sid: The unique string that we created to identify the CustomerProfile resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "customer_profile_sid": customer_profile_sid, + } + self._uri = "/CustomerProfiles/{customer_profile_sid}/EntityAssignments".format( + **self._solution + ) + + def create(self, object_sid: str) -> CustomerProfilesEntityAssignmentsInstance: + """ + Create the CustomerProfilesEntityAssignmentsInstance + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: The created CustomerProfilesEntityAssignmentsInstance + """ + + data = values.of( + { + "ObjectSid": object_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomerProfilesEntityAssignmentsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + async def create_async( + self, object_sid: str + ) -> CustomerProfilesEntityAssignmentsInstance: + """ + Asynchronously create the CustomerProfilesEntityAssignmentsInstance + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: The created CustomerProfilesEntityAssignmentsInstance + """ + + data = values.of( + { + "ObjectSid": object_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomerProfilesEntityAssignmentsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + def stream( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CustomerProfilesEntityAssignmentsInstance]: + """ + Streams CustomerProfilesEntityAssignmentsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(object_type=object_type, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CustomerProfilesEntityAssignmentsInstance]: + """ + Asynchronously streams CustomerProfilesEntityAssignmentsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + object_type=object_type, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CustomerProfilesEntityAssignmentsInstance]: + """ + Lists CustomerProfilesEntityAssignmentsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + object_type=object_type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CustomerProfilesEntityAssignmentsInstance]: + """ + Asynchronously lists CustomerProfilesEntityAssignmentsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + object_type=object_type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + object_type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CustomerProfilesEntityAssignmentsPage: + """ + Retrieve a single page of CustomerProfilesEntityAssignmentsInstance records from the API. + Request is executed immediately + + :param object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CustomerProfilesEntityAssignmentsInstance + """ + data = values.of( + { + "ObjectType": object_type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CustomerProfilesEntityAssignmentsPage( + self._version, response, self._solution + ) + + async def page_async( + self, + object_type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CustomerProfilesEntityAssignmentsPage: + """ + Asynchronously retrieve a single page of CustomerProfilesEntityAssignmentsInstance records from the API. + Request is executed immediately + + :param object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CustomerProfilesEntityAssignmentsInstance + """ + data = values.of( + { + "ObjectType": object_type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CustomerProfilesEntityAssignmentsPage( + self._version, response, self._solution + ) + + def get_page(self, target_url: str) -> CustomerProfilesEntityAssignmentsPage: + """ + Retrieve a specific page of CustomerProfilesEntityAssignmentsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CustomerProfilesEntityAssignmentsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CustomerProfilesEntityAssignmentsPage( + self._version, response, self._solution + ) + + async def get_page_async( + self, target_url: str + ) -> CustomerProfilesEntityAssignmentsPage: + """ + Asynchronously retrieve a specific page of CustomerProfilesEntityAssignmentsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CustomerProfilesEntityAssignmentsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CustomerProfilesEntityAssignmentsPage( + self._version, response, self._solution + ) + + def get(self, sid: str) -> CustomerProfilesEntityAssignmentsContext: + """ + Constructs a CustomerProfilesEntityAssignmentsContext + + :param sid: The unique string that we created to identify the Identity resource. + """ + return CustomerProfilesEntityAssignmentsContext( + self._version, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> CustomerProfilesEntityAssignmentsContext: + """ + Constructs a CustomerProfilesEntityAssignmentsContext + + :param sid: The unique string that we created to identify the Identity resource. + """ + return CustomerProfilesEntityAssignmentsContext( + self._version, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_evaluations.py b/venv/Lib/site-packages/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_evaluations.py new file mode 100644 index 00000000..648467aa --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_evaluations.py @@ -0,0 +1,523 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CustomerProfilesEvaluationsInstance(InstanceResource): + + class Status(object): + COMPLIANT = "compliant" + NONCOMPLIANT = "noncompliant" + + """ + :ivar sid: The unique string that identifies the Evaluation resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the customer_profile resource. + :ivar policy_sid: The unique string of a policy that is associated to the customer_profile resource. + :ivar customer_profile_sid: The unique string that we created to identify the customer_profile resource. + :ivar status: + :ivar results: The results of the Evaluation which includes the valid and invalid attributes. + :ivar date_created: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + customer_profile_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.policy_sid: Optional[str] = payload.get("policy_sid") + self.customer_profile_sid: Optional[str] = payload.get("customer_profile_sid") + self.status: Optional["CustomerProfilesEvaluationsInstance.Status"] = ( + payload.get("status") + ) + self.results: Optional[List[Dict[str, object]]] = payload.get("results") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "customer_profile_sid": customer_profile_sid, + "sid": sid or self.sid, + } + self._context: Optional[CustomerProfilesEvaluationsContext] = None + + @property + def _proxy(self) -> "CustomerProfilesEvaluationsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CustomerProfilesEvaluationsContext for this CustomerProfilesEvaluationsInstance + """ + if self._context is None: + self._context = CustomerProfilesEvaluationsContext( + self._version, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "CustomerProfilesEvaluationsInstance": + """ + Fetch the CustomerProfilesEvaluationsInstance + + + :returns: The fetched CustomerProfilesEvaluationsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CustomerProfilesEvaluationsInstance": + """ + Asynchronous coroutine to fetch the CustomerProfilesEvaluationsInstance + + + :returns: The fetched CustomerProfilesEvaluationsInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class CustomerProfilesEvaluationsContext(InstanceContext): + + def __init__(self, version: Version, customer_profile_sid: str, sid: str): + """ + Initialize the CustomerProfilesEvaluationsContext + + :param version: Version that contains the resource + :param customer_profile_sid: The unique string that we created to identify the customer_profile resource. + :param sid: The unique string that identifies the Evaluation resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "customer_profile_sid": customer_profile_sid, + "sid": sid, + } + self._uri = "/CustomerProfiles/{customer_profile_sid}/Evaluations/{sid}".format( + **self._solution + ) + + def fetch(self) -> CustomerProfilesEvaluationsInstance: + """ + Fetch the CustomerProfilesEvaluationsInstance + + + :returns: The fetched CustomerProfilesEvaluationsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CustomerProfilesEvaluationsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CustomerProfilesEvaluationsInstance: + """ + Asynchronous coroutine to fetch the CustomerProfilesEvaluationsInstance + + + :returns: The fetched CustomerProfilesEvaluationsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CustomerProfilesEvaluationsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class CustomerProfilesEvaluationsPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> CustomerProfilesEvaluationsInstance: + """ + Build an instance of CustomerProfilesEvaluationsInstance + + :param payload: Payload response from the API + """ + return CustomerProfilesEvaluationsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CustomerProfilesEvaluationsList(ListResource): + + def __init__(self, version: Version, customer_profile_sid: str): + """ + Initialize the CustomerProfilesEvaluationsList + + :param version: Version that contains the resource + :param customer_profile_sid: The unique string that we created to identify the CustomerProfile resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "customer_profile_sid": customer_profile_sid, + } + self._uri = "/CustomerProfiles/{customer_profile_sid}/Evaluations".format( + **self._solution + ) + + def create(self, policy_sid: str) -> CustomerProfilesEvaluationsInstance: + """ + Create the CustomerProfilesEvaluationsInstance + + :param policy_sid: The unique string of a policy that is associated to the customer_profile resource. + + :returns: The created CustomerProfilesEvaluationsInstance + """ + + data = values.of( + { + "PolicySid": policy_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomerProfilesEvaluationsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + async def create_async( + self, policy_sid: str + ) -> CustomerProfilesEvaluationsInstance: + """ + Asynchronously create the CustomerProfilesEvaluationsInstance + + :param policy_sid: The unique string of a policy that is associated to the customer_profile resource. + + :returns: The created CustomerProfilesEvaluationsInstance + """ + + data = values.of( + { + "PolicySid": policy_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomerProfilesEvaluationsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CustomerProfilesEvaluationsInstance]: + """ + Streams CustomerProfilesEvaluationsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CustomerProfilesEvaluationsInstance]: + """ + Asynchronously streams CustomerProfilesEvaluationsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CustomerProfilesEvaluationsInstance]: + """ + Lists CustomerProfilesEvaluationsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CustomerProfilesEvaluationsInstance]: + """ + Asynchronously lists CustomerProfilesEvaluationsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CustomerProfilesEvaluationsPage: + """ + Retrieve a single page of CustomerProfilesEvaluationsInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CustomerProfilesEvaluationsInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CustomerProfilesEvaluationsPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CustomerProfilesEvaluationsPage: + """ + Asynchronously retrieve a single page of CustomerProfilesEvaluationsInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CustomerProfilesEvaluationsInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CustomerProfilesEvaluationsPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> CustomerProfilesEvaluationsPage: + """ + Retrieve a specific page of CustomerProfilesEvaluationsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CustomerProfilesEvaluationsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CustomerProfilesEvaluationsPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> CustomerProfilesEvaluationsPage: + """ + Asynchronously retrieve a specific page of CustomerProfilesEvaluationsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CustomerProfilesEvaluationsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CustomerProfilesEvaluationsPage(self._version, response, self._solution) + + def get(self, sid: str) -> CustomerProfilesEvaluationsContext: + """ + Constructs a CustomerProfilesEvaluationsContext + + :param sid: The unique string that identifies the Evaluation resource. + """ + return CustomerProfilesEvaluationsContext( + self._version, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> CustomerProfilesEvaluationsContext: + """ + Constructs a CustomerProfilesEvaluationsContext + + :param sid: The unique string that identifies the Evaluation resource. + """ + return CustomerProfilesEvaluationsContext( + self._version, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/end_user.py b/venv/Lib/site-packages/twilio/rest/trusthub/v1/end_user.py new file mode 100644 index 00000000..5ce3b819 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trusthub/v1/end_user.py @@ -0,0 +1,633 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class EndUserInstance(InstanceResource): + """ + :ivar sid: The unique string created by Twilio to identify the End User resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the End User resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: The type of end user of the Bundle resource - can be `individual` or `business`. + :ivar attributes: The set of parameters that are the attributes of the End Users resource which are listed in the End User Types. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the End User resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional[str] = payload.get("type") + self.attributes: Optional[Dict[str, object]] = payload.get("attributes") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[EndUserContext] = None + + @property + def _proxy(self) -> "EndUserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EndUserContext for this EndUserInstance + """ + if self._context is None: + self._context = EndUserContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the EndUserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the EndUserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "EndUserInstance": + """ + Fetch the EndUserInstance + + + :returns: The fetched EndUserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EndUserInstance": + """ + Asynchronous coroutine to fetch the EndUserInstance + + + :returns: The fetched EndUserInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> "EndUserInstance": + """ + Update the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The updated EndUserInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + attributes=attributes, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> "EndUserInstance": + """ + Asynchronous coroutine to update the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The updated EndUserInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + attributes=attributes, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EndUserContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the EndUserContext + + :param version: Version that contains the resource + :param sid: The unique string created by Twilio to identify the End User resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/EndUsers/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the EndUserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the EndUserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> EndUserInstance: + """ + Fetch the EndUserInstance + + + :returns: The fetched EndUserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> EndUserInstance: + """ + Asynchronous coroutine to fetch the EndUserInstance + + + :returns: The fetched EndUserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: + """ + Update the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The updated EndUserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EndUserInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: + """ + Asynchronous coroutine to update the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The updated EndUserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EndUserInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EndUserPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EndUserInstance: + """ + Build an instance of EndUserInstance + + :param payload: Payload response from the API + """ + return EndUserInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class EndUserList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the EndUserList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/EndUsers" + + def create( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: + """ + Create the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of end user of the Bundle resource - can be `individual` or `business`. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The created EndUserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EndUserInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: + """ + Asynchronously create the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of end user of the Bundle resource - can be `individual` or `business`. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The created EndUserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EndUserInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EndUserInstance]: + """ + Streams EndUserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EndUserInstance]: + """ + Asynchronously streams EndUserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EndUserInstance]: + """ + Lists EndUserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EndUserInstance]: + """ + Asynchronously lists EndUserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EndUserPage: + """ + Retrieve a single page of EndUserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EndUserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EndUserPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EndUserPage: + """ + Asynchronously retrieve a single page of EndUserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EndUserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EndUserPage(self._version, response) + + def get_page(self, target_url: str) -> EndUserPage: + """ + Retrieve a specific page of EndUserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EndUserInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EndUserPage(self._version, response) + + async def get_page_async(self, target_url: str) -> EndUserPage: + """ + Asynchronously retrieve a specific page of EndUserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EndUserInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EndUserPage(self._version, response) + + def get(self, sid: str) -> EndUserContext: + """ + Constructs a EndUserContext + + :param sid: The unique string created by Twilio to identify the End User resource. + """ + return EndUserContext(self._version, sid=sid) + + def __call__(self, sid: str) -> EndUserContext: + """ + Constructs a EndUserContext + + :param sid: The unique string created by Twilio to identify the End User resource. + """ + return EndUserContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/end_user_type.py b/venv/Lib/site-packages/twilio/rest/trusthub/v1/end_user_type.py new file mode 100644 index 00000000..0eb2957e --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trusthub/v1/end_user_type.py @@ -0,0 +1,408 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class EndUserTypeInstance(InstanceResource): + """ + :ivar sid: The unique string that identifies the End-User Type resource. + :ivar friendly_name: A human-readable description that is assigned to describe the End-User Type resource. Examples can include first name, last name, email, business name, etc + :ivar machine_name: A machine-readable description of the End-User Type resource. Examples can include first_name, last_name, email, business_name, etc. + :ivar fields: The required information for creating an End-User. The required fields will change as regulatory needs change and will differ for businesses and individuals. + :ivar url: The absolute URL of the End-User Type resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.machine_name: Optional[str] = payload.get("machine_name") + self.fields: Optional[List[Dict[str, object]]] = payload.get("fields") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[EndUserTypeContext] = None + + @property + def _proxy(self) -> "EndUserTypeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EndUserTypeContext for this EndUserTypeInstance + """ + if self._context is None: + self._context = EndUserTypeContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "EndUserTypeInstance": + """ + Fetch the EndUserTypeInstance + + + :returns: The fetched EndUserTypeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EndUserTypeInstance": + """ + Asynchronous coroutine to fetch the EndUserTypeInstance + + + :returns: The fetched EndUserTypeInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EndUserTypeContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the EndUserTypeContext + + :param version: Version that contains the resource + :param sid: The unique string that identifies the End-User Type resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/EndUserTypes/{sid}".format(**self._solution) + + def fetch(self) -> EndUserTypeInstance: + """ + Fetch the EndUserTypeInstance + + + :returns: The fetched EndUserTypeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> EndUserTypeInstance: + """ + Asynchronous coroutine to fetch the EndUserTypeInstance + + + :returns: The fetched EndUserTypeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EndUserTypePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EndUserTypeInstance: + """ + Build an instance of EndUserTypeInstance + + :param payload: Payload response from the API + """ + return EndUserTypeInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class EndUserTypeList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the EndUserTypeList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/EndUserTypes" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EndUserTypeInstance]: + """ + Streams EndUserTypeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EndUserTypeInstance]: + """ + Asynchronously streams EndUserTypeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EndUserTypeInstance]: + """ + Lists EndUserTypeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EndUserTypeInstance]: + """ + Asynchronously lists EndUserTypeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EndUserTypePage: + """ + Retrieve a single page of EndUserTypeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EndUserTypeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EndUserTypePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EndUserTypePage: + """ + Asynchronously retrieve a single page of EndUserTypeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EndUserTypeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EndUserTypePage(self._version, response) + + def get_page(self, target_url: str) -> EndUserTypePage: + """ + Retrieve a specific page of EndUserTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EndUserTypeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EndUserTypePage(self._version, response) + + async def get_page_async(self, target_url: str) -> EndUserTypePage: + """ + Asynchronously retrieve a specific page of EndUserTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EndUserTypeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EndUserTypePage(self._version, response) + + def get(self, sid: str) -> EndUserTypeContext: + """ + Constructs a EndUserTypeContext + + :param sid: The unique string that identifies the End-User Type resource. + """ + return EndUserTypeContext(self._version, sid=sid) + + def __call__(self, sid: str) -> EndUserTypeContext: + """ + Constructs a EndUserTypeContext + + :param sid: The unique string that identifies the End-User Type resource. + """ + return EndUserTypeContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/policies.py b/venv/Lib/site-packages/twilio/rest/trusthub/v1/policies.py new file mode 100644 index 00000000..36a0916c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trusthub/v1/policies.py @@ -0,0 +1,406 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class PoliciesInstance(InstanceResource): + """ + :ivar sid: The unique string that identifies the Policy resource. + :ivar friendly_name: A human-readable description that is assigned to describe the Policy resource. Examples can include Primary Customer profile policy + :ivar requirements: The SID of an object that holds the policy information + :ivar url: The absolute URL of the Policy resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.requirements: Optional[Dict[str, object]] = payload.get("requirements") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[PoliciesContext] = None + + @property + def _proxy(self) -> "PoliciesContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PoliciesContext for this PoliciesInstance + """ + if self._context is None: + self._context = PoliciesContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "PoliciesInstance": + """ + Fetch the PoliciesInstance + + + :returns: The fetched PoliciesInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PoliciesInstance": + """ + Asynchronous coroutine to fetch the PoliciesInstance + + + :returns: The fetched PoliciesInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PoliciesContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the PoliciesContext + + :param version: Version that contains the resource + :param sid: The unique string that identifies the Policy resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Policies/{sid}".format(**self._solution) + + def fetch(self) -> PoliciesInstance: + """ + Fetch the PoliciesInstance + + + :returns: The fetched PoliciesInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PoliciesInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> PoliciesInstance: + """ + Asynchronous coroutine to fetch the PoliciesInstance + + + :returns: The fetched PoliciesInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PoliciesInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PoliciesPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PoliciesInstance: + """ + Build an instance of PoliciesInstance + + :param payload: Payload response from the API + """ + return PoliciesInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class PoliciesList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PoliciesList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Policies" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PoliciesInstance]: + """ + Streams PoliciesInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PoliciesInstance]: + """ + Asynchronously streams PoliciesInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PoliciesInstance]: + """ + Lists PoliciesInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PoliciesInstance]: + """ + Asynchronously lists PoliciesInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PoliciesPage: + """ + Retrieve a single page of PoliciesInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PoliciesInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PoliciesPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PoliciesPage: + """ + Asynchronously retrieve a single page of PoliciesInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PoliciesInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PoliciesPage(self._version, response) + + def get_page(self, target_url: str) -> PoliciesPage: + """ + Retrieve a specific page of PoliciesInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PoliciesInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PoliciesPage(self._version, response) + + async def get_page_async(self, target_url: str) -> PoliciesPage: + """ + Asynchronously retrieve a specific page of PoliciesInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PoliciesInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PoliciesPage(self._version, response) + + def get(self, sid: str) -> PoliciesContext: + """ + Constructs a PoliciesContext + + :param sid: The unique string that identifies the Policy resource. + """ + return PoliciesContext(self._version, sid=sid) + + def __call__(self, sid: str) -> PoliciesContext: + """ + Constructs a PoliciesContext + + :param sid: The unique string that identifies the Policy resource. + """ + return PoliciesContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/supporting_document.py b/venv/Lib/site-packages/twilio/rest/trusthub/v1/supporting_document.py new file mode 100644 index 00000000..f2fd3b7e --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trusthub/v1/supporting_document.py @@ -0,0 +1,652 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SupportingDocumentInstance(InstanceResource): + + class Status(object): + DRAFT = "DRAFT" + PENDING_REVIEW = "PENDING_REVIEW" + REJECTED = "REJECTED" + APPROVED = "APPROVED" + EXPIRED = "EXPIRED" + PROVISIONALLY_APPROVED = "PROVISIONALLY_APPROVED" + + """ + :ivar sid: The unique string created by Twilio to identify the Supporting Document resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Document resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar mime_type: The image type uploaded in the Supporting Document container. + :ivar status: + :ivar type: The type of the Supporting Document. + :ivar attributes: The set of parameters that are the attributes of the Supporting Documents resource which are listed in the Supporting Document Types. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Supporting Document resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.mime_type: Optional[str] = payload.get("mime_type") + self.status: Optional["SupportingDocumentInstance.Status"] = payload.get( + "status" + ) + self.type: Optional[str] = payload.get("type") + self.attributes: Optional[Dict[str, object]] = payload.get("attributes") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SupportingDocumentContext] = None + + @property + def _proxy(self) -> "SupportingDocumentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SupportingDocumentContext for this SupportingDocumentInstance + """ + if self._context is None: + self._context = SupportingDocumentContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SupportingDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SupportingDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SupportingDocumentInstance": + """ + Fetch the SupportingDocumentInstance + + + :returns: The fetched SupportingDocumentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SupportingDocumentInstance": + """ + Asynchronous coroutine to fetch the SupportingDocumentInstance + + + :returns: The fetched SupportingDocumentInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> "SupportingDocumentInstance": + """ + Update the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: The updated SupportingDocumentInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + attributes=attributes, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> "SupportingDocumentInstance": + """ + Asynchronous coroutine to update the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: The updated SupportingDocumentInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + attributes=attributes, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SupportingDocumentContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SupportingDocumentContext + + :param version: Version that contains the resource + :param sid: The unique string created by Twilio to identify the Supporting Document resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/SupportingDocuments/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the SupportingDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SupportingDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SupportingDocumentInstance: + """ + Fetch the SupportingDocumentInstance + + + :returns: The fetched SupportingDocumentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SupportingDocumentInstance: + """ + Asynchronous coroutine to fetch the SupportingDocumentInstance + + + :returns: The fetched SupportingDocumentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: + """ + Update the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: The updated SupportingDocumentInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SupportingDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: + """ + Asynchronous coroutine to update the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: The updated SupportingDocumentInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SupportingDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SupportingDocumentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SupportingDocumentInstance: + """ + Build an instance of SupportingDocumentInstance + + :param payload: Payload response from the API + """ + return SupportingDocumentInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SupportingDocumentList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SupportingDocumentList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/SupportingDocuments" + + def create( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: + """ + Create the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of the Supporting Document. + :param attributes: The set of parameters that are the attributes of the Supporting Documents resource which are derived Supporting Document Types. + + :returns: The created SupportingDocumentInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SupportingDocumentInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: + """ + Asynchronously create the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of the Supporting Document. + :param attributes: The set of parameters that are the attributes of the Supporting Documents resource which are derived Supporting Document Types. + + :returns: The created SupportingDocumentInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SupportingDocumentInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SupportingDocumentInstance]: + """ + Streams SupportingDocumentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SupportingDocumentInstance]: + """ + Asynchronously streams SupportingDocumentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SupportingDocumentInstance]: + """ + Lists SupportingDocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SupportingDocumentInstance]: + """ + Asynchronously lists SupportingDocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SupportingDocumentPage: + """ + Retrieve a single page of SupportingDocumentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SupportingDocumentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SupportingDocumentPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SupportingDocumentPage: + """ + Asynchronously retrieve a single page of SupportingDocumentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SupportingDocumentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SupportingDocumentPage(self._version, response) + + def get_page(self, target_url: str) -> SupportingDocumentPage: + """ + Retrieve a specific page of SupportingDocumentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SupportingDocumentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SupportingDocumentPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SupportingDocumentPage: + """ + Asynchronously retrieve a specific page of SupportingDocumentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SupportingDocumentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SupportingDocumentPage(self._version, response) + + def get(self, sid: str) -> SupportingDocumentContext: + """ + Constructs a SupportingDocumentContext + + :param sid: The unique string created by Twilio to identify the Supporting Document resource. + """ + return SupportingDocumentContext(self._version, sid=sid) + + def __call__(self, sid: str) -> SupportingDocumentContext: + """ + Constructs a SupportingDocumentContext + + :param sid: The unique string created by Twilio to identify the Supporting Document resource. + """ + return SupportingDocumentContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/supporting_document_type.py b/venv/Lib/site-packages/twilio/rest/trusthub/v1/supporting_document_type.py new file mode 100644 index 00000000..f107397a --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trusthub/v1/supporting_document_type.py @@ -0,0 +1,408 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SupportingDocumentTypeInstance(InstanceResource): + """ + :ivar sid: The unique string that identifies the Supporting Document Type resource. + :ivar friendly_name: A human-readable description of the Supporting Document Type resource. + :ivar machine_name: The machine-readable description of the Supporting Document Type resource. + :ivar fields: The required information for creating a Supporting Document. The required fields will change as regulatory needs change and will differ for businesses and individuals. + :ivar url: The absolute URL of the Supporting Document Type resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.machine_name: Optional[str] = payload.get("machine_name") + self.fields: Optional[List[Dict[str, object]]] = payload.get("fields") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SupportingDocumentTypeContext] = None + + @property + def _proxy(self) -> "SupportingDocumentTypeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SupportingDocumentTypeContext for this SupportingDocumentTypeInstance + """ + if self._context is None: + self._context = SupportingDocumentTypeContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "SupportingDocumentTypeInstance": + """ + Fetch the SupportingDocumentTypeInstance + + + :returns: The fetched SupportingDocumentTypeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SupportingDocumentTypeInstance": + """ + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance + + + :returns: The fetched SupportingDocumentTypeInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SupportingDocumentTypeContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SupportingDocumentTypeContext + + :param version: Version that contains the resource + :param sid: The unique string that identifies the Supporting Document Type resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/SupportingDocumentTypes/{sid}".format(**self._solution) + + def fetch(self) -> SupportingDocumentTypeInstance: + """ + Fetch the SupportingDocumentTypeInstance + + + :returns: The fetched SupportingDocumentTypeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SupportingDocumentTypeInstance: + """ + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance + + + :returns: The fetched SupportingDocumentTypeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SupportingDocumentTypePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SupportingDocumentTypeInstance: + """ + Build an instance of SupportingDocumentTypeInstance + + :param payload: Payload response from the API + """ + return SupportingDocumentTypeInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SupportingDocumentTypeList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SupportingDocumentTypeList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/SupportingDocumentTypes" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SupportingDocumentTypeInstance]: + """ + Streams SupportingDocumentTypeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SupportingDocumentTypeInstance]: + """ + Asynchronously streams SupportingDocumentTypeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SupportingDocumentTypeInstance]: + """ + Lists SupportingDocumentTypeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SupportingDocumentTypeInstance]: + """ + Asynchronously lists SupportingDocumentTypeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SupportingDocumentTypePage: + """ + Retrieve a single page of SupportingDocumentTypeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SupportingDocumentTypeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SupportingDocumentTypePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SupportingDocumentTypePage: + """ + Asynchronously retrieve a single page of SupportingDocumentTypeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SupportingDocumentTypeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SupportingDocumentTypePage(self._version, response) + + def get_page(self, target_url: str) -> SupportingDocumentTypePage: + """ + Retrieve a specific page of SupportingDocumentTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SupportingDocumentTypeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SupportingDocumentTypePage(self._version, response) + + async def get_page_async(self, target_url: str) -> SupportingDocumentTypePage: + """ + Asynchronously retrieve a specific page of SupportingDocumentTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SupportingDocumentTypeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SupportingDocumentTypePage(self._version, response) + + def get(self, sid: str) -> SupportingDocumentTypeContext: + """ + Constructs a SupportingDocumentTypeContext + + :param sid: The unique string that identifies the Supporting Document Type resource. + """ + return SupportingDocumentTypeContext(self._version, sid=sid) + + def __call__(self, sid: str) -> SupportingDocumentTypeContext: + """ + Constructs a SupportingDocumentTypeContext + + :param sid: The unique string that identifies the Supporting Document Type resource. + """ + return SupportingDocumentTypeContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/trust_products/__init__.py b/venv/Lib/site-packages/twilio/rest/trusthub/v1/trust_products/__init__.py new file mode 100644 index 00000000..6bb01d61 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trusthub/v1/trust_products/__init__.py @@ -0,0 +1,823 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.trusthub.v1.trust_products.trust_products_channel_endpoint_assignment import ( + TrustProductsChannelEndpointAssignmentList, +) +from twilio.rest.trusthub.v1.trust_products.trust_products_entity_assignments import ( + TrustProductsEntityAssignmentsList, +) +from twilio.rest.trusthub.v1.trust_products.trust_products_evaluations import ( + TrustProductsEvaluationsList, +) + + +class TrustProductsInstance(InstanceResource): + + class Status(object): + DRAFT = "draft" + PENDING_REVIEW = "pending-review" + IN_REVIEW = "in-review" + TWILIO_REJECTED = "twilio-rejected" + TWILIO_APPROVED = "twilio-approved" + + """ + :ivar sid: The unique string that we created to identify the Trust Product resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Trust Product resource. + :ivar policy_sid: The unique string of the policy that is associated with the Trust Product resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar status: + :ivar valid_until: The date and time in GMT in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format until which the resource will be valid. + :ivar email: The email address that will receive updates when the Trust Product resource changes status. + :ivar status_callback: The URL we call to inform your application of status changes. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Trust Product resource. + :ivar links: The URLs of the Assigned Items of the Trust Product resource. + :ivar errors: The error codes associated with the rejection of the Trust Product. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.policy_sid: Optional[str] = payload.get("policy_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["TrustProductsInstance.Status"] = payload.get("status") + self.valid_until: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("valid_until") + ) + self.email: Optional[str] = payload.get("email") + self.status_callback: Optional[str] = payload.get("status_callback") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.errors: Optional[List[Dict[str, object]]] = payload.get("errors") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[TrustProductsContext] = None + + @property + def _proxy(self) -> "TrustProductsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TrustProductsContext for this TrustProductsInstance + """ + if self._context is None: + self._context = TrustProductsContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TrustProductsInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TrustProductsInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "TrustProductsInstance": + """ + Fetch the TrustProductsInstance + + + :returns: The fetched TrustProductsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TrustProductsInstance": + """ + Asynchronous coroutine to fetch the TrustProductsInstance + + + :returns: The fetched TrustProductsInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> "TrustProductsInstance": + """ + Update the TrustProductsInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Trust Product resource changes status. + + :returns: The updated TrustProductsInstance + """ + return self._proxy.update( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + + async def update_async( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> "TrustProductsInstance": + """ + Asynchronous coroutine to update the TrustProductsInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Trust Product resource changes status. + + :returns: The updated TrustProductsInstance + """ + return await self._proxy.update_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + + @property + def trust_products_channel_endpoint_assignment( + self, + ) -> TrustProductsChannelEndpointAssignmentList: + """ + Access the trust_products_channel_endpoint_assignment + """ + return self._proxy.trust_products_channel_endpoint_assignment + + @property + def trust_products_entity_assignments(self) -> TrustProductsEntityAssignmentsList: + """ + Access the trust_products_entity_assignments + """ + return self._proxy.trust_products_entity_assignments + + @property + def trust_products_evaluations(self) -> TrustProductsEvaluationsList: + """ + Access the trust_products_evaluations + """ + return self._proxy.trust_products_evaluations + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TrustProductsContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the TrustProductsContext + + :param version: Version that contains the resource + :param sid: The unique string that we created to identify the Trust Product resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/TrustProducts/{sid}".format(**self._solution) + + self._trust_products_channel_endpoint_assignment: Optional[ + TrustProductsChannelEndpointAssignmentList + ] = None + self._trust_products_entity_assignments: Optional[ + TrustProductsEntityAssignmentsList + ] = None + self._trust_products_evaluations: Optional[TrustProductsEvaluationsList] = None + + def delete(self) -> bool: + """ + Deletes the TrustProductsInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TrustProductsInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TrustProductsInstance: + """ + Fetch the TrustProductsInstance + + + :returns: The fetched TrustProductsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TrustProductsInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TrustProductsInstance: + """ + Asynchronous coroutine to fetch the TrustProductsInstance + + + :returns: The fetched TrustProductsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TrustProductsInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> TrustProductsInstance: + """ + Update the TrustProductsInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Trust Product resource changes status. + + :returns: The updated TrustProductsInstance + """ + + data = values.of( + { + "Status": status, + "StatusCallback": status_callback, + "FriendlyName": friendly_name, + "Email": email, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrustProductsInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> TrustProductsInstance: + """ + Asynchronous coroutine to update the TrustProductsInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Trust Product resource changes status. + + :returns: The updated TrustProductsInstance + """ + + data = values.of( + { + "Status": status, + "StatusCallback": status_callback, + "FriendlyName": friendly_name, + "Email": email, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrustProductsInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def trust_products_channel_endpoint_assignment( + self, + ) -> TrustProductsChannelEndpointAssignmentList: + """ + Access the trust_products_channel_endpoint_assignment + """ + if self._trust_products_channel_endpoint_assignment is None: + self._trust_products_channel_endpoint_assignment = ( + TrustProductsChannelEndpointAssignmentList( + self._version, + self._solution["sid"], + ) + ) + return self._trust_products_channel_endpoint_assignment + + @property + def trust_products_entity_assignments(self) -> TrustProductsEntityAssignmentsList: + """ + Access the trust_products_entity_assignments + """ + if self._trust_products_entity_assignments is None: + self._trust_products_entity_assignments = ( + TrustProductsEntityAssignmentsList( + self._version, + self._solution["sid"], + ) + ) + return self._trust_products_entity_assignments + + @property + def trust_products_evaluations(self) -> TrustProductsEvaluationsList: + """ + Access the trust_products_evaluations + """ + if self._trust_products_evaluations is None: + self._trust_products_evaluations = TrustProductsEvaluationsList( + self._version, + self._solution["sid"], + ) + return self._trust_products_evaluations + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TrustProductsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TrustProductsInstance: + """ + Build an instance of TrustProductsInstance + + :param payload: Payload response from the API + """ + return TrustProductsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TrustProductsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TrustProductsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/TrustProducts" + + def create( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> TrustProductsInstance: + """ + Create the TrustProductsInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Trust Product resource changes status. + :param policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param status_callback: The URL we call to inform your application of status changes. + + :returns: The created TrustProductsInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Email": email, + "PolicySid": policy_sid, + "StatusCallback": status_callback, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrustProductsInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> TrustProductsInstance: + """ + Asynchronously create the TrustProductsInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Trust Product resource changes status. + :param policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param status_callback: The URL we call to inform your application of status changes. + + :returns: The created TrustProductsInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Email": email, + "PolicySid": policy_sid, + "StatusCallback": status_callback, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrustProductsInstance(self._version, payload) + + def stream( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TrustProductsInstance]: + """ + Streams TrustProductsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "TrustProductsInstance.Status" status: The verification status of the Trust Product resource. + :param str friendly_name: The string that you assigned to describe the resource. + :param str policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TrustProductsInstance]: + """ + Asynchronously streams TrustProductsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "TrustProductsInstance.Status" status: The verification status of the Trust Product resource. + :param str friendly_name: The string that you assigned to describe the resource. + :param str policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TrustProductsInstance]: + """ + Lists TrustProductsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "TrustProductsInstance.Status" status: The verification status of the Trust Product resource. + :param str friendly_name: The string that you assigned to describe the resource. + :param str policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TrustProductsInstance]: + """ + Asynchronously lists TrustProductsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "TrustProductsInstance.Status" status: The verification status of the Trust Product resource. + :param str friendly_name: The string that you assigned to describe the resource. + :param str policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TrustProductsPage: + """ + Retrieve a single page of TrustProductsInstance records from the API. + Request is executed immediately + + :param status: The verification status of the Trust Product resource. + :param friendly_name: The string that you assigned to describe the resource. + :param policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TrustProductsInstance + """ + data = values.of( + { + "Status": status, + "FriendlyName": friendly_name, + "PolicySid": policy_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TrustProductsPage(self._version, response) + + async def page_async( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TrustProductsPage: + """ + Asynchronously retrieve a single page of TrustProductsInstance records from the API. + Request is executed immediately + + :param status: The verification status of the Trust Product resource. + :param friendly_name: The string that you assigned to describe the resource. + :param policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TrustProductsInstance + """ + data = values.of( + { + "Status": status, + "FriendlyName": friendly_name, + "PolicySid": policy_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TrustProductsPage(self._version, response) + + def get_page(self, target_url: str) -> TrustProductsPage: + """ + Retrieve a specific page of TrustProductsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TrustProductsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TrustProductsPage(self._version, response) + + async def get_page_async(self, target_url: str) -> TrustProductsPage: + """ + Asynchronously retrieve a specific page of TrustProductsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TrustProductsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TrustProductsPage(self._version, response) + + def get(self, sid: str) -> TrustProductsContext: + """ + Constructs a TrustProductsContext + + :param sid: The unique string that we created to identify the Trust Product resource. + """ + return TrustProductsContext(self._version, sid=sid) + + def __call__(self, sid: str) -> TrustProductsContext: + """ + Constructs a TrustProductsContext + + :param sid: The unique string that we created to identify the Trust Product resource. + """ + return TrustProductsContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/trust_products/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trusthub/v1/trust_products/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..381ded90 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trusthub/v1/trust_products/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/trust_products/__pycache__/trust_products_channel_endpoint_assignment.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trusthub/v1/trust_products/__pycache__/trust_products_channel_endpoint_assignment.cpython-312.pyc new file mode 100644 index 00000000..943e9335 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trusthub/v1/trust_products/__pycache__/trust_products_channel_endpoint_assignment.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/trust_products/__pycache__/trust_products_entity_assignments.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trusthub/v1/trust_products/__pycache__/trust_products_entity_assignments.cpython-312.pyc new file mode 100644 index 00000000..0e27193f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trusthub/v1/trust_products/__pycache__/trust_products_entity_assignments.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/trust_products/__pycache__/trust_products_evaluations.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/trusthub/v1/trust_products/__pycache__/trust_products_evaluations.cpython-312.pyc new file mode 100644 index 00000000..c3b644fc Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/trusthub/v1/trust_products/__pycache__/trust_products_evaluations.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/trust_products/trust_products_channel_endpoint_assignment.py b/venv/Lib/site-packages/twilio/rest/trusthub/v1/trust_products/trust_products_channel_endpoint_assignment.py new file mode 100644 index 00000000..adf9c51f --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trusthub/v1/trust_products/trust_products_channel_endpoint_assignment.py @@ -0,0 +1,616 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TrustProductsChannelEndpointAssignmentInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Item Assignment resource. + :ivar trust_product_sid: The unique string that we created to identify the CustomerProfile resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Item Assignment resource. + :ivar channel_endpoint_type: The type of channel endpoint. eg: phone-number + :ivar channel_endpoint_sid: The SID of an channel endpoint + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Identity resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + trust_product_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.trust_product_sid: Optional[str] = payload.get("trust_product_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.channel_endpoint_type: Optional[str] = payload.get("channel_endpoint_type") + self.channel_endpoint_sid: Optional[str] = payload.get("channel_endpoint_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "trust_product_sid": trust_product_sid, + "sid": sid or self.sid, + } + self._context: Optional[TrustProductsChannelEndpointAssignmentContext] = None + + @property + def _proxy(self) -> "TrustProductsChannelEndpointAssignmentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TrustProductsChannelEndpointAssignmentContext for this TrustProductsChannelEndpointAssignmentInstance + """ + if self._context is None: + self._context = TrustProductsChannelEndpointAssignmentContext( + self._version, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TrustProductsChannelEndpointAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TrustProductsChannelEndpointAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "TrustProductsChannelEndpointAssignmentInstance": + """ + Fetch the TrustProductsChannelEndpointAssignmentInstance + + + :returns: The fetched TrustProductsChannelEndpointAssignmentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TrustProductsChannelEndpointAssignmentInstance": + """ + Asynchronous coroutine to fetch the TrustProductsChannelEndpointAssignmentInstance + + + :returns: The fetched TrustProductsChannelEndpointAssignmentInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class TrustProductsChannelEndpointAssignmentContext(InstanceContext): + + def __init__(self, version: Version, trust_product_sid: str, sid: str): + """ + Initialize the TrustProductsChannelEndpointAssignmentContext + + :param version: Version that contains the resource + :param trust_product_sid: The unique string that we created to identify the CustomerProfile resource. + :param sid: The unique string that we created to identify the resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trust_product_sid": trust_product_sid, + "sid": sid, + } + self._uri = "/TrustProducts/{trust_product_sid}/ChannelEndpointAssignments/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the TrustProductsChannelEndpointAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TrustProductsChannelEndpointAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TrustProductsChannelEndpointAssignmentInstance: + """ + Fetch the TrustProductsChannelEndpointAssignmentInstance + + + :returns: The fetched TrustProductsChannelEndpointAssignmentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TrustProductsChannelEndpointAssignmentInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TrustProductsChannelEndpointAssignmentInstance: + """ + Asynchronous coroutine to fetch the TrustProductsChannelEndpointAssignmentInstance + + + :returns: The fetched TrustProductsChannelEndpointAssignmentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TrustProductsChannelEndpointAssignmentInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class TrustProductsChannelEndpointAssignmentPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> TrustProductsChannelEndpointAssignmentInstance: + """ + Build an instance of TrustProductsChannelEndpointAssignmentInstance + + :param payload: Payload response from the API + """ + return TrustProductsChannelEndpointAssignmentInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TrustProductsChannelEndpointAssignmentList(ListResource): + + def __init__(self, version: Version, trust_product_sid: str): + """ + Initialize the TrustProductsChannelEndpointAssignmentList + + :param version: Version that contains the resource + :param trust_product_sid: The unique string that we created to identify the CustomerProfile resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trust_product_sid": trust_product_sid, + } + self._uri = ( + "/TrustProducts/{trust_product_sid}/ChannelEndpointAssignments".format( + **self._solution + ) + ) + + def create( + self, channel_endpoint_type: str, channel_endpoint_sid: str + ) -> TrustProductsChannelEndpointAssignmentInstance: + """ + Create the TrustProductsChannelEndpointAssignmentInstance + + :param channel_endpoint_type: The type of channel endpoint. eg: phone-number + :param channel_endpoint_sid: The SID of an channel endpoint + + :returns: The created TrustProductsChannelEndpointAssignmentInstance + """ + + data = values.of( + { + "ChannelEndpointType": channel_endpoint_type, + "ChannelEndpointSid": channel_endpoint_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrustProductsChannelEndpointAssignmentInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + async def create_async( + self, channel_endpoint_type: str, channel_endpoint_sid: str + ) -> TrustProductsChannelEndpointAssignmentInstance: + """ + Asynchronously create the TrustProductsChannelEndpointAssignmentInstance + + :param channel_endpoint_type: The type of channel endpoint. eg: phone-number + :param channel_endpoint_sid: The SID of an channel endpoint + + :returns: The created TrustProductsChannelEndpointAssignmentInstance + """ + + data = values.of( + { + "ChannelEndpointType": channel_endpoint_type, + "ChannelEndpointSid": channel_endpoint_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrustProductsChannelEndpointAssignmentInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + def stream( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TrustProductsChannelEndpointAssignmentInstance]: + """ + Streams TrustProductsChannelEndpointAssignmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str channel_endpoint_sid: The SID of an channel endpoint + :param str channel_endpoint_sids: comma separated list of channel endpoint sids + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TrustProductsChannelEndpointAssignmentInstance]: + """ + Asynchronously streams TrustProductsChannelEndpointAssignmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str channel_endpoint_sid: The SID of an channel endpoint + :param str channel_endpoint_sids: comma separated list of channel endpoint sids + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TrustProductsChannelEndpointAssignmentInstance]: + """ + Lists TrustProductsChannelEndpointAssignmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str channel_endpoint_sid: The SID of an channel endpoint + :param str channel_endpoint_sids: comma separated list of channel endpoint sids + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TrustProductsChannelEndpointAssignmentInstance]: + """ + Asynchronously lists TrustProductsChannelEndpointAssignmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str channel_endpoint_sid: The SID of an channel endpoint + :param str channel_endpoint_sids: comma separated list of channel endpoint sids + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TrustProductsChannelEndpointAssignmentPage: + """ + Retrieve a single page of TrustProductsChannelEndpointAssignmentInstance records from the API. + Request is executed immediately + + :param channel_endpoint_sid: The SID of an channel endpoint + :param channel_endpoint_sids: comma separated list of channel endpoint sids + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TrustProductsChannelEndpointAssignmentInstance + """ + data = values.of( + { + "ChannelEndpointSid": channel_endpoint_sid, + "ChannelEndpointSids": channel_endpoint_sids, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TrustProductsChannelEndpointAssignmentPage( + self._version, response, self._solution + ) + + async def page_async( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TrustProductsChannelEndpointAssignmentPage: + """ + Asynchronously retrieve a single page of TrustProductsChannelEndpointAssignmentInstance records from the API. + Request is executed immediately + + :param channel_endpoint_sid: The SID of an channel endpoint + :param channel_endpoint_sids: comma separated list of channel endpoint sids + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TrustProductsChannelEndpointAssignmentInstance + """ + data = values.of( + { + "ChannelEndpointSid": channel_endpoint_sid, + "ChannelEndpointSids": channel_endpoint_sids, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TrustProductsChannelEndpointAssignmentPage( + self._version, response, self._solution + ) + + def get_page(self, target_url: str) -> TrustProductsChannelEndpointAssignmentPage: + """ + Retrieve a specific page of TrustProductsChannelEndpointAssignmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TrustProductsChannelEndpointAssignmentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TrustProductsChannelEndpointAssignmentPage( + self._version, response, self._solution + ) + + async def get_page_async( + self, target_url: str + ) -> TrustProductsChannelEndpointAssignmentPage: + """ + Asynchronously retrieve a specific page of TrustProductsChannelEndpointAssignmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TrustProductsChannelEndpointAssignmentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TrustProductsChannelEndpointAssignmentPage( + self._version, response, self._solution + ) + + def get(self, sid: str) -> TrustProductsChannelEndpointAssignmentContext: + """ + Constructs a TrustProductsChannelEndpointAssignmentContext + + :param sid: The unique string that we created to identify the resource. + """ + return TrustProductsChannelEndpointAssignmentContext( + self._version, + trust_product_sid=self._solution["trust_product_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> TrustProductsChannelEndpointAssignmentContext: + """ + Constructs a TrustProductsChannelEndpointAssignmentContext + + :param sid: The unique string that we created to identify the resource. + """ + return TrustProductsChannelEndpointAssignmentContext( + self._version, + trust_product_sid=self._solution["trust_product_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/trust_products/trust_products_entity_assignments.py b/venv/Lib/site-packages/twilio/rest/trusthub/v1/trust_products/trust_products_entity_assignments.py new file mode 100644 index 00000000..ebda7ee8 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trusthub/v1/trust_products/trust_products_entity_assignments.py @@ -0,0 +1,584 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TrustProductsEntityAssignmentsInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Item Assignment resource. + :ivar trust_product_sid: The unique string that we created to identify the TrustProduct resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Item Assignment resource. + :ivar object_sid: The SID of an object bag that holds information of the different items. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Identity resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + trust_product_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.trust_product_sid: Optional[str] = payload.get("trust_product_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.object_sid: Optional[str] = payload.get("object_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "trust_product_sid": trust_product_sid, + "sid": sid or self.sid, + } + self._context: Optional[TrustProductsEntityAssignmentsContext] = None + + @property + def _proxy(self) -> "TrustProductsEntityAssignmentsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TrustProductsEntityAssignmentsContext for this TrustProductsEntityAssignmentsInstance + """ + if self._context is None: + self._context = TrustProductsEntityAssignmentsContext( + self._version, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TrustProductsEntityAssignmentsInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TrustProductsEntityAssignmentsInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "TrustProductsEntityAssignmentsInstance": + """ + Fetch the TrustProductsEntityAssignmentsInstance + + + :returns: The fetched TrustProductsEntityAssignmentsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TrustProductsEntityAssignmentsInstance": + """ + Asynchronous coroutine to fetch the TrustProductsEntityAssignmentsInstance + + + :returns: The fetched TrustProductsEntityAssignmentsInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class TrustProductsEntityAssignmentsContext(InstanceContext): + + def __init__(self, version: Version, trust_product_sid: str, sid: str): + """ + Initialize the TrustProductsEntityAssignmentsContext + + :param version: Version that contains the resource + :param trust_product_sid: The unique string that we created to identify the TrustProduct resource. + :param sid: The unique string that we created to identify the Identity resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trust_product_sid": trust_product_sid, + "sid": sid, + } + self._uri = "/TrustProducts/{trust_product_sid}/EntityAssignments/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the TrustProductsEntityAssignmentsInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TrustProductsEntityAssignmentsInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TrustProductsEntityAssignmentsInstance: + """ + Fetch the TrustProductsEntityAssignmentsInstance + + + :returns: The fetched TrustProductsEntityAssignmentsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TrustProductsEntityAssignmentsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TrustProductsEntityAssignmentsInstance: + """ + Asynchronous coroutine to fetch the TrustProductsEntityAssignmentsInstance + + + :returns: The fetched TrustProductsEntityAssignmentsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TrustProductsEntityAssignmentsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class TrustProductsEntityAssignmentsPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> TrustProductsEntityAssignmentsInstance: + """ + Build an instance of TrustProductsEntityAssignmentsInstance + + :param payload: Payload response from the API + """ + return TrustProductsEntityAssignmentsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TrustProductsEntityAssignmentsList(ListResource): + + def __init__(self, version: Version, trust_product_sid: str): + """ + Initialize the TrustProductsEntityAssignmentsList + + :param version: Version that contains the resource + :param trust_product_sid: The unique string that we created to identify the TrustProduct resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trust_product_sid": trust_product_sid, + } + self._uri = "/TrustProducts/{trust_product_sid}/EntityAssignments".format( + **self._solution + ) + + def create(self, object_sid: str) -> TrustProductsEntityAssignmentsInstance: + """ + Create the TrustProductsEntityAssignmentsInstance + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: The created TrustProductsEntityAssignmentsInstance + """ + + data = values.of( + { + "ObjectSid": object_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrustProductsEntityAssignmentsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + async def create_async( + self, object_sid: str + ) -> TrustProductsEntityAssignmentsInstance: + """ + Asynchronously create the TrustProductsEntityAssignmentsInstance + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: The created TrustProductsEntityAssignmentsInstance + """ + + data = values.of( + { + "ObjectSid": object_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrustProductsEntityAssignmentsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + def stream( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TrustProductsEntityAssignmentsInstance]: + """ + Streams TrustProductsEntityAssignmentsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(object_type=object_type, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TrustProductsEntityAssignmentsInstance]: + """ + Asynchronously streams TrustProductsEntityAssignmentsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + object_type=object_type, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TrustProductsEntityAssignmentsInstance]: + """ + Lists TrustProductsEntityAssignmentsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + object_type=object_type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TrustProductsEntityAssignmentsInstance]: + """ + Asynchronously lists TrustProductsEntityAssignmentsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + object_type=object_type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + object_type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TrustProductsEntityAssignmentsPage: + """ + Retrieve a single page of TrustProductsEntityAssignmentsInstance records from the API. + Request is executed immediately + + :param object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TrustProductsEntityAssignmentsInstance + """ + data = values.of( + { + "ObjectType": object_type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TrustProductsEntityAssignmentsPage( + self._version, response, self._solution + ) + + async def page_async( + self, + object_type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TrustProductsEntityAssignmentsPage: + """ + Asynchronously retrieve a single page of TrustProductsEntityAssignmentsInstance records from the API. + Request is executed immediately + + :param object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TrustProductsEntityAssignmentsInstance + """ + data = values.of( + { + "ObjectType": object_type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TrustProductsEntityAssignmentsPage( + self._version, response, self._solution + ) + + def get_page(self, target_url: str) -> TrustProductsEntityAssignmentsPage: + """ + Retrieve a specific page of TrustProductsEntityAssignmentsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TrustProductsEntityAssignmentsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TrustProductsEntityAssignmentsPage( + self._version, response, self._solution + ) + + async def get_page_async( + self, target_url: str + ) -> TrustProductsEntityAssignmentsPage: + """ + Asynchronously retrieve a specific page of TrustProductsEntityAssignmentsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TrustProductsEntityAssignmentsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TrustProductsEntityAssignmentsPage( + self._version, response, self._solution + ) + + def get(self, sid: str) -> TrustProductsEntityAssignmentsContext: + """ + Constructs a TrustProductsEntityAssignmentsContext + + :param sid: The unique string that we created to identify the Identity resource. + """ + return TrustProductsEntityAssignmentsContext( + self._version, + trust_product_sid=self._solution["trust_product_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> TrustProductsEntityAssignmentsContext: + """ + Constructs a TrustProductsEntityAssignmentsContext + + :param sid: The unique string that we created to identify the Identity resource. + """ + return TrustProductsEntityAssignmentsContext( + self._version, + trust_product_sid=self._solution["trust_product_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/trusthub/v1/trust_products/trust_products_evaluations.py b/venv/Lib/site-packages/twilio/rest/trusthub/v1/trust_products/trust_products_evaluations.py new file mode 100644 index 00000000..3691aa01 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/trusthub/v1/trust_products/trust_products_evaluations.py @@ -0,0 +1,517 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TrustProductsEvaluationsInstance(InstanceResource): + + class Status(object): + COMPLIANT = "compliant" + NONCOMPLIANT = "noncompliant" + + """ + :ivar sid: The unique string that identifies the Evaluation resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the trust_product resource. + :ivar policy_sid: The unique string of a policy that is associated to the trust_product resource. + :ivar trust_product_sid: The unique string that we created to identify the trust_product resource. + :ivar status: + :ivar results: The results of the Evaluation which includes the valid and invalid attributes. + :ivar date_created: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + trust_product_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.policy_sid: Optional[str] = payload.get("policy_sid") + self.trust_product_sid: Optional[str] = payload.get("trust_product_sid") + self.status: Optional["TrustProductsEvaluationsInstance.Status"] = payload.get( + "status" + ) + self.results: Optional[List[Dict[str, object]]] = payload.get("results") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "trust_product_sid": trust_product_sid, + "sid": sid or self.sid, + } + self._context: Optional[TrustProductsEvaluationsContext] = None + + @property + def _proxy(self) -> "TrustProductsEvaluationsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TrustProductsEvaluationsContext for this TrustProductsEvaluationsInstance + """ + if self._context is None: + self._context = TrustProductsEvaluationsContext( + self._version, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "TrustProductsEvaluationsInstance": + """ + Fetch the TrustProductsEvaluationsInstance + + + :returns: The fetched TrustProductsEvaluationsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TrustProductsEvaluationsInstance": + """ + Asynchronous coroutine to fetch the TrustProductsEvaluationsInstance + + + :returns: The fetched TrustProductsEvaluationsInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class TrustProductsEvaluationsContext(InstanceContext): + + def __init__(self, version: Version, trust_product_sid: str, sid: str): + """ + Initialize the TrustProductsEvaluationsContext + + :param version: Version that contains the resource + :param trust_product_sid: The unique string that we created to identify the trust_product resource. + :param sid: The unique string that identifies the Evaluation resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trust_product_sid": trust_product_sid, + "sid": sid, + } + self._uri = "/TrustProducts/{trust_product_sid}/Evaluations/{sid}".format( + **self._solution + ) + + def fetch(self) -> TrustProductsEvaluationsInstance: + """ + Fetch the TrustProductsEvaluationsInstance + + + :returns: The fetched TrustProductsEvaluationsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TrustProductsEvaluationsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TrustProductsEvaluationsInstance: + """ + Asynchronous coroutine to fetch the TrustProductsEvaluationsInstance + + + :returns: The fetched TrustProductsEvaluationsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TrustProductsEvaluationsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TrustProductsEvaluationsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TrustProductsEvaluationsInstance: + """ + Build an instance of TrustProductsEvaluationsInstance + + :param payload: Payload response from the API + """ + return TrustProductsEvaluationsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TrustProductsEvaluationsList(ListResource): + + def __init__(self, version: Version, trust_product_sid: str): + """ + Initialize the TrustProductsEvaluationsList + + :param version: Version that contains the resource + :param trust_product_sid: The unique string that we created to identify the trust_product resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trust_product_sid": trust_product_sid, + } + self._uri = "/TrustProducts/{trust_product_sid}/Evaluations".format( + **self._solution + ) + + def create(self, policy_sid: str) -> TrustProductsEvaluationsInstance: + """ + Create the TrustProductsEvaluationsInstance + + :param policy_sid: The unique string of a policy that is associated to the customer_profile resource. + + :returns: The created TrustProductsEvaluationsInstance + """ + + data = values.of( + { + "PolicySid": policy_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrustProductsEvaluationsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + async def create_async(self, policy_sid: str) -> TrustProductsEvaluationsInstance: + """ + Asynchronously create the TrustProductsEvaluationsInstance + + :param policy_sid: The unique string of a policy that is associated to the customer_profile resource. + + :returns: The created TrustProductsEvaluationsInstance + """ + + data = values.of( + { + "PolicySid": policy_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrustProductsEvaluationsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TrustProductsEvaluationsInstance]: + """ + Streams TrustProductsEvaluationsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TrustProductsEvaluationsInstance]: + """ + Asynchronously streams TrustProductsEvaluationsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TrustProductsEvaluationsInstance]: + """ + Lists TrustProductsEvaluationsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TrustProductsEvaluationsInstance]: + """ + Asynchronously lists TrustProductsEvaluationsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TrustProductsEvaluationsPage: + """ + Retrieve a single page of TrustProductsEvaluationsInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TrustProductsEvaluationsInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TrustProductsEvaluationsPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TrustProductsEvaluationsPage: + """ + Asynchronously retrieve a single page of TrustProductsEvaluationsInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TrustProductsEvaluationsInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TrustProductsEvaluationsPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> TrustProductsEvaluationsPage: + """ + Retrieve a specific page of TrustProductsEvaluationsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TrustProductsEvaluationsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TrustProductsEvaluationsPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> TrustProductsEvaluationsPage: + """ + Asynchronously retrieve a specific page of TrustProductsEvaluationsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TrustProductsEvaluationsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TrustProductsEvaluationsPage(self._version, response, self._solution) + + def get(self, sid: str) -> TrustProductsEvaluationsContext: + """ + Constructs a TrustProductsEvaluationsContext + + :param sid: The unique string that identifies the Evaluation resource. + """ + return TrustProductsEvaluationsContext( + self._version, + trust_product_sid=self._solution["trust_product_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> TrustProductsEvaluationsContext: + """ + Constructs a TrustProductsEvaluationsContext + + :param sid: The unique string that identifies the Evaluation resource. + """ + return TrustProductsEvaluationsContext( + self._version, + trust_product_sid=self._solution["trust_product_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/verify/VerifyBase.py b/venv/Lib/site-packages/twilio/rest/verify/VerifyBase.py new file mode 100644 index 00000000..076f0631 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/verify/VerifyBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.verify.v2 import V2 + + +class VerifyBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Verify Domain + + :returns: Domain for Verify + """ + super().__init__(twilio, "https://verify.twilio.com") + self._v2: Optional[V2] = None + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Verify + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/verify/__init__.py b/venv/Lib/site-packages/twilio/rest/verify/__init__.py new file mode 100644 index 00000000..a66b3333 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/verify/__init__.py @@ -0,0 +1,67 @@ +from warnings import warn + +from twilio.rest.verify.VerifyBase import VerifyBase +from twilio.rest.verify.v2.form import FormList +from twilio.rest.verify.v2.safelist import SafelistList +from twilio.rest.verify.v2.service import ServiceList +from twilio.rest.verify.v2.template import TemplateList +from twilio.rest.verify.v2.verification_attempt import VerificationAttemptList +from twilio.rest.verify.v2.verification_attempts_summary import ( + VerificationAttemptsSummaryList, +) + + +class Verify(VerifyBase): + @property + def forms(self) -> FormList: + warn( + "forms is deprecated. Use v2.forms instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.forms + + @property + def safelist(self) -> SafelistList: + warn( + "safelist is deprecated. Use v2.safelist instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.safelist + + @property + def services(self) -> ServiceList: + warn( + "services is deprecated. Use v2.services instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.services + + @property + def verification_attempts(self) -> VerificationAttemptList: + warn( + "verification_attempts is deprecated. Use v2.verification_attempts instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.verification_attempts + + @property + def verification_attempts_summary(self) -> VerificationAttemptsSummaryList: + warn( + "verification_attempts_summary is deprecated. Use v2.verification_attempts_summary instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.verification_attempts_summary + + @property + def templates(self) -> TemplateList: + warn( + "templates is deprecated. Use v2.templates instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.templates diff --git a/venv/Lib/site-packages/twilio/rest/verify/__pycache__/VerifyBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/verify/__pycache__/VerifyBase.cpython-312.pyc new file mode 100644 index 00000000..b19de3b0 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/verify/__pycache__/VerifyBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/verify/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/verify/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..fc3627b8 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/verify/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/__init__.py b/venv/Lib/site-packages/twilio/rest/verify/v2/__init__.py new file mode 100644 index 00000000..01bee13b --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/verify/v2/__init__.py @@ -0,0 +1,87 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.verify.v2.form import FormList +from twilio.rest.verify.v2.safelist import SafelistList +from twilio.rest.verify.v2.service import ServiceList +from twilio.rest.verify.v2.template import TemplateList +from twilio.rest.verify.v2.verification_attempt import VerificationAttemptList +from twilio.rest.verify.v2.verification_attempts_summary import ( + VerificationAttemptsSummaryList, +) + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Verify + + :param domain: The Twilio.verify domain + """ + super().__init__(domain, "v2") + self._forms: Optional[FormList] = None + self._safelist: Optional[SafelistList] = None + self._services: Optional[ServiceList] = None + self._templates: Optional[TemplateList] = None + self._verification_attempts: Optional[VerificationAttemptList] = None + self._verification_attempts_summary: Optional[ + VerificationAttemptsSummaryList + ] = None + + @property + def forms(self) -> FormList: + if self._forms is None: + self._forms = FormList(self) + return self._forms + + @property + def safelist(self) -> SafelistList: + if self._safelist is None: + self._safelist = SafelistList(self) + return self._safelist + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + @property + def templates(self) -> TemplateList: + if self._templates is None: + self._templates = TemplateList(self) + return self._templates + + @property + def verification_attempts(self) -> VerificationAttemptList: + if self._verification_attempts is None: + self._verification_attempts = VerificationAttemptList(self) + return self._verification_attempts + + @property + def verification_attempts_summary(self) -> VerificationAttemptsSummaryList: + if self._verification_attempts_summary is None: + self._verification_attempts_summary = VerificationAttemptsSummaryList(self) + return self._verification_attempts_summary + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/verify/v2/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..68f7eeab Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/verify/v2/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/__pycache__/form.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/verify/v2/__pycache__/form.cpython-312.pyc new file mode 100644 index 00000000..2b19981a Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/verify/v2/__pycache__/form.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/__pycache__/safelist.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/verify/v2/__pycache__/safelist.cpython-312.pyc new file mode 100644 index 00000000..c0cae0c6 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/verify/v2/__pycache__/safelist.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/__pycache__/template.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/verify/v2/__pycache__/template.cpython-312.pyc new file mode 100644 index 00000000..4d1050d6 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/verify/v2/__pycache__/template.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/__pycache__/verification_attempt.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/verify/v2/__pycache__/verification_attempt.cpython-312.pyc new file mode 100644 index 00000000..987cba71 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/verify/v2/__pycache__/verification_attempt.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/__pycache__/verification_attempts_summary.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/verify/v2/__pycache__/verification_attempts_summary.cpython-312.pyc new file mode 100644 index 00000000..e1e7fe85 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/verify/v2/__pycache__/verification_attempts_summary.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/form.py b/venv/Lib/site-packages/twilio/rest/verify/v2/form.py new file mode 100644 index 00000000..45403020 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/verify/v2/form.py @@ -0,0 +1,198 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class FormInstance(InstanceResource): + + class FormTypes(object): + FORM_PUSH = "form-push" + + """ + :ivar form_type: + :ivar forms: Object that contains the available forms for this type. This available forms are given in the standard [JSON Schema](https://json-schema.org/) format + :ivar form_meta: Additional information for the available forms for this type. E.g. The separator string used for `binding` in a Factor push. + :ivar url: The URL to access the forms for this type. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + form_type: Optional[FormTypes] = None, + ): + super().__init__(version) + + self.form_type: Optional["FormInstance.FormTypes"] = payload.get("form_type") + self.forms: Optional[Dict[str, object]] = payload.get("forms") + self.form_meta: Optional[Dict[str, object]] = payload.get("form_meta") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "form_type": form_type or self.form_type, + } + self._context: Optional[FormContext] = None + + @property + def _proxy(self) -> "FormContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FormContext for this FormInstance + """ + if self._context is None: + self._context = FormContext( + self._version, + form_type=self._solution["form_type"], + ) + return self._context + + def fetch(self) -> "FormInstance": + """ + Fetch the FormInstance + + + :returns: The fetched FormInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FormInstance": + """ + Asynchronous coroutine to fetch the FormInstance + + + :returns: The fetched FormInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FormContext(InstanceContext): + + def __init__(self, version: Version, form_type: "FormInstance.FormTypes"): + """ + Initialize the FormContext + + :param version: Version that contains the resource + :param form_type: The Type of this Form. Currently only `form-push` is supported. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "form_type": form_type, + } + self._uri = "/Forms/{form_type}".format(**self._solution) + + def fetch(self) -> FormInstance: + """ + Fetch the FormInstance + + + :returns: The fetched FormInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FormInstance( + self._version, + payload, + form_type=self._solution["form_type"], + ) + + async def fetch_async(self) -> FormInstance: + """ + Asynchronous coroutine to fetch the FormInstance + + + :returns: The fetched FormInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FormInstance( + self._version, + payload, + form_type=self._solution["form_type"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FormList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the FormList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, form_type: "FormInstance.FormTypes") -> FormContext: + """ + Constructs a FormContext + + :param form_type: The Type of this Form. Currently only `form-push` is supported. + """ + return FormContext(self._version, form_type=form_type) + + def __call__(self, form_type: "FormInstance.FormTypes") -> FormContext: + """ + Constructs a FormContext + + :param form_type: The Type of this Form. Currently only `form-push` is supported. + """ + return FormContext(self._version, form_type=form_type) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/safelist.py b/venv/Lib/site-packages/twilio/rest/verify/v2/safelist.py new file mode 100644 index 00000000..00fc0976 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/verify/v2/safelist.py @@ -0,0 +1,290 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class SafelistInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the SafeList resource. + :ivar phone_number: The phone number in SafeList. + :ivar url: The absolute URL of the SafeList resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + phone_number: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.phone_number: Optional[str] = payload.get("phone_number") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "phone_number": phone_number or self.phone_number, + } + self._context: Optional[SafelistContext] = None + + @property + def _proxy(self) -> "SafelistContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SafelistContext for this SafelistInstance + """ + if self._context is None: + self._context = SafelistContext( + self._version, + phone_number=self._solution["phone_number"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SafelistInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SafelistInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SafelistInstance": + """ + Fetch the SafelistInstance + + + :returns: The fetched SafelistInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SafelistInstance": + """ + Asynchronous coroutine to fetch the SafelistInstance + + + :returns: The fetched SafelistInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SafelistContext(InstanceContext): + + def __init__(self, version: Version, phone_number: str): + """ + Initialize the SafelistContext + + :param version: Version that contains the resource + :param phone_number: The phone number to be fetched from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + """ + super().__init__(version) + + # Path Solution + self._solution = { + "phone_number": phone_number, + } + self._uri = "/SafeList/Numbers/{phone_number}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the SafelistInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SafelistInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SafelistInstance: + """ + Fetch the SafelistInstance + + + :returns: The fetched SafelistInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SafelistInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + async def fetch_async(self) -> SafelistInstance: + """ + Asynchronous coroutine to fetch the SafelistInstance + + + :returns: The fetched SafelistInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SafelistInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SafelistList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SafelistList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/SafeList/Numbers" + + def create(self, phone_number: str) -> SafelistInstance: + """ + Create the SafelistInstance + + :param phone_number: The phone number to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + + :returns: The created SafelistInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SafelistInstance(self._version, payload) + + async def create_async(self, phone_number: str) -> SafelistInstance: + """ + Asynchronously create the SafelistInstance + + :param phone_number: The phone number to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + + :returns: The created SafelistInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SafelistInstance(self._version, payload) + + def get(self, phone_number: str) -> SafelistContext: + """ + Constructs a SafelistContext + + :param phone_number: The phone number to be fetched from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + """ + return SafelistContext(self._version, phone_number=phone_number) + + def __call__(self, phone_number: str) -> SafelistContext: + """ + Constructs a SafelistContext + + :param phone_number: The phone number to be fetched from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + """ + return SafelistContext(self._version, phone_number=phone_number) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/__init__.py b/venv/Lib/site-packages/twilio/rest/verify/v2/service/__init__.py new file mode 100644 index 00000000..a64ab7a5 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/verify/v2/service/__init__.py @@ -0,0 +1,1157 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.verify.v2.service.access_token import AccessTokenList +from twilio.rest.verify.v2.service.entity import EntityList +from twilio.rest.verify.v2.service.messaging_configuration import ( + MessagingConfigurationList, +) +from twilio.rest.verify.v2.service.rate_limit import RateLimitList +from twilio.rest.verify.v2.service.verification import VerificationList +from twilio.rest.verify.v2.service.verification_check import VerificationCheckList +from twilio.rest.verify.v2.service.webhook import WebhookList + + +class ServiceInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Service resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + :ivar friendly_name: The name that appears in the body of your verification messages. It can be up to 30 characters long and can include letters, numbers, spaces, dashes, underscores. Phone numbers, special characters or links are NOT allowed. It cannot contain more than 4 (consecutive or non-consecutive) digits. **This value should not contain PII.** + :ivar code_length: The length of the verification code to generate. + :ivar lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :ivar psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :ivar skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :ivar dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :ivar tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :ivar do_not_share_warning_enabled: Whether to add a security warning at the end of an SMS verification body. Disabled by default and applies only to SMS. Example SMS body: `Your AppName verification code is: 1234. Don’t share this code with anyone; our employees will never ask for the code` + :ivar custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :ivar push: Configurations for the Push factors (channel) created under this Service. + :ivar totp: Configurations for the TOTP factors (channel) created under this Service. + :ivar default_template_sid: + :ivar whatsapp: + :ivar verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.code_length: Optional[int] = deserialize.integer( + payload.get("code_length") + ) + self.lookup_enabled: Optional[bool] = payload.get("lookup_enabled") + self.psd2_enabled: Optional[bool] = payload.get("psd2_enabled") + self.skip_sms_to_landlines: Optional[bool] = payload.get( + "skip_sms_to_landlines" + ) + self.dtmf_input_required: Optional[bool] = payload.get("dtmf_input_required") + self.tts_name: Optional[str] = payload.get("tts_name") + self.do_not_share_warning_enabled: Optional[bool] = payload.get( + "do_not_share_warning_enabled" + ) + self.custom_code_enabled: Optional[bool] = payload.get("custom_code_enabled") + self.push: Optional[Dict[str, object]] = payload.get("push") + self.totp: Optional[Dict[str, object]] = payload.get("totp") + self.default_template_sid: Optional[str] = payload.get("default_template_sid") + self.whatsapp: Optional[Dict[str, object]] = payload.get("whatsapp") + self.verify_event_subscription_enabled: Optional[bool] = payload.get( + "verify_event_subscription_enabled" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a privacy warning at the end of an SMS. **Disabled by default and applies only for SMS.** + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. + :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + code_length=code_length, + lookup_enabled=lookup_enabled, + skip_sms_to_landlines=skip_sms_to_landlines, + dtmf_input_required=dtmf_input_required, + tts_name=tts_name, + psd2_enabled=psd2_enabled, + do_not_share_warning_enabled=do_not_share_warning_enabled, + custom_code_enabled=custom_code_enabled, + push_include_date=push_include_date, + push_apn_credential_sid=push_apn_credential_sid, + push_fcm_credential_sid=push_fcm_credential_sid, + totp_issuer=totp_issuer, + totp_time_step=totp_time_step, + totp_code_length=totp_code_length, + totp_skew=totp_skew, + default_template_sid=default_template_sid, + whatsapp_msg_service_sid=whatsapp_msg_service_sid, + whatsapp_from=whatsapp_from, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a privacy warning at the end of an SMS. **Disabled by default and applies only for SMS.** + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. + :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + code_length=code_length, + lookup_enabled=lookup_enabled, + skip_sms_to_landlines=skip_sms_to_landlines, + dtmf_input_required=dtmf_input_required, + tts_name=tts_name, + psd2_enabled=psd2_enabled, + do_not_share_warning_enabled=do_not_share_warning_enabled, + custom_code_enabled=custom_code_enabled, + push_include_date=push_include_date, + push_apn_credential_sid=push_apn_credential_sid, + push_fcm_credential_sid=push_fcm_credential_sid, + totp_issuer=totp_issuer, + totp_time_step=totp_time_step, + totp_code_length=totp_code_length, + totp_skew=totp_skew, + default_template_sid=default_template_sid, + whatsapp_msg_service_sid=whatsapp_msg_service_sid, + whatsapp_from=whatsapp_from, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + + @property + def access_tokens(self) -> AccessTokenList: + """ + Access the access_tokens + """ + return self._proxy.access_tokens + + @property + def entities(self) -> EntityList: + """ + Access the entities + """ + return self._proxy.entities + + @property + def messaging_configurations(self) -> MessagingConfigurationList: + """ + Access the messaging_configurations + """ + return self._proxy.messaging_configurations + + @property + def rate_limits(self) -> RateLimitList: + """ + Access the rate_limits + """ + return self._proxy.rate_limits + + @property + def verifications(self) -> VerificationList: + """ + Access the verifications + """ + return self._proxy.verifications + + @property + def verification_checks(self) -> VerificationCheckList: + """ + Access the verification_checks + """ + return self._proxy.verification_checks + + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + return self._proxy.webhooks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._access_tokens: Optional[AccessTokenList] = None + self._entities: Optional[EntityList] = None + self._messaging_configurations: Optional[MessagingConfigurationList] = None + self._rate_limits: Optional[RateLimitList] = None + self._verifications: Optional[VerificationList] = None + self._verification_checks: Optional[VerificationCheckList] = None + self._webhooks: Optional[WebhookList] = None + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a privacy warning at the end of an SMS. **Disabled by default and applies only for SMS.** + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. + :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "CodeLength": code_length, + "LookupEnabled": serialize.boolean_to_string(lookup_enabled), + "SkipSmsToLandlines": serialize.boolean_to_string( + skip_sms_to_landlines + ), + "DtmfInputRequired": serialize.boolean_to_string(dtmf_input_required), + "TtsName": tts_name, + "Psd2Enabled": serialize.boolean_to_string(psd2_enabled), + "DoNotShareWarningEnabled": serialize.boolean_to_string( + do_not_share_warning_enabled + ), + "CustomCodeEnabled": serialize.boolean_to_string(custom_code_enabled), + "Push.IncludeDate": serialize.boolean_to_string(push_include_date), + "Push.ApnCredentialSid": push_apn_credential_sid, + "Push.FcmCredentialSid": push_fcm_credential_sid, + "Totp.Issuer": totp_issuer, + "Totp.TimeStep": totp_time_step, + "Totp.CodeLength": totp_code_length, + "Totp.Skew": totp_skew, + "DefaultTemplateSid": default_template_sid, + "Whatsapp.MsgServiceSid": whatsapp_msg_service_sid, + "Whatsapp.From": whatsapp_from, + "VerifyEventSubscriptionEnabled": serialize.boolean_to_string( + verify_event_subscription_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a privacy warning at the end of an SMS. **Disabled by default and applies only for SMS.** + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. + :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "CodeLength": code_length, + "LookupEnabled": serialize.boolean_to_string(lookup_enabled), + "SkipSmsToLandlines": serialize.boolean_to_string( + skip_sms_to_landlines + ), + "DtmfInputRequired": serialize.boolean_to_string(dtmf_input_required), + "TtsName": tts_name, + "Psd2Enabled": serialize.boolean_to_string(psd2_enabled), + "DoNotShareWarningEnabled": serialize.boolean_to_string( + do_not_share_warning_enabled + ), + "CustomCodeEnabled": serialize.boolean_to_string(custom_code_enabled), + "Push.IncludeDate": serialize.boolean_to_string(push_include_date), + "Push.ApnCredentialSid": push_apn_credential_sid, + "Push.FcmCredentialSid": push_fcm_credential_sid, + "Totp.Issuer": totp_issuer, + "Totp.TimeStep": totp_time_step, + "Totp.CodeLength": totp_code_length, + "Totp.Skew": totp_skew, + "DefaultTemplateSid": default_template_sid, + "Whatsapp.MsgServiceSid": whatsapp_msg_service_sid, + "Whatsapp.From": whatsapp_from, + "VerifyEventSubscriptionEnabled": serialize.boolean_to_string( + verify_event_subscription_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def access_tokens(self) -> AccessTokenList: + """ + Access the access_tokens + """ + if self._access_tokens is None: + self._access_tokens = AccessTokenList( + self._version, + self._solution["sid"], + ) + return self._access_tokens + + @property + def entities(self) -> EntityList: + """ + Access the entities + """ + if self._entities is None: + self._entities = EntityList( + self._version, + self._solution["sid"], + ) + return self._entities + + @property + def messaging_configurations(self) -> MessagingConfigurationList: + """ + Access the messaging_configurations + """ + if self._messaging_configurations is None: + self._messaging_configurations = MessagingConfigurationList( + self._version, + self._solution["sid"], + ) + return self._messaging_configurations + + @property + def rate_limits(self) -> RateLimitList: + """ + Access the rate_limits + """ + if self._rate_limits is None: + self._rate_limits = RateLimitList( + self._version, + self._solution["sid"], + ) + return self._rate_limits + + @property + def verifications(self) -> VerificationList: + """ + Access the verifications + """ + if self._verifications is None: + self._verifications = VerificationList( + self._version, + self._solution["sid"], + ) + return self._verifications + + @property + def verification_checks(self) -> VerificationCheckList: + """ + Access the verification_checks + """ + if self._verification_checks is None: + self._verification_checks = VerificationCheckList( + self._version, + self._solution["sid"], + ) + return self._verification_checks + + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + if self._webhooks is None: + self._webhooks = WebhookList( + self._version, + self._solution["sid"], + ) + return self._webhooks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def create( + self, + friendly_name: str, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a security warning at the end of an SMS verification body. Disabled by default and applies only to SMS. Example SMS body: `Your AppName verification code is: 1234. Don’t share this code with anyone; our employees will never ask for the code` + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. This timestamp value is the same one as the one found in `date_created`, please use that one instead. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. Defaults to the service friendly name if not provided. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the Messaging Service containing WhatsApp Sender(s) that Verify will use to send WhatsApp messages to your users. + :param whatsapp_from: The number to use as the WhatsApp Sender that Verify will use to send WhatsApp messages to your users.This WhatsApp Sender must be associated with a Messaging Service SID. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "CodeLength": code_length, + "LookupEnabled": serialize.boolean_to_string(lookup_enabled), + "SkipSmsToLandlines": serialize.boolean_to_string( + skip_sms_to_landlines + ), + "DtmfInputRequired": serialize.boolean_to_string(dtmf_input_required), + "TtsName": tts_name, + "Psd2Enabled": serialize.boolean_to_string(psd2_enabled), + "DoNotShareWarningEnabled": serialize.boolean_to_string( + do_not_share_warning_enabled + ), + "CustomCodeEnabled": serialize.boolean_to_string(custom_code_enabled), + "Push.IncludeDate": serialize.boolean_to_string(push_include_date), + "Push.ApnCredentialSid": push_apn_credential_sid, + "Push.FcmCredentialSid": push_fcm_credential_sid, + "Totp.Issuer": totp_issuer, + "Totp.TimeStep": totp_time_step, + "Totp.CodeLength": totp_code_length, + "Totp.Skew": totp_skew, + "DefaultTemplateSid": default_template_sid, + "Whatsapp.MsgServiceSid": whatsapp_msg_service_sid, + "Whatsapp.From": whatsapp_from, + "VerifyEventSubscriptionEnabled": serialize.boolean_to_string( + verify_event_subscription_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a security warning at the end of an SMS verification body. Disabled by default and applies only to SMS. Example SMS body: `Your AppName verification code is: 1234. Don’t share this code with anyone; our employees will never ask for the code` + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. This timestamp value is the same one as the one found in `date_created`, please use that one instead. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. Defaults to the service friendly name if not provided. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the Messaging Service containing WhatsApp Sender(s) that Verify will use to send WhatsApp messages to your users. + :param whatsapp_from: The number to use as the WhatsApp Sender that Verify will use to send WhatsApp messages to your users.This WhatsApp Sender must be associated with a Messaging Service SID. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "CodeLength": code_length, + "LookupEnabled": serialize.boolean_to_string(lookup_enabled), + "SkipSmsToLandlines": serialize.boolean_to_string( + skip_sms_to_landlines + ), + "DtmfInputRequired": serialize.boolean_to_string(dtmf_input_required), + "TtsName": tts_name, + "Psd2Enabled": serialize.boolean_to_string(psd2_enabled), + "DoNotShareWarningEnabled": serialize.boolean_to_string( + do_not_share_warning_enabled + ), + "CustomCodeEnabled": serialize.boolean_to_string(custom_code_enabled), + "Push.IncludeDate": serialize.boolean_to_string(push_include_date), + "Push.ApnCredentialSid": push_apn_credential_sid, + "Push.FcmCredentialSid": push_fcm_credential_sid, + "Totp.Issuer": totp_issuer, + "Totp.TimeStep": totp_time_step, + "Totp.CodeLength": totp_code_length, + "Totp.Skew": totp_skew, + "DefaultTemplateSid": default_template_sid, + "Whatsapp.MsgServiceSid": whatsapp_msg_service_sid, + "Whatsapp.From": whatsapp_from, + "VerifyEventSubscriptionEnabled": serialize.boolean_to_string( + verify_event_subscription_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/verify/v2/service/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..9619e561 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/verify/v2/service/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/__pycache__/access_token.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/verify/v2/service/__pycache__/access_token.cpython-312.pyc new file mode 100644 index 00000000..ac920ab2 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/verify/v2/service/__pycache__/access_token.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/__pycache__/messaging_configuration.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/verify/v2/service/__pycache__/messaging_configuration.cpython-312.pyc new file mode 100644 index 00000000..633aab31 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/verify/v2/service/__pycache__/messaging_configuration.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/__pycache__/verification.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/verify/v2/service/__pycache__/verification.cpython-312.pyc new file mode 100644 index 00000000..7853fb86 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/verify/v2/service/__pycache__/verification.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/__pycache__/verification_check.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/verify/v2/service/__pycache__/verification_check.cpython-312.pyc new file mode 100644 index 00000000..28a04790 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/verify/v2/service/__pycache__/verification_check.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/__pycache__/webhook.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/verify/v2/service/__pycache__/webhook.cpython-312.pyc new file mode 100644 index 00000000..2233633f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/verify/v2/service/__pycache__/webhook.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/access_token.py b/venv/Lib/site-packages/twilio/rest/verify/v2/service/access_token.py new file mode 100644 index 00000000..45a0094e --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/verify/v2/service/access_token.py @@ -0,0 +1,315 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class AccessTokenInstance(InstanceResource): + + class FactorTypes(object): + PUSH = "push" + + """ + :ivar sid: A 34 character string that uniquely identifies this Access Token. + :ivar account_sid: The unique SID identifier of the Account. + :ivar service_sid: The unique SID identifier of the Verify Service. + :ivar entity_identity: The unique external identifier for the Entity of the Service. + :ivar factor_type: + :ivar factor_friendly_name: A human readable description of this factor, up to 64 characters. For a push factor, this can be the device's name. + :ivar token: The access token generated for enrollment, this is an encrypted json web token. + :ivar url: The URL of this resource. + :ivar ttl: How long, in seconds, the access token is valid. Max: 5 minutes + :ivar date_created: The date that this access token was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.entity_identity: Optional[str] = payload.get("entity_identity") + self.factor_type: Optional["AccessTokenInstance.FactorTypes"] = payload.get( + "factor_type" + ) + self.factor_friendly_name: Optional[str] = payload.get("factor_friendly_name") + self.token: Optional[str] = payload.get("token") + self.url: Optional[str] = payload.get("url") + self.ttl: Optional[int] = deserialize.integer(payload.get("ttl")) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[AccessTokenContext] = None + + @property + def _proxy(self) -> "AccessTokenContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AccessTokenContext for this AccessTokenInstance + """ + if self._context is None: + self._context = AccessTokenContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "AccessTokenInstance": + """ + Fetch the AccessTokenInstance + + + :returns: The fetched AccessTokenInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AccessTokenInstance": + """ + Asynchronous coroutine to fetch the AccessTokenInstance + + + :returns: The fetched AccessTokenInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AccessTokenContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the AccessTokenContext + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param sid: A 34 character string that uniquely identifies this Access Token. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/AccessTokens/{sid}".format( + **self._solution + ) + + def fetch(self) -> AccessTokenInstance: + """ + Fetch the AccessTokenInstance + + + :returns: The fetched AccessTokenInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AccessTokenInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AccessTokenInstance: + """ + Asynchronous coroutine to fetch the AccessTokenInstance + + + :returns: The fetched AccessTokenInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AccessTokenInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AccessTokenList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the AccessTokenList + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/AccessTokens".format(**self._solution) + + def create( + self, + identity: str, + factor_type: "AccessTokenInstance.FactorTypes", + factor_friendly_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> AccessTokenInstance: + """ + Create the AccessTokenInstance + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, and generated by your external system, such as your user's UUID, GUID, or SID. + :param factor_type: + :param factor_friendly_name: The friendly name of the factor that is going to be created with this access token + :param ttl: How long, in seconds, the access token is valid. Can be an integer between 60 and 300. Default is 60. + + :returns: The created AccessTokenInstance + """ + + data = values.of( + { + "Identity": identity, + "FactorType": factor_type, + "FactorFriendlyName": factor_friendly_name, + "Ttl": ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AccessTokenInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + identity: str, + factor_type: "AccessTokenInstance.FactorTypes", + factor_friendly_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> AccessTokenInstance: + """ + Asynchronously create the AccessTokenInstance + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, and generated by your external system, such as your user's UUID, GUID, or SID. + :param factor_type: + :param factor_friendly_name: The friendly name of the factor that is going to be created with this access token + :param ttl: How long, in seconds, the access token is valid. Can be an integer between 60 and 300. Default is 60. + + :returns: The created AccessTokenInstance + """ + + data = values.of( + { + "Identity": identity, + "FactorType": factor_type, + "FactorFriendlyName": factor_friendly_name, + "Ttl": ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AccessTokenInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def get(self, sid: str) -> AccessTokenContext: + """ + Constructs a AccessTokenContext + + :param sid: A 34 character string that uniquely identifies this Access Token. + """ + return AccessTokenContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> AccessTokenContext: + """ + Constructs a AccessTokenContext + + :param sid: A 34 character string that uniquely identifies this Access Token. + """ + return AccessTokenContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/__init__.py b/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/__init__.py new file mode 100644 index 00000000..fa4bc1df --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/__init__.py @@ -0,0 +1,609 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.verify.v2.service.entity.challenge import ChallengeList +from twilio.rest.verify.v2.service.entity.factor import FactorList +from twilio.rest.verify.v2.service.entity.new_factor import NewFactorList + + +class EntityInstance(InstanceResource): + """ + :ivar sid: A 34 character string that uniquely identifies this Entity. + :ivar identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + :ivar account_sid: The unique SID identifier of the Account. + :ivar service_sid: The unique SID identifier of the Service. + :ivar date_created: The date that this Entity was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date that this Entity was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The URL of this resource. + :ivar links: Contains a dictionary of URL links to nested resources of this Entity. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + identity: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.identity: Optional[str] = payload.get("identity") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "identity": identity or self.identity, + } + self._context: Optional[EntityContext] = None + + @property + def _proxy(self) -> "EntityContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EntityContext for this EntityInstance + """ + if self._context is None: + self._context = EntityContext( + self._version, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the EntityInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the EntityInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "EntityInstance": + """ + Fetch the EntityInstance + + + :returns: The fetched EntityInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EntityInstance": + """ + Asynchronous coroutine to fetch the EntityInstance + + + :returns: The fetched EntityInstance + """ + return await self._proxy.fetch_async() + + @property + def challenges(self) -> ChallengeList: + """ + Access the challenges + """ + return self._proxy.challenges + + @property + def factors(self) -> FactorList: + """ + Access the factors + """ + return self._proxy.factors + + @property + def new_factors(self) -> NewFactorList: + """ + Access the new_factors + """ + return self._proxy.new_factors + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EntityContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, identity: str): + """ + Initialize the EntityContext + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "identity": identity, + } + self._uri = "/Services/{service_sid}/Entities/{identity}".format( + **self._solution + ) + + self._challenges: Optional[ChallengeList] = None + self._factors: Optional[FactorList] = None + self._new_factors: Optional[NewFactorList] = None + + def delete(self) -> bool: + """ + Deletes the EntityInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the EntityInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> EntityInstance: + """ + Fetch the EntityInstance + + + :returns: The fetched EntityInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EntityInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + + async def fetch_async(self) -> EntityInstance: + """ + Asynchronous coroutine to fetch the EntityInstance + + + :returns: The fetched EntityInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EntityInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + + @property + def challenges(self) -> ChallengeList: + """ + Access the challenges + """ + if self._challenges is None: + self._challenges = ChallengeList( + self._version, + self._solution["service_sid"], + self._solution["identity"], + ) + return self._challenges + + @property + def factors(self) -> FactorList: + """ + Access the factors + """ + if self._factors is None: + self._factors = FactorList( + self._version, + self._solution["service_sid"], + self._solution["identity"], + ) + return self._factors + + @property + def new_factors(self) -> NewFactorList: + """ + Access the new_factors + """ + if self._new_factors is None: + self._new_factors = NewFactorList( + self._version, + self._solution["service_sid"], + self._solution["identity"], + ) + return self._new_factors + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EntityPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EntityInstance: + """ + Build an instance of EntityInstance + + :param payload: Payload response from the API + """ + return EntityInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class EntityList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the EntityList + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Entities".format(**self._solution) + + def create(self, identity: str) -> EntityInstance: + """ + Create the EntityInstance + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + + :returns: The created EntityInstance + """ + + data = values.of( + { + "Identity": identity, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EntityInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async(self, identity: str) -> EntityInstance: + """ + Asynchronously create the EntityInstance + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + + :returns: The created EntityInstance + """ + + data = values.of( + { + "Identity": identity, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EntityInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EntityInstance]: + """ + Streams EntityInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EntityInstance]: + """ + Asynchronously streams EntityInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EntityInstance]: + """ + Lists EntityInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EntityInstance]: + """ + Asynchronously lists EntityInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EntityPage: + """ + Retrieve a single page of EntityInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EntityInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EntityPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EntityPage: + """ + Asynchronously retrieve a single page of EntityInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EntityInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EntityPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> EntityPage: + """ + Retrieve a specific page of EntityInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EntityInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EntityPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> EntityPage: + """ + Asynchronously retrieve a specific page of EntityInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EntityInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EntityPage(self._version, response, self._solution) + + def get(self, identity: str) -> EntityContext: + """ + Constructs a EntityContext + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + """ + return EntityContext( + self._version, service_sid=self._solution["service_sid"], identity=identity + ) + + def __call__(self, identity: str) -> EntityContext: + """ + Constructs a EntityContext + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + """ + return EntityContext( + self._version, service_sid=self._solution["service_sid"], identity=identity + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..e3a1a1f8 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/__pycache__/factor.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/__pycache__/factor.cpython-312.pyc new file mode 100644 index 00000000..5baf2b34 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/__pycache__/factor.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/__pycache__/new_factor.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/__pycache__/new_factor.cpython-312.pyc new file mode 100644 index 00000000..bacfe378 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/__pycache__/new_factor.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/challenge/__init__.py b/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/challenge/__init__.py new file mode 100644 index 00000000..146a95d9 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/challenge/__init__.py @@ -0,0 +1,810 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.verify.v2.service.entity.challenge.notification import NotificationList + + +class ChallengeInstance(InstanceResource): + + class ChallengeReasons(object): + NONE = "none" + NOT_NEEDED = "not_needed" + NOT_REQUESTED = "not_requested" + + class ChallengeStatuses(object): + PENDING = "pending" + EXPIRED = "expired" + APPROVED = "approved" + DENIED = "denied" + + class FactorTypes(object): + PUSH = "push" + TOTP = "totp" + + class ListOrders(object): + ASC = "asc" + DESC = "desc" + + """ + :ivar sid: A 34 character string that uniquely identifies this Challenge. + :ivar account_sid: The unique SID identifier of the Account. + :ivar service_sid: The unique SID identifier of the Service. + :ivar entity_sid: The unique SID identifier of the Entity. + :ivar identity: Customer unique identity for the Entity owner of the Challenge. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + :ivar factor_sid: The unique SID identifier of the Factor. + :ivar date_created: The date that this Challenge was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date that this Challenge was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_responded: The date that this Challenge was responded, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar expiration_date: The date-time when this Challenge expires, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. The default value is five (5) minutes after Challenge creation. The max value is sixty (60) minutes after creation. + :ivar status: + :ivar responded_reason: + :ivar details: Details provided to give context about the Challenge. Intended to be shown to the end user. + :ivar hidden_details: Details provided to give context about the Challenge. Intended to be hidden from the end user. It must be a stringified JSON with only strings values eg. `{\"ip\": \"172.168.1.234\"}` + :ivar metadata: Custom metadata associated with the challenge. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\"os\": \"Android\"}`. Can be up to 1024 characters in length. + :ivar factor_type: + :ivar url: The URL of this resource. + :ivar links: Contains a dictionary of URL links to nested resources of this Challenge. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + identity: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.entity_sid: Optional[str] = payload.get("entity_sid") + self.identity: Optional[str] = payload.get("identity") + self.factor_sid: Optional[str] = payload.get("factor_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.date_responded: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_responded") + ) + self.expiration_date: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("expiration_date") + ) + self.status: Optional["ChallengeInstance.ChallengeStatuses"] = payload.get( + "status" + ) + self.responded_reason: Optional["ChallengeInstance.ChallengeReasons"] = ( + payload.get("responded_reason") + ) + self.details: Optional[Dict[str, object]] = payload.get("details") + self.hidden_details: Optional[Dict[str, object]] = payload.get("hidden_details") + self.metadata: Optional[Dict[str, object]] = payload.get("metadata") + self.factor_type: Optional["ChallengeInstance.FactorTypes"] = payload.get( + "factor_type" + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "identity": identity, + "sid": sid or self.sid, + } + self._context: Optional[ChallengeContext] = None + + @property + def _proxy(self) -> "ChallengeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ChallengeContext for this ChallengeInstance + """ + if self._context is None: + self._context = ChallengeContext( + self._version, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "ChallengeInstance": + """ + Fetch the ChallengeInstance + + + :returns: The fetched ChallengeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ChallengeInstance": + """ + Asynchronous coroutine to fetch the ChallengeInstance + + + :returns: The fetched ChallengeInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + auth_payload: Union[str, object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> "ChallengeInstance": + """ + Update the ChallengeInstance + + :param auth_payload: The optional payload needed to verify the Challenge. E.g., a TOTP would use the numeric code. For `TOTP` this value must be between 3 and 8 characters long. For `Push` this value can be up to 5456 characters in length + :param metadata: Custom metadata associated with the challenge. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + + :returns: The updated ChallengeInstance + """ + return self._proxy.update( + auth_payload=auth_payload, + metadata=metadata, + ) + + async def update_async( + self, + auth_payload: Union[str, object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> "ChallengeInstance": + """ + Asynchronous coroutine to update the ChallengeInstance + + :param auth_payload: The optional payload needed to verify the Challenge. E.g., a TOTP would use the numeric code. For `TOTP` this value must be between 3 and 8 characters long. For `Push` this value can be up to 5456 characters in length + :param metadata: Custom metadata associated with the challenge. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + + :returns: The updated ChallengeInstance + """ + return await self._proxy.update_async( + auth_payload=auth_payload, + metadata=metadata, + ) + + @property + def notifications(self) -> NotificationList: + """ + Access the notifications + """ + return self._proxy.notifications + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ChallengeContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, identity: str, sid: str): + """ + Initialize the ChallengeContext + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param identity: Customer unique identity for the Entity owner of the Challenge. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + :param sid: A 34 character string that uniquely identifies this Challenge. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "identity": identity, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Entities/{identity}/Challenges/{sid}".format( + **self._solution + ) + ) + + self._notifications: Optional[NotificationList] = None + + def fetch(self) -> ChallengeInstance: + """ + Fetch the ChallengeInstance + + + :returns: The fetched ChallengeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ChallengeInstance: + """ + Asynchronous coroutine to fetch the ChallengeInstance + + + :returns: The fetched ChallengeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + + def update( + self, + auth_payload: Union[str, object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> ChallengeInstance: + """ + Update the ChallengeInstance + + :param auth_payload: The optional payload needed to verify the Challenge. E.g., a TOTP would use the numeric code. For `TOTP` this value must be between 3 and 8 characters long. For `Push` this value can be up to 5456 characters in length + :param metadata: Custom metadata associated with the challenge. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + + :returns: The updated ChallengeInstance + """ + + data = values.of( + { + "AuthPayload": auth_payload, + "Metadata": serialize.object(metadata), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + auth_payload: Union[str, object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> ChallengeInstance: + """ + Asynchronous coroutine to update the ChallengeInstance + + :param auth_payload: The optional payload needed to verify the Challenge. E.g., a TOTP would use the numeric code. For `TOTP` this value must be between 3 and 8 characters long. For `Push` this value can be up to 5456 characters in length + :param metadata: Custom metadata associated with the challenge. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + + :returns: The updated ChallengeInstance + """ + + data = values.of( + { + "AuthPayload": auth_payload, + "Metadata": serialize.object(metadata), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + + @property + def notifications(self) -> NotificationList: + """ + Access the notifications + """ + if self._notifications is None: + self._notifications = NotificationList( + self._version, + self._solution["service_sid"], + self._solution["identity"], + self._solution["sid"], + ) + return self._notifications + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ChallengePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ChallengeInstance: + """ + Build an instance of ChallengeInstance + + :param payload: Payload response from the API + """ + return ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ChallengeList(ListResource): + + def __init__(self, version: Version, service_sid: str, identity: str): + """ + Initialize the ChallengeList + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param identity: Customer unique identity for the Entity owner of the Challenge. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "identity": identity, + } + self._uri = "/Services/{service_sid}/Entities/{identity}/Challenges".format( + **self._solution + ) + + def create( + self, + factor_sid: str, + expiration_date: Union[datetime, object] = values.unset, + details_message: Union[str, object] = values.unset, + details_fields: Union[List[object], object] = values.unset, + hidden_details: Union[object, object] = values.unset, + auth_payload: Union[str, object] = values.unset, + ) -> ChallengeInstance: + """ + Create the ChallengeInstance + + :param factor_sid: The unique SID identifier of the Factor. + :param expiration_date: The date-time when this Challenge expires, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. The default value is five (5) minutes after Challenge creation. The max value is sixty (60) minutes after creation. + :param details_message: Shown to the user when the push notification arrives. Required when `factor_type` is `push`. Can be up to 256 characters in length + :param details_fields: A list of objects that describe the Fields included in the Challenge. Each object contains the label and value of the field, the label can be up to 36 characters in length and the value can be up to 128 characters in length. Used when `factor_type` is `push`. There can be up to 20 details fields. + :param hidden_details: Details provided to give context about the Challenge. Not shown to the end user. It must be a stringified JSON with only strings values eg. `{\\\"ip\\\": \\\"172.168.1.234\\\"}`. Can be up to 1024 characters in length + :param auth_payload: Optional payload used to verify the Challenge upon creation. Only used with a Factor of type `totp` to carry the TOTP code that needs to be verified. For `TOTP` this value must be between 3 and 8 characters long. + + :returns: The created ChallengeInstance + """ + + data = values.of( + { + "FactorSid": factor_sid, + "ExpirationDate": serialize.iso8601_datetime(expiration_date), + "Details.Message": details_message, + "Details.Fields": serialize.map( + details_fields, lambda e: serialize.object(e) + ), + "HiddenDetails": serialize.object(hidden_details), + "AuthPayload": auth_payload, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + + async def create_async( + self, + factor_sid: str, + expiration_date: Union[datetime, object] = values.unset, + details_message: Union[str, object] = values.unset, + details_fields: Union[List[object], object] = values.unset, + hidden_details: Union[object, object] = values.unset, + auth_payload: Union[str, object] = values.unset, + ) -> ChallengeInstance: + """ + Asynchronously create the ChallengeInstance + + :param factor_sid: The unique SID identifier of the Factor. + :param expiration_date: The date-time when this Challenge expires, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. The default value is five (5) minutes after Challenge creation. The max value is sixty (60) minutes after creation. + :param details_message: Shown to the user when the push notification arrives. Required when `factor_type` is `push`. Can be up to 256 characters in length + :param details_fields: A list of objects that describe the Fields included in the Challenge. Each object contains the label and value of the field, the label can be up to 36 characters in length and the value can be up to 128 characters in length. Used when `factor_type` is `push`. There can be up to 20 details fields. + :param hidden_details: Details provided to give context about the Challenge. Not shown to the end user. It must be a stringified JSON with only strings values eg. `{\\\"ip\\\": \\\"172.168.1.234\\\"}`. Can be up to 1024 characters in length + :param auth_payload: Optional payload used to verify the Challenge upon creation. Only used with a Factor of type `totp` to carry the TOTP code that needs to be verified. For `TOTP` this value must be between 3 and 8 characters long. + + :returns: The created ChallengeInstance + """ + + data = values.of( + { + "FactorSid": factor_sid, + "ExpirationDate": serialize.iso8601_datetime(expiration_date), + "Details.Message": details_message, + "Details.Fields": serialize.map( + details_fields, lambda e: serialize.object(e) + ), + "HiddenDetails": serialize.object(hidden_details), + "AuthPayload": auth_payload, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + + def stream( + self, + factor_sid: Union[str, object] = values.unset, + status: Union["ChallengeInstance.ChallengeStatuses", object] = values.unset, + order: Union["ChallengeInstance.ListOrders", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChallengeInstance]: + """ + Streams ChallengeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str factor_sid: The unique SID identifier of the Factor. + :param "ChallengeInstance.ChallengeStatuses" status: The Status of the Challenges to fetch. One of `pending`, `expired`, `approved` or `denied`. + :param "ChallengeInstance.ListOrders" order: The desired sort order of the Challenges list. One of `asc` or `desc` for ascending and descending respectively. Defaults to `asc`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + factor_sid=factor_sid, + status=status, + order=order, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + factor_sid: Union[str, object] = values.unset, + status: Union["ChallengeInstance.ChallengeStatuses", object] = values.unset, + order: Union["ChallengeInstance.ListOrders", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ChallengeInstance]: + """ + Asynchronously streams ChallengeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str factor_sid: The unique SID identifier of the Factor. + :param "ChallengeInstance.ChallengeStatuses" status: The Status of the Challenges to fetch. One of `pending`, `expired`, `approved` or `denied`. + :param "ChallengeInstance.ListOrders" order: The desired sort order of the Challenges list. One of `asc` or `desc` for ascending and descending respectively. Defaults to `asc`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + factor_sid=factor_sid, + status=status, + order=order, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + factor_sid: Union[str, object] = values.unset, + status: Union["ChallengeInstance.ChallengeStatuses", object] = values.unset, + order: Union["ChallengeInstance.ListOrders", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChallengeInstance]: + """ + Lists ChallengeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str factor_sid: The unique SID identifier of the Factor. + :param "ChallengeInstance.ChallengeStatuses" status: The Status of the Challenges to fetch. One of `pending`, `expired`, `approved` or `denied`. + :param "ChallengeInstance.ListOrders" order: The desired sort order of the Challenges list. One of `asc` or `desc` for ascending and descending respectively. Defaults to `asc`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + factor_sid=factor_sid, + status=status, + order=order, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + factor_sid: Union[str, object] = values.unset, + status: Union["ChallengeInstance.ChallengeStatuses", object] = values.unset, + order: Union["ChallengeInstance.ListOrders", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChallengeInstance]: + """ + Asynchronously lists ChallengeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str factor_sid: The unique SID identifier of the Factor. + :param "ChallengeInstance.ChallengeStatuses" status: The Status of the Challenges to fetch. One of `pending`, `expired`, `approved` or `denied`. + :param "ChallengeInstance.ListOrders" order: The desired sort order of the Challenges list. One of `asc` or `desc` for ascending and descending respectively. Defaults to `asc`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + factor_sid=factor_sid, + status=status, + order=order, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + factor_sid: Union[str, object] = values.unset, + status: Union["ChallengeInstance.ChallengeStatuses", object] = values.unset, + order: Union["ChallengeInstance.ListOrders", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChallengePage: + """ + Retrieve a single page of ChallengeInstance records from the API. + Request is executed immediately + + :param factor_sid: The unique SID identifier of the Factor. + :param status: The Status of the Challenges to fetch. One of `pending`, `expired`, `approved` or `denied`. + :param order: The desired sort order of the Challenges list. One of `asc` or `desc` for ascending and descending respectively. Defaults to `asc`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChallengeInstance + """ + data = values.of( + { + "FactorSid": factor_sid, + "Status": status, + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChallengePage(self._version, response, self._solution) + + async def page_async( + self, + factor_sid: Union[str, object] = values.unset, + status: Union["ChallengeInstance.ChallengeStatuses", object] = values.unset, + order: Union["ChallengeInstance.ListOrders", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChallengePage: + """ + Asynchronously retrieve a single page of ChallengeInstance records from the API. + Request is executed immediately + + :param factor_sid: The unique SID identifier of the Factor. + :param status: The Status of the Challenges to fetch. One of `pending`, `expired`, `approved` or `denied`. + :param order: The desired sort order of the Challenges list. One of `asc` or `desc` for ascending and descending respectively. Defaults to `asc`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChallengeInstance + """ + data = values.of( + { + "FactorSid": factor_sid, + "Status": status, + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChallengePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ChallengePage: + """ + Retrieve a specific page of ChallengeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChallengeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ChallengePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ChallengePage: + """ + Asynchronously retrieve a specific page of ChallengeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChallengeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChallengePage(self._version, response, self._solution) + + def get(self, sid: str) -> ChallengeContext: + """ + Constructs a ChallengeContext + + :param sid: A 34 character string that uniquely identifies this Challenge. + """ + return ChallengeContext( + self._version, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=sid, + ) + + def __call__(self, sid: str) -> ChallengeContext: + """ + Constructs a ChallengeContext + + :param sid: A 34 character string that uniquely identifies this Challenge. + """ + return ChallengeContext( + self._version, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/challenge/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/challenge/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..bbcc0866 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/challenge/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/challenge/__pycache__/notification.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/challenge/__pycache__/notification.cpython-312.pyc new file mode 100644 index 00000000..c1fa27e0 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/challenge/__pycache__/notification.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/challenge/notification.py b/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/challenge/notification.py new file mode 100644 index 00000000..3802cc1a --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/challenge/notification.py @@ -0,0 +1,173 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NotificationInstance(InstanceResource): + """ + :ivar sid: A 34 character string that uniquely identifies this Notification. + :ivar account_sid: The unique SID identifier of the Account. + :ivar service_sid: The unique SID identifier of the Service. + :ivar entity_sid: The unique SID identifier of the Entity. + :ivar identity: Customer unique identity for the Entity owner of the Challenge. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + :ivar challenge_sid: The unique SID identifier of the Challenge. + :ivar priority: The priority of the notification. For `push` Challenges it's always `high` which sends the notification immediately, and can wake up a sleeping device. + :ivar ttl: How long, in seconds, the notification is valid. Max: 5 minutes + :ivar date_created: The date that this Notification was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + identity: str, + challenge_sid: str, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.entity_sid: Optional[str] = payload.get("entity_sid") + self.identity: Optional[str] = payload.get("identity") + self.challenge_sid: Optional[str] = payload.get("challenge_sid") + self.priority: Optional[str] = payload.get("priority") + self.ttl: Optional[int] = deserialize.integer(payload.get("ttl")) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + + self._solution = { + "service_sid": service_sid, + "identity": identity, + "challenge_sid": challenge_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NotificationList(ListResource): + + def __init__( + self, version: Version, service_sid: str, identity: str, challenge_sid: str + ): + """ + Initialize the NotificationList + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param identity: Customer unique identity for the Entity owner of the Challenge. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + :param challenge_sid: The unique SID identifier of the Challenge. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "identity": identity, + "challenge_sid": challenge_sid, + } + self._uri = "/Services/{service_sid}/Entities/{identity}/Challenges/{challenge_sid}/Notifications".format( + **self._solution + ) + + def create(self, ttl: Union[int, object] = values.unset) -> NotificationInstance: + """ + Create the NotificationInstance + + :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 300. Default is 300. Delivery is attempted until the TTL elapses, even if the device is offline. 0 means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. + + :returns: The created NotificationInstance + """ + + data = values.of( + { + "Ttl": ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NotificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + challenge_sid=self._solution["challenge_sid"], + ) + + async def create_async( + self, ttl: Union[int, object] = values.unset + ) -> NotificationInstance: + """ + Asynchronously create the NotificationInstance + + :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 300. Default is 300. Delivery is attempted until the TTL elapses, even if the device is offline. 0 means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. + + :returns: The created NotificationInstance + """ + + data = values.of( + { + "Ttl": ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NotificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + challenge_sid=self._solution["challenge_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/factor.py b/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/factor.py new file mode 100644 index 00000000..7bf91cd8 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/factor.py @@ -0,0 +1,728 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class FactorInstance(InstanceResource): + + class FactorStatuses(object): + UNVERIFIED = "unverified" + VERIFIED = "verified" + + class FactorTypes(object): + PUSH = "push" + TOTP = "totp" + + class TotpAlgorithms(object): + SHA1 = "sha1" + SHA256 = "sha256" + SHA512 = "sha512" + + """ + :ivar sid: A 34 character string that uniquely identifies this Factor. + :ivar account_sid: The unique SID identifier of the Account. + :ivar service_sid: The unique SID identifier of the Service. + :ivar entity_sid: The unique SID identifier of the Entity. + :ivar identity: Customer unique identity for the Entity owner of the Factor. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + :ivar date_created: The date that this Factor was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date that this Factor was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar friendly_name: A human readable description of this resource, up to 64 characters. For a push factor, this can be the device's name. + :ivar status: + :ivar factor_type: + :ivar config: An object that contains configurations specific to a `factor_type`. + :ivar metadata: Custom metadata associated with the factor. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\"os\": \"Android\"}`. Can be up to 1024 characters in length. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + identity: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.entity_sid: Optional[str] = payload.get("entity_sid") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["FactorInstance.FactorStatuses"] = payload.get("status") + self.factor_type: Optional["FactorInstance.FactorTypes"] = payload.get( + "factor_type" + ) + self.config: Optional[Dict[str, object]] = payload.get("config") + self.metadata: Optional[Dict[str, object]] = payload.get("metadata") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "identity": identity, + "sid": sid or self.sid, + } + self._context: Optional[FactorContext] = None + + @property + def _proxy(self) -> "FactorContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FactorContext for this FactorInstance + """ + if self._context is None: + self._context = FactorContext( + self._version, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the FactorInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FactorInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "FactorInstance": + """ + Fetch the FactorInstance + + + :returns: The fetched FactorInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FactorInstance": + """ + Asynchronous coroutine to fetch the FactorInstance + + + :returns: The fetched FactorInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + auth_payload: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["FactorInstance.TotpAlgorithms", object] = values.unset, + config_notification_platform: Union[str, object] = values.unset, + ) -> "FactorInstance": + """ + Update the FactorInstance + + :param auth_payload: The optional payload needed to verify the Factor for the first time. E.g. for a TOTP, the numeric code. + :param friendly_name: The new friendly name of this Factor. It can be up to 64 characters. + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Required when `factor_type` is `push`. If specified, this value must be between 32 and 255 characters long. + :param config_sdk_version: The Verify Push SDK version used to configure the factor + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive + :param config_alg: + :param config_notification_platform: The transport technology used to generate the Notification Token. Can be `apn`, `fcm` or `none`. Required when `factor_type` is `push`. + + :returns: The updated FactorInstance + """ + return self._proxy.update( + auth_payload=auth_payload, + friendly_name=friendly_name, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + config_notification_platform=config_notification_platform, + ) + + async def update_async( + self, + auth_payload: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["FactorInstance.TotpAlgorithms", object] = values.unset, + config_notification_platform: Union[str, object] = values.unset, + ) -> "FactorInstance": + """ + Asynchronous coroutine to update the FactorInstance + + :param auth_payload: The optional payload needed to verify the Factor for the first time. E.g. for a TOTP, the numeric code. + :param friendly_name: The new friendly name of this Factor. It can be up to 64 characters. + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Required when `factor_type` is `push`. If specified, this value must be between 32 and 255 characters long. + :param config_sdk_version: The Verify Push SDK version used to configure the factor + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive + :param config_alg: + :param config_notification_platform: The transport technology used to generate the Notification Token. Can be `apn`, `fcm` or `none`. Required when `factor_type` is `push`. + + :returns: The updated FactorInstance + """ + return await self._proxy.update_async( + auth_payload=auth_payload, + friendly_name=friendly_name, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + config_notification_platform=config_notification_platform, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FactorContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, identity: str, sid: str): + """ + Initialize the FactorContext + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param identity: Customer unique identity for the Entity owner of the Factor. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + :param sid: A 34 character string that uniquely identifies this Factor. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "identity": identity, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Entities/{identity}/Factors/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the FactorInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FactorInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> FactorInstance: + """ + Fetch the FactorInstance + + + :returns: The fetched FactorInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> FactorInstance: + """ + Asynchronous coroutine to fetch the FactorInstance + + + :returns: The fetched FactorInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + + def update( + self, + auth_payload: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["FactorInstance.TotpAlgorithms", object] = values.unset, + config_notification_platform: Union[str, object] = values.unset, + ) -> FactorInstance: + """ + Update the FactorInstance + + :param auth_payload: The optional payload needed to verify the Factor for the first time. E.g. for a TOTP, the numeric code. + :param friendly_name: The new friendly name of this Factor. It can be up to 64 characters. + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Required when `factor_type` is `push`. If specified, this value must be between 32 and 255 characters long. + :param config_sdk_version: The Verify Push SDK version used to configure the factor + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive + :param config_alg: + :param config_notification_platform: The transport technology used to generate the Notification Token. Can be `apn`, `fcm` or `none`. Required when `factor_type` is `push`. + + :returns: The updated FactorInstance + """ + + data = values.of( + { + "AuthPayload": auth_payload, + "FriendlyName": friendly_name, + "Config.NotificationToken": config_notification_token, + "Config.SdkVersion": config_sdk_version, + "Config.TimeStep": config_time_step, + "Config.Skew": config_skew, + "Config.CodeLength": config_code_length, + "Config.Alg": config_alg, + "Config.NotificationPlatform": config_notification_platform, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + auth_payload: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["FactorInstance.TotpAlgorithms", object] = values.unset, + config_notification_platform: Union[str, object] = values.unset, + ) -> FactorInstance: + """ + Asynchronous coroutine to update the FactorInstance + + :param auth_payload: The optional payload needed to verify the Factor for the first time. E.g. for a TOTP, the numeric code. + :param friendly_name: The new friendly name of this Factor. It can be up to 64 characters. + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Required when `factor_type` is `push`. If specified, this value must be between 32 and 255 characters long. + :param config_sdk_version: The Verify Push SDK version used to configure the factor + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive + :param config_alg: + :param config_notification_platform: The transport technology used to generate the Notification Token. Can be `apn`, `fcm` or `none`. Required when `factor_type` is `push`. + + :returns: The updated FactorInstance + """ + + data = values.of( + { + "AuthPayload": auth_payload, + "FriendlyName": friendly_name, + "Config.NotificationToken": config_notification_token, + "Config.SdkVersion": config_sdk_version, + "Config.TimeStep": config_time_step, + "Config.Skew": config_skew, + "Config.CodeLength": config_code_length, + "Config.Alg": config_alg, + "Config.NotificationPlatform": config_notification_platform, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FactorPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> FactorInstance: + """ + Build an instance of FactorInstance + + :param payload: Payload response from the API + """ + return FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class FactorList(ListResource): + + def __init__(self, version: Version, service_sid: str, identity: str): + """ + Initialize the FactorList + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param identity: Customer unique identity for the Entity owner of the Factors. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "identity": identity, + } + self._uri = "/Services/{service_sid}/Entities/{identity}/Factors".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FactorInstance]: + """ + Streams FactorInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FactorInstance]: + """ + Asynchronously streams FactorInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FactorInstance]: + """ + Lists FactorInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FactorInstance]: + """ + Asynchronously lists FactorInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FactorPage: + """ + Retrieve a single page of FactorInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FactorInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FactorPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FactorPage: + """ + Asynchronously retrieve a single page of FactorInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FactorInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FactorPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> FactorPage: + """ + Retrieve a specific page of FactorInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FactorInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return FactorPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> FactorPage: + """ + Asynchronously retrieve a specific page of FactorInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FactorInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return FactorPage(self._version, response, self._solution) + + def get(self, sid: str) -> FactorContext: + """ + Constructs a FactorContext + + :param sid: A 34 character string that uniquely identifies this Factor. + """ + return FactorContext( + self._version, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=sid, + ) + + def __call__(self, sid: str) -> FactorContext: + """ + Constructs a FactorContext + + :param sid: A 34 character string that uniquely identifies this Factor. + """ + return FactorContext( + self._version, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/new_factor.py b/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/new_factor.py new file mode 100644 index 00000000..2a2d77d5 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/verify/v2/service/entity/new_factor.py @@ -0,0 +1,282 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NewFactorInstance(InstanceResource): + + class FactorStatuses(object): + UNVERIFIED = "unverified" + VERIFIED = "verified" + + class FactorTypes(object): + PUSH = "push" + TOTP = "totp" + + class NotificationPlatforms(object): + APN = "apn" + FCM = "fcm" + NONE = "none" + + class TotpAlgorithms(object): + SHA1 = "sha1" + SHA256 = "sha256" + SHA512 = "sha512" + + """ + :ivar sid: A 34 character string that uniquely identifies this Factor. + :ivar account_sid: The unique SID identifier of the Account. + :ivar service_sid: The unique SID identifier of the Service. + :ivar entity_sid: The unique SID identifier of the Entity. + :ivar identity: Customer unique identity for the Entity owner of the Factor. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + :ivar binding: Contains the `factor_type` specific secret and metadata. For push, this is `binding.public_key` and `binding.alg`. For totp, this is `binding.secret` and `binding.uri`. The `binding.uri` property is generated following the [google authenticator key URI format](https://github.com/google/google-authenticator/wiki/Key-Uri-Format), and `Factor.friendly_name` is used for the “accountname” value and `Service.friendly_name` or `Service.totp.issuer` is used for the `issuer` value. The Binding property is ONLY returned upon Factor creation. + :ivar date_created: The date that this Factor was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date that this Factor was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar friendly_name: The friendly name of this Factor. This can be any string up to 64 characters, meant for humans to distinguish between Factors. For `factor_type` `push`, this could be a device name. For `factor_type` `totp`, this value is used as the “account name” in constructing the `binding.uri` property. At the same time, we recommend avoiding providing PII. + :ivar status: + :ivar factor_type: + :ivar config: An object that contains configurations specific to a `factor_type`. + :ivar metadata: Custom metadata associated with the factor. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\"os\": \"Android\"}`. Can be up to 1024 characters in length. + :ivar url: The URL of this resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], service_sid: str, identity: str + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.entity_sid: Optional[str] = payload.get("entity_sid") + self.identity: Optional[str] = payload.get("identity") + self.binding: Optional[Dict[str, object]] = payload.get("binding") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["NewFactorInstance.FactorStatuses"] = payload.get( + "status" + ) + self.factor_type: Optional["NewFactorInstance.FactorTypes"] = payload.get( + "factor_type" + ) + self.config: Optional[Dict[str, object]] = payload.get("config") + self.metadata: Optional[Dict[str, object]] = payload.get("metadata") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "identity": identity, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class NewFactorList(ListResource): + + def __init__(self, version: Version, service_sid: str, identity: str): + """ + Initialize the NewFactorList + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param identity: Customer unique identity for the Entity owner of the Factor. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "identity": identity, + } + self._uri = "/Services/{service_sid}/Entities/{identity}/Factors".format( + **self._solution + ) + + def create( + self, + friendly_name: str, + factor_type: "NewFactorInstance.FactorTypes", + binding_alg: Union[str, object] = values.unset, + binding_public_key: Union[str, object] = values.unset, + config_app_id: Union[str, object] = values.unset, + config_notification_platform: Union[ + "NewFactorInstance.NotificationPlatforms", object + ] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + binding_secret: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["NewFactorInstance.TotpAlgorithms", object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> NewFactorInstance: + """ + Create the NewFactorInstance + + :param friendly_name: The friendly name of this Factor. This can be any string up to 64 characters, meant for humans to distinguish between Factors. For `factor_type` `push`, this could be a device name. For `factor_type` `totp`, this value is used as the “account name” in constructing the `binding.uri` property. At the same time, we recommend avoiding providing PII. + :param factor_type: + :param binding_alg: The algorithm used when `factor_type` is `push`. Algorithm supported: `ES256` + :param binding_public_key: The Ecdsa public key in PKIX, ASN.1 DER format encoded in Base64. Required when `factor_type` is `push` + :param config_app_id: The ID that uniquely identifies your app in the Google or Apple store, such as `com.example.myapp`. It can be up to 100 characters long. Required when `factor_type` is `push`. + :param config_notification_platform: + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Must be between 32 and 255 characters long. Required when `factor_type` is `push`. + :param config_sdk_version: The Verify Push SDK version used to configure the factor Required when `factor_type` is `push` + :param binding_secret: The shared secret for TOTP factors encoded in Base32. This can be provided when creating the Factor, otherwise it will be generated. Used when `factor_type` is `totp` + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. The default value is defined at the service level in the property `totp.time_step`. Defaults to 30 seconds if not configured. Used when `factor_type` is `totp` + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. The default value is defined at the service level in the property `totp.skew`. If not configured defaults to 1. Used when `factor_type` is `totp` + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. The default value is defined at the service level in the property `totp.code_length`. If not configured defaults to 6. Used when `factor_type` is `totp` + :param config_alg: + :param metadata: Custom metadata associated with the factor. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + + :returns: The created NewFactorInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "FactorType": factor_type, + "Binding.Alg": binding_alg, + "Binding.PublicKey": binding_public_key, + "Config.AppId": config_app_id, + "Config.NotificationPlatform": config_notification_platform, + "Config.NotificationToken": config_notification_token, + "Config.SdkVersion": config_sdk_version, + "Binding.Secret": binding_secret, + "Config.TimeStep": config_time_step, + "Config.Skew": config_skew, + "Config.CodeLength": config_code_length, + "Config.Alg": config_alg, + "Metadata": serialize.object(metadata), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NewFactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + + async def create_async( + self, + friendly_name: str, + factor_type: "NewFactorInstance.FactorTypes", + binding_alg: Union[str, object] = values.unset, + binding_public_key: Union[str, object] = values.unset, + config_app_id: Union[str, object] = values.unset, + config_notification_platform: Union[ + "NewFactorInstance.NotificationPlatforms", object + ] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + binding_secret: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["NewFactorInstance.TotpAlgorithms", object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> NewFactorInstance: + """ + Asynchronously create the NewFactorInstance + + :param friendly_name: The friendly name of this Factor. This can be any string up to 64 characters, meant for humans to distinguish between Factors. For `factor_type` `push`, this could be a device name. For `factor_type` `totp`, this value is used as the “account name” in constructing the `binding.uri` property. At the same time, we recommend avoiding providing PII. + :param factor_type: + :param binding_alg: The algorithm used when `factor_type` is `push`. Algorithm supported: `ES256` + :param binding_public_key: The Ecdsa public key in PKIX, ASN.1 DER format encoded in Base64. Required when `factor_type` is `push` + :param config_app_id: The ID that uniquely identifies your app in the Google or Apple store, such as `com.example.myapp`. It can be up to 100 characters long. Required when `factor_type` is `push`. + :param config_notification_platform: + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Must be between 32 and 255 characters long. Required when `factor_type` is `push`. + :param config_sdk_version: The Verify Push SDK version used to configure the factor Required when `factor_type` is `push` + :param binding_secret: The shared secret for TOTP factors encoded in Base32. This can be provided when creating the Factor, otherwise it will be generated. Used when `factor_type` is `totp` + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. The default value is defined at the service level in the property `totp.time_step`. Defaults to 30 seconds if not configured. Used when `factor_type` is `totp` + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. The default value is defined at the service level in the property `totp.skew`. If not configured defaults to 1. Used when `factor_type` is `totp` + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. The default value is defined at the service level in the property `totp.code_length`. If not configured defaults to 6. Used when `factor_type` is `totp` + :param config_alg: + :param metadata: Custom metadata associated with the factor. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + + :returns: The created NewFactorInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "FactorType": factor_type, + "Binding.Alg": binding_alg, + "Binding.PublicKey": binding_public_key, + "Config.AppId": config_app_id, + "Config.NotificationPlatform": config_notification_platform, + "Config.NotificationToken": config_notification_token, + "Config.SdkVersion": config_sdk_version, + "Binding.Secret": binding_secret, + "Config.TimeStep": config_time_step, + "Config.Skew": config_skew, + "Config.CodeLength": config_code_length, + "Config.Alg": config_alg, + "Metadata": serialize.object(metadata), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NewFactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/messaging_configuration.py b/venv/Lib/site-packages/twilio/rest/verify/v2/service/messaging_configuration.py new file mode 100644 index 00000000..03f494f6 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/verify/v2/service/messaging_configuration.py @@ -0,0 +1,640 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MessagingConfigurationInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) that the resource is associated with. + :ivar country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. + :ivar messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + country: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.country: Optional[str] = payload.get("country") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "country": country or self.country, + } + self._context: Optional[MessagingConfigurationContext] = None + + @property + def _proxy(self) -> "MessagingConfigurationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MessagingConfigurationContext for this MessagingConfigurationInstance + """ + if self._context is None: + self._context = MessagingConfigurationContext( + self._version, + service_sid=self._solution["service_sid"], + country=self._solution["country"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the MessagingConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MessagingConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "MessagingConfigurationInstance": + """ + Fetch the MessagingConfigurationInstance + + + :returns: The fetched MessagingConfigurationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MessagingConfigurationInstance": + """ + Asynchronous coroutine to fetch the MessagingConfigurationInstance + + + :returns: The fetched MessagingConfigurationInstance + """ + return await self._proxy.fetch_async() + + def update(self, messaging_service_sid: str) -> "MessagingConfigurationInstance": + """ + Update the MessagingConfigurationInstance + + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: The updated MessagingConfigurationInstance + """ + return self._proxy.update( + messaging_service_sid=messaging_service_sid, + ) + + async def update_async( + self, messaging_service_sid: str + ) -> "MessagingConfigurationInstance": + """ + Asynchronous coroutine to update the MessagingConfigurationInstance + + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: The updated MessagingConfigurationInstance + """ + return await self._proxy.update_async( + messaging_service_sid=messaging_service_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MessagingConfigurationContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, country: str): + """ + Initialize the MessagingConfigurationContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) that the resource is associated with. + :param country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "country": country, + } + self._uri = "/Services/{service_sid}/MessagingConfigurations/{country}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the MessagingConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MessagingConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessagingConfigurationInstance: + """ + Fetch the MessagingConfigurationInstance + + + :returns: The fetched MessagingConfigurationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MessagingConfigurationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + country=self._solution["country"], + ) + + async def fetch_async(self) -> MessagingConfigurationInstance: + """ + Asynchronous coroutine to fetch the MessagingConfigurationInstance + + + :returns: The fetched MessagingConfigurationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MessagingConfigurationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + country=self._solution["country"], + ) + + def update(self, messaging_service_sid: str) -> MessagingConfigurationInstance: + """ + Update the MessagingConfigurationInstance + + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: The updated MessagingConfigurationInstance + """ + + data = values.of( + { + "MessagingServiceSid": messaging_service_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessagingConfigurationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + country=self._solution["country"], + ) + + async def update_async( + self, messaging_service_sid: str + ) -> MessagingConfigurationInstance: + """ + Asynchronous coroutine to update the MessagingConfigurationInstance + + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: The updated MessagingConfigurationInstance + """ + + data = values.of( + { + "MessagingServiceSid": messaging_service_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessagingConfigurationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + country=self._solution["country"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MessagingConfigurationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MessagingConfigurationInstance: + """ + Build an instance of MessagingConfigurationInstance + + :param payload: Payload response from the API + """ + return MessagingConfigurationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class MessagingConfigurationList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the MessagingConfigurationList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) that the resource is associated with. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/MessagingConfigurations".format( + **self._solution + ) + + def create( + self, country: str, messaging_service_sid: str + ) -> MessagingConfigurationInstance: + """ + Create the MessagingConfigurationInstance + + :param country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: The created MessagingConfigurationInstance + """ + + data = values.of( + { + "Country": country, + "MessagingServiceSid": messaging_service_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessagingConfigurationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, country: str, messaging_service_sid: str + ) -> MessagingConfigurationInstance: + """ + Asynchronously create the MessagingConfigurationInstance + + :param country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: The created MessagingConfigurationInstance + """ + + data = values.of( + { + "Country": country, + "MessagingServiceSid": messaging_service_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessagingConfigurationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessagingConfigurationInstance]: + """ + Streams MessagingConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessagingConfigurationInstance]: + """ + Asynchronously streams MessagingConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessagingConfigurationInstance]: + """ + Lists MessagingConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessagingConfigurationInstance]: + """ + Asynchronously lists MessagingConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagingConfigurationPage: + """ + Retrieve a single page of MessagingConfigurationInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessagingConfigurationInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagingConfigurationPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagingConfigurationPage: + """ + Asynchronously retrieve a single page of MessagingConfigurationInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessagingConfigurationInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagingConfigurationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MessagingConfigurationPage: + """ + Retrieve a specific page of MessagingConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessagingConfigurationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MessagingConfigurationPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MessagingConfigurationPage: + """ + Asynchronously retrieve a specific page of MessagingConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessagingConfigurationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagingConfigurationPage(self._version, response, self._solution) + + def get(self, country: str) -> MessagingConfigurationContext: + """ + Constructs a MessagingConfigurationContext + + :param country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. + """ + return MessagingConfigurationContext( + self._version, service_sid=self._solution["service_sid"], country=country + ) + + def __call__(self, country: str) -> MessagingConfigurationContext: + """ + Constructs a MessagingConfigurationContext + + :param country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. + """ + return MessagingConfigurationContext( + self._version, service_sid=self._solution["service_sid"], country=country + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/rate_limit/__init__.py b/venv/Lib/site-packages/twilio/rest/verify/v2/service/rate_limit/__init__.py new file mode 100644 index 00000000..ced5ab6a --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/verify/v2/service/rate_limit/__init__.py @@ -0,0 +1,667 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.verify.v2.service.rate_limit.bucket import BucketList + + +class RateLimitInstance(InstanceResource): + """ + :ivar sid: A 34 character string that uniquely identifies this Rate Limit. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) the resource is associated with. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Rate Limit resource. + :ivar unique_name: Provides a unique and addressable name to be assigned to this Rate Limit, assigned by the developer, to be optionally used in addition to SID. **This value should not contain PII.** + :ivar description: Description of this Rate Limit + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The URL of this resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.description: Optional[str] = payload.get("description") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[RateLimitContext] = None + + @property + def _proxy(self) -> "RateLimitContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RateLimitContext for this RateLimitInstance + """ + if self._context is None: + self._context = RateLimitContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RateLimitInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RateLimitInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RateLimitInstance": + """ + Fetch the RateLimitInstance + + + :returns: The fetched RateLimitInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RateLimitInstance": + """ + Asynchronous coroutine to fetch the RateLimitInstance + + + :returns: The fetched RateLimitInstance + """ + return await self._proxy.fetch_async() + + def update( + self, description: Union[str, object] = values.unset + ) -> "RateLimitInstance": + """ + Update the RateLimitInstance + + :param description: Description of this Rate Limit + + :returns: The updated RateLimitInstance + """ + return self._proxy.update( + description=description, + ) + + async def update_async( + self, description: Union[str, object] = values.unset + ) -> "RateLimitInstance": + """ + Asynchronous coroutine to update the RateLimitInstance + + :param description: Description of this Rate Limit + + :returns: The updated RateLimitInstance + """ + return await self._proxy.update_async( + description=description, + ) + + @property + def buckets(self) -> BucketList: + """ + Access the buckets + """ + return self._proxy.buckets + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RateLimitContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the RateLimitContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) the resource is associated with. + :param sid: The Twilio-provided string that uniquely identifies the Rate Limit resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/RateLimits/{sid}".format(**self._solution) + + self._buckets: Optional[BucketList] = None + + def delete(self) -> bool: + """ + Deletes the RateLimitInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RateLimitInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RateLimitInstance: + """ + Fetch the RateLimitInstance + + + :returns: The fetched RateLimitInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RateLimitInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RateLimitInstance: + """ + Asynchronous coroutine to fetch the RateLimitInstance + + + :returns: The fetched RateLimitInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RateLimitInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, description: Union[str, object] = values.unset + ) -> RateLimitInstance: + """ + Update the RateLimitInstance + + :param description: Description of this Rate Limit + + :returns: The updated RateLimitInstance + """ + + data = values.of( + { + "Description": description, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RateLimitInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, description: Union[str, object] = values.unset + ) -> RateLimitInstance: + """ + Asynchronous coroutine to update the RateLimitInstance + + :param description: Description of this Rate Limit + + :returns: The updated RateLimitInstance + """ + + data = values.of( + { + "Description": description, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RateLimitInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def buckets(self) -> BucketList: + """ + Access the buckets + """ + if self._buckets is None: + self._buckets = BucketList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._buckets + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RateLimitPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RateLimitInstance: + """ + Build an instance of RateLimitInstance + + :param payload: Payload response from the API + """ + return RateLimitInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RateLimitList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the RateLimitList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) the resource is associated with. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/RateLimits".format(**self._solution) + + def create( + self, unique_name: str, description: Union[str, object] = values.unset + ) -> RateLimitInstance: + """ + Create the RateLimitInstance + + :param unique_name: Provides a unique and addressable name to be assigned to this Rate Limit, assigned by the developer, to be optionally used in addition to SID. **This value should not contain PII.** + :param description: Description of this Rate Limit + + :returns: The created RateLimitInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Description": description, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RateLimitInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, unique_name: str, description: Union[str, object] = values.unset + ) -> RateLimitInstance: + """ + Asynchronously create the RateLimitInstance + + :param unique_name: Provides a unique and addressable name to be assigned to this Rate Limit, assigned by the developer, to be optionally used in addition to SID. **This value should not contain PII.** + :param description: Description of this Rate Limit + + :returns: The created RateLimitInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Description": description, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RateLimitInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RateLimitInstance]: + """ + Streams RateLimitInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RateLimitInstance]: + """ + Asynchronously streams RateLimitInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RateLimitInstance]: + """ + Lists RateLimitInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RateLimitInstance]: + """ + Asynchronously lists RateLimitInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RateLimitPage: + """ + Retrieve a single page of RateLimitInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RateLimitInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RateLimitPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RateLimitPage: + """ + Asynchronously retrieve a single page of RateLimitInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RateLimitInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RateLimitPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RateLimitPage: + """ + Retrieve a specific page of RateLimitInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RateLimitInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RateLimitPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RateLimitPage: + """ + Asynchronously retrieve a specific page of RateLimitInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RateLimitInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RateLimitPage(self._version, response, self._solution) + + def get(self, sid: str) -> RateLimitContext: + """ + Constructs a RateLimitContext + + :param sid: The Twilio-provided string that uniquely identifies the Rate Limit resource to fetch. + """ + return RateLimitContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RateLimitContext: + """ + Constructs a RateLimitContext + + :param sid: The Twilio-provided string that uniquely identifies the Rate Limit resource to fetch. + """ + return RateLimitContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/rate_limit/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/verify/v2/service/rate_limit/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..371030ff Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/verify/v2/service/rate_limit/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/rate_limit/__pycache__/bucket.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/verify/v2/service/rate_limit/__pycache__/bucket.cpython-312.pyc new file mode 100644 index 00000000..5786057e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/verify/v2/service/rate_limit/__pycache__/bucket.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/rate_limit/bucket.py b/venv/Lib/site-packages/twilio/rest/verify/v2/service/rate_limit/bucket.py new file mode 100644 index 00000000..4ac50cfc --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/verify/v2/service/rate_limit/bucket.py @@ -0,0 +1,692 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class BucketInstance(InstanceResource): + """ + :ivar sid: A 34 character string that uniquely identifies this Bucket. + :ivar rate_limit_sid: The Twilio-provided string that uniquely identifies the Rate Limit resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) the resource is associated with. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Rate Limit resource. + :ivar max: Maximum number of requests permitted in during the interval. + :ivar interval: Number of seconds that the rate limit will be enforced over. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + rate_limit_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.rate_limit_sid: Optional[str] = payload.get("rate_limit_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.max: Optional[int] = deserialize.integer(payload.get("max")) + self.interval: Optional[int] = deserialize.integer(payload.get("interval")) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "rate_limit_sid": rate_limit_sid, + "sid": sid or self.sid, + } + self._context: Optional[BucketContext] = None + + @property + def _proxy(self) -> "BucketContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BucketContext for this BucketInstance + """ + if self._context is None: + self._context = BucketContext( + self._version, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the BucketInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BucketInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "BucketInstance": + """ + Fetch the BucketInstance + + + :returns: The fetched BucketInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BucketInstance": + """ + Asynchronous coroutine to fetch the BucketInstance + + + :returns: The fetched BucketInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> "BucketInstance": + """ + Update the BucketInstance + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. + + :returns: The updated BucketInstance + """ + return self._proxy.update( + max=max, + interval=interval, + ) + + async def update_async( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> "BucketInstance": + """ + Asynchronous coroutine to update the BucketInstance + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. + + :returns: The updated BucketInstance + """ + return await self._proxy.update_async( + max=max, + interval=interval, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BucketContext(InstanceContext): + + def __init__( + self, version: Version, service_sid: str, rate_limit_sid: str, sid: str + ): + """ + Initialize the BucketContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) the resource is associated with. + :param rate_limit_sid: The Twilio-provided string that uniquely identifies the Rate Limit resource. + :param sid: A 34 character string that uniquely identifies this Bucket. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "rate_limit_sid": rate_limit_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/RateLimits/{rate_limit_sid}/Buckets/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the BucketInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BucketInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> BucketInstance: + """ + Fetch the BucketInstance + + + :returns: The fetched BucketInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> BucketInstance: + """ + Asynchronous coroutine to fetch the BucketInstance + + + :returns: The fetched BucketInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> BucketInstance: + """ + Update the BucketInstance + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. + + :returns: The updated BucketInstance + """ + + data = values.of( + { + "Max": max, + "Interval": interval, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> BucketInstance: + """ + Asynchronous coroutine to update the BucketInstance + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. + + :returns: The updated BucketInstance + """ + + data = values.of( + { + "Max": max, + "Interval": interval, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BucketPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> BucketInstance: + """ + Build an instance of BucketInstance + + :param payload: Payload response from the API + """ + return BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class BucketList(ListResource): + + def __init__(self, version: Version, service_sid: str, rate_limit_sid: str): + """ + Initialize the BucketList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) the resource is associated with. + :param rate_limit_sid: The Twilio-provided string that uniquely identifies the Rate Limit resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "rate_limit_sid": rate_limit_sid, + } + self._uri = ( + "/Services/{service_sid}/RateLimits/{rate_limit_sid}/Buckets".format( + **self._solution + ) + ) + + def create(self, max: int, interval: int) -> BucketInstance: + """ + Create the BucketInstance + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. + + :returns: The created BucketInstance + """ + + data = values.of( + { + "Max": max, + "Interval": interval, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + ) + + async def create_async(self, max: int, interval: int) -> BucketInstance: + """ + Asynchronously create the BucketInstance + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. + + :returns: The created BucketInstance + """ + + data = values.of( + { + "Max": max, + "Interval": interval, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BucketInstance]: + """ + Streams BucketInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BucketInstance]: + """ + Asynchronously streams BucketInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BucketInstance]: + """ + Lists BucketInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BucketInstance]: + """ + Asynchronously lists BucketInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BucketPage: + """ + Retrieve a single page of BucketInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BucketInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BucketPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BucketPage: + """ + Asynchronously retrieve a single page of BucketInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BucketInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BucketPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> BucketPage: + """ + Retrieve a specific page of BucketInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BucketInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return BucketPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> BucketPage: + """ + Asynchronously retrieve a specific page of BucketInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BucketInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return BucketPage(self._version, response, self._solution) + + def get(self, sid: str) -> BucketContext: + """ + Constructs a BucketContext + + :param sid: A 34 character string that uniquely identifies this Bucket. + """ + return BucketContext( + self._version, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> BucketContext: + """ + Constructs a BucketContext + + :param sid: A 34 character string that uniquely identifies this Bucket. + """ + return BucketContext( + self._version, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/verification.py b/venv/Lib/site-packages/twilio/rest/verify/v2/service/verification.py new file mode 100644 index 00000000..64988a59 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/verify/v2/service/verification.py @@ -0,0 +1,517 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class VerificationInstance(InstanceResource): + + class Channel(object): + SMS = "sms" + CALL = "call" + EMAIL = "email" + WHATSAPP = "whatsapp" + SNA = "sna" + + class RiskCheck(object): + ENABLE = "enable" + DISABLE = "disable" + + class Status(object): + CANCELED = "canceled" + APPROVED = "approved" + + """ + :ivar sid: The unique string that we created to identify the Verification resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) the resource is associated with. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Verification resource. + :ivar to: The phone number or [email](https://www.twilio.com/docs/verify/email) being verified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :ivar channel: + :ivar status: The status of the verification. Can be: `pending`, `approved`, `canceled`, `max_attempts_reached`, `deleted`, `failed` or `expired`. + :ivar valid: Use \"status\" instead. Legacy property indicating whether the verification was successful. + :ivar lookup: Information about the phone number being verified. + :ivar amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :ivar payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :ivar send_code_attempts: An array of verification attempt objects containing the channel attempted and the channel-specific transaction SID. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar sna: The set of fields used for a silent network auth (`sna`) verification. Contains a single field with the URL to be invoked to verify the phone number. + :ivar url: The absolute URL of the Verification resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.to: Optional[str] = payload.get("to") + self.channel: Optional["VerificationInstance.Channel"] = payload.get("channel") + self.status: Optional[str] = payload.get("status") + self.valid: Optional[bool] = payload.get("valid") + self.lookup: Optional[Dict[str, object]] = payload.get("lookup") + self.amount: Optional[str] = payload.get("amount") + self.payee: Optional[str] = payload.get("payee") + self.send_code_attempts: Optional[List[Dict[str, object]]] = payload.get( + "send_code_attempts" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.sna: Optional[Dict[str, object]] = payload.get("sna") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[VerificationContext] = None + + @property + def _proxy(self) -> "VerificationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: VerificationContext for this VerificationInstance + """ + if self._context is None: + self._context = VerificationContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "VerificationInstance": + """ + Fetch the VerificationInstance + + + :returns: The fetched VerificationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "VerificationInstance": + """ + Asynchronous coroutine to fetch the VerificationInstance + + + :returns: The fetched VerificationInstance + """ + return await self._proxy.fetch_async() + + def update(self, status: "VerificationInstance.Status") -> "VerificationInstance": + """ + Update the VerificationInstance + + :param status: + + :returns: The updated VerificationInstance + """ + return self._proxy.update( + status=status, + ) + + async def update_async( + self, status: "VerificationInstance.Status" + ) -> "VerificationInstance": + """ + Asynchronous coroutine to update the VerificationInstance + + :param status: + + :returns: The updated VerificationInstance + """ + return await self._proxy.update_async( + status=status, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class VerificationContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the VerificationContext + + :param version: Version that contains the resource + :param service_sid: The SID of the verification [Service](https://www.twilio.com/docs/verify/api/service) to update the resource from. + :param sid: The Twilio-provided string that uniquely identifies the Verification resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Verifications/{sid}".format( + **self._solution + ) + + def fetch(self) -> VerificationInstance: + """ + Fetch the VerificationInstance + + + :returns: The fetched VerificationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return VerificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> VerificationInstance: + """ + Asynchronous coroutine to fetch the VerificationInstance + + + :returns: The fetched VerificationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return VerificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update(self, status: "VerificationInstance.Status") -> VerificationInstance: + """ + Update the VerificationInstance + + :param status: + + :returns: The updated VerificationInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return VerificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, status: "VerificationInstance.Status" + ) -> VerificationInstance: + """ + Asynchronous coroutine to update the VerificationInstance + + :param status: + + :returns: The updated VerificationInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return VerificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class VerificationList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the VerificationList + + :param version: Version that contains the resource + :param service_sid: The SID of the verification [Service](https://www.twilio.com/docs/verify/api/service) to create the resource under. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Verifications".format(**self._solution) + + def create( + self, + to: str, + channel: str, + custom_friendly_name: Union[str, object] = values.unset, + custom_message: Union[str, object] = values.unset, + send_digits: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + custom_code: Union[str, object] = values.unset, + amount: Union[str, object] = values.unset, + payee: Union[str, object] = values.unset, + rate_limits: Union[object, object] = values.unset, + channel_configuration: Union[object, object] = values.unset, + app_hash: Union[str, object] = values.unset, + template_sid: Union[str, object] = values.unset, + template_custom_substitutions: Union[str, object] = values.unset, + device_ip: Union[str, object] = values.unset, + enable_sna_client_token: Union[bool, object] = values.unset, + risk_check: Union["VerificationInstance.RiskCheck", object] = values.unset, + tags: Union[str, object] = values.unset, + ) -> VerificationInstance: + """ + Create the VerificationInstance + + :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param channel: The verification method to use. One of: [`email`](https://www.twilio.com/docs/verify/email), `sms`, `whatsapp`, `call`, `sna` or `auto`. + :param custom_friendly_name: A custom user defined friendly name that overwrites the existing one in the verification message + :param custom_message: The text of a custom message to use for the verification. + :param send_digits: The digits to send after a phone call is answered, for example, to dial an extension. For more information, see the Programmable Voice documentation of [sendDigits](https://www.twilio.com/docs/voice/twiml/number#attributes-sendDigits). + :param locale: Locale will automatically resolve based on phone number country code for SMS, WhatsApp, and call channel verifications. It will fallback to English or the template’s default translation if the selected translation is not available. This parameter will override the automatic locale resolution. [See supported languages and more information here](https://www.twilio.com/docs/verify/supported-languages). + :param custom_code: A pre-generated code to use for verification. The code can be between 4 and 10 characters, inclusive. + :param amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param rate_limits: The custom key-value pairs of Programmable Rate Limits. Keys correspond to `unique_name` fields defined when [creating your Rate Limit](https://www.twilio.com/docs/verify/api/service-rate-limits). Associated value pairs represent values in the request that you are rate limiting on. You may include multiple Rate Limit values in each request. + :param channel_configuration: [`email`](https://www.twilio.com/docs/verify/email) channel configuration in json format. The fields 'from' and 'from_name' are optional but if included the 'from' field must have a valid email address. + :param app_hash: Your [App Hash](https://developers.google.com/identity/sms-retriever/verify#computing_your_apps_hash_string) to be appended at the end of your verification SMS body. Applies only to SMS. Example SMS body: `<#> Your AppName verification code is: 1234 He42w354ol9`. + :param template_sid: The message [template](https://www.twilio.com/docs/verify/api/templates). If provided, will override the default template for the Service. SMS and Voice channels only. + :param template_custom_substitutions: A stringified JSON object in which the keys are the template's special variables and the values are the variables substitutions. + :param device_ip: Strongly encouraged if using the auto channel. The IP address of the client's device. If provided, it has to be a valid IPv4 or IPv6 address. + :param enable_sna_client_token: An optional Boolean value to indicate the requirement of sna client token in the SNA URL invocation response for added security. This token must match in the Verification Check request to confirm phone number verification. + :param risk_check: + :param tags: A string containing a JSON map of key value pairs of tags to be recorded as metadata for the message. The object may contain up to 10 tags. Keys and values can each be up to 128 characters in length. + + :returns: The created VerificationInstance + """ + + data = values.of( + { + "To": to, + "Channel": channel, + "CustomFriendlyName": custom_friendly_name, + "CustomMessage": custom_message, + "SendDigits": send_digits, + "Locale": locale, + "CustomCode": custom_code, + "Amount": amount, + "Payee": payee, + "RateLimits": serialize.object(rate_limits), + "ChannelConfiguration": serialize.object(channel_configuration), + "AppHash": app_hash, + "TemplateSid": template_sid, + "TemplateCustomSubstitutions": template_custom_substitutions, + "DeviceIp": device_ip, + "EnableSnaClientToken": serialize.boolean_to_string( + enable_sna_client_token + ), + "RiskCheck": risk_check, + "Tags": tags, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return VerificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + to: str, + channel: str, + custom_friendly_name: Union[str, object] = values.unset, + custom_message: Union[str, object] = values.unset, + send_digits: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + custom_code: Union[str, object] = values.unset, + amount: Union[str, object] = values.unset, + payee: Union[str, object] = values.unset, + rate_limits: Union[object, object] = values.unset, + channel_configuration: Union[object, object] = values.unset, + app_hash: Union[str, object] = values.unset, + template_sid: Union[str, object] = values.unset, + template_custom_substitutions: Union[str, object] = values.unset, + device_ip: Union[str, object] = values.unset, + enable_sna_client_token: Union[bool, object] = values.unset, + risk_check: Union["VerificationInstance.RiskCheck", object] = values.unset, + tags: Union[str, object] = values.unset, + ) -> VerificationInstance: + """ + Asynchronously create the VerificationInstance + + :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param channel: The verification method to use. One of: [`email`](https://www.twilio.com/docs/verify/email), `sms`, `whatsapp`, `call`, `sna` or `auto`. + :param custom_friendly_name: A custom user defined friendly name that overwrites the existing one in the verification message + :param custom_message: The text of a custom message to use for the verification. + :param send_digits: The digits to send after a phone call is answered, for example, to dial an extension. For more information, see the Programmable Voice documentation of [sendDigits](https://www.twilio.com/docs/voice/twiml/number#attributes-sendDigits). + :param locale: Locale will automatically resolve based on phone number country code for SMS, WhatsApp, and call channel verifications. It will fallback to English or the template’s default translation if the selected translation is not available. This parameter will override the automatic locale resolution. [See supported languages and more information here](https://www.twilio.com/docs/verify/supported-languages). + :param custom_code: A pre-generated code to use for verification. The code can be between 4 and 10 characters, inclusive. + :param amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param rate_limits: The custom key-value pairs of Programmable Rate Limits. Keys correspond to `unique_name` fields defined when [creating your Rate Limit](https://www.twilio.com/docs/verify/api/service-rate-limits). Associated value pairs represent values in the request that you are rate limiting on. You may include multiple Rate Limit values in each request. + :param channel_configuration: [`email`](https://www.twilio.com/docs/verify/email) channel configuration in json format. The fields 'from' and 'from_name' are optional but if included the 'from' field must have a valid email address. + :param app_hash: Your [App Hash](https://developers.google.com/identity/sms-retriever/verify#computing_your_apps_hash_string) to be appended at the end of your verification SMS body. Applies only to SMS. Example SMS body: `<#> Your AppName verification code is: 1234 He42w354ol9`. + :param template_sid: The message [template](https://www.twilio.com/docs/verify/api/templates). If provided, will override the default template for the Service. SMS and Voice channels only. + :param template_custom_substitutions: A stringified JSON object in which the keys are the template's special variables and the values are the variables substitutions. + :param device_ip: Strongly encouraged if using the auto channel. The IP address of the client's device. If provided, it has to be a valid IPv4 or IPv6 address. + :param enable_sna_client_token: An optional Boolean value to indicate the requirement of sna client token in the SNA URL invocation response for added security. This token must match in the Verification Check request to confirm phone number verification. + :param risk_check: + :param tags: A string containing a JSON map of key value pairs of tags to be recorded as metadata for the message. The object may contain up to 10 tags. Keys and values can each be up to 128 characters in length. + + :returns: The created VerificationInstance + """ + + data = values.of( + { + "To": to, + "Channel": channel, + "CustomFriendlyName": custom_friendly_name, + "CustomMessage": custom_message, + "SendDigits": send_digits, + "Locale": locale, + "CustomCode": custom_code, + "Amount": amount, + "Payee": payee, + "RateLimits": serialize.object(rate_limits), + "ChannelConfiguration": serialize.object(channel_configuration), + "AppHash": app_hash, + "TemplateSid": template_sid, + "TemplateCustomSubstitutions": template_custom_substitutions, + "DeviceIp": device_ip, + "EnableSnaClientToken": serialize.boolean_to_string( + enable_sna_client_token + ), + "RiskCheck": risk_check, + "Tags": tags, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return VerificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def get(self, sid: str) -> VerificationContext: + """ + Constructs a VerificationContext + + :param sid: The Twilio-provided string that uniquely identifies the Verification resource to update. + """ + return VerificationContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> VerificationContext: + """ + Constructs a VerificationContext + + :param sid: The Twilio-provided string that uniquely identifies the Verification resource to update. + """ + return VerificationContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/verification_check.py b/venv/Lib/site-packages/twilio/rest/verify/v2/service/verification_check.py new file mode 100644 index 00000000..c09057eb --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/verify/v2/service/verification_check.py @@ -0,0 +1,202 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class VerificationCheckInstance(InstanceResource): + + class Channel(object): + SMS = "sms" + CALL = "call" + EMAIL = "email" + WHATSAPP = "whatsapp" + SNA = "sna" + + """ + :ivar sid: The unique string that we created to identify the VerificationCheck resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) the resource is associated with. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the VerificationCheck resource. + :ivar to: The phone number or [email](https://www.twilio.com/docs/verify/email) being verified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :ivar channel: + :ivar status: The status of the verification. Can be: `pending`, `approved`, `canceled`, `max_attempts_reached`, `deleted`, `failed` or `expired`. + :ivar valid: Use \"status\" instead. Legacy property indicating whether the verification was successful. + :ivar amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :ivar payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :ivar date_created: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the Verification Check resource was created. + :ivar date_updated: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the Verification Check resource was last updated. + :ivar sna_attempts_error_codes: List of error codes as a result of attempting a verification using the `sna` channel. The error codes are chronologically ordered, from the first attempt to the latest attempt. This will be an empty list if no errors occured or `null` if the last channel used wasn't `sna`. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], service_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.to: Optional[str] = payload.get("to") + self.channel: Optional["VerificationCheckInstance.Channel"] = payload.get( + "channel" + ) + self.status: Optional[str] = payload.get("status") + self.valid: Optional[bool] = payload.get("valid") + self.amount: Optional[str] = payload.get("amount") + self.payee: Optional[str] = payload.get("payee") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.sna_attempts_error_codes: Optional[List[Dict[str, object]]] = payload.get( + "sna_attempts_error_codes" + ) + + self._solution = { + "service_sid": service_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class VerificationCheckList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the VerificationCheckList + + :param version: Version that contains the resource + :param service_sid: The SID of the verification [Service](https://www.twilio.com/docs/verify/api/service) to create the resource under. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/VerificationCheck".format(**self._solution) + + def create( + self, + code: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + amount: Union[str, object] = values.unset, + payee: Union[str, object] = values.unset, + sna_client_token: Union[str, object] = values.unset, + ) -> VerificationCheckInstance: + """ + Create the VerificationCheckInstance + + :param code: The 4-10 character string being verified. + :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Either this parameter or the `verification_sid` must be specified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param verification_sid: A SID that uniquely identifies the Verification Check. Either this parameter or the `to` phone number/[email](https://www.twilio.com/docs/verify/email) must be specified. + :param amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param sna_client_token: A sna client token received in sna url invocation response needs to be passed in Verification Check request and should match to get successful response. + + :returns: The created VerificationCheckInstance + """ + + data = values.of( + { + "Code": code, + "To": to, + "VerificationSid": verification_sid, + "Amount": amount, + "Payee": payee, + "SnaClientToken": sna_client_token, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return VerificationCheckInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + code: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + amount: Union[str, object] = values.unset, + payee: Union[str, object] = values.unset, + sna_client_token: Union[str, object] = values.unset, + ) -> VerificationCheckInstance: + """ + Asynchronously create the VerificationCheckInstance + + :param code: The 4-10 character string being verified. + :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Either this parameter or the `verification_sid` must be specified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param verification_sid: A SID that uniquely identifies the Verification Check. Either this parameter or the `to` phone number/[email](https://www.twilio.com/docs/verify/email) must be specified. + :param amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param sna_client_token: A sna client token received in sna url invocation response needs to be passed in Verification Check request and should match to get successful response. + + :returns: The created VerificationCheckInstance + """ + + data = values.of( + { + "Code": code, + "To": to, + "VerificationSid": verification_sid, + "Amount": amount, + "Payee": payee, + "SnaClientToken": sna_client_token, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return VerificationCheckInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/service/webhook.py b/venv/Lib/site-packages/twilio/rest/verify/v2/service/webhook.py new file mode 100644 index 00000000..dd68cf30 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/verify/v2/service/webhook.py @@ -0,0 +1,739 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class WebhookInstance(InstanceResource): + + class Methods(object): + GET = "GET" + POST = "POST" + + class Status(object): + ENABLED = "enabled" + DISABLED = "disabled" + + class Version(object): + V1 = "v1" + V2 = "v2" + + """ + :ivar sid: The unique string that we created to identify the Webhook resource. + :ivar service_sid: The unique SID identifier of the Service. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + :ivar friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :ivar event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :ivar status: + :ivar version: + :ivar webhook_url: The URL associated with this Webhook. + :ivar webhook_method: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Webhook resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.event_types: Optional[List[str]] = payload.get("event_types") + self.status: Optional["WebhookInstance.Status"] = payload.get("status") + self.version: Optional["WebhookInstance.Version"] = payload.get("version") + self.webhook_url: Optional[str] = payload.get("webhook_url") + self.webhook_method: Optional["WebhookInstance.Methods"] = payload.get( + "webhook_method" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[WebhookContext] = None + + @property + def _proxy(self) -> "WebhookContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WebhookContext for this WebhookInstance + """ + if self._context is None: + self._context = WebhookContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "WebhookInstance": + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "WebhookInstance": + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + event_types: Union[List[str], object] = values.unset, + webhook_url: Union[str, object] = values.unset, + status: Union["WebhookInstance.Status", object] = values.unset, + version: Union["WebhookInstance.Version", object] = values.unset, + ) -> "WebhookInstance": + """ + Update the WebhookInstance + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param version: + + :returns: The updated WebhookInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + version=version, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + event_types: Union[List[str], object] = values.unset, + webhook_url: Union[str, object] = values.unset, + status: Union["WebhookInstance.Status", object] = values.unset, + version: Union["WebhookInstance.Version", object] = values.unset, + ) -> "WebhookInstance": + """ + Asynchronous coroutine to update the WebhookInstance + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param version: + + :returns: The updated WebhookInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + version=version, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WebhookContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the WebhookContext + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param sid: The Twilio-provided string that uniquely identifies the Webhook resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Webhooks/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + event_types: Union[List[str], object] = values.unset, + webhook_url: Union[str, object] = values.unset, + status: Union["WebhookInstance.Status", object] = values.unset, + version: Union["WebhookInstance.Version", object] = values.unset, + ) -> WebhookInstance: + """ + Update the WebhookInstance + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param version: + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "EventTypes": serialize.map(event_types, lambda e: e), + "WebhookUrl": webhook_url, + "Status": status, + "Version": version, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + event_types: Union[List[str], object] = values.unset, + webhook_url: Union[str, object] = values.unset, + status: Union["WebhookInstance.Status", object] = values.unset, + version: Union["WebhookInstance.Version", object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronous coroutine to update the WebhookInstance + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param version: + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "EventTypes": serialize.map(event_types, lambda e: e), + "WebhookUrl": webhook_url, + "Status": status, + "Version": version, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WebhookPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: + """ + Build an instance of WebhookInstance + + :param payload: Payload response from the API + """ + return WebhookInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class WebhookList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the WebhookList + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Webhooks".format(**self._solution) + + def create( + self, + friendly_name: str, + event_types: List[str], + webhook_url: str, + status: Union["WebhookInstance.Status", object] = values.unset, + version: Union["WebhookInstance.Version", object] = values.unset, + ) -> WebhookInstance: + """ + Create the WebhookInstance + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param version: + + :returns: The created WebhookInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "EventTypes": serialize.map(event_types, lambda e: e), + "WebhookUrl": webhook_url, + "Status": status, + "Version": version, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + friendly_name: str, + event_types: List[str], + webhook_url: str, + status: Union["WebhookInstance.Status", object] = values.unset, + version: Union["WebhookInstance.Version", object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronously create the WebhookInstance + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param version: + + :returns: The created WebhookInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "EventTypes": serialize.map(event_types, lambda e: e), + "WebhookUrl": webhook_url, + "Status": status, + "Version": version, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WebhookInstance]: + """ + Streams WebhookInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WebhookInstance]: + """ + Asynchronously streams WebhookInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: + """ + Lists WebhookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: + """ + Asynchronously lists WebhookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebhookPage: + """ + Retrieve a single page of WebhookInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebhookInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebhookPage: + """ + Asynchronously retrieve a single page of WebhookInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebhookInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> WebhookPage: + """ + Retrieve a specific page of WebhookInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebhookInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return WebhookPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> WebhookPage: + """ + Asynchronously retrieve a specific page of WebhookInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebhookInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return WebhookPage(self._version, response, self._solution) + + def get(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: The Twilio-provided string that uniquely identifies the Webhook resource to update. + """ + return WebhookContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: The Twilio-provided string that uniquely identifies the Webhook resource to update. + """ + return WebhookContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/template.py b/venv/Lib/site-packages/twilio/rest/verify/v2/template.py new file mode 100644 index 00000000..5a242c15 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/verify/v2/template.py @@ -0,0 +1,301 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TemplateInstance(InstanceResource): + """ + :ivar sid: A 34 character string that uniquely identifies a Verification Template. + :ivar account_sid: The unique SID identifier of the Account. + :ivar friendly_name: A descriptive string that you create to describe a Template. It can be up to 32 characters long. + :ivar channels: A list of channels that support the Template. Can include: sms, voice. + :ivar translations: An object that contains the different translations of the template. Every translation is identified by the language short name and contains its respective information as the approval status, text and created/modified date. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.channels: Optional[List[str]] = payload.get("channels") + self.translations: Optional[Dict[str, object]] = payload.get("translations") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class TemplatePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TemplateInstance: + """ + Build an instance of TemplateInstance + + :param payload: Payload response from the API + """ + return TemplateInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TemplateList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TemplateList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Templates" + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TemplateInstance]: + """ + Streams TemplateInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: String filter used to query templates with a given friendly name. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(friendly_name=friendly_name, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TemplateInstance]: + """ + Asynchronously streams TemplateInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: String filter used to query templates with a given friendly name. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TemplateInstance]: + """ + Lists TemplateInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: String filter used to query templates with a given friendly name. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TemplateInstance]: + """ + Asynchronously lists TemplateInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: String filter used to query templates with a given friendly name. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TemplatePage: + """ + Retrieve a single page of TemplateInstance records from the API. + Request is executed immediately + + :param friendly_name: String filter used to query templates with a given friendly name. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TemplateInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TemplatePage(self._version, response) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TemplatePage: + """ + Asynchronously retrieve a single page of TemplateInstance records from the API. + Request is executed immediately + + :param friendly_name: String filter used to query templates with a given friendly name. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TemplateInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TemplatePage(self._version, response) + + def get_page(self, target_url: str) -> TemplatePage: + """ + Retrieve a specific page of TemplateInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TemplateInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TemplatePage(self._version, response) + + async def get_page_async(self, target_url: str) -> TemplatePage: + """ + Asynchronously retrieve a specific page of TemplateInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TemplateInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TemplatePage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/verification_attempt.py b/venv/Lib/site-packages/twilio/rest/verify/v2/verification_attempt.py new file mode 100644 index 00000000..129a65a5 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/verify/v2/verification_attempt.py @@ -0,0 +1,602 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class VerificationAttemptInstance(InstanceResource): + + class Channels(object): + SMS = "sms" + CALL = "call" + EMAIL = "email" + WHATSAPP = "whatsapp" + RBM = "rbm" + SNA = "sna" + + class ConversionStatus(object): + CONVERTED = "converted" + UNCONVERTED = "unconverted" + + """ + :ivar sid: The SID that uniquely identifies the verification attempt resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Verification resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) used to generate the attempt. + :ivar verification_sid: The SID of the [Verification](https://www.twilio.com/docs/verify/api/verification) that generated the attempt. + :ivar date_created: The date that this Attempt was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date that this Attempt was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar conversion_status: + :ivar channel: + :ivar price: An object containing the charge for this verification attempt related to the channel costs and the currency used. The costs related to the succeeded verifications are not included. May not be immediately available. More information on pricing is available [here](https://www.twilio.com/en-us/verify/pricing). + :ivar channel_data: An object containing the channel specific information for an attempt. + :ivar url: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.verification_sid: Optional[str] = payload.get("verification_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.conversion_status: Optional[ + "VerificationAttemptInstance.ConversionStatus" + ] = payload.get("conversion_status") + self.channel: Optional["VerificationAttemptInstance.Channels"] = payload.get( + "channel" + ) + self.price: Optional[Dict[str, object]] = payload.get("price") + self.channel_data: Optional[Dict[str, object]] = payload.get("channel_data") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[VerificationAttemptContext] = None + + @property + def _proxy(self) -> "VerificationAttemptContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: VerificationAttemptContext for this VerificationAttemptInstance + """ + if self._context is None: + self._context = VerificationAttemptContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "VerificationAttemptInstance": + """ + Fetch the VerificationAttemptInstance + + + :returns: The fetched VerificationAttemptInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "VerificationAttemptInstance": + """ + Asynchronous coroutine to fetch the VerificationAttemptInstance + + + :returns: The fetched VerificationAttemptInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class VerificationAttemptContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the VerificationAttemptContext + + :param version: Version that contains the resource + :param sid: The unique SID identifier of a Verification Attempt + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Attempts/{sid}".format(**self._solution) + + def fetch(self) -> VerificationAttemptInstance: + """ + Fetch the VerificationAttemptInstance + + + :returns: The fetched VerificationAttemptInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return VerificationAttemptInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> VerificationAttemptInstance: + """ + Asynchronous coroutine to fetch the VerificationAttemptInstance + + + :returns: The fetched VerificationAttemptInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return VerificationAttemptInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class VerificationAttemptPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> VerificationAttemptInstance: + """ + Build an instance of VerificationAttemptInstance + + :param payload: Payload response from the API + """ + return VerificationAttemptInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class VerificationAttemptList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the VerificationAttemptList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Attempts" + + def stream( + self, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + channel_data_to: Union[str, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union["VerificationAttemptInstance.Channels", object] = values.unset, + verify_service_sid: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + status: Union[ + "VerificationAttemptInstance.ConversionStatus", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[VerificationAttemptInstance]: + """ + Streams VerificationAttemptInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param datetime date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param str channel_data_to: Destination of a verification. It is phone number in E.164 format. + :param str country: Filter used to query Verification Attempts sent to the specified destination country. + :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. Valid values are `SMS` and `CALL` + :param str verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. + :param str verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. + :param "VerificationAttemptInstance.ConversionStatus" status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + date_created_after=date_created_after, + date_created_before=date_created_before, + channel_data_to=channel_data_to, + country=country, + channel=channel, + verify_service_sid=verify_service_sid, + verification_sid=verification_sid, + status=status, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + channel_data_to: Union[str, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union["VerificationAttemptInstance.Channels", object] = values.unset, + verify_service_sid: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + status: Union[ + "VerificationAttemptInstance.ConversionStatus", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[VerificationAttemptInstance]: + """ + Asynchronously streams VerificationAttemptInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param datetime date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param str channel_data_to: Destination of a verification. It is phone number in E.164 format. + :param str country: Filter used to query Verification Attempts sent to the specified destination country. + :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. Valid values are `SMS` and `CALL` + :param str verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. + :param str verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. + :param "VerificationAttemptInstance.ConversionStatus" status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + date_created_after=date_created_after, + date_created_before=date_created_before, + channel_data_to=channel_data_to, + country=country, + channel=channel, + verify_service_sid=verify_service_sid, + verification_sid=verification_sid, + status=status, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + channel_data_to: Union[str, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union["VerificationAttemptInstance.Channels", object] = values.unset, + verify_service_sid: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + status: Union[ + "VerificationAttemptInstance.ConversionStatus", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[VerificationAttemptInstance]: + """ + Lists VerificationAttemptInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param datetime date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param str channel_data_to: Destination of a verification. It is phone number in E.164 format. + :param str country: Filter used to query Verification Attempts sent to the specified destination country. + :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. Valid values are `SMS` and `CALL` + :param str verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. + :param str verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. + :param "VerificationAttemptInstance.ConversionStatus" status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + date_created_after=date_created_after, + date_created_before=date_created_before, + channel_data_to=channel_data_to, + country=country, + channel=channel, + verify_service_sid=verify_service_sid, + verification_sid=verification_sid, + status=status, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + channel_data_to: Union[str, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union["VerificationAttemptInstance.Channels", object] = values.unset, + verify_service_sid: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + status: Union[ + "VerificationAttemptInstance.ConversionStatus", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[VerificationAttemptInstance]: + """ + Asynchronously lists VerificationAttemptInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param datetime date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param str channel_data_to: Destination of a verification. It is phone number in E.164 format. + :param str country: Filter used to query Verification Attempts sent to the specified destination country. + :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. Valid values are `SMS` and `CALL` + :param str verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. + :param str verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. + :param "VerificationAttemptInstance.ConversionStatus" status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + date_created_after=date_created_after, + date_created_before=date_created_before, + channel_data_to=channel_data_to, + country=country, + channel=channel, + verify_service_sid=verify_service_sid, + verification_sid=verification_sid, + status=status, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + channel_data_to: Union[str, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union["VerificationAttemptInstance.Channels", object] = values.unset, + verify_service_sid: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + status: Union[ + "VerificationAttemptInstance.ConversionStatus", object + ] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> VerificationAttemptPage: + """ + Retrieve a single page of VerificationAttemptInstance records from the API. + Request is executed immediately + + :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param channel_data_to: Destination of a verification. It is phone number in E.164 format. + :param country: Filter used to query Verification Attempts sent to the specified destination country. + :param channel: Filter used to query Verification Attempts by communication channel. Valid values are `SMS` and `CALL` + :param verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. + :param verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. + :param status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of VerificationAttemptInstance + """ + data = values.of( + { + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "ChannelData.To": channel_data_to, + "Country": country, + "Channel": channel, + "VerifyServiceSid": verify_service_sid, + "VerificationSid": verification_sid, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return VerificationAttemptPage(self._version, response) + + async def page_async( + self, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + channel_data_to: Union[str, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union["VerificationAttemptInstance.Channels", object] = values.unset, + verify_service_sid: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + status: Union[ + "VerificationAttemptInstance.ConversionStatus", object + ] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> VerificationAttemptPage: + """ + Asynchronously retrieve a single page of VerificationAttemptInstance records from the API. + Request is executed immediately + + :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param channel_data_to: Destination of a verification. It is phone number in E.164 format. + :param country: Filter used to query Verification Attempts sent to the specified destination country. + :param channel: Filter used to query Verification Attempts by communication channel. Valid values are `SMS` and `CALL` + :param verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. + :param verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. + :param status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of VerificationAttemptInstance + """ + data = values.of( + { + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "ChannelData.To": channel_data_to, + "Country": country, + "Channel": channel, + "VerifyServiceSid": verify_service_sid, + "VerificationSid": verification_sid, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return VerificationAttemptPage(self._version, response) + + def get_page(self, target_url: str) -> VerificationAttemptPage: + """ + Retrieve a specific page of VerificationAttemptInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of VerificationAttemptInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return VerificationAttemptPage(self._version, response) + + async def get_page_async(self, target_url: str) -> VerificationAttemptPage: + """ + Asynchronously retrieve a specific page of VerificationAttemptInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of VerificationAttemptInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return VerificationAttemptPage(self._version, response) + + def get(self, sid: str) -> VerificationAttemptContext: + """ + Constructs a VerificationAttemptContext + + :param sid: The unique SID identifier of a Verification Attempt + """ + return VerificationAttemptContext(self._version, sid=sid) + + def __call__(self, sid: str) -> VerificationAttemptContext: + """ + Constructs a VerificationAttemptContext + + :param sid: The unique SID identifier of a Verification Attempt + """ + return VerificationAttemptContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/verify/v2/verification_attempts_summary.py b/venv/Lib/site-packages/twilio/rest/verify/v2/verification_attempts_summary.py new file mode 100644 index 00000000..d662cf8f --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/verify/v2/verification_attempts_summary.py @@ -0,0 +1,296 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class VerificationAttemptsSummaryInstance(InstanceResource): + + class Channels(object): + SMS = "sms" + CALL = "call" + EMAIL = "email" + WHATSAPP = "whatsapp" + + """ + :ivar total_attempts: Total of attempts made according to the provided filters + :ivar total_converted: Total of attempts made that were confirmed by the end user, according to the provided filters. + :ivar total_unconverted: Total of attempts made that were not confirmed by the end user, according to the provided filters. + :ivar conversion_rate_percentage: Percentage of the confirmed messages over the total, defined by (total_converted/total_attempts)*100. + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.total_attempts: Optional[int] = deserialize.integer( + payload.get("total_attempts") + ) + self.total_converted: Optional[int] = deserialize.integer( + payload.get("total_converted") + ) + self.total_unconverted: Optional[int] = deserialize.integer( + payload.get("total_unconverted") + ) + self.conversion_rate_percentage: Optional[str] = payload.get( + "conversion_rate_percentage" + ) + self.url: Optional[str] = payload.get("url") + + self._context: Optional[VerificationAttemptsSummaryContext] = None + + @property + def _proxy(self) -> "VerificationAttemptsSummaryContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: VerificationAttemptsSummaryContext for this VerificationAttemptsSummaryInstance + """ + if self._context is None: + self._context = VerificationAttemptsSummaryContext( + self._version, + ) + return self._context + + def fetch( + self, + verify_service_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union[ + "VerificationAttemptsSummaryInstance.Channels", object + ] = values.unset, + destination_prefix: Union[str, object] = values.unset, + ) -> "VerificationAttemptsSummaryInstance": + """ + Fetch the VerificationAttemptsSummaryInstance + + :param verify_service_sid: Filter used to consider only Verification Attempts of the given verify service on the summary aggregation. + :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param country: Filter used to consider only Verification Attempts sent to the specified destination country on the summary aggregation. + :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. Valid values are `SMS`, `CALL` and `WHATSAPP` + :param destination_prefix: Filter the Verification Attempts considered on the summary aggregation by Destination prefix. It is the prefix of a phone number in E.164 format. + + :returns: The fetched VerificationAttemptsSummaryInstance + """ + return self._proxy.fetch( + verify_service_sid=verify_service_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + country=country, + channel=channel, + destination_prefix=destination_prefix, + ) + + async def fetch_async( + self, + verify_service_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union[ + "VerificationAttemptsSummaryInstance.Channels", object + ] = values.unset, + destination_prefix: Union[str, object] = values.unset, + ) -> "VerificationAttemptsSummaryInstance": + """ + Asynchronous coroutine to fetch the VerificationAttemptsSummaryInstance + + :param verify_service_sid: Filter used to consider only Verification Attempts of the given verify service on the summary aggregation. + :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param country: Filter used to consider only Verification Attempts sent to the specified destination country on the summary aggregation. + :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. Valid values are `SMS`, `CALL` and `WHATSAPP` + :param destination_prefix: Filter the Verification Attempts considered on the summary aggregation by Destination prefix. It is the prefix of a phone number in E.164 format. + + :returns: The fetched VerificationAttemptsSummaryInstance + """ + return await self._proxy.fetch_async( + verify_service_sid=verify_service_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + country=country, + channel=channel, + destination_prefix=destination_prefix, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class VerificationAttemptsSummaryContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the VerificationAttemptsSummaryContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/Attempts/Summary" + + def fetch( + self, + verify_service_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union[ + "VerificationAttemptsSummaryInstance.Channels", object + ] = values.unset, + destination_prefix: Union[str, object] = values.unset, + ) -> VerificationAttemptsSummaryInstance: + """ + Fetch the VerificationAttemptsSummaryInstance + + :param verify_service_sid: Filter used to consider only Verification Attempts of the given verify service on the summary aggregation. + :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param country: Filter used to consider only Verification Attempts sent to the specified destination country on the summary aggregation. + :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. Valid values are `SMS`, `CALL` and `WHATSAPP` + :param destination_prefix: Filter the Verification Attempts considered on the summary aggregation by Destination prefix. It is the prefix of a phone number in E.164 format. + + :returns: The fetched VerificationAttemptsSummaryInstance + """ + + data = values.of( + { + "VerifyServiceSid": verify_service_sid, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "Country": country, + "Channel": channel, + "DestinationPrefix": destination_prefix, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return VerificationAttemptsSummaryInstance( + self._version, + payload, + ) + + async def fetch_async( + self, + verify_service_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union[ + "VerificationAttemptsSummaryInstance.Channels", object + ] = values.unset, + destination_prefix: Union[str, object] = values.unset, + ) -> VerificationAttemptsSummaryInstance: + """ + Asynchronous coroutine to fetch the VerificationAttemptsSummaryInstance + + :param verify_service_sid: Filter used to consider only Verification Attempts of the given verify service on the summary aggregation. + :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param country: Filter used to consider only Verification Attempts sent to the specified destination country on the summary aggregation. + :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. Valid values are `SMS`, `CALL` and `WHATSAPP` + :param destination_prefix: Filter the Verification Attempts considered on the summary aggregation by Destination prefix. It is the prefix of a phone number in E.164 format. + + :returns: The fetched VerificationAttemptsSummaryInstance + """ + + data = values.of( + { + "VerifyServiceSid": verify_service_sid, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "Country": country, + "Channel": channel, + "DestinationPrefix": destination_prefix, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return VerificationAttemptsSummaryInstance( + self._version, + payload, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class VerificationAttemptsSummaryList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the VerificationAttemptsSummaryList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> VerificationAttemptsSummaryContext: + """ + Constructs a VerificationAttemptsSummaryContext + + """ + return VerificationAttemptsSummaryContext(self._version) + + def __call__(self) -> VerificationAttemptsSummaryContext: + """ + Constructs a VerificationAttemptsSummaryContext + + """ + return VerificationAttemptsSummaryContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/video/VideoBase.py b/venv/Lib/site-packages/twilio/rest/video/VideoBase.py new file mode 100644 index 00000000..0d2cf7e3 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/video/VideoBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.video.v1 import V1 + + +class VideoBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Video Domain + + :returns: Domain for Video + """ + super().__init__(twilio, "https://video.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Video + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/video/__init__.py b/venv/Lib/site-packages/twilio/rest/video/__init__.py new file mode 100644 index 00000000..d57e4f1e --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/video/__init__.py @@ -0,0 +1,65 @@ +from warnings import warn + +from twilio.rest.video.VideoBase import VideoBase +from twilio.rest.video.v1.composition import CompositionList +from twilio.rest.video.v1.composition_hook import CompositionHookList +from twilio.rest.video.v1.composition_settings import CompositionSettingsList +from twilio.rest.video.v1.recording import RecordingList +from twilio.rest.video.v1.recording_settings import RecordingSettingsList +from twilio.rest.video.v1.room import RoomList + + +class Video(VideoBase): + @property + def compositions(self) -> CompositionList: + warn( + "compositions is deprecated. Use v1.compositions instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.compositions + + @property + def composition_hooks(self) -> CompositionHookList: + warn( + "composition_hooks is deprecated. Use v1.composition_hooks instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.composition_hooks + + @property + def composition_settings(self) -> CompositionSettingsList: + warn( + "composition_settings is deprecated. Use v1.composition_settings instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.composition_settings + + @property + def recordings(self) -> RecordingList: + warn( + "recordings is deprecated. Use v1.recordings instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.recordings + + @property + def recording_settings(self) -> RecordingSettingsList: + warn( + "recording_settings is deprecated. Use v1.recording_settings instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.recording_settings + + @property + def rooms(self) -> RoomList: + warn( + "rooms is deprecated. Use v1.rooms instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.rooms diff --git a/venv/Lib/site-packages/twilio/rest/video/__pycache__/VideoBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/video/__pycache__/VideoBase.cpython-312.pyc new file mode 100644 index 00000000..5b934b1d Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/video/__pycache__/VideoBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/video/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/video/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..a84e7e7f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/video/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/video/v1/__init__.py new file mode 100644 index 00000000..0667596a --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/video/v1/__init__.py @@ -0,0 +1,83 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.video.v1.composition import CompositionList +from twilio.rest.video.v1.composition_hook import CompositionHookList +from twilio.rest.video.v1.composition_settings import CompositionSettingsList +from twilio.rest.video.v1.recording import RecordingList +from twilio.rest.video.v1.recording_settings import RecordingSettingsList +from twilio.rest.video.v1.room import RoomList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Video + + :param domain: The Twilio.video domain + """ + super().__init__(domain, "v1") + self._compositions: Optional[CompositionList] = None + self._composition_hooks: Optional[CompositionHookList] = None + self._composition_settings: Optional[CompositionSettingsList] = None + self._recordings: Optional[RecordingList] = None + self._recording_settings: Optional[RecordingSettingsList] = None + self._rooms: Optional[RoomList] = None + + @property + def compositions(self) -> CompositionList: + if self._compositions is None: + self._compositions = CompositionList(self) + return self._compositions + + @property + def composition_hooks(self) -> CompositionHookList: + if self._composition_hooks is None: + self._composition_hooks = CompositionHookList(self) + return self._composition_hooks + + @property + def composition_settings(self) -> CompositionSettingsList: + if self._composition_settings is None: + self._composition_settings = CompositionSettingsList(self) + return self._composition_settings + + @property + def recordings(self) -> RecordingList: + if self._recordings is None: + self._recordings = RecordingList(self) + return self._recordings + + @property + def recording_settings(self) -> RecordingSettingsList: + if self._recording_settings is None: + self._recording_settings = RecordingSettingsList(self) + return self._recording_settings + + @property + def rooms(self) -> RoomList: + if self._rooms is None: + self._rooms = RoomList(self) + return self._rooms + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/video/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..7ef4a4ba Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/video/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/__pycache__/composition.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/video/v1/__pycache__/composition.cpython-312.pyc new file mode 100644 index 00000000..8d0389c5 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/video/v1/__pycache__/composition.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/__pycache__/composition_hook.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/video/v1/__pycache__/composition_hook.cpython-312.pyc new file mode 100644 index 00000000..0f9bafdd Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/video/v1/__pycache__/composition_hook.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/__pycache__/composition_settings.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/video/v1/__pycache__/composition_settings.cpython-312.pyc new file mode 100644 index 00000000..eb6f6881 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/video/v1/__pycache__/composition_settings.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/__pycache__/recording.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/video/v1/__pycache__/recording.cpython-312.pyc new file mode 100644 index 00000000..927c1e2a Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/video/v1/__pycache__/recording.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/__pycache__/recording_settings.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/video/v1/__pycache__/recording_settings.cpython-312.pyc new file mode 100644 index 00000000..f3ee5171 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/video/v1/__pycache__/recording_settings.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/composition.py b/venv/Lib/site-packages/twilio/rest/video/v1/composition.py new file mode 100644 index 00000000..06f4d05f --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/video/v1/composition.py @@ -0,0 +1,695 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CompositionInstance(InstanceResource): + + class Format(object): + MP4 = "mp4" + WEBM = "webm" + + class Status(object): + ENQUEUED = "enqueued" + PROCESSING = "processing" + COMPLETED = "completed" + DELETED = "deleted" + FAILED = "failed" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Composition resource. + :ivar status: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_completed: The date and time in GMT when the composition's media processing task finished, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_deleted: The date and time in GMT when the composition generated media was deleted, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar sid: The unique string that we created to identify the Composition resource. + :ivar room_sid: The SID of the Group Room that generated the audio and video tracks used in the composition. All media sources included in a composition must belong to the same Group Room. + :ivar audio_sources: The array of track names to include in the composition. The composition includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this property can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :ivar audio_sources_excluded: The array of track names to exclude from the composition. The composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this property can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :ivar video_layout: An object that describes the video layout of the composition in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :ivar resolution: The dimensions of the video image in pixels expressed as columns (width) and rows (height). The string's format is `{width}x{height}`, such as `640x480`. + :ivar trim: Whether to remove intervals with no media, as specified in the POST request that created the composition. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :ivar format: + :ivar bitrate: The average bit rate of the composition's media. + :ivar size: The size of the composed media file in bytes. + :ivar duration: The duration of the composition's media file in seconds. + :ivar media_external_location: The URL of the media file associated with the composition when stored externally. See [External S3 Compositions](/docs/video/api/external-s3-compositions) for more details. + :ivar status_callback: The URL called using the `status_callback_method` to send status information on every composition event. + :ivar status_callback_method: The HTTP method used to call `status_callback`. Can be: `POST` or `GET`, defaults to `POST`. + :ivar url: The absolute URL of the resource. + :ivar links: The URL of the media file associated with the composition. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.status: Optional["CompositionInstance.Status"] = payload.get("status") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_completed: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_completed") + ) + self.date_deleted: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_deleted") + ) + self.sid: Optional[str] = payload.get("sid") + self.room_sid: Optional[str] = payload.get("room_sid") + self.audio_sources: Optional[List[str]] = payload.get("audio_sources") + self.audio_sources_excluded: Optional[List[str]] = payload.get( + "audio_sources_excluded" + ) + self.video_layout: Optional[Dict[str, object]] = payload.get("video_layout") + self.resolution: Optional[str] = payload.get("resolution") + self.trim: Optional[bool] = payload.get("trim") + self.format: Optional["CompositionInstance.Format"] = payload.get("format") + self.bitrate: Optional[int] = deserialize.integer(payload.get("bitrate")) + self.size: Optional[int] = payload.get("size") + self.duration: Optional[int] = deserialize.integer(payload.get("duration")) + self.media_external_location: Optional[str] = payload.get( + "media_external_location" + ) + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CompositionContext] = None + + @property + def _proxy(self) -> "CompositionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CompositionContext for this CompositionInstance + """ + if self._context is None: + self._context = CompositionContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CompositionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CompositionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CompositionInstance": + """ + Fetch the CompositionInstance + + + :returns: The fetched CompositionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CompositionInstance": + """ + Asynchronous coroutine to fetch the CompositionInstance + + + :returns: The fetched CompositionInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CompositionContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CompositionContext + + :param version: Version that contains the resource + :param sid: The SID of the Composition resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Compositions/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the CompositionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CompositionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CompositionInstance: + """ + Fetch the CompositionInstance + + + :returns: The fetched CompositionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CompositionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CompositionInstance: + """ + Asynchronous coroutine to fetch the CompositionInstance + + + :returns: The fetched CompositionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CompositionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CompositionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CompositionInstance: + """ + Build an instance of CompositionInstance + + :param payload: Payload response from the API + """ + return CompositionInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CompositionList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CompositionList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Compositions" + + def create( + self, + room_sid: str, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> CompositionInstance: + """ + Create the CompositionInstance + + :param room_sid: The SID of the Group Room with the media tracks to be used as composition sources. + :param video_layout: An object that describes the video layout of the composition in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + :param audio_sources: An array of track names from the same group room to merge into the new composition. Can include zero or more track names. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` includes `student` as well as `studentTeam`. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + :param audio_sources_excluded: An array of track names to exclude. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param trim: Whether to clip the intervals where there is no active media in the composition. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + + :returns: The created CompositionInstance + """ + + data = values.of( + { + "RoomSid": room_sid, + "VideoLayout": serialize.object(video_layout), + "AudioSources": serialize.map(audio_sources, lambda e: e), + "AudioSourcesExcluded": serialize.map( + audio_sources_excluded, lambda e: e + ), + "Resolution": resolution, + "Format": format, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Trim": serialize.boolean_to_string(trim), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CompositionInstance(self._version, payload) + + async def create_async( + self, + room_sid: str, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> CompositionInstance: + """ + Asynchronously create the CompositionInstance + + :param room_sid: The SID of the Group Room with the media tracks to be used as composition sources. + :param video_layout: An object that describes the video layout of the composition in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + :param audio_sources: An array of track names from the same group room to merge into the new composition. Can include zero or more track names. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` includes `student` as well as `studentTeam`. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + :param audio_sources_excluded: An array of track names to exclude. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param trim: Whether to clip the intervals where there is no active media in the composition. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + + :returns: The created CompositionInstance + """ + + data = values.of( + { + "RoomSid": room_sid, + "VideoLayout": serialize.object(video_layout), + "AudioSources": serialize.map(audio_sources, lambda e: e), + "AudioSourcesExcluded": serialize.map( + audio_sources_excluded, lambda e: e + ), + "Resolution": resolution, + "Format": format, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Trim": serialize.boolean_to_string(trim), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CompositionInstance(self._version, payload) + + def stream( + self, + status: Union["CompositionInstance.Status", object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + room_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CompositionInstance]: + """ + Streams CompositionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "CompositionInstance.Status" status: Read only Composition resources with this status. Can be: `enqueued`, `processing`, `completed`, `deleted`, or `failed`. + :param datetime date_created_after: Read only Composition resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param datetime date_created_before: Read only Composition resources created before this ISO 8601 date-time with time zone. + :param str room_sid: Read only Composition resources with this Room SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + date_created_after=date_created_after, + date_created_before=date_created_before, + room_sid=room_sid, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["CompositionInstance.Status", object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + room_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CompositionInstance]: + """ + Asynchronously streams CompositionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "CompositionInstance.Status" status: Read only Composition resources with this status. Can be: `enqueued`, `processing`, `completed`, `deleted`, or `failed`. + :param datetime date_created_after: Read only Composition resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param datetime date_created_before: Read only Composition resources created before this ISO 8601 date-time with time zone. + :param str room_sid: Read only Composition resources with this Room SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + date_created_after=date_created_after, + date_created_before=date_created_before, + room_sid=room_sid, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["CompositionInstance.Status", object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + room_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CompositionInstance]: + """ + Lists CompositionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "CompositionInstance.Status" status: Read only Composition resources with this status. Can be: `enqueued`, `processing`, `completed`, `deleted`, or `failed`. + :param datetime date_created_after: Read only Composition resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param datetime date_created_before: Read only Composition resources created before this ISO 8601 date-time with time zone. + :param str room_sid: Read only Composition resources with this Room SID. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + date_created_after=date_created_after, + date_created_before=date_created_before, + room_sid=room_sid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["CompositionInstance.Status", object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + room_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CompositionInstance]: + """ + Asynchronously lists CompositionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "CompositionInstance.Status" status: Read only Composition resources with this status. Can be: `enqueued`, `processing`, `completed`, `deleted`, or `failed`. + :param datetime date_created_after: Read only Composition resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param datetime date_created_before: Read only Composition resources created before this ISO 8601 date-time with time zone. + :param str room_sid: Read only Composition resources with this Room SID. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + date_created_after=date_created_after, + date_created_before=date_created_before, + room_sid=room_sid, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["CompositionInstance.Status", object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + room_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CompositionPage: + """ + Retrieve a single page of CompositionInstance records from the API. + Request is executed immediately + + :param status: Read only Composition resources with this status. Can be: `enqueued`, `processing`, `completed`, `deleted`, or `failed`. + :param date_created_after: Read only Composition resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param date_created_before: Read only Composition resources created before this ISO 8601 date-time with time zone. + :param room_sid: Read only Composition resources with this Room SID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CompositionInstance + """ + data = values.of( + { + "Status": status, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "RoomSid": room_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CompositionPage(self._version, response) + + async def page_async( + self, + status: Union["CompositionInstance.Status", object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + room_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CompositionPage: + """ + Asynchronously retrieve a single page of CompositionInstance records from the API. + Request is executed immediately + + :param status: Read only Composition resources with this status. Can be: `enqueued`, `processing`, `completed`, `deleted`, or `failed`. + :param date_created_after: Read only Composition resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param date_created_before: Read only Composition resources created before this ISO 8601 date-time with time zone. + :param room_sid: Read only Composition resources with this Room SID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CompositionInstance + """ + data = values.of( + { + "Status": status, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "RoomSid": room_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CompositionPage(self._version, response) + + def get_page(self, target_url: str) -> CompositionPage: + """ + Retrieve a specific page of CompositionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CompositionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CompositionPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CompositionPage: + """ + Asynchronously retrieve a specific page of CompositionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CompositionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CompositionPage(self._version, response) + + def get(self, sid: str) -> CompositionContext: + """ + Constructs a CompositionContext + + :param sid: The SID of the Composition resource to fetch. + """ + return CompositionContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CompositionContext: + """ + Constructs a CompositionContext + + :param sid: The SID of the Composition resource to fetch. + """ + return CompositionContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/composition_hook.py b/venv/Lib/site-packages/twilio/rest/video/v1/composition_hook.py new file mode 100644 index 00000000..30fead17 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/video/v1/composition_hook.py @@ -0,0 +1,882 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CompositionHookInstance(InstanceResource): + + class Format(object): + MP4 = "mp4" + WEBM = "webm" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CompositionHook resource. + :ivar friendly_name: The string that you assigned to describe the resource. Can be up to 100 characters long and must be unique within the account. + :ivar enabled: Whether the CompositionHook is active. When `true`, the CompositionHook is triggered for every completed Group Room on the account. When `false`, the CompositionHook is never triggered. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar sid: The unique string that we created to identify the CompositionHook resource. + :ivar audio_sources: The array of track names to include in the compositions created by the composition hook. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this property can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + :ivar audio_sources_excluded: The array of track names to exclude from the compositions created by the composition hook. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this property can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :ivar video_layout: A JSON object that describes the video layout of the composition in terms of regions as specified in the HTTP POST request that created the CompositionHook resource. See [POST Parameters](https://www.twilio.com/docs/video/api/compositions-resource#http-post-parameters) for more information. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + :ivar resolution: The dimensions of the video image in pixels expressed as columns (width) and rows (height). The string's format is `{width}x{height}`, such as `640x480`. + :ivar trim: Whether intervals with no media are clipped, as specified in the POST request that created the CompositionHook resource. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :ivar format: + :ivar status_callback: The URL we call using the `status_callback_method` to send status information to your application. + :ivar status_callback_method: The HTTP method we should use to call `status_callback`. Can be `POST` or `GET` and defaults to `POST`. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.enabled: Optional[bool] = payload.get("enabled") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.sid: Optional[str] = payload.get("sid") + self.audio_sources: Optional[List[str]] = payload.get("audio_sources") + self.audio_sources_excluded: Optional[List[str]] = payload.get( + "audio_sources_excluded" + ) + self.video_layout: Optional[Dict[str, object]] = payload.get("video_layout") + self.resolution: Optional[str] = payload.get("resolution") + self.trim: Optional[bool] = payload.get("trim") + self.format: Optional["CompositionHookInstance.Format"] = payload.get("format") + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CompositionHookContext] = None + + @property + def _proxy(self) -> "CompositionHookContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CompositionHookContext for this CompositionHookInstance + """ + if self._context is None: + self._context = CompositionHookContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CompositionHookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CompositionHookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CompositionHookInstance": + """ + Fetch the CompositionHookInstance + + + :returns: The fetched CompositionHookInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CompositionHookInstance": + """ + Asynchronous coroutine to fetch the CompositionHookInstance + + + :returns: The fetched CompositionHookInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + trim: Union[bool, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + resolution: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> "CompositionHookInstance": + """ + Update the CompositionHookInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook never triggers. + :param video_layout: A JSON object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param trim: Whether to clip the intervals where there is no active media in the compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + + :returns: The updated CompositionHookInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + trim=trim, + format=format, + resolution=resolution, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) + + async def update_async( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + trim: Union[bool, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + resolution: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> "CompositionHookInstance": + """ + Asynchronous coroutine to update the CompositionHookInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook never triggers. + :param video_layout: A JSON object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param trim: Whether to clip the intervals where there is no active media in the compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + + :returns: The updated CompositionHookInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + trim=trim, + format=format, + resolution=resolution, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CompositionHookContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CompositionHookContext + + :param version: Version that contains the resource + :param sid: The SID of the CompositionHook resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/CompositionHooks/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the CompositionHookInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CompositionHookInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CompositionHookInstance: + """ + Fetch the CompositionHookInstance + + + :returns: The fetched CompositionHookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CompositionHookInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CompositionHookInstance: + """ + Asynchronous coroutine to fetch the CompositionHookInstance + + + :returns: The fetched CompositionHookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CompositionHookInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + trim: Union[bool, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + resolution: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> CompositionHookInstance: + """ + Update the CompositionHookInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook never triggers. + :param video_layout: A JSON object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param trim: Whether to clip the intervals where there is no active media in the compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + + :returns: The updated CompositionHookInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Enabled": serialize.boolean_to_string(enabled), + "VideoLayout": serialize.object(video_layout), + "AudioSources": serialize.map(audio_sources, lambda e: e), + "AudioSourcesExcluded": serialize.map( + audio_sources_excluded, lambda e: e + ), + "Trim": serialize.boolean_to_string(trim), + "Format": format, + "Resolution": resolution, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CompositionHookInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + trim: Union[bool, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + resolution: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> CompositionHookInstance: + """ + Asynchronous coroutine to update the CompositionHookInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook never triggers. + :param video_layout: A JSON object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param trim: Whether to clip the intervals where there is no active media in the compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + + :returns: The updated CompositionHookInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Enabled": serialize.boolean_to_string(enabled), + "VideoLayout": serialize.object(video_layout), + "AudioSources": serialize.map(audio_sources, lambda e: e), + "AudioSourcesExcluded": serialize.map( + audio_sources_excluded, lambda e: e + ), + "Trim": serialize.boolean_to_string(trim), + "Format": format, + "Resolution": resolution, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CompositionHookInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CompositionHookPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CompositionHookInstance: + """ + Build an instance of CompositionHookInstance + + :param payload: Payload response from the API + """ + return CompositionHookInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CompositionHookList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CompositionHookList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/CompositionHooks" + + def create( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> CompositionHookInstance: + """ + Create the CompositionHookInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook will never be triggered. + :param video_layout: An object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param trim: Whether to clip the intervals where there is no active media in the Compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + + :returns: The created CompositionHookInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Enabled": serialize.boolean_to_string(enabled), + "VideoLayout": serialize.object(video_layout), + "AudioSources": serialize.map(audio_sources, lambda e: e), + "AudioSourcesExcluded": serialize.map( + audio_sources_excluded, lambda e: e + ), + "Resolution": resolution, + "Format": format, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Trim": serialize.boolean_to_string(trim), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CompositionHookInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> CompositionHookInstance: + """ + Asynchronously create the CompositionHookInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook will never be triggered. + :param video_layout: An object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param trim: Whether to clip the intervals where there is no active media in the Compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + + :returns: The created CompositionHookInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Enabled": serialize.boolean_to_string(enabled), + "VideoLayout": serialize.object(video_layout), + "AudioSources": serialize.map(audio_sources, lambda e: e), + "AudioSourcesExcluded": serialize.map( + audio_sources_excluded, lambda e: e + ), + "Resolution": resolution, + "Format": format, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Trim": serialize.boolean_to_string(trim), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CompositionHookInstance(self._version, payload) + + def stream( + self, + enabled: Union[bool, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CompositionHookInstance]: + """ + Streams CompositionHookInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool enabled: Read only CompositionHook resources with an `enabled` value that matches this parameter. + :param datetime date_created_after: Read only CompositionHook resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param datetime date_created_before: Read only CompositionHook resources created before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param str friendly_name: Read only CompositionHook resources with friendly names that match this string. The match is not case sensitive and can include asterisk `*` characters as wildcard match. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + enabled=enabled, + date_created_after=date_created_after, + date_created_before=date_created_before, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + enabled: Union[bool, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CompositionHookInstance]: + """ + Asynchronously streams CompositionHookInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool enabled: Read only CompositionHook resources with an `enabled` value that matches this parameter. + :param datetime date_created_after: Read only CompositionHook resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param datetime date_created_before: Read only CompositionHook resources created before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param str friendly_name: Read only CompositionHook resources with friendly names that match this string. The match is not case sensitive and can include asterisk `*` characters as wildcard match. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + enabled=enabled, + date_created_after=date_created_after, + date_created_before=date_created_before, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + enabled: Union[bool, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CompositionHookInstance]: + """ + Lists CompositionHookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool enabled: Read only CompositionHook resources with an `enabled` value that matches this parameter. + :param datetime date_created_after: Read only CompositionHook resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param datetime date_created_before: Read only CompositionHook resources created before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param str friendly_name: Read only CompositionHook resources with friendly names that match this string. The match is not case sensitive and can include asterisk `*` characters as wildcard match. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + enabled=enabled, + date_created_after=date_created_after, + date_created_before=date_created_before, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + enabled: Union[bool, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CompositionHookInstance]: + """ + Asynchronously lists CompositionHookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool enabled: Read only CompositionHook resources with an `enabled` value that matches this parameter. + :param datetime date_created_after: Read only CompositionHook resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param datetime date_created_before: Read only CompositionHook resources created before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param str friendly_name: Read only CompositionHook resources with friendly names that match this string. The match is not case sensitive and can include asterisk `*` characters as wildcard match. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + enabled=enabled, + date_created_after=date_created_after, + date_created_before=date_created_before, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + enabled: Union[bool, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CompositionHookPage: + """ + Retrieve a single page of CompositionHookInstance records from the API. + Request is executed immediately + + :param enabled: Read only CompositionHook resources with an `enabled` value that matches this parameter. + :param date_created_after: Read only CompositionHook resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param date_created_before: Read only CompositionHook resources created before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param friendly_name: Read only CompositionHook resources with friendly names that match this string. The match is not case sensitive and can include asterisk `*` characters as wildcard match. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CompositionHookInstance + """ + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CompositionHookPage(self._version, response) + + async def page_async( + self, + enabled: Union[bool, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CompositionHookPage: + """ + Asynchronously retrieve a single page of CompositionHookInstance records from the API. + Request is executed immediately + + :param enabled: Read only CompositionHook resources with an `enabled` value that matches this parameter. + :param date_created_after: Read only CompositionHook resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param date_created_before: Read only CompositionHook resources created before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param friendly_name: Read only CompositionHook resources with friendly names that match this string. The match is not case sensitive and can include asterisk `*` characters as wildcard match. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CompositionHookInstance + """ + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CompositionHookPage(self._version, response) + + def get_page(self, target_url: str) -> CompositionHookPage: + """ + Retrieve a specific page of CompositionHookInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CompositionHookInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CompositionHookPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CompositionHookPage: + """ + Asynchronously retrieve a specific page of CompositionHookInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CompositionHookInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CompositionHookPage(self._version, response) + + def get(self, sid: str) -> CompositionHookContext: + """ + Constructs a CompositionHookContext + + :param sid: The SID of the CompositionHook resource to update. + """ + return CompositionHookContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CompositionHookContext: + """ + Constructs a CompositionHookContext + + :param sid: The SID of the CompositionHook resource to update. + """ + return CompositionHookContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/composition_settings.py b/venv/Lib/site-packages/twilio/rest/video/v1/composition_settings.py new file mode 100644 index 00000000..384ae692 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/video/v1/composition_settings.py @@ -0,0 +1,318 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class CompositionSettingsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CompositionSettings resource. + :ivar friendly_name: The string that you assigned to describe the resource and that will be shown in the console + :ivar aws_credentials_sid: The SID of the stored Credential resource. + :ivar aws_s3_url: The URL of the AWS S3 bucket where the compositions are stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/compositions`, where `compositions` is the path in which you want the compositions to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :ivar aws_storage_enabled: Whether all compositions are written to the `aws_s3_url`. When `false`, all compositions are stored in our cloud. + :ivar encryption_key_sid: The SID of the Public Key resource used for encryption. + :ivar encryption_enabled: Whether all compositions are stored in an encrypted form. The default is `false`. + :ivar url: The absolute URL of the resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.aws_credentials_sid: Optional[str] = payload.get("aws_credentials_sid") + self.aws_s3_url: Optional[str] = payload.get("aws_s3_url") + self.aws_storage_enabled: Optional[bool] = payload.get("aws_storage_enabled") + self.encryption_key_sid: Optional[str] = payload.get("encryption_key_sid") + self.encryption_enabled: Optional[bool] = payload.get("encryption_enabled") + self.url: Optional[str] = payload.get("url") + + self._context: Optional[CompositionSettingsContext] = None + + @property + def _proxy(self) -> "CompositionSettingsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CompositionSettingsContext for this CompositionSettingsInstance + """ + if self._context is None: + self._context = CompositionSettingsContext( + self._version, + ) + return self._context + + def create( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> "CompositionSettingsInstance": + """ + Create the CompositionSettingsInstance + + :param friendly_name: A descriptive string that you create to describe the resource and show to the user in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the compositions should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/compositions`, where `compositions` is the path in which you want the compositions to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all compositions should be written to the `aws_s3_url`. When `false`, all compositions are stored in our cloud. + :param encryption_enabled: Whether all compositions should be stored in an encrypted form. The default is `false`. + + :returns: The created CompositionSettingsInstance + """ + return self._proxy.create( + friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + + async def create_async( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> "CompositionSettingsInstance": + """ + Asynchronous coroutine to create the CompositionSettingsInstance + + :param friendly_name: A descriptive string that you create to describe the resource and show to the user in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the compositions should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/compositions`, where `compositions` is the path in which you want the compositions to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all compositions should be written to the `aws_s3_url`. When `false`, all compositions are stored in our cloud. + :param encryption_enabled: Whether all compositions should be stored in an encrypted form. The default is `false`. + + :returns: The created CompositionSettingsInstance + """ + return await self._proxy.create_async( + friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + + def fetch(self) -> "CompositionSettingsInstance": + """ + Fetch the CompositionSettingsInstance + + + :returns: The fetched CompositionSettingsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CompositionSettingsInstance": + """ + Asynchronous coroutine to fetch the CompositionSettingsInstance + + + :returns: The fetched CompositionSettingsInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class CompositionSettingsContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the CompositionSettingsContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/CompositionSettings/Default" + + def create( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> CompositionSettingsInstance: + """ + Create the CompositionSettingsInstance + + :param friendly_name: A descriptive string that you create to describe the resource and show to the user in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the compositions should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/compositions`, where `compositions` is the path in which you want the compositions to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all compositions should be written to the `aws_s3_url`. When `false`, all compositions are stored in our cloud. + :param encryption_enabled: Whether all compositions should be stored in an encrypted form. The default is `false`. + + :returns: The created CompositionSettingsInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "AwsCredentialsSid": aws_credentials_sid, + "EncryptionKeySid": encryption_key_sid, + "AwsS3Url": aws_s3_url, + "AwsStorageEnabled": serialize.boolean_to_string(aws_storage_enabled), + "EncryptionEnabled": serialize.boolean_to_string(encryption_enabled), + } + ) + + payload = self._version.create(method="POST", uri=self._uri, data=data) + + return CompositionSettingsInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> CompositionSettingsInstance: + """ + Asynchronous coroutine to create the CompositionSettingsInstance + + :param friendly_name: A descriptive string that you create to describe the resource and show to the user in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the compositions should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/compositions`, where `compositions` is the path in which you want the compositions to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all compositions should be written to the `aws_s3_url`. When `false`, all compositions are stored in our cloud. + :param encryption_enabled: Whether all compositions should be stored in an encrypted form. The default is `false`. + + :returns: The created CompositionSettingsInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "AwsCredentialsSid": aws_credentials_sid, + "EncryptionKeySid": encryption_key_sid, + "AwsS3Url": aws_s3_url, + "AwsStorageEnabled": serialize.boolean_to_string(aws_storage_enabled), + "EncryptionEnabled": serialize.boolean_to_string(encryption_enabled), + } + ) + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data + ) + + return CompositionSettingsInstance(self._version, payload) + + def fetch(self) -> CompositionSettingsInstance: + """ + Fetch the CompositionSettingsInstance + + + :returns: The fetched CompositionSettingsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CompositionSettingsInstance( + self._version, + payload, + ) + + async def fetch_async(self) -> CompositionSettingsInstance: + """ + Asynchronous coroutine to fetch the CompositionSettingsInstance + + + :returns: The fetched CompositionSettingsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CompositionSettingsInstance( + self._version, + payload, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class CompositionSettingsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CompositionSettingsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> CompositionSettingsContext: + """ + Constructs a CompositionSettingsContext + + """ + return CompositionSettingsContext(self._version) + + def __call__(self) -> CompositionSettingsContext: + """ + Constructs a CompositionSettingsContext + + """ + return CompositionSettingsContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/recording.py b/venv/Lib/site-packages/twilio/rest/video/v1/recording.py new file mode 100644 index 00000000..f474345f --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/video/v1/recording.py @@ -0,0 +1,621 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RecordingInstance(InstanceResource): + + class Codec(object): + VP8 = "VP8" + H264 = "H264" + OPUS = "OPUS" + PCMU = "PCMU" + + class Format(object): + MKA = "mka" + MKV = "mkv" + + class Status(object): + PROCESSING = "processing" + COMPLETED = "completed" + DELETED = "deleted" + FAILED = "failed" + + class Type(object): + AUDIO = "audio" + VIDEO = "video" + DATA = "data" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording resource. + :ivar status: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar sid: The unique string that we created to identify the Recording resource. + :ivar source_sid: The SID of the recording source. For a Room Recording, this value is a `track_sid`. + :ivar size: The size of the recorded track, in bytes. + :ivar url: The absolute URL of the resource. + :ivar type: + :ivar duration: The duration of the recording in seconds rounded to the nearest second. Sub-second tracks have a `Duration` property of 1 second + :ivar container_format: + :ivar codec: + :ivar grouping_sids: A list of SIDs related to the recording. Includes the `room_sid` and `participant_sid`. + :ivar track_name: The name that was given to the source track of the recording. If no name is given, the `source_sid` is used. + :ivar offset: The time in milliseconds elapsed between an arbitrary point in time, common to all group rooms, and the moment when the source room of this track started. This information provides a synchronization mechanism for recordings belonging to the same room. + :ivar media_external_location: The URL of the media file associated with the recording when stored externally. See [External S3 Recordings](/docs/video/api/external-s3-recordings) for more details. + :ivar status_callback: The URL called using the `status_callback_method` to send status information on every recording event. + :ivar status_callback_method: The HTTP method used to call `status_callback`. Can be: `POST` or `GET`, defaults to `POST`. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.status: Optional["RecordingInstance.Status"] = payload.get("status") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.sid: Optional[str] = payload.get("sid") + self.source_sid: Optional[str] = payload.get("source_sid") + self.size: Optional[int] = payload.get("size") + self.url: Optional[str] = payload.get("url") + self.type: Optional["RecordingInstance.Type"] = payload.get("type") + self.duration: Optional[int] = deserialize.integer(payload.get("duration")) + self.container_format: Optional["RecordingInstance.Format"] = payload.get( + "container_format" + ) + self.codec: Optional["RecordingInstance.Codec"] = payload.get("codec") + self.grouping_sids: Optional[Dict[str, object]] = payload.get("grouping_sids") + self.track_name: Optional[str] = payload.get("track_name") + self.offset: Optional[int] = payload.get("offset") + self.media_external_location: Optional[str] = payload.get( + "media_external_location" + ) + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[RecordingContext] = None + + @property + def _proxy(self) -> "RecordingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RecordingContext for this RecordingInstance + """ + if self._context is None: + self._context = RecordingContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RecordingInstance": + """ + Fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RecordingInstance": + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RecordingContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the RecordingContext + + :param version: Version that contains the resource + :param sid: The SID of the Recording resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Recordings/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RecordingInstance: + """ + Fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RecordingInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RecordingInstance: + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RecordingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RecordingInstance: + """ + Build an instance of RecordingInstance + + :param payload: Payload response from the API + """ + return RecordingInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RecordingList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the RecordingList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Recordings" + + def stream( + self, + status: Union["RecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + grouping_sid: Union[List[str], object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + media_type: Union["RecordingInstance.Type", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RecordingInstance]: + """ + Streams RecordingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "RecordingInstance.Status" status: Read only the recordings that have this status. Can be: `processing`, `completed`, or `deleted`. + :param str source_sid: Read only the recordings that have this `source_sid`. + :param List[str] grouping_sid: Read only recordings with this `grouping_sid`, which may include a `participant_sid` and/or a `room_sid`. + :param datetime date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param datetime date_created_before: Read only recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone, given as `YYYY-MM-DDThh:mm:ss+|-hh:mm` or `YYYY-MM-DDThh:mm:ssZ`. + :param "RecordingInstance.Type" media_type: Read only recordings that have this media type. Can be either `audio` or `video`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + source_sid=source_sid, + grouping_sid=grouping_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + media_type=media_type, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["RecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + grouping_sid: Union[List[str], object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + media_type: Union["RecordingInstance.Type", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RecordingInstance]: + """ + Asynchronously streams RecordingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "RecordingInstance.Status" status: Read only the recordings that have this status. Can be: `processing`, `completed`, or `deleted`. + :param str source_sid: Read only the recordings that have this `source_sid`. + :param List[str] grouping_sid: Read only recordings with this `grouping_sid`, which may include a `participant_sid` and/or a `room_sid`. + :param datetime date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param datetime date_created_before: Read only recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone, given as `YYYY-MM-DDThh:mm:ss+|-hh:mm` or `YYYY-MM-DDThh:mm:ssZ`. + :param "RecordingInstance.Type" media_type: Read only recordings that have this media type. Can be either `audio` or `video`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + source_sid=source_sid, + grouping_sid=grouping_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + media_type=media_type, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["RecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + grouping_sid: Union[List[str], object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + media_type: Union["RecordingInstance.Type", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RecordingInstance]: + """ + Lists RecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "RecordingInstance.Status" status: Read only the recordings that have this status. Can be: `processing`, `completed`, or `deleted`. + :param str source_sid: Read only the recordings that have this `source_sid`. + :param List[str] grouping_sid: Read only recordings with this `grouping_sid`, which may include a `participant_sid` and/or a `room_sid`. + :param datetime date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param datetime date_created_before: Read only recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone, given as `YYYY-MM-DDThh:mm:ss+|-hh:mm` or `YYYY-MM-DDThh:mm:ssZ`. + :param "RecordingInstance.Type" media_type: Read only recordings that have this media type. Can be either `audio` or `video`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + source_sid=source_sid, + grouping_sid=grouping_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + media_type=media_type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["RecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + grouping_sid: Union[List[str], object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + media_type: Union["RecordingInstance.Type", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RecordingInstance]: + """ + Asynchronously lists RecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "RecordingInstance.Status" status: Read only the recordings that have this status. Can be: `processing`, `completed`, or `deleted`. + :param str source_sid: Read only the recordings that have this `source_sid`. + :param List[str] grouping_sid: Read only recordings with this `grouping_sid`, which may include a `participant_sid` and/or a `room_sid`. + :param datetime date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param datetime date_created_before: Read only recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone, given as `YYYY-MM-DDThh:mm:ss+|-hh:mm` or `YYYY-MM-DDThh:mm:ssZ`. + :param "RecordingInstance.Type" media_type: Read only recordings that have this media type. Can be either `audio` or `video`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + source_sid=source_sid, + grouping_sid=grouping_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + media_type=media_type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["RecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + grouping_sid: Union[List[str], object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + media_type: Union["RecordingInstance.Type", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RecordingPage: + """ + Retrieve a single page of RecordingInstance records from the API. + Request is executed immediately + + :param status: Read only the recordings that have this status. Can be: `processing`, `completed`, or `deleted`. + :param source_sid: Read only the recordings that have this `source_sid`. + :param grouping_sid: Read only recordings with this `grouping_sid`, which may include a `participant_sid` and/or a `room_sid`. + :param date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param date_created_before: Read only recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone, given as `YYYY-MM-DDThh:mm:ss+|-hh:mm` or `YYYY-MM-DDThh:mm:ssZ`. + :param media_type: Read only recordings that have this media type. Can be either `audio` or `video`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordingInstance + """ + data = values.of( + { + "Status": status, + "SourceSid": source_sid, + "GroupingSid": serialize.map(grouping_sid, lambda e: e), + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "MediaType": media_type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordingPage(self._version, response) + + async def page_async( + self, + status: Union["RecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + grouping_sid: Union[List[str], object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + media_type: Union["RecordingInstance.Type", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RecordingPage: + """ + Asynchronously retrieve a single page of RecordingInstance records from the API. + Request is executed immediately + + :param status: Read only the recordings that have this status. Can be: `processing`, `completed`, or `deleted`. + :param source_sid: Read only the recordings that have this `source_sid`. + :param grouping_sid: Read only recordings with this `grouping_sid`, which may include a `participant_sid` and/or a `room_sid`. + :param date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param date_created_before: Read only recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone, given as `YYYY-MM-DDThh:mm:ss+|-hh:mm` or `YYYY-MM-DDThh:mm:ssZ`. + :param media_type: Read only recordings that have this media type. Can be either `audio` or `video`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordingInstance + """ + data = values.of( + { + "Status": status, + "SourceSid": source_sid, + "GroupingSid": serialize.map(grouping_sid, lambda e: e), + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "MediaType": media_type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordingPage(self._version, response) + + def get_page(self, target_url: str) -> RecordingPage: + """ + Retrieve a specific page of RecordingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RecordingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RecordingPage(self._version, response) + + async def get_page_async(self, target_url: str) -> RecordingPage: + """ + Asynchronously retrieve a specific page of RecordingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RecordingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RecordingPage(self._version, response) + + def get(self, sid: str) -> RecordingContext: + """ + Constructs a RecordingContext + + :param sid: The SID of the Recording resource to fetch. + """ + return RecordingContext(self._version, sid=sid) + + def __call__(self, sid: str) -> RecordingContext: + """ + Constructs a RecordingContext + + :param sid: The SID of the Recording resource to fetch. + """ + return RecordingContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/recording_settings.py b/venv/Lib/site-packages/twilio/rest/video/v1/recording_settings.py new file mode 100644 index 00000000..46259b6c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/video/v1/recording_settings.py @@ -0,0 +1,318 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class RecordingSettingsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the RecordingSettings resource. + :ivar friendly_name: The string that you assigned to describe the resource and show the user in the console + :ivar aws_credentials_sid: The SID of the stored Credential resource. + :ivar aws_s3_url: The URL of the AWS S3 bucket where the recordings are stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/recordings`, where `recordings` is the path in which you want the recordings to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :ivar aws_storage_enabled: Whether all recordings are written to the `aws_s3_url`. When `false`, all recordings are stored in our cloud. + :ivar encryption_key_sid: The SID of the Public Key resource used for encryption. + :ivar encryption_enabled: Whether all recordings are stored in an encrypted form. The default is `false`. + :ivar url: The absolute URL of the resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.aws_credentials_sid: Optional[str] = payload.get("aws_credentials_sid") + self.aws_s3_url: Optional[str] = payload.get("aws_s3_url") + self.aws_storage_enabled: Optional[bool] = payload.get("aws_storage_enabled") + self.encryption_key_sid: Optional[str] = payload.get("encryption_key_sid") + self.encryption_enabled: Optional[bool] = payload.get("encryption_enabled") + self.url: Optional[str] = payload.get("url") + + self._context: Optional[RecordingSettingsContext] = None + + @property + def _proxy(self) -> "RecordingSettingsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RecordingSettingsContext for this RecordingSettingsInstance + """ + if self._context is None: + self._context = RecordingSettingsContext( + self._version, + ) + return self._context + + def create( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> "RecordingSettingsInstance": + """ + Create the RecordingSettingsInstance + + :param friendly_name: A descriptive string that you create to describe the resource and be shown to users in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the recordings should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/recordings`, where `recordings` is the path in which you want the recordings to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all recordings should be written to the `aws_s3_url`. When `false`, all recordings are stored in our cloud. + :param encryption_enabled: Whether all recordings should be stored in an encrypted form. The default is `false`. + + :returns: The created RecordingSettingsInstance + """ + return self._proxy.create( + friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + + async def create_async( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> "RecordingSettingsInstance": + """ + Asynchronous coroutine to create the RecordingSettingsInstance + + :param friendly_name: A descriptive string that you create to describe the resource and be shown to users in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the recordings should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/recordings`, where `recordings` is the path in which you want the recordings to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all recordings should be written to the `aws_s3_url`. When `false`, all recordings are stored in our cloud. + :param encryption_enabled: Whether all recordings should be stored in an encrypted form. The default is `false`. + + :returns: The created RecordingSettingsInstance + """ + return await self._proxy.create_async( + friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + + def fetch(self) -> "RecordingSettingsInstance": + """ + Fetch the RecordingSettingsInstance + + + :returns: The fetched RecordingSettingsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RecordingSettingsInstance": + """ + Asynchronous coroutine to fetch the RecordingSettingsInstance + + + :returns: The fetched RecordingSettingsInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class RecordingSettingsContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the RecordingSettingsContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/RecordingSettings/Default" + + def create( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> RecordingSettingsInstance: + """ + Create the RecordingSettingsInstance + + :param friendly_name: A descriptive string that you create to describe the resource and be shown to users in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the recordings should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/recordings`, where `recordings` is the path in which you want the recordings to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all recordings should be written to the `aws_s3_url`. When `false`, all recordings are stored in our cloud. + :param encryption_enabled: Whether all recordings should be stored in an encrypted form. The default is `false`. + + :returns: The created RecordingSettingsInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "AwsCredentialsSid": aws_credentials_sid, + "EncryptionKeySid": encryption_key_sid, + "AwsS3Url": aws_s3_url, + "AwsStorageEnabled": serialize.boolean_to_string(aws_storage_enabled), + "EncryptionEnabled": serialize.boolean_to_string(encryption_enabled), + } + ) + + payload = self._version.create(method="POST", uri=self._uri, data=data) + + return RecordingSettingsInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> RecordingSettingsInstance: + """ + Asynchronous coroutine to create the RecordingSettingsInstance + + :param friendly_name: A descriptive string that you create to describe the resource and be shown to users in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the recordings should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/recordings`, where `recordings` is the path in which you want the recordings to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all recordings should be written to the `aws_s3_url`. When `false`, all recordings are stored in our cloud. + :param encryption_enabled: Whether all recordings should be stored in an encrypted form. The default is `false`. + + :returns: The created RecordingSettingsInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "AwsCredentialsSid": aws_credentials_sid, + "EncryptionKeySid": encryption_key_sid, + "AwsS3Url": aws_s3_url, + "AwsStorageEnabled": serialize.boolean_to_string(aws_storage_enabled), + "EncryptionEnabled": serialize.boolean_to_string(encryption_enabled), + } + ) + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data + ) + + return RecordingSettingsInstance(self._version, payload) + + def fetch(self) -> RecordingSettingsInstance: + """ + Fetch the RecordingSettingsInstance + + + :returns: The fetched RecordingSettingsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RecordingSettingsInstance( + self._version, + payload, + ) + + async def fetch_async(self) -> RecordingSettingsInstance: + """ + Asynchronous coroutine to fetch the RecordingSettingsInstance + + + :returns: The fetched RecordingSettingsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RecordingSettingsInstance( + self._version, + payload, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class RecordingSettingsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the RecordingSettingsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> RecordingSettingsContext: + """ + Constructs a RecordingSettingsContext + + """ + return RecordingSettingsContext(self._version) + + def __call__(self) -> RecordingSettingsContext: + """ + Constructs a RecordingSettingsContext + + """ + return RecordingSettingsContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/room/__init__.py b/venv/Lib/site-packages/twilio/rest/video/v1/room/__init__.py new file mode 100644 index 00000000..d51b8b87 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/video/v1/room/__init__.py @@ -0,0 +1,867 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.video.v1.room.participant import ParticipantList +from twilio.rest.video.v1.room.recording_rules import RecordingRulesList +from twilio.rest.video.v1.room.room_recording import RoomRecordingList + + +class RoomInstance(InstanceResource): + + class RoomStatus(object): + IN_PROGRESS = "in-progress" + COMPLETED = "completed" + FAILED = "failed" + + class RoomType(object): + GO = "go" + PEER_TO_PEER = "peer-to-peer" + GROUP = "group" + GROUP_SMALL = "group-small" + + class VideoCodec(object): + VP8 = "VP8" + H264 = "H264" + + """ + :ivar sid: The unique string that Twilio created to identify the Room resource. + :ivar status: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Room resource. + :ivar enable_turn: Deprecated, now always considered to be true. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used as a `room_sid` in place of the resource's `sid` in the URL to address the resource, assuming it does not contain any [reserved characters](https://tools.ietf.org/html/rfc3986#section-2.2) that would need to be URL encoded. This value is unique for `in-progress` rooms. SDK clients can use this name to connect to the room. REST API clients can use this name in place of the Room SID to interact with the room as long as the room is `in-progress`. + :ivar status_callback: The URL Twilio calls using the `status_callback_method` to send status information to your application on every room event. See [Status Callbacks](https://www.twilio.com/docs/video/api/status-callbacks) for more info. + :ivar status_callback_method: The HTTP method Twilio uses to call `status_callback`. Can be `POST` or `GET` and defaults to `POST`. + :ivar end_time: The UTC end time of the room in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :ivar duration: The duration of the room in seconds. + :ivar type: + :ivar max_participants: The maximum number of concurrent Participants allowed in the room. + :ivar max_participant_duration: The maximum number of seconds a Participant can be connected to the room. The maximum possible value is 86400 seconds (24 hours). The default is 14400 seconds (4 hours). + :ivar max_concurrent_published_tracks: The maximum number of published audio, video, and data tracks all participants combined are allowed to publish in the room at the same time. Check [Programmable Video Limits](https://www.twilio.com/docs/video/programmable-video-limits) for more details. If it is set to 0 it means unconstrained. + :ivar record_participants_on_connect: Whether to start recording when Participants connect. + :ivar video_codecs: An array of the video codecs that are supported when publishing a track in the room. Can be: `VP8` and `H264`. + :ivar media_region: The region for the Room's media server. Can be one of the [available Media Regions](https://www.twilio.com/docs/video/ip-addresses#media-servers). + :ivar audio_only: When set to true, indicates that the participants in the room will only publish audio. No video tracks will be allowed. + :ivar empty_room_timeout: Specifies how long (in minutes) a room will remain active after last participant leaves. Can be configured when creating a room via REST API. For Ad-Hoc rooms this value cannot be changed. + :ivar unused_room_timeout: Specifies how long (in minutes) a room will remain active if no one joins. Can be configured when creating a room via REST API. For Ad-Hoc rooms this value cannot be changed. + :ivar large_room: Indicates if this is a large room. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.status: Optional["RoomInstance.RoomStatus"] = payload.get("status") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.account_sid: Optional[str] = payload.get("account_sid") + self.enable_turn: Optional[bool] = payload.get("enable_turn") + self.unique_name: Optional[str] = payload.get("unique_name") + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.duration: Optional[int] = deserialize.integer(payload.get("duration")) + self.type: Optional["RoomInstance.RoomType"] = payload.get("type") + self.max_participants: Optional[int] = deserialize.integer( + payload.get("max_participants") + ) + self.max_participant_duration: Optional[int] = deserialize.integer( + payload.get("max_participant_duration") + ) + self.max_concurrent_published_tracks: Optional[int] = deserialize.integer( + payload.get("max_concurrent_published_tracks") + ) + self.record_participants_on_connect: Optional[bool] = payload.get( + "record_participants_on_connect" + ) + self.video_codecs: Optional[List["RoomInstance.VideoCodec"]] = payload.get( + "video_codecs" + ) + self.media_region: Optional[str] = payload.get("media_region") + self.audio_only: Optional[bool] = payload.get("audio_only") + self.empty_room_timeout: Optional[int] = deserialize.integer( + payload.get("empty_room_timeout") + ) + self.unused_room_timeout: Optional[int] = deserialize.integer( + payload.get("unused_room_timeout") + ) + self.large_room: Optional[bool] = payload.get("large_room") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[RoomContext] = None + + @property + def _proxy(self) -> "RoomContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RoomContext for this RoomInstance + """ + if self._context is None: + self._context = RoomContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "RoomInstance": + """ + Fetch the RoomInstance + + + :returns: The fetched RoomInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RoomInstance": + """ + Asynchronous coroutine to fetch the RoomInstance + + + :returns: The fetched RoomInstance + """ + return await self._proxy.fetch_async() + + def update(self, status: "RoomInstance.RoomStatus") -> "RoomInstance": + """ + Update the RoomInstance + + :param status: + + :returns: The updated RoomInstance + """ + return self._proxy.update( + status=status, + ) + + async def update_async(self, status: "RoomInstance.RoomStatus") -> "RoomInstance": + """ + Asynchronous coroutine to update the RoomInstance + + :param status: + + :returns: The updated RoomInstance + """ + return await self._proxy.update_async( + status=status, + ) + + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + return self._proxy.participants + + @property + def recording_rules(self) -> RecordingRulesList: + """ + Access the recording_rules + """ + return self._proxy.recording_rules + + @property + def recordings(self) -> RoomRecordingList: + """ + Access the recordings + """ + return self._proxy.recordings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RoomContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the RoomContext + + :param version: Version that contains the resource + :param sid: The SID of the Room resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Rooms/{sid}".format(**self._solution) + + self._participants: Optional[ParticipantList] = None + self._recording_rules: Optional[RecordingRulesList] = None + self._recordings: Optional[RoomRecordingList] = None + + def fetch(self) -> RoomInstance: + """ + Fetch the RoomInstance + + + :returns: The fetched RoomInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RoomInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RoomInstance: + """ + Asynchronous coroutine to fetch the RoomInstance + + + :returns: The fetched RoomInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RoomInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update(self, status: "RoomInstance.RoomStatus") -> RoomInstance: + """ + Update the RoomInstance + + :param status: + + :returns: The updated RoomInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoomInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async(self, status: "RoomInstance.RoomStatus") -> RoomInstance: + """ + Asynchronous coroutine to update the RoomInstance + + :param status: + + :returns: The updated RoomInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoomInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + if self._participants is None: + self._participants = ParticipantList( + self._version, + self._solution["sid"], + ) + return self._participants + + @property + def recording_rules(self) -> RecordingRulesList: + """ + Access the recording_rules + """ + if self._recording_rules is None: + self._recording_rules = RecordingRulesList( + self._version, + self._solution["sid"], + ) + return self._recording_rules + + @property + def recordings(self) -> RoomRecordingList: + """ + Access the recordings + """ + if self._recordings is None: + self._recordings = RoomRecordingList( + self._version, + self._solution["sid"], + ) + return self._recordings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RoomPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RoomInstance: + """ + Build an instance of RoomInstance + + :param payload: Payload response from the API + """ + return RoomInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RoomList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the RoomList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Rooms" + + def create( + self, + enable_turn: Union[bool, object] = values.unset, + type: Union["RoomInstance.RoomType", object] = values.unset, + unique_name: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + max_participants: Union[int, object] = values.unset, + record_participants_on_connect: Union[bool, object] = values.unset, + transcribe_participants_on_connect: Union[bool, object] = values.unset, + video_codecs: Union[List["RoomInstance.VideoCodec"], object] = values.unset, + media_region: Union[str, object] = values.unset, + recording_rules: Union[object, object] = values.unset, + transcriptions_configuration: Union[object, object] = values.unset, + audio_only: Union[bool, object] = values.unset, + max_participant_duration: Union[int, object] = values.unset, + empty_room_timeout: Union[int, object] = values.unset, + unused_room_timeout: Union[int, object] = values.unset, + large_room: Union[bool, object] = values.unset, + ) -> RoomInstance: + """ + Create the RoomInstance + + :param enable_turn: Deprecated, now always considered to be true. + :param type: + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as a `room_sid` in place of the resource's `sid` in the URL to address the resource, assuming it does not contain any [reserved characters](https://tools.ietf.org/html/rfc3986#section-2.2) that would need to be URL encoded. This value is unique for `in-progress` rooms. SDK clients can use this name to connect to the room. REST API clients can use this name in place of the Room SID to interact with the room as long as the room is `in-progress`. + :param status_callback: The URL Twilio should call using the `status_callback_method` to send status information to your application on every room event. See [Status Callbacks](https://www.twilio.com/docs/video/api/status-callbacks) for more info. + :param status_callback_method: The HTTP method Twilio should use to call `status_callback`. Can be `POST` or `GET`. + :param max_participants: The maximum number of concurrent Participants allowed in the room. The maximum allowed value is 50. + :param record_participants_on_connect: Whether to start recording when Participants connect. + :param transcribe_participants_on_connect: Whether to start transcriptions when Participants connect. If TranscriptionsConfiguration is not provided, default settings will be used. + :param video_codecs: An array of the video codecs that are supported when publishing a track in the room. Can be: `VP8` and `H264`. + :param media_region: The region for the Room's media server. Can be one of the [available Media Regions](https://www.twilio.com/docs/video/ip-addresses#group-rooms-media-servers). + :param recording_rules: A collection of Recording Rules that describe how to include or exclude matching tracks for recording + :param transcriptions_configuration: A collection of properties that describe transcription behaviour. If TranscribeParticipantsOnConnect is set to true and TranscriptionsConfiguration is not provided, default settings will be used. + :param audio_only: When set to true, indicates that the participants in the room will only publish audio. No video tracks will be allowed. + :param max_participant_duration: The maximum number of seconds a Participant can be connected to the room. The maximum possible value is 86400 seconds (24 hours). The default is 14400 seconds (4 hours). + :param empty_room_timeout: Configures how long (in minutes) a room will remain active after last participant leaves. Valid values range from 1 to 60 minutes (no fractions). + :param unused_room_timeout: Configures how long (in minutes) a room will remain active if no one joins. Valid values range from 1 to 60 minutes (no fractions). + :param large_room: When set to true, indicated that this is the large room. + + :returns: The created RoomInstance + """ + + data = values.of( + { + "EnableTurn": serialize.boolean_to_string(enable_turn), + "Type": type, + "UniqueName": unique_name, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "MaxParticipants": max_participants, + "RecordParticipantsOnConnect": serialize.boolean_to_string( + record_participants_on_connect + ), + "TranscribeParticipantsOnConnect": serialize.boolean_to_string( + transcribe_participants_on_connect + ), + "VideoCodecs": serialize.map(video_codecs, lambda e: e), + "MediaRegion": media_region, + "RecordingRules": serialize.object(recording_rules), + "TranscriptionsConfiguration": serialize.object( + transcriptions_configuration + ), + "AudioOnly": serialize.boolean_to_string(audio_only), + "MaxParticipantDuration": max_participant_duration, + "EmptyRoomTimeout": empty_room_timeout, + "UnusedRoomTimeout": unused_room_timeout, + "LargeRoom": serialize.boolean_to_string(large_room), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoomInstance(self._version, payload) + + async def create_async( + self, + enable_turn: Union[bool, object] = values.unset, + type: Union["RoomInstance.RoomType", object] = values.unset, + unique_name: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + max_participants: Union[int, object] = values.unset, + record_participants_on_connect: Union[bool, object] = values.unset, + transcribe_participants_on_connect: Union[bool, object] = values.unset, + video_codecs: Union[List["RoomInstance.VideoCodec"], object] = values.unset, + media_region: Union[str, object] = values.unset, + recording_rules: Union[object, object] = values.unset, + transcriptions_configuration: Union[object, object] = values.unset, + audio_only: Union[bool, object] = values.unset, + max_participant_duration: Union[int, object] = values.unset, + empty_room_timeout: Union[int, object] = values.unset, + unused_room_timeout: Union[int, object] = values.unset, + large_room: Union[bool, object] = values.unset, + ) -> RoomInstance: + """ + Asynchronously create the RoomInstance + + :param enable_turn: Deprecated, now always considered to be true. + :param type: + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as a `room_sid` in place of the resource's `sid` in the URL to address the resource, assuming it does not contain any [reserved characters](https://tools.ietf.org/html/rfc3986#section-2.2) that would need to be URL encoded. This value is unique for `in-progress` rooms. SDK clients can use this name to connect to the room. REST API clients can use this name in place of the Room SID to interact with the room as long as the room is `in-progress`. + :param status_callback: The URL Twilio should call using the `status_callback_method` to send status information to your application on every room event. See [Status Callbacks](https://www.twilio.com/docs/video/api/status-callbacks) for more info. + :param status_callback_method: The HTTP method Twilio should use to call `status_callback`. Can be `POST` or `GET`. + :param max_participants: The maximum number of concurrent Participants allowed in the room. The maximum allowed value is 50. + :param record_participants_on_connect: Whether to start recording when Participants connect. + :param transcribe_participants_on_connect: Whether to start transcriptions when Participants connect. If TranscriptionsConfiguration is not provided, default settings will be used. + :param video_codecs: An array of the video codecs that are supported when publishing a track in the room. Can be: `VP8` and `H264`. + :param media_region: The region for the Room's media server. Can be one of the [available Media Regions](https://www.twilio.com/docs/video/ip-addresses#group-rooms-media-servers). + :param recording_rules: A collection of Recording Rules that describe how to include or exclude matching tracks for recording + :param transcriptions_configuration: A collection of properties that describe transcription behaviour. If TranscribeParticipantsOnConnect is set to true and TranscriptionsConfiguration is not provided, default settings will be used. + :param audio_only: When set to true, indicates that the participants in the room will only publish audio. No video tracks will be allowed. + :param max_participant_duration: The maximum number of seconds a Participant can be connected to the room. The maximum possible value is 86400 seconds (24 hours). The default is 14400 seconds (4 hours). + :param empty_room_timeout: Configures how long (in minutes) a room will remain active after last participant leaves. Valid values range from 1 to 60 minutes (no fractions). + :param unused_room_timeout: Configures how long (in minutes) a room will remain active if no one joins. Valid values range from 1 to 60 minutes (no fractions). + :param large_room: When set to true, indicated that this is the large room. + + :returns: The created RoomInstance + """ + + data = values.of( + { + "EnableTurn": serialize.boolean_to_string(enable_turn), + "Type": type, + "UniqueName": unique_name, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "MaxParticipants": max_participants, + "RecordParticipantsOnConnect": serialize.boolean_to_string( + record_participants_on_connect + ), + "TranscribeParticipantsOnConnect": serialize.boolean_to_string( + transcribe_participants_on_connect + ), + "VideoCodecs": serialize.map(video_codecs, lambda e: e), + "MediaRegion": media_region, + "RecordingRules": serialize.object(recording_rules), + "TranscriptionsConfiguration": serialize.object( + transcriptions_configuration + ), + "AudioOnly": serialize.boolean_to_string(audio_only), + "MaxParticipantDuration": max_participant_duration, + "EmptyRoomTimeout": empty_room_timeout, + "UnusedRoomTimeout": unused_room_timeout, + "LargeRoom": serialize.boolean_to_string(large_room), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoomInstance(self._version, payload) + + def stream( + self, + status: Union["RoomInstance.RoomStatus", object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoomInstance]: + """ + Streams RoomInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "RoomInstance.RoomStatus" status: Read only the rooms with this status. Can be: `in-progress` (default) or `completed` + :param str unique_name: Read only rooms with the this `unique_name`. + :param datetime date_created_after: Read only rooms that started on or after this date, given as `YYYY-MM-DD`. + :param datetime date_created_before: Read only rooms that started before this date, given as `YYYY-MM-DD`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + unique_name=unique_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["RoomInstance.RoomStatus", object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RoomInstance]: + """ + Asynchronously streams RoomInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "RoomInstance.RoomStatus" status: Read only the rooms with this status. Can be: `in-progress` (default) or `completed` + :param str unique_name: Read only rooms with the this `unique_name`. + :param datetime date_created_after: Read only rooms that started on or after this date, given as `YYYY-MM-DD`. + :param datetime date_created_before: Read only rooms that started before this date, given as `YYYY-MM-DD`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + unique_name=unique_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["RoomInstance.RoomStatus", object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoomInstance]: + """ + Lists RoomInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "RoomInstance.RoomStatus" status: Read only the rooms with this status. Can be: `in-progress` (default) or `completed` + :param str unique_name: Read only rooms with the this `unique_name`. + :param datetime date_created_after: Read only rooms that started on or after this date, given as `YYYY-MM-DD`. + :param datetime date_created_before: Read only rooms that started before this date, given as `YYYY-MM-DD`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + unique_name=unique_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["RoomInstance.RoomStatus", object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoomInstance]: + """ + Asynchronously lists RoomInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "RoomInstance.RoomStatus" status: Read only the rooms with this status. Can be: `in-progress` (default) or `completed` + :param str unique_name: Read only rooms with the this `unique_name`. + :param datetime date_created_after: Read only rooms that started on or after this date, given as `YYYY-MM-DD`. + :param datetime date_created_before: Read only rooms that started before this date, given as `YYYY-MM-DD`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + unique_name=unique_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["RoomInstance.RoomStatus", object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RoomPage: + """ + Retrieve a single page of RoomInstance records from the API. + Request is executed immediately + + :param status: Read only the rooms with this status. Can be: `in-progress` (default) or `completed` + :param unique_name: Read only rooms with the this `unique_name`. + :param date_created_after: Read only rooms that started on or after this date, given as `YYYY-MM-DD`. + :param date_created_before: Read only rooms that started before this date, given as `YYYY-MM-DD`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoomInstance + """ + data = values.of( + { + "Status": status, + "UniqueName": unique_name, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RoomPage(self._version, response) + + async def page_async( + self, + status: Union["RoomInstance.RoomStatus", object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RoomPage: + """ + Asynchronously retrieve a single page of RoomInstance records from the API. + Request is executed immediately + + :param status: Read only the rooms with this status. Can be: `in-progress` (default) or `completed` + :param unique_name: Read only rooms with the this `unique_name`. + :param date_created_after: Read only rooms that started on or after this date, given as `YYYY-MM-DD`. + :param date_created_before: Read only rooms that started before this date, given as `YYYY-MM-DD`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoomInstance + """ + data = values.of( + { + "Status": status, + "UniqueName": unique_name, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RoomPage(self._version, response) + + def get_page(self, target_url: str) -> RoomPage: + """ + Retrieve a specific page of RoomInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoomInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RoomPage(self._version, response) + + async def get_page_async(self, target_url: str) -> RoomPage: + """ + Asynchronously retrieve a specific page of RoomInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoomInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RoomPage(self._version, response) + + def get(self, sid: str) -> RoomContext: + """ + Constructs a RoomContext + + :param sid: The SID of the Room resource to update. + """ + return RoomContext(self._version, sid=sid) + + def __call__(self, sid: str) -> RoomContext: + """ + Constructs a RoomContext + + :param sid: The SID of the Room resource to update. + """ + return RoomContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/room/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/video/v1/room/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..9c2caa30 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/video/v1/room/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/room/__pycache__/recording_rules.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/video/v1/room/__pycache__/recording_rules.cpython-312.pyc new file mode 100644 index 00000000..b0e24699 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/video/v1/room/__pycache__/recording_rules.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/room/__pycache__/room_recording.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/video/v1/room/__pycache__/room_recording.cpython-312.pyc new file mode 100644 index 00000000..47c846a1 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/video/v1/room/__pycache__/room_recording.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/__init__.py b/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/__init__.py new file mode 100644 index 00000000..7e012e8d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/__init__.py @@ -0,0 +1,717 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.video.v1.room.participant.anonymize import AnonymizeList +from twilio.rest.video.v1.room.participant.published_track import PublishedTrackList +from twilio.rest.video.v1.room.participant.subscribe_rules import SubscribeRulesList +from twilio.rest.video.v1.room.participant.subscribed_track import SubscribedTrackList + + +class ParticipantInstance(InstanceResource): + + class Status(object): + CONNECTED = "connected" + DISCONNECTED = "disconnected" + RECONNECTING = "reconnecting" + + """ + :ivar sid: The unique string that we created to identify the RoomParticipant resource. + :ivar room_sid: The SID of the participant's room. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the RoomParticipant resource. + :ivar status: + :ivar identity: The application-defined string that uniquely identifies the resource's User within a Room. If a client joins with an existing Identity, the existing client is disconnected. See [access tokens](https://www.twilio.com/docs/video/tutorials/user-identity-access-tokens) and [limits](https://www.twilio.com/docs/video/programmable-video-limits) for more info. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar start_time: The time of participant connected to the room in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :ivar end_time: The time when the participant disconnected from the room in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :ivar duration: The duration in seconds that the participant was `connected`. Populated only after the participant is `disconnected`. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + room_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.room_sid: Optional[str] = payload.get("room_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.status: Optional["ParticipantInstance.Status"] = payload.get("status") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.duration: Optional[int] = deserialize.integer(payload.get("duration")) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "room_sid": room_sid, + "sid": sid or self.sid, + } + self._context: Optional[ParticipantContext] = None + + @property + def _proxy(self) -> "ParticipantContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ParticipantContext for this ParticipantInstance + """ + if self._context is None: + self._context = ParticipantContext( + self._version, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "ParticipantInstance": + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ParticipantInstance": + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return await self._proxy.fetch_async() + + def update( + self, status: Union["ParticipantInstance.Status", object] = values.unset + ) -> "ParticipantInstance": + """ + Update the ParticipantInstance + + :param status: + + :returns: The updated ParticipantInstance + """ + return self._proxy.update( + status=status, + ) + + async def update_async( + self, status: Union["ParticipantInstance.Status", object] = values.unset + ) -> "ParticipantInstance": + """ + Asynchronous coroutine to update the ParticipantInstance + + :param status: + + :returns: The updated ParticipantInstance + """ + return await self._proxy.update_async( + status=status, + ) + + @property + def anonymize(self) -> AnonymizeList: + """ + Access the anonymize + """ + return self._proxy.anonymize + + @property + def published_tracks(self) -> PublishedTrackList: + """ + Access the published_tracks + """ + return self._proxy.published_tracks + + @property + def subscribe_rules(self) -> SubscribeRulesList: + """ + Access the subscribe_rules + """ + return self._proxy.subscribe_rules + + @property + def subscribed_tracks(self) -> SubscribedTrackList: + """ + Access the subscribed_tracks + """ + return self._proxy.subscribed_tracks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ParticipantContext(InstanceContext): + + def __init__(self, version: Version, room_sid: str, sid: str): + """ + Initialize the ParticipantContext + + :param version: Version that contains the resource + :param room_sid: The SID of the room with the participant to update. + :param sid: The SID of the RoomParticipant resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + "sid": sid, + } + self._uri = "/Rooms/{room_sid}/Participants/{sid}".format(**self._solution) + + self._anonymize: Optional[AnonymizeList] = None + self._published_tracks: Optional[PublishedTrackList] = None + self._subscribe_rules: Optional[SubscribeRulesList] = None + self._subscribed_tracks: Optional[SubscribedTrackList] = None + + def fetch(self) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ParticipantInstance: + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + def update( + self, status: Union["ParticipantInstance.Status", object] = values.unset + ) -> ParticipantInstance: + """ + Update the ParticipantInstance + + :param status: + + :returns: The updated ParticipantInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, status: Union["ParticipantInstance.Status", object] = values.unset + ) -> ParticipantInstance: + """ + Asynchronous coroutine to update the ParticipantInstance + + :param status: + + :returns: The updated ParticipantInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + @property + def anonymize(self) -> AnonymizeList: + """ + Access the anonymize + """ + if self._anonymize is None: + self._anonymize = AnonymizeList( + self._version, + self._solution["room_sid"], + self._solution["sid"], + ) + return self._anonymize + + @property + def published_tracks(self) -> PublishedTrackList: + """ + Access the published_tracks + """ + if self._published_tracks is None: + self._published_tracks = PublishedTrackList( + self._version, + self._solution["room_sid"], + self._solution["sid"], + ) + return self._published_tracks + + @property + def subscribe_rules(self) -> SubscribeRulesList: + """ + Access the subscribe_rules + """ + if self._subscribe_rules is None: + self._subscribe_rules = SubscribeRulesList( + self._version, + self._solution["room_sid"], + self._solution["sid"], + ) + return self._subscribe_rules + + @property + def subscribed_tracks(self) -> SubscribedTrackList: + """ + Access the subscribed_tracks + """ + if self._subscribed_tracks is None: + self._subscribed_tracks = SubscribedTrackList( + self._version, + self._solution["room_sid"], + self._solution["sid"], + ) + return self._subscribed_tracks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ParticipantPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: + """ + Build an instance of ParticipantInstance + + :param payload: Payload response from the API + """ + return ParticipantInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ParticipantList(ListResource): + + def __init__(self, version: Version, room_sid: str): + """ + Initialize the ParticipantList + + :param version: Version that contains the resource + :param room_sid: The SID of the room with the Participant resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + } + self._uri = "/Rooms/{room_sid}/Participants".format(**self._solution) + + def stream( + self, + status: Union["ParticipantInstance.Status", object] = values.unset, + identity: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ParticipantInstance]: + """ + Streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "ParticipantInstance.Status" status: Read only the participants with this status. Can be: `connected` or `disconnected`. For `in-progress` Rooms the default Status is `connected`, for `completed` Rooms only `disconnected` Participants are returned. + :param str identity: Read only the Participants with this [User](https://www.twilio.com/docs/chat/rest/user-resource) `identity` value. + :param datetime date_created_after: Read only Participants that started after this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param datetime date_created_before: Read only Participants that started before this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + identity=identity, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["ParticipantInstance.Status", object] = values.unset, + identity: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ParticipantInstance]: + """ + Asynchronously streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "ParticipantInstance.Status" status: Read only the participants with this status. Can be: `connected` or `disconnected`. For `in-progress` Rooms the default Status is `connected`, for `completed` Rooms only `disconnected` Participants are returned. + :param str identity: Read only the Participants with this [User](https://www.twilio.com/docs/chat/rest/user-resource) `identity` value. + :param datetime date_created_after: Read only Participants that started after this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param datetime date_created_before: Read only Participants that started before this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + identity=identity, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["ParticipantInstance.Status", object] = values.unset, + identity: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "ParticipantInstance.Status" status: Read only the participants with this status. Can be: `connected` or `disconnected`. For `in-progress` Rooms the default Status is `connected`, for `completed` Rooms only `disconnected` Participants are returned. + :param str identity: Read only the Participants with this [User](https://www.twilio.com/docs/chat/rest/user-resource) `identity` value. + :param datetime date_created_after: Read only Participants that started after this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param datetime date_created_before: Read only Participants that started before this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + identity=identity, + date_created_after=date_created_after, + date_created_before=date_created_before, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["ParticipantInstance.Status", object] = values.unset, + identity: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Asynchronously lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "ParticipantInstance.Status" status: Read only the participants with this status. Can be: `connected` or `disconnected`. For `in-progress` Rooms the default Status is `connected`, for `completed` Rooms only `disconnected` Participants are returned. + :param str identity: Read only the Participants with this [User](https://www.twilio.com/docs/chat/rest/user-resource) `identity` value. + :param datetime date_created_after: Read only Participants that started after this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param datetime date_created_before: Read only Participants that started before this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + identity=identity, + date_created_after=date_created_after, + date_created_before=date_created_before, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["ParticipantInstance.Status", object] = values.unset, + identity: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param status: Read only the participants with this status. Can be: `connected` or `disconnected`. For `in-progress` Rooms the default Status is `connected`, for `completed` Rooms only `disconnected` Participants are returned. + :param identity: Read only the Participants with this [User](https://www.twilio.com/docs/chat/rest/user-resource) `identity` value. + :param date_created_after: Read only Participants that started after this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param date_created_before: Read only Participants that started before this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "Status": status, + "Identity": identity, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) + + async def page_async( + self, + status: Union["ParticipantInstance.Status", object] = values.unset, + identity: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Asynchronously retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param status: Read only the participants with this status. Can be: `connected` or `disconnected`. For `in-progress` Rooms the default Status is `connected`, for `completed` Rooms only `disconnected` Participants are returned. + :param identity: Read only the Participants with this [User](https://www.twilio.com/docs/chat/rest/user-resource) `identity` value. + :param date_created_after: Read only Participants that started after this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param date_created_before: Read only Participants that started before this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "Status": status, + "Identity": identity, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ParticipantPage: + """ + Retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ParticipantPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ParticipantPage: + """ + Asynchronously retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ParticipantPage(self._version, response, self._solution) + + def get(self, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param sid: The SID of the RoomParticipant resource to update. + """ + return ParticipantContext( + self._version, room_sid=self._solution["room_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param sid: The SID of the RoomParticipant resource to update. + """ + return ParticipantContext( + self._version, room_sid=self._solution["room_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..01ec912e Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/__pycache__/anonymize.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/__pycache__/anonymize.cpython-312.pyc new file mode 100644 index 00000000..d66ba857 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/__pycache__/anonymize.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/__pycache__/published_track.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/__pycache__/published_track.cpython-312.pyc new file mode 100644 index 00000000..1358c962 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/__pycache__/published_track.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/__pycache__/subscribe_rules.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/__pycache__/subscribe_rules.cpython-312.pyc new file mode 100644 index 00000000..dc6eefd8 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/__pycache__/subscribe_rules.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/__pycache__/subscribed_track.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/__pycache__/subscribed_track.cpython-312.pyc new file mode 100644 index 00000000..6452ba31 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/__pycache__/subscribed_track.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/anonymize.py b/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/anonymize.py new file mode 100644 index 00000000..0560d3ef --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/anonymize.py @@ -0,0 +1,245 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class AnonymizeInstance(InstanceResource): + + class Status(object): + CONNECTED = "connected" + DISCONNECTED = "disconnected" + + """ + :ivar sid: The unique string that we created to identify the RoomParticipant resource. + :ivar room_sid: The SID of the participant's room. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the RoomParticipant resource. + :ivar status: + :ivar identity: The SID of the participant. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar start_time: The time of participant connected to the room in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :ivar end_time: The time when the participant disconnected from the room in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :ivar duration: The duration in seconds that the participant was `connected`. Populated only after the participant is `disconnected`. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], room_sid: str, sid: str + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.room_sid: Optional[str] = payload.get("room_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.status: Optional["AnonymizeInstance.Status"] = payload.get("status") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.duration: Optional[int] = deserialize.integer(payload.get("duration")) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "room_sid": room_sid, + "sid": sid, + } + self._context: Optional[AnonymizeContext] = None + + @property + def _proxy(self) -> "AnonymizeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AnonymizeContext for this AnonymizeInstance + """ + if self._context is None: + self._context = AnonymizeContext( + self._version, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + return self._context + + def update(self) -> "AnonymizeInstance": + """ + Update the AnonymizeInstance + + + :returns: The updated AnonymizeInstance + """ + return self._proxy.update() + + async def update_async(self) -> "AnonymizeInstance": + """ + Asynchronous coroutine to update the AnonymizeInstance + + + :returns: The updated AnonymizeInstance + """ + return await self._proxy.update_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AnonymizeContext(InstanceContext): + + def __init__(self, version: Version, room_sid: str, sid: str): + """ + Initialize the AnonymizeContext + + :param version: Version that contains the resource + :param room_sid: The SID of the room with the participant to update. + :param sid: The SID of the RoomParticipant resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + "sid": sid, + } + self._uri = "/Rooms/{room_sid}/Participants/{sid}/Anonymize".format( + **self._solution + ) + + def update(self) -> AnonymizeInstance: + """ + Update the AnonymizeInstance + + + :returns: The updated AnonymizeInstance + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AnonymizeInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self) -> AnonymizeInstance: + """ + Asynchronous coroutine to update the AnonymizeInstance + + + :returns: The updated AnonymizeInstance + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AnonymizeInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AnonymizeList(ListResource): + + def __init__(self, version: Version, room_sid: str, sid: str): + """ + Initialize the AnonymizeList + + :param version: Version that contains the resource + :param room_sid: The SID of the room with the participant to update. + :param sid: The SID of the RoomParticipant resource to update. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + "sid": sid, + } + + def get(self) -> AnonymizeContext: + """ + Constructs a AnonymizeContext + + """ + return AnonymizeContext( + self._version, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + def __call__(self) -> AnonymizeContext: + """ + Constructs a AnonymizeContext + + """ + return AnonymizeContext( + self._version, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/published_track.py b/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/published_track.py new file mode 100644 index 00000000..a766b276 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/published_track.py @@ -0,0 +1,472 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class PublishedTrackInstance(InstanceResource): + + class Kind(object): + AUDIO = "audio" + VIDEO = "video" + DATA = "data" + + """ + :ivar sid: The unique string that we created to identify the RoomParticipantPublishedTrack resource. + :ivar participant_sid: The SID of the Participant resource with the published track. + :ivar room_sid: The SID of the Room resource where the track is published. + :ivar name: The track name. Must be no more than 128 characters, and be unique among the participant's published tracks. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar enabled: Whether the track is enabled. + :ivar kind: + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + room_sid: str, + participant_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.room_sid: Optional[str] = payload.get("room_sid") + self.name: Optional[str] = payload.get("name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.enabled: Optional[bool] = payload.get("enabled") + self.kind: Optional["PublishedTrackInstance.Kind"] = payload.get("kind") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "room_sid": room_sid, + "participant_sid": participant_sid, + "sid": sid or self.sid, + } + self._context: Optional[PublishedTrackContext] = None + + @property + def _proxy(self) -> "PublishedTrackContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PublishedTrackContext for this PublishedTrackInstance + """ + if self._context is None: + self._context = PublishedTrackContext( + self._version, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "PublishedTrackInstance": + """ + Fetch the PublishedTrackInstance + + + :returns: The fetched PublishedTrackInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PublishedTrackInstance": + """ + Asynchronous coroutine to fetch the PublishedTrackInstance + + + :returns: The fetched PublishedTrackInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PublishedTrackContext(InstanceContext): + + def __init__(self, version: Version, room_sid: str, participant_sid: str, sid: str): + """ + Initialize the PublishedTrackContext + + :param version: Version that contains the resource + :param room_sid: The SID of the Room resource where the Track resource to fetch is published. + :param participant_sid: The SID of the Participant resource with the published track to fetch. + :param sid: The SID of the RoomParticipantPublishedTrack resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + "participant_sid": participant_sid, + "sid": sid, + } + self._uri = "/Rooms/{room_sid}/Participants/{participant_sid}/PublishedTracks/{sid}".format( + **self._solution + ) + + def fetch(self) -> PublishedTrackInstance: + """ + Fetch the PublishedTrackInstance + + + :returns: The fetched PublishedTrackInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PublishedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> PublishedTrackInstance: + """ + Asynchronous coroutine to fetch the PublishedTrackInstance + + + :returns: The fetched PublishedTrackInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PublishedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PublishedTrackPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PublishedTrackInstance: + """ + Build an instance of PublishedTrackInstance + + :param payload: Payload response from the API + """ + return PublishedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class PublishedTrackList(ListResource): + + def __init__(self, version: Version, room_sid: str, participant_sid: str): + """ + Initialize the PublishedTrackList + + :param version: Version that contains the resource + :param room_sid: The SID of the Room resource where the Track resources to read are published. + :param participant_sid: The SID of the Participant resource with the published tracks to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + "participant_sid": participant_sid, + } + self._uri = ( + "/Rooms/{room_sid}/Participants/{participant_sid}/PublishedTracks".format( + **self._solution + ) + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PublishedTrackInstance]: + """ + Streams PublishedTrackInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PublishedTrackInstance]: + """ + Asynchronously streams PublishedTrackInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PublishedTrackInstance]: + """ + Lists PublishedTrackInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PublishedTrackInstance]: + """ + Asynchronously lists PublishedTrackInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PublishedTrackPage: + """ + Retrieve a single page of PublishedTrackInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PublishedTrackInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PublishedTrackPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PublishedTrackPage: + """ + Asynchronously retrieve a single page of PublishedTrackInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PublishedTrackInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PublishedTrackPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> PublishedTrackPage: + """ + Retrieve a specific page of PublishedTrackInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PublishedTrackInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PublishedTrackPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> PublishedTrackPage: + """ + Asynchronously retrieve a specific page of PublishedTrackInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PublishedTrackInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PublishedTrackPage(self._version, response, self._solution) + + def get(self, sid: str) -> PublishedTrackContext: + """ + Constructs a PublishedTrackContext + + :param sid: The SID of the RoomParticipantPublishedTrack resource to fetch. + """ + return PublishedTrackContext( + self._version, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> PublishedTrackContext: + """ + Constructs a PublishedTrackContext + + :param sid: The SID of the RoomParticipantPublishedTrack resource to fetch. + """ + return PublishedTrackContext( + self._version, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/subscribe_rules.py b/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/subscribe_rules.py new file mode 100644 index 00000000..992f8a37 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/subscribe_rules.py @@ -0,0 +1,205 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class SubscribeRulesInstance(InstanceResource): + """ + :ivar participant_sid: The SID of the Participant resource for the Subscribe Rules. + :ivar room_sid: The SID of the Room resource for the Subscribe Rules + :ivar rules: A collection of Subscribe Rules that describe how to include or exclude matching tracks. See the [Specifying Subscribe Rules](https://www.twilio.com/docs/video/api/track-subscriptions#specifying-sr) section for further information. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + room_sid: str, + participant_sid: str, + ): + super().__init__(version) + + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.room_sid: Optional[str] = payload.get("room_sid") + self.rules: Optional[List[str]] = payload.get("rules") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "room_sid": room_sid, + "participant_sid": participant_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SubscribeRulesList(ListResource): + + def __init__(self, version: Version, room_sid: str, participant_sid: str): + """ + Initialize the SubscribeRulesList + + :param version: Version that contains the resource + :param room_sid: The SID of the Room resource where the subscribe rules to update apply. + :param participant_sid: The SID of the Participant resource to update the Subscribe Rules. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + "participant_sid": participant_sid, + } + self._uri = ( + "/Rooms/{room_sid}/Participants/{participant_sid}/SubscribeRules".format( + **self._solution + ) + ) + + def fetch(self) -> SubscribeRulesInstance: + """ + Asynchronously fetch the SubscribeRulesInstance + + + :returns: The fetched SubscribeRulesInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SubscribeRulesInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + + async def fetch_async(self) -> SubscribeRulesInstance: + """ + Asynchronously fetch the SubscribeRulesInstance + + + :returns: The fetched SubscribeRulesInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SubscribeRulesInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + + def update( + self, rules: Union[object, object] = values.unset + ) -> SubscribeRulesInstance: + """ + Update the SubscribeRulesInstance + + :param rules: A JSON-encoded array of subscribe rules. See the [Specifying Subscribe Rules](https://www.twilio.com/docs/video/api/track-subscriptions#specifying-sr) section for further information. + + :returns: The created SubscribeRulesInstance + """ + + data = values.of( + { + "Rules": serialize.object(rules), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SubscribeRulesInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + + async def update_async( + self, rules: Union[object, object] = values.unset + ) -> SubscribeRulesInstance: + """ + Asynchronously update the SubscribeRulesInstance + + :param rules: A JSON-encoded array of subscribe rules. See the [Specifying Subscribe Rules](https://www.twilio.com/docs/video/api/track-subscriptions#specifying-sr) section for further information. + + :returns: The created SubscribeRulesInstance + """ + + data = values.of( + { + "Rules": serialize.object(rules), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SubscribeRulesInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/subscribed_track.py b/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/subscribed_track.py new file mode 100644 index 00000000..8baea148 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/video/v1/room/participant/subscribed_track.py @@ -0,0 +1,474 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SubscribedTrackInstance(InstanceResource): + + class Kind(object): + AUDIO = "audio" + VIDEO = "video" + DATA = "data" + + """ + :ivar sid: The unique string that we created to identify the RoomParticipantSubscribedTrack resource. + :ivar participant_sid: The SID of the participant that subscribes to the track. + :ivar publisher_sid: The SID of the participant that publishes the track. + :ivar room_sid: The SID of the room where the track is published. + :ivar name: The track name. Must have no more than 128 characters and be unique among the participant's published tracks. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar enabled: Whether the track is enabled. + :ivar kind: + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + room_sid: str, + participant_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.publisher_sid: Optional[str] = payload.get("publisher_sid") + self.room_sid: Optional[str] = payload.get("room_sid") + self.name: Optional[str] = payload.get("name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.enabled: Optional[bool] = payload.get("enabled") + self.kind: Optional["SubscribedTrackInstance.Kind"] = payload.get("kind") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "room_sid": room_sid, + "participant_sid": participant_sid, + "sid": sid or self.sid, + } + self._context: Optional[SubscribedTrackContext] = None + + @property + def _proxy(self) -> "SubscribedTrackContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SubscribedTrackContext for this SubscribedTrackInstance + """ + if self._context is None: + self._context = SubscribedTrackContext( + self._version, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "SubscribedTrackInstance": + """ + Fetch the SubscribedTrackInstance + + + :returns: The fetched SubscribedTrackInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SubscribedTrackInstance": + """ + Asynchronous coroutine to fetch the SubscribedTrackInstance + + + :returns: The fetched SubscribedTrackInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SubscribedTrackContext(InstanceContext): + + def __init__(self, version: Version, room_sid: str, participant_sid: str, sid: str): + """ + Initialize the SubscribedTrackContext + + :param version: Version that contains the resource + :param room_sid: The SID of the Room where the Track resource to fetch is subscribed. + :param participant_sid: The SID of the participant that subscribes to the Track resource to fetch. + :param sid: The SID of the RoomParticipantSubscribedTrack resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + "participant_sid": participant_sid, + "sid": sid, + } + self._uri = "/Rooms/{room_sid}/Participants/{participant_sid}/SubscribedTracks/{sid}".format( + **self._solution + ) + + def fetch(self) -> SubscribedTrackInstance: + """ + Fetch the SubscribedTrackInstance + + + :returns: The fetched SubscribedTrackInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SubscribedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SubscribedTrackInstance: + """ + Asynchronous coroutine to fetch the SubscribedTrackInstance + + + :returns: The fetched SubscribedTrackInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SubscribedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SubscribedTrackPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SubscribedTrackInstance: + """ + Build an instance of SubscribedTrackInstance + + :param payload: Payload response from the API + """ + return SubscribedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SubscribedTrackList(ListResource): + + def __init__(self, version: Version, room_sid: str, participant_sid: str): + """ + Initialize the SubscribedTrackList + + :param version: Version that contains the resource + :param room_sid: The SID of the Room resource with the Track resources to read. + :param participant_sid: The SID of the participant that subscribes to the Track resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + "participant_sid": participant_sid, + } + self._uri = ( + "/Rooms/{room_sid}/Participants/{participant_sid}/SubscribedTracks".format( + **self._solution + ) + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SubscribedTrackInstance]: + """ + Streams SubscribedTrackInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SubscribedTrackInstance]: + """ + Asynchronously streams SubscribedTrackInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SubscribedTrackInstance]: + """ + Lists SubscribedTrackInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SubscribedTrackInstance]: + """ + Asynchronously lists SubscribedTrackInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SubscribedTrackPage: + """ + Retrieve a single page of SubscribedTrackInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SubscribedTrackInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SubscribedTrackPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SubscribedTrackPage: + """ + Asynchronously retrieve a single page of SubscribedTrackInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SubscribedTrackInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SubscribedTrackPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SubscribedTrackPage: + """ + Retrieve a specific page of SubscribedTrackInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SubscribedTrackInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SubscribedTrackPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SubscribedTrackPage: + """ + Asynchronously retrieve a specific page of SubscribedTrackInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SubscribedTrackInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SubscribedTrackPage(self._version, response, self._solution) + + def get(self, sid: str) -> SubscribedTrackContext: + """ + Constructs a SubscribedTrackContext + + :param sid: The SID of the RoomParticipantSubscribedTrack resource to fetch. + """ + return SubscribedTrackContext( + self._version, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> SubscribedTrackContext: + """ + Constructs a SubscribedTrackContext + + :param sid: The SID of the RoomParticipantSubscribedTrack resource to fetch. + """ + return SubscribedTrackContext( + self._version, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/room/recording_rules.py b/venv/Lib/site-packages/twilio/rest/video/v1/room/recording_rules.py new file mode 100644 index 00000000..d79d465c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/video/v1/room/recording_rules.py @@ -0,0 +1,178 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class RecordingRulesInstance(InstanceResource): + """ + :ivar room_sid: The SID of the Room resource for the Recording Rules + :ivar rules: A collection of Recording Rules that describe how to include or exclude matching tracks for recording + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], room_sid: str): + super().__init__(version) + + self.room_sid: Optional[str] = payload.get("room_sid") + self.rules: Optional[List[str]] = payload.get("rules") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "room_sid": room_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RecordingRulesList(ListResource): + + def __init__(self, version: Version, room_sid: str): + """ + Initialize the RecordingRulesList + + :param version: Version that contains the resource + :param room_sid: The SID of the Room resource where the recording rules to update apply. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + } + self._uri = "/Rooms/{room_sid}/RecordingRules".format(**self._solution) + + def fetch(self) -> RecordingRulesInstance: + """ + Asynchronously fetch the RecordingRulesInstance + + + :returns: The fetched RecordingRulesInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RecordingRulesInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + + async def fetch_async(self) -> RecordingRulesInstance: + """ + Asynchronously fetch the RecordingRulesInstance + + + :returns: The fetched RecordingRulesInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RecordingRulesInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + + def update( + self, rules: Union[object, object] = values.unset + ) -> RecordingRulesInstance: + """ + Update the RecordingRulesInstance + + :param rules: A JSON-encoded array of recording rules. + + :returns: The created RecordingRulesInstance + """ + + data = values.of( + { + "Rules": serialize.object(rules), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RecordingRulesInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + + async def update_async( + self, rules: Union[object, object] = values.unset + ) -> RecordingRulesInstance: + """ + Asynchronously update the RecordingRulesInstance + + :param rules: A JSON-encoded array of recording rules. + + :returns: The created RecordingRulesInstance + """ + + data = values.of( + { + "Rules": serialize.object(rules), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RecordingRulesInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/video/v1/room/room_recording.py b/venv/Lib/site-packages/twilio/rest/video/v1/room/room_recording.py new file mode 100644 index 00000000..21d433ce --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/video/v1/room/room_recording.py @@ -0,0 +1,602 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RoomRecordingInstance(InstanceResource): + + class Codec(object): + VP8 = "VP8" + H264 = "H264" + OPUS = "OPUS" + PCMU = "PCMU" + + class Format(object): + MKA = "mka" + MKV = "mkv" + + class Status(object): + PROCESSING = "processing" + COMPLETED = "completed" + DELETED = "deleted" + FAILED = "failed" + + class Type(object): + AUDIO = "audio" + VIDEO = "video" + DATA = "data" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the RoomRecording resource. + :ivar status: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar sid: The unique string that we created to identify the RoomRecording resource. + :ivar source_sid: The SID of the recording source. For a Room Recording, this value is a `track_sid`. + :ivar size: The size of the recorded track in bytes. + :ivar url: The absolute URL of the resource. + :ivar type: + :ivar duration: The duration of the recording rounded to the nearest second. Sub-second duration tracks have a `duration` of 1 second + :ivar container_format: + :ivar codec: + :ivar grouping_sids: A list of SIDs related to the Recording. Includes the `room_sid` and `participant_sid`. + :ivar track_name: The name that was given to the source track of the recording. If no name is given, the `source_sid` is used. + :ivar offset: The time in milliseconds elapsed between an arbitrary point in time, common to all group rooms, and the moment when the source room of this track started. This information provides a synchronization mechanism for recordings belonging to the same room. + :ivar media_external_location: The URL of the media file associated with the recording when stored externally. See [External S3 Recordings](/docs/video/api/external-s3-recordings) for more details. + :ivar room_sid: The SID of the Room resource the recording is associated with. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + room_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.status: Optional["RoomRecordingInstance.Status"] = payload.get("status") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.sid: Optional[str] = payload.get("sid") + self.source_sid: Optional[str] = payload.get("source_sid") + self.size: Optional[int] = payload.get("size") + self.url: Optional[str] = payload.get("url") + self.type: Optional["RoomRecordingInstance.Type"] = payload.get("type") + self.duration: Optional[int] = deserialize.integer(payload.get("duration")) + self.container_format: Optional["RoomRecordingInstance.Format"] = payload.get( + "container_format" + ) + self.codec: Optional["RoomRecordingInstance.Codec"] = payload.get("codec") + self.grouping_sids: Optional[Dict[str, object]] = payload.get("grouping_sids") + self.track_name: Optional[str] = payload.get("track_name") + self.offset: Optional[int] = payload.get("offset") + self.media_external_location: Optional[str] = payload.get( + "media_external_location" + ) + self.room_sid: Optional[str] = payload.get("room_sid") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "room_sid": room_sid, + "sid": sid or self.sid, + } + self._context: Optional[RoomRecordingContext] = None + + @property + def _proxy(self) -> "RoomRecordingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RoomRecordingContext for this RoomRecordingInstance + """ + if self._context is None: + self._context = RoomRecordingContext( + self._version, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RoomRecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoomRecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RoomRecordingInstance": + """ + Fetch the RoomRecordingInstance + + + :returns: The fetched RoomRecordingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RoomRecordingInstance": + """ + Asynchronous coroutine to fetch the RoomRecordingInstance + + + :returns: The fetched RoomRecordingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RoomRecordingContext(InstanceContext): + + def __init__(self, version: Version, room_sid: str, sid: str): + """ + Initialize the RoomRecordingContext + + :param version: Version that contains the resource + :param room_sid: The SID of the Room resource with the recording to fetch. + :param sid: The SID of the RoomRecording resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + "sid": sid, + } + self._uri = "/Rooms/{room_sid}/Recordings/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the RoomRecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoomRecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoomRecordingInstance: + """ + Fetch the RoomRecordingInstance + + + :returns: The fetched RoomRecordingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RoomRecordingInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RoomRecordingInstance: + """ + Asynchronous coroutine to fetch the RoomRecordingInstance + + + :returns: The fetched RoomRecordingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RoomRecordingInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RoomRecordingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RoomRecordingInstance: + """ + Build an instance of RoomRecordingInstance + + :param payload: Payload response from the API + """ + return RoomRecordingInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RoomRecordingList(ListResource): + + def __init__(self, version: Version, room_sid: str): + """ + Initialize the RoomRecordingList + + :param version: Version that contains the resource + :param room_sid: The SID of the room with the RoomRecording resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + } + self._uri = "/Rooms/{room_sid}/Recordings".format(**self._solution) + + def stream( + self, + status: Union["RoomRecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoomRecordingInstance]: + """ + Streams RoomRecordingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "RoomRecordingInstance.Status" status: Read only the recordings with this status. Can be: `processing`, `completed`, or `deleted`. + :param str source_sid: Read only the recordings that have this `source_sid`. + :param datetime date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param datetime date_created_before: Read only Recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + source_sid=source_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["RoomRecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RoomRecordingInstance]: + """ + Asynchronously streams RoomRecordingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "RoomRecordingInstance.Status" status: Read only the recordings with this status. Can be: `processing`, `completed`, or `deleted`. + :param str source_sid: Read only the recordings that have this `source_sid`. + :param datetime date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param datetime date_created_before: Read only Recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + source_sid=source_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["RoomRecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoomRecordingInstance]: + """ + Lists RoomRecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "RoomRecordingInstance.Status" status: Read only the recordings with this status. Can be: `processing`, `completed`, or `deleted`. + :param str source_sid: Read only the recordings that have this `source_sid`. + :param datetime date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param datetime date_created_before: Read only Recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + source_sid=source_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["RoomRecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoomRecordingInstance]: + """ + Asynchronously lists RoomRecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "RoomRecordingInstance.Status" status: Read only the recordings with this status. Can be: `processing`, `completed`, or `deleted`. + :param str source_sid: Read only the recordings that have this `source_sid`. + :param datetime date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param datetime date_created_before: Read only Recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + source_sid=source_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["RoomRecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RoomRecordingPage: + """ + Retrieve a single page of RoomRecordingInstance records from the API. + Request is executed immediately + + :param status: Read only the recordings with this status. Can be: `processing`, `completed`, or `deleted`. + :param source_sid: Read only the recordings that have this `source_sid`. + :param date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param date_created_before: Read only Recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoomRecordingInstance + """ + data = values.of( + { + "Status": status, + "SourceSid": source_sid, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RoomRecordingPage(self._version, response, self._solution) + + async def page_async( + self, + status: Union["RoomRecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RoomRecordingPage: + """ + Asynchronously retrieve a single page of RoomRecordingInstance records from the API. + Request is executed immediately + + :param status: Read only the recordings with this status. Can be: `processing`, `completed`, or `deleted`. + :param source_sid: Read only the recordings that have this `source_sid`. + :param date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param date_created_before: Read only Recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoomRecordingInstance + """ + data = values.of( + { + "Status": status, + "SourceSid": source_sid, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RoomRecordingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RoomRecordingPage: + """ + Retrieve a specific page of RoomRecordingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoomRecordingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RoomRecordingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RoomRecordingPage: + """ + Asynchronously retrieve a specific page of RoomRecordingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoomRecordingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RoomRecordingPage(self._version, response, self._solution) + + def get(self, sid: str) -> RoomRecordingContext: + """ + Constructs a RoomRecordingContext + + :param sid: The SID of the RoomRecording resource to fetch. + """ + return RoomRecordingContext( + self._version, room_sid=self._solution["room_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RoomRecordingContext: + """ + Constructs a RoomRecordingContext + + :param sid: The SID of the RoomRecording resource to fetch. + """ + return RoomRecordingContext( + self._version, room_sid=self._solution["room_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/voice/VoiceBase.py b/venv/Lib/site-packages/twilio/rest/voice/VoiceBase.py new file mode 100644 index 00000000..4394ab1a --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/voice/VoiceBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.voice.v1 import V1 + + +class VoiceBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Voice Domain + + :returns: Domain for Voice + """ + super().__init__(twilio, "https://voice.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Voice + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/voice/__init__.py b/venv/Lib/site-packages/twilio/rest/voice/__init__.py new file mode 100644 index 00000000..019a3a20 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/voice/__init__.py @@ -0,0 +1,65 @@ +from warnings import warn + +from twilio.rest.voice.VoiceBase import VoiceBase +from twilio.rest.voice.v1.archived_call import ArchivedCallList +from twilio.rest.voice.v1.byoc_trunk import ByocTrunkList +from twilio.rest.voice.v1.connection_policy import ConnectionPolicyList +from twilio.rest.voice.v1.dialing_permissions import DialingPermissionsList +from twilio.rest.voice.v1.ip_record import IpRecordList +from twilio.rest.voice.v1.source_ip_mapping import SourceIpMappingList + + +class Voice(VoiceBase): + @property + def archived_calls(self) -> ArchivedCallList: + warn( + "archived_calls is deprecated. Use v1.archived_calls instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.archived_calls + + @property + def byoc_trunks(self) -> ByocTrunkList: + warn( + "byoc_trunks is deprecated. Use v1.byoc_trunks instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.byoc_trunks + + @property + def connection_policies(self) -> ConnectionPolicyList: + warn( + "connection_policies is deprecated. Use v1.connection_policies instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.connection_policies + + @property + def dialing_permissions(self) -> DialingPermissionsList: + warn( + "dialing_permissions is deprecated. Use v1.dialing_permissions instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.dialing_permissions + + @property + def ip_records(self) -> IpRecordList: + warn( + "ip_records is deprecated. Use v1.ip_records instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.ip_records + + @property + def source_ip_mappings(self) -> SourceIpMappingList: + warn( + "source_ip_mappings is deprecated. Use v1.source_ip_mappings instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.source_ip_mappings diff --git a/venv/Lib/site-packages/twilio/rest/voice/__pycache__/VoiceBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/voice/__pycache__/VoiceBase.cpython-312.pyc new file mode 100644 index 00000000..9990536a Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/voice/__pycache__/VoiceBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/voice/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/voice/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..82b4e56a Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/voice/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/voice/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/voice/v1/__init__.py new file mode 100644 index 00000000..75c0c7fc --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/voice/v1/__init__.py @@ -0,0 +1,83 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.voice.v1.archived_call import ArchivedCallList +from twilio.rest.voice.v1.byoc_trunk import ByocTrunkList +from twilio.rest.voice.v1.connection_policy import ConnectionPolicyList +from twilio.rest.voice.v1.dialing_permissions import DialingPermissionsList +from twilio.rest.voice.v1.ip_record import IpRecordList +from twilio.rest.voice.v1.source_ip_mapping import SourceIpMappingList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Voice + + :param domain: The Twilio.voice domain + """ + super().__init__(domain, "v1") + self._archived_calls: Optional[ArchivedCallList] = None + self._byoc_trunks: Optional[ByocTrunkList] = None + self._connection_policies: Optional[ConnectionPolicyList] = None + self._dialing_permissions: Optional[DialingPermissionsList] = None + self._ip_records: Optional[IpRecordList] = None + self._source_ip_mappings: Optional[SourceIpMappingList] = None + + @property + def archived_calls(self) -> ArchivedCallList: + if self._archived_calls is None: + self._archived_calls = ArchivedCallList(self) + return self._archived_calls + + @property + def byoc_trunks(self) -> ByocTrunkList: + if self._byoc_trunks is None: + self._byoc_trunks = ByocTrunkList(self) + return self._byoc_trunks + + @property + def connection_policies(self) -> ConnectionPolicyList: + if self._connection_policies is None: + self._connection_policies = ConnectionPolicyList(self) + return self._connection_policies + + @property + def dialing_permissions(self) -> DialingPermissionsList: + if self._dialing_permissions is None: + self._dialing_permissions = DialingPermissionsList(self) + return self._dialing_permissions + + @property + def ip_records(self) -> IpRecordList: + if self._ip_records is None: + self._ip_records = IpRecordList(self) + return self._ip_records + + @property + def source_ip_mappings(self) -> SourceIpMappingList: + if self._source_ip_mappings is None: + self._source_ip_mappings = SourceIpMappingList(self) + return self._source_ip_mappings + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/voice/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/voice/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..2e8ac8db Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/voice/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/voice/v1/__pycache__/archived_call.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/voice/v1/__pycache__/archived_call.cpython-312.pyc new file mode 100644 index 00000000..94640fd7 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/voice/v1/__pycache__/archived_call.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/voice/v1/__pycache__/byoc_trunk.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/voice/v1/__pycache__/byoc_trunk.cpython-312.pyc new file mode 100644 index 00000000..bf1ea602 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/voice/v1/__pycache__/byoc_trunk.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/voice/v1/__pycache__/ip_record.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/voice/v1/__pycache__/ip_record.cpython-312.pyc new file mode 100644 index 00000000..03007baa Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/voice/v1/__pycache__/ip_record.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/voice/v1/__pycache__/source_ip_mapping.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/voice/v1/__pycache__/source_ip_mapping.cpython-312.pyc new file mode 100644 index 00000000..7370b0d9 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/voice/v1/__pycache__/source_ip_mapping.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/voice/v1/archived_call.py b/venv/Lib/site-packages/twilio/rest/voice/v1/archived_call.py new file mode 100644 index 00000000..939f1a03 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/voice/v1/archived_call.py @@ -0,0 +1,113 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date +from twilio.base import values +from twilio.base.instance_context import InstanceContext + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ArchivedCallContext(InstanceContext): + + def __init__(self, version: Version, date: date, sid: str): + """ + Initialize the ArchivedCallContext + + :param version: Version that contains the resource + :param date: The date of the Call in UTC. + :param sid: The Twilio-provided Call SID that uniquely identifies the Call resource to delete + """ + super().__init__(version) + + # Path Solution + self._solution = { + "date": date, + "sid": sid, + } + self._uri = "/Archives/{date}/Calls/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the ArchivedCallInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ArchivedCallInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ArchivedCallList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ArchivedCallList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, date: date, sid: str) -> ArchivedCallContext: + """ + Constructs a ArchivedCallContext + + :param date: The date of the Call in UTC. + :param sid: The Twilio-provided Call SID that uniquely identifies the Call resource to delete + """ + return ArchivedCallContext(self._version, date=date, sid=sid) + + def __call__(self, date: date, sid: str) -> ArchivedCallContext: + """ + Constructs a ArchivedCallContext + + :param date: The date of the Call in UTC. + :param sid: The Twilio-provided Call SID that uniquely identifies the Call resource to delete + """ + return ArchivedCallContext(self._version, date=date, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/voice/v1/byoc_trunk.py b/venv/Lib/site-packages/twilio/rest/voice/v1/byoc_trunk.py new file mode 100644 index 00000000..304bdd78 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/voice/v1/byoc_trunk.py @@ -0,0 +1,787 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ByocTrunkInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the BYOC Trunk resource. + :ivar sid: The unique string that that we created to identify the BYOC Trunk resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar voice_url: The URL we call using the `voice_method` when the BYOC Trunk receives a call. + :ivar voice_method: The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_url: The URL that we call when an error occurs while retrieving or executing the TwiML requested from `voice_url`. + :ivar voice_fallback_method: The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :ivar status_callback_url: The URL that we call to pass status parameters (such as call ended) to your application. + :ivar status_callback_method: The HTTP method we use to call `status_callback_url`. Either `GET` or `POST`. + :ivar cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :ivar connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :ivar from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \"call back\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \"sip.twilio.com\". + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.voice_url: Optional[str] = payload.get("voice_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.status_callback_url: Optional[str] = payload.get("status_callback_url") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.cnam_lookup_enabled: Optional[bool] = payload.get("cnam_lookup_enabled") + self.connection_policy_sid: Optional[str] = payload.get("connection_policy_sid") + self.from_domain_sid: Optional[str] = payload.get("from_domain_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ByocTrunkContext] = None + + @property + def _proxy(self) -> "ByocTrunkContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ByocTrunkContext for this ByocTrunkInstance + """ + if self._context is None: + self._context = ByocTrunkContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ByocTrunkInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ByocTrunkInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ByocTrunkInstance": + """ + Fetch the ByocTrunkInstance + + + :returns: The fetched ByocTrunkInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ByocTrunkInstance": + """ + Asynchronous coroutine to fetch the ByocTrunkInstance + + + :returns: The fetched ByocTrunkInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> "ByocTrunkInstance": + """ + Update the ByocTrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: The updated ByocTrunkInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + cnam_lookup_enabled=cnam_lookup_enabled, + connection_policy_sid=connection_policy_sid, + from_domain_sid=from_domain_sid, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> "ByocTrunkInstance": + """ + Asynchronous coroutine to update the ByocTrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: The updated ByocTrunkInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + cnam_lookup_enabled=cnam_lookup_enabled, + connection_policy_sid=connection_policy_sid, + from_domain_sid=from_domain_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ByocTrunkContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ByocTrunkContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the BYOC Trunk resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/ByocTrunks/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the ByocTrunkInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ByocTrunkInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ByocTrunkInstance: + """ + Fetch the ByocTrunkInstance + + + :returns: The fetched ByocTrunkInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ByocTrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ByocTrunkInstance: + """ + Asynchronous coroutine to fetch the ByocTrunkInstance + + + :returns: The fetched ByocTrunkInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ByocTrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> ByocTrunkInstance: + """ + Update the ByocTrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: The updated ByocTrunkInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), + "ConnectionPolicySid": connection_policy_sid, + "FromDomainSid": from_domain_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ByocTrunkInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> ByocTrunkInstance: + """ + Asynchronous coroutine to update the ByocTrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: The updated ByocTrunkInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), + "ConnectionPolicySid": connection_policy_sid, + "FromDomainSid": from_domain_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ByocTrunkInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ByocTrunkPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ByocTrunkInstance: + """ + Build an instance of ByocTrunkInstance + + :param payload: Payload response from the API + """ + return ByocTrunkInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ByocTrunkList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ByocTrunkList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ByocTrunks" + + def create( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> ByocTrunkInstance: + """ + Create the ByocTrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: The created ByocTrunkInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), + "ConnectionPolicySid": connection_policy_sid, + "FromDomainSid": from_domain_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ByocTrunkInstance(self._version, payload) + + async def create_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> ByocTrunkInstance: + """ + Asynchronously create the ByocTrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: The created ByocTrunkInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), + "ConnectionPolicySid": connection_policy_sid, + "FromDomainSid": from_domain_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ByocTrunkInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ByocTrunkInstance]: + """ + Streams ByocTrunkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ByocTrunkInstance]: + """ + Asynchronously streams ByocTrunkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ByocTrunkInstance]: + """ + Lists ByocTrunkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ByocTrunkInstance]: + """ + Asynchronously lists ByocTrunkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ByocTrunkPage: + """ + Retrieve a single page of ByocTrunkInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ByocTrunkInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ByocTrunkPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ByocTrunkPage: + """ + Asynchronously retrieve a single page of ByocTrunkInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ByocTrunkInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ByocTrunkPage(self._version, response) + + def get_page(self, target_url: str) -> ByocTrunkPage: + """ + Retrieve a specific page of ByocTrunkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ByocTrunkInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ByocTrunkPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ByocTrunkPage: + """ + Asynchronously retrieve a specific page of ByocTrunkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ByocTrunkInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ByocTrunkPage(self._version, response) + + def get(self, sid: str) -> ByocTrunkContext: + """ + Constructs a ByocTrunkContext + + :param sid: The Twilio-provided string that uniquely identifies the BYOC Trunk resource to update. + """ + return ByocTrunkContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ByocTrunkContext: + """ + Constructs a ByocTrunkContext + + :param sid: The Twilio-provided string that uniquely identifies the BYOC Trunk resource to update. + """ + return ByocTrunkContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/voice/v1/connection_policy/__init__.py b/venv/Lib/site-packages/twilio/rest/voice/v1/connection_policy/__init__.py new file mode 100644 index 00000000..e2a56929 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/voice/v1/connection_policy/__init__.py @@ -0,0 +1,629 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.voice.v1.connection_policy.connection_policy_target import ( + ConnectionPolicyTargetList, +) + + +class ConnectionPolicyInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Connection Policy resource. + :ivar sid: The unique string that we created to identify the Connection Policy resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ConnectionPolicyContext] = None + + @property + def _proxy(self) -> "ConnectionPolicyContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConnectionPolicyContext for this ConnectionPolicyInstance + """ + if self._context is None: + self._context = ConnectionPolicyContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ConnectionPolicyInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConnectionPolicyInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ConnectionPolicyInstance": + """ + Fetch the ConnectionPolicyInstance + + + :returns: The fetched ConnectionPolicyInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConnectionPolicyInstance": + """ + Asynchronous coroutine to fetch the ConnectionPolicyInstance + + + :returns: The fetched ConnectionPolicyInstance + """ + return await self._proxy.fetch_async() + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> "ConnectionPolicyInstance": + """ + Update the ConnectionPolicyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated ConnectionPolicyInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "ConnectionPolicyInstance": + """ + Asynchronous coroutine to update the ConnectionPolicyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated ConnectionPolicyInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + @property + def targets(self) -> ConnectionPolicyTargetList: + """ + Access the targets + """ + return self._proxy.targets + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConnectionPolicyContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ConnectionPolicyContext + + :param version: Version that contains the resource + :param sid: The unique string that we created to identify the Connection Policy resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/ConnectionPolicies/{sid}".format(**self._solution) + + self._targets: Optional[ConnectionPolicyTargetList] = None + + def delete(self) -> bool: + """ + Deletes the ConnectionPolicyInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConnectionPolicyInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConnectionPolicyInstance: + """ + Fetch the ConnectionPolicyInstance + + + :returns: The fetched ConnectionPolicyInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ConnectionPolicyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ConnectionPolicyInstance: + """ + Asynchronous coroutine to fetch the ConnectionPolicyInstance + + + :returns: The fetched ConnectionPolicyInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ConnectionPolicyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> ConnectionPolicyInstance: + """ + Update the ConnectionPolicyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated ConnectionPolicyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConnectionPolicyInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ConnectionPolicyInstance: + """ + Asynchronous coroutine to update the ConnectionPolicyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated ConnectionPolicyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConnectionPolicyInstance( + self._version, payload, sid=self._solution["sid"] + ) + + @property + def targets(self) -> ConnectionPolicyTargetList: + """ + Access the targets + """ + if self._targets is None: + self._targets = ConnectionPolicyTargetList( + self._version, + self._solution["sid"], + ) + return self._targets + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConnectionPolicyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ConnectionPolicyInstance: + """ + Build an instance of ConnectionPolicyInstance + + :param payload: Payload response from the API + """ + return ConnectionPolicyInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ConnectionPolicyList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ConnectionPolicyList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ConnectionPolicies" + + def create( + self, friendly_name: Union[str, object] = values.unset + ) -> ConnectionPolicyInstance: + """ + Create the ConnectionPolicyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The created ConnectionPolicyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConnectionPolicyInstance(self._version, payload) + + async def create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ConnectionPolicyInstance: + """ + Asynchronously create the ConnectionPolicyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The created ConnectionPolicyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConnectionPolicyInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConnectionPolicyInstance]: + """ + Streams ConnectionPolicyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConnectionPolicyInstance]: + """ + Asynchronously streams ConnectionPolicyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConnectionPolicyInstance]: + """ + Lists ConnectionPolicyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConnectionPolicyInstance]: + """ + Asynchronously lists ConnectionPolicyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConnectionPolicyPage: + """ + Retrieve a single page of ConnectionPolicyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConnectionPolicyInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConnectionPolicyPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConnectionPolicyPage: + """ + Asynchronously retrieve a single page of ConnectionPolicyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConnectionPolicyInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConnectionPolicyPage(self._version, response) + + def get_page(self, target_url: str) -> ConnectionPolicyPage: + """ + Retrieve a specific page of ConnectionPolicyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConnectionPolicyInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConnectionPolicyPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ConnectionPolicyPage: + """ + Asynchronously retrieve a specific page of ConnectionPolicyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConnectionPolicyInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConnectionPolicyPage(self._version, response) + + def get(self, sid: str) -> ConnectionPolicyContext: + """ + Constructs a ConnectionPolicyContext + + :param sid: The unique string that we created to identify the Connection Policy resource to update. + """ + return ConnectionPolicyContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ConnectionPolicyContext: + """ + Constructs a ConnectionPolicyContext + + :param sid: The unique string that we created to identify the Connection Policy resource to update. + """ + return ConnectionPolicyContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/voice/v1/connection_policy/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/voice/v1/connection_policy/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..69d899eb Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/voice/v1/connection_policy/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/voice/v1/connection_policy/__pycache__/connection_policy_target.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/voice/v1/connection_policy/__pycache__/connection_policy_target.cpython-312.pyc new file mode 100644 index 00000000..7f619e50 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/voice/v1/connection_policy/__pycache__/connection_policy_target.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/voice/v1/connection_policy/connection_policy_target.py b/venv/Lib/site-packages/twilio/rest/voice/v1/connection_policy/connection_policy_target.py new file mode 100644 index 00000000..03f4fd60 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/voice/v1/connection_policy/connection_policy_target.py @@ -0,0 +1,736 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ConnectionPolicyTargetInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Target resource. + :ivar connection_policy_sid: The SID of the Connection Policy that owns the Target. + :ivar sid: The unique string that we created to identify the Target resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :ivar priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important target. + :ivar weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. Targets with higher values receive more load than those with lower ones with the same priority. + :ivar enabled: Whether the target is enabled. The default is `true`. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + connection_policy_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.connection_policy_sid: Optional[str] = payload.get("connection_policy_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.target: Optional[str] = payload.get("target") + self.priority: Optional[int] = deserialize.integer(payload.get("priority")) + self.weight: Optional[int] = deserialize.integer(payload.get("weight")) + self.enabled: Optional[bool] = payload.get("enabled") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "connection_policy_sid": connection_policy_sid, + "sid": sid or self.sid, + } + self._context: Optional[ConnectionPolicyTargetContext] = None + + @property + def _proxy(self) -> "ConnectionPolicyTargetContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConnectionPolicyTargetContext for this ConnectionPolicyTargetInstance + """ + if self._context is None: + self._context = ConnectionPolicyTargetContext( + self._version, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ConnectionPolicyTargetInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConnectionPolicyTargetInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ConnectionPolicyTargetInstance": + """ + Fetch the ConnectionPolicyTargetInstance + + + :returns: The fetched ConnectionPolicyTargetInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConnectionPolicyTargetInstance": + """ + Asynchronous coroutine to fetch the ConnectionPolicyTargetInstance + + + :returns: The fetched ConnectionPolicyTargetInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + target: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> "ConnectionPolicyTargetInstance": + """ + Update the ConnectionPolicyTargetInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. + + :returns: The updated ConnectionPolicyTargetInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + target=target, + priority=priority, + weight=weight, + enabled=enabled, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + target: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> "ConnectionPolicyTargetInstance": + """ + Asynchronous coroutine to update the ConnectionPolicyTargetInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. + + :returns: The updated ConnectionPolicyTargetInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + target=target, + priority=priority, + weight=weight, + enabled=enabled, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConnectionPolicyTargetContext(InstanceContext): + + def __init__(self, version: Version, connection_policy_sid: str, sid: str): + """ + Initialize the ConnectionPolicyTargetContext + + :param version: Version that contains the resource + :param connection_policy_sid: The SID of the Connection Policy that owns the Target. + :param sid: The unique string that we created to identify the Target resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "connection_policy_sid": connection_policy_sid, + "sid": sid, + } + self._uri = "/ConnectionPolicies/{connection_policy_sid}/Targets/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the ConnectionPolicyTargetInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConnectionPolicyTargetInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConnectionPolicyTargetInstance: + """ + Fetch the ConnectionPolicyTargetInstance + + + :returns: The fetched ConnectionPolicyTargetInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ConnectionPolicyTargetInstance: + """ + Asynchronous coroutine to fetch the ConnectionPolicyTargetInstance + + + :returns: The fetched ConnectionPolicyTargetInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + target: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> ConnectionPolicyTargetInstance: + """ + Update the ConnectionPolicyTargetInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. + + :returns: The updated ConnectionPolicyTargetInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Target": target, + "Priority": priority, + "Weight": weight, + "Enabled": serialize.boolean_to_string(enabled), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + target: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> ConnectionPolicyTargetInstance: + """ + Asynchronous coroutine to update the ConnectionPolicyTargetInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. + + :returns: The updated ConnectionPolicyTargetInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Target": target, + "Priority": priority, + "Weight": weight, + "Enabled": serialize.boolean_to_string(enabled), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConnectionPolicyTargetPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ConnectionPolicyTargetInstance: + """ + Build an instance of ConnectionPolicyTargetInstance + + :param payload: Payload response from the API + """ + return ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ConnectionPolicyTargetList(ListResource): + + def __init__(self, version: Version, connection_policy_sid: str): + """ + Initialize the ConnectionPolicyTargetList + + :param version: Version that contains the resource + :param connection_policy_sid: The SID of the Connection Policy from which to read the Targets. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "connection_policy_sid": connection_policy_sid, + } + self._uri = "/ConnectionPolicies/{connection_policy_sid}/Targets".format( + **self._solution + ) + + def create( + self, + target: str, + friendly_name: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> ConnectionPolicyTargetInstance: + """ + Create the ConnectionPolicyTargetInstance + + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. The default is `true`. + + :returns: The created ConnectionPolicyTargetInstance + """ + + data = values.of( + { + "Target": target, + "FriendlyName": friendly_name, + "Priority": priority, + "Weight": weight, + "Enabled": serialize.boolean_to_string(enabled), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + ) + + async def create_async( + self, + target: str, + friendly_name: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> ConnectionPolicyTargetInstance: + """ + Asynchronously create the ConnectionPolicyTargetInstance + + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. The default is `true`. + + :returns: The created ConnectionPolicyTargetInstance + """ + + data = values.of( + { + "Target": target, + "FriendlyName": friendly_name, + "Priority": priority, + "Weight": weight, + "Enabled": serialize.boolean_to_string(enabled), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConnectionPolicyTargetInstance]: + """ + Streams ConnectionPolicyTargetInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConnectionPolicyTargetInstance]: + """ + Asynchronously streams ConnectionPolicyTargetInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConnectionPolicyTargetInstance]: + """ + Lists ConnectionPolicyTargetInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConnectionPolicyTargetInstance]: + """ + Asynchronously lists ConnectionPolicyTargetInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConnectionPolicyTargetPage: + """ + Retrieve a single page of ConnectionPolicyTargetInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConnectionPolicyTargetInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConnectionPolicyTargetPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConnectionPolicyTargetPage: + """ + Asynchronously retrieve a single page of ConnectionPolicyTargetInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConnectionPolicyTargetInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConnectionPolicyTargetPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ConnectionPolicyTargetPage: + """ + Retrieve a specific page of ConnectionPolicyTargetInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConnectionPolicyTargetInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConnectionPolicyTargetPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ConnectionPolicyTargetPage: + """ + Asynchronously retrieve a specific page of ConnectionPolicyTargetInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConnectionPolicyTargetInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConnectionPolicyTargetPage(self._version, response, self._solution) + + def get(self, sid: str) -> ConnectionPolicyTargetContext: + """ + Constructs a ConnectionPolicyTargetContext + + :param sid: The unique string that we created to identify the Target resource to update. + """ + return ConnectionPolicyTargetContext( + self._version, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> ConnectionPolicyTargetContext: + """ + Constructs a ConnectionPolicyTargetContext + + :param sid: The unique string that we created to identify the Target resource to update. + """ + return ConnectionPolicyTargetContext( + self._version, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/__init__.py b/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/__init__.py new file mode 100644 index 00000000..2346430a --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/__init__.py @@ -0,0 +1,78 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.voice.v1.dialing_permissions.bulk_country_update import ( + BulkCountryUpdateList, +) +from twilio.rest.voice.v1.dialing_permissions.country import CountryList +from twilio.rest.voice.v1.dialing_permissions.settings import SettingsList + + +class DialingPermissionsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the DialingPermissionsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/DialingPermissions" + + self._bulk_country_updates: Optional[BulkCountryUpdateList] = None + self._countries: Optional[CountryList] = None + self._settings: Optional[SettingsList] = None + + @property + def bulk_country_updates(self) -> BulkCountryUpdateList: + """ + Access the bulk_country_updates + """ + if self._bulk_country_updates is None: + self._bulk_country_updates = BulkCountryUpdateList(self._version) + return self._bulk_country_updates + + @property + def countries(self) -> CountryList: + """ + Access the countries + """ + if self._countries is None: + self._countries = CountryList(self._version) + return self._countries + + @property + def settings(self) -> SettingsList: + """ + Access the settings + """ + if self._settings is None: + self._settings = SettingsList(self._version) + return self._settings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..677b91e1 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/__pycache__/bulk_country_update.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/__pycache__/bulk_country_update.cpython-312.pyc new file mode 100644 index 00000000..862a4352 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/__pycache__/bulk_country_update.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/__pycache__/settings.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/__pycache__/settings.cpython-312.pyc new file mode 100644 index 00000000..330703fe Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/__pycache__/settings.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/bulk_country_update.py b/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/bulk_country_update.py new file mode 100644 index 00000000..4059be8d --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/bulk_country_update.py @@ -0,0 +1,118 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class BulkCountryUpdateInstance(InstanceResource): + """ + :ivar update_count: The number of countries updated + :ivar update_request: A bulk update request to change voice dialing country permissions stored as a URL-encoded, JSON array of update objects. For example : `[ { \"iso_code\": \"GB\", \"low_risk_numbers_enabled\": \"true\", \"high_risk_special_numbers_enabled\":\"true\", \"high_risk_tollfraud_numbers_enabled\": \"false\" } ]` + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.update_count: Optional[int] = deserialize.integer( + payload.get("update_count") + ) + self.update_request: Optional[str] = payload.get("update_request") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class BulkCountryUpdateList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the BulkCountryUpdateList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/DialingPermissions/BulkCountryUpdates" + + def create(self, update_request: str) -> BulkCountryUpdateInstance: + """ + Create the BulkCountryUpdateInstance + + :param update_request: URL encoded JSON array of update objects. example : `[ { \\\"iso_code\\\": \\\"GB\\\", \\\"low_risk_numbers_enabled\\\": \\\"true\\\", \\\"high_risk_special_numbers_enabled\\\":\\\"true\\\", \\\"high_risk_tollfraud_numbers_enabled\\\": \\\"false\\\" } ]` + + :returns: The created BulkCountryUpdateInstance + """ + + data = values.of( + { + "UpdateRequest": update_request, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BulkCountryUpdateInstance(self._version, payload) + + async def create_async(self, update_request: str) -> BulkCountryUpdateInstance: + """ + Asynchronously create the BulkCountryUpdateInstance + + :param update_request: URL encoded JSON array of update objects. example : `[ { \\\"iso_code\\\": \\\"GB\\\", \\\"low_risk_numbers_enabled\\\": \\\"true\\\", \\\"high_risk_special_numbers_enabled\\\":\\\"true\\\", \\\"high_risk_tollfraud_numbers_enabled\\\": \\\"false\\\" } ]` + + :returns: The created BulkCountryUpdateInstance + """ + + data = values.of( + { + "UpdateRequest": update_request, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BulkCountryUpdateInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/country/__init__.py b/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/country/__init__.py new file mode 100644 index 00000000..6a60c23a --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/country/__init__.py @@ -0,0 +1,570 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix import ( + HighriskSpecialPrefixList, +) + + +class CountryInstance(InstanceResource): + """ + :ivar iso_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + :ivar name: The name of the country. + :ivar continent: The name of the continent in which the country is located. + :ivar country_codes: The E.164 assigned [country codes(s)](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + :ivar low_risk_numbers_enabled: Whether dialing to low-risk numbers is enabled. + :ivar high_risk_special_numbers_enabled: Whether dialing to high-risk special services numbers is enabled. These prefixes include number ranges allocated by the country and include premium numbers, special services, shared cost, and others + :ivar high_risk_tollfraud_numbers_enabled: Whether dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers is enabled. These prefixes include narrow number ranges that have a high-risk of international revenue sharing fraud (IRSF) attacks, also known as [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html). These prefixes are collected from anti-fraud databases and verified by analyzing calls on our network. These prefixes are not available for download and are updated frequently + :ivar url: The absolute URL of this resource. + :ivar links: A list of URLs related to this resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], iso_code: Optional[str] = None + ): + super().__init__(version) + + self.iso_code: Optional[str] = payload.get("iso_code") + self.name: Optional[str] = payload.get("name") + self.continent: Optional[str] = payload.get("continent") + self.country_codes: Optional[List[str]] = payload.get("country_codes") + self.low_risk_numbers_enabled: Optional[bool] = payload.get( + "low_risk_numbers_enabled" + ) + self.high_risk_special_numbers_enabled: Optional[bool] = payload.get( + "high_risk_special_numbers_enabled" + ) + self.high_risk_tollfraud_numbers_enabled: Optional[bool] = payload.get( + "high_risk_tollfraud_numbers_enabled" + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "iso_code": iso_code or self.iso_code, + } + self._context: Optional[CountryContext] = None + + @property + def _proxy(self) -> "CountryContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CountryContext for this CountryInstance + """ + if self._context is None: + self._context = CountryContext( + self._version, + iso_code=self._solution["iso_code"], + ) + return self._context + + def fetch(self) -> "CountryInstance": + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CountryInstance": + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + return await self._proxy.fetch_async() + + @property + def highrisk_special_prefixes(self) -> HighriskSpecialPrefixList: + """ + Access the highrisk_special_prefixes + """ + return self._proxy.highrisk_special_prefixes + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CountryContext(InstanceContext): + + def __init__(self, version: Version, iso_code: str): + """ + Initialize the CountryContext + + :param version: Version that contains the resource + :param iso_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the DialingPermissions Country resource to fetch + """ + super().__init__(version) + + # Path Solution + self._solution = { + "iso_code": iso_code, + } + self._uri = "/DialingPermissions/Countries/{iso_code}".format(**self._solution) + + self._highrisk_special_prefixes: Optional[HighriskSpecialPrefixList] = None + + def fetch(self) -> CountryInstance: + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CountryInstance( + self._version, + payload, + iso_code=self._solution["iso_code"], + ) + + async def fetch_async(self) -> CountryInstance: + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CountryInstance( + self._version, + payload, + iso_code=self._solution["iso_code"], + ) + + @property + def highrisk_special_prefixes(self) -> HighriskSpecialPrefixList: + """ + Access the highrisk_special_prefixes + """ + if self._highrisk_special_prefixes is None: + self._highrisk_special_prefixes = HighriskSpecialPrefixList( + self._version, + self._solution["iso_code"], + ) + return self._highrisk_special_prefixes + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CountryPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: + """ + Build an instance of CountryInstance + + :param payload: Payload response from the API + """ + return CountryInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CountryList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CountryList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/DialingPermissions/Countries" + + def stream( + self, + iso_code: Union[str, object] = values.unset, + continent: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + low_risk_numbers_enabled: Union[bool, object] = values.unset, + high_risk_special_numbers_enabled: Union[bool, object] = values.unset, + high_risk_tollfraud_numbers_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CountryInstance]: + """ + Streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str iso_code: Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :param str continent: Filter to retrieve the country permissions by specifying the continent + :param str country_code: Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + :param bool low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. + :param bool high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` + :param bool high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + iso_code=iso_code, + continent=continent, + country_code=country_code, + low_risk_numbers_enabled=low_risk_numbers_enabled, + high_risk_special_numbers_enabled=high_risk_special_numbers_enabled, + high_risk_tollfraud_numbers_enabled=high_risk_tollfraud_numbers_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + iso_code: Union[str, object] = values.unset, + continent: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + low_risk_numbers_enabled: Union[bool, object] = values.unset, + high_risk_special_numbers_enabled: Union[bool, object] = values.unset, + high_risk_tollfraud_numbers_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CountryInstance]: + """ + Asynchronously streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str iso_code: Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :param str continent: Filter to retrieve the country permissions by specifying the continent + :param str country_code: Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + :param bool low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. + :param bool high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` + :param bool high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + iso_code=iso_code, + continent=continent, + country_code=country_code, + low_risk_numbers_enabled=low_risk_numbers_enabled, + high_risk_special_numbers_enabled=high_risk_special_numbers_enabled, + high_risk_tollfraud_numbers_enabled=high_risk_tollfraud_numbers_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + iso_code: Union[str, object] = values.unset, + continent: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + low_risk_numbers_enabled: Union[bool, object] = values.unset, + high_risk_special_numbers_enabled: Union[bool, object] = values.unset, + high_risk_tollfraud_numbers_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str iso_code: Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :param str continent: Filter to retrieve the country permissions by specifying the continent + :param str country_code: Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + :param bool low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. + :param bool high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` + :param bool high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + iso_code=iso_code, + continent=continent, + country_code=country_code, + low_risk_numbers_enabled=low_risk_numbers_enabled, + high_risk_special_numbers_enabled=high_risk_special_numbers_enabled, + high_risk_tollfraud_numbers_enabled=high_risk_tollfraud_numbers_enabled, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + iso_code: Union[str, object] = values.unset, + continent: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + low_risk_numbers_enabled: Union[bool, object] = values.unset, + high_risk_special_numbers_enabled: Union[bool, object] = values.unset, + high_risk_tollfraud_numbers_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Asynchronously lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str iso_code: Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :param str continent: Filter to retrieve the country permissions by specifying the continent + :param str country_code: Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + :param bool low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. + :param bool high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` + :param bool high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + iso_code=iso_code, + continent=continent, + country_code=country_code, + low_risk_numbers_enabled=low_risk_numbers_enabled, + high_risk_special_numbers_enabled=high_risk_special_numbers_enabled, + high_risk_tollfraud_numbers_enabled=high_risk_tollfraud_numbers_enabled, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + iso_code: Union[str, object] = values.unset, + continent: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + low_risk_numbers_enabled: Union[bool, object] = values.unset, + high_risk_special_numbers_enabled: Union[bool, object] = values.unset, + high_risk_tollfraud_numbers_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param iso_code: Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :param continent: Filter to retrieve the country permissions by specifying the continent + :param country_code: Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + :param low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. + :param high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` + :param high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance + """ + data = values.of( + { + "IsoCode": iso_code, + "Continent": continent, + "CountryCode": country_code, + "LowRiskNumbersEnabled": serialize.boolean_to_string( + low_risk_numbers_enabled + ), + "HighRiskSpecialNumbersEnabled": serialize.boolean_to_string( + high_risk_special_numbers_enabled + ), + "HighRiskTollfraudNumbersEnabled": serialize.boolean_to_string( + high_risk_tollfraud_numbers_enabled + ), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + async def page_async( + self, + iso_code: Union[str, object] = values.unset, + continent: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + low_risk_numbers_enabled: Union[bool, object] = values.unset, + high_risk_special_numbers_enabled: Union[bool, object] = values.unset, + high_risk_tollfraud_numbers_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Asynchronously retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param iso_code: Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :param continent: Filter to retrieve the country permissions by specifying the continent + :param country_code: Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + :param low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. + :param high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` + :param high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance + """ + data = values.of( + { + "IsoCode": iso_code, + "Continent": continent, + "CountryCode": country_code, + "LowRiskNumbersEnabled": serialize.boolean_to_string( + low_risk_numbers_enabled + ), + "HighRiskSpecialNumbersEnabled": serialize.boolean_to_string( + high_risk_special_numbers_enabled + ), + "HighRiskTollfraudNumbersEnabled": serialize.boolean_to_string( + high_risk_tollfraud_numbers_enabled + ), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + def get_page(self, target_url: str) -> CountryPage: + """ + Retrieve a specific page of CountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CountryPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CountryPage: + """ + Asynchronously retrieve a specific page of CountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CountryPage(self._version, response) + + def get(self, iso_code: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the DialingPermissions Country resource to fetch + """ + return CountryContext(self._version, iso_code=iso_code) + + def __call__(self, iso_code: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the DialingPermissions Country resource to fetch + """ + return CountryContext(self._version, iso_code=iso_code) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/country/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/country/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..ba3614f3 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/country/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/country/__pycache__/highrisk_special_prefix.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/country/__pycache__/highrisk_special_prefix.cpython-312.pyc new file mode 100644 index 00000000..0c7b61e9 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/country/__pycache__/highrisk_special_prefix.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/country/highrisk_special_prefix.py b/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/country/highrisk_special_prefix.py new file mode 100644 index 00000000..75300e92 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/country/highrisk_special_prefix.py @@ -0,0 +1,290 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class HighriskSpecialPrefixInstance(InstanceResource): + """ + :ivar prefix: A prefix is a contiguous number range for a block of E.164 numbers that includes the E.164 assigned country code. For example, a North American Numbering Plan prefix like `+1510720` written like `+1(510) 720` matches all numbers inclusive from `+1(510) 720-0000` to `+1(510) 720-9999`. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], iso_code: str): + super().__init__(version) + + self.prefix: Optional[str] = payload.get("prefix") + + self._solution = { + "iso_code": iso_code, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class HighriskSpecialPrefixPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> HighriskSpecialPrefixInstance: + """ + Build an instance of HighriskSpecialPrefixInstance + + :param payload: Payload response from the API + """ + return HighriskSpecialPrefixInstance( + self._version, payload, iso_code=self._solution["iso_code"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class HighriskSpecialPrefixList(ListResource): + + def __init__(self, version: Version, iso_code: str): + """ + Initialize the HighriskSpecialPrefixList + + :param version: Version that contains the resource + :param iso_code: The [ISO 3166-1 country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) to identify the country permissions from which high-risk special service number prefixes are fetched + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "iso_code": iso_code, + } + self._uri = ( + "/DialingPermissions/Countries/{iso_code}/HighRiskSpecialPrefixes".format( + **self._solution + ) + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[HighriskSpecialPrefixInstance]: + """ + Streams HighriskSpecialPrefixInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[HighriskSpecialPrefixInstance]: + """ + Asynchronously streams HighriskSpecialPrefixInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[HighriskSpecialPrefixInstance]: + """ + Lists HighriskSpecialPrefixInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[HighriskSpecialPrefixInstance]: + """ + Asynchronously lists HighriskSpecialPrefixInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> HighriskSpecialPrefixPage: + """ + Retrieve a single page of HighriskSpecialPrefixInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of HighriskSpecialPrefixInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return HighriskSpecialPrefixPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> HighriskSpecialPrefixPage: + """ + Asynchronously retrieve a single page of HighriskSpecialPrefixInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of HighriskSpecialPrefixInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return HighriskSpecialPrefixPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> HighriskSpecialPrefixPage: + """ + Retrieve a specific page of HighriskSpecialPrefixInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of HighriskSpecialPrefixInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return HighriskSpecialPrefixPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> HighriskSpecialPrefixPage: + """ + Asynchronously retrieve a specific page of HighriskSpecialPrefixInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of HighriskSpecialPrefixInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return HighriskSpecialPrefixPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/settings.py b/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/settings.py new file mode 100644 index 00000000..9e7aa0ba --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/voice/v1/dialing_permissions/settings.py @@ -0,0 +1,262 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class SettingsInstance(InstanceResource): + """ + :ivar dialing_permissions_inheritance: `true` if the sub-account will inherit voice dialing permissions from the Master Project; otherwise `false`. + :ivar url: The absolute URL of this resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.dialing_permissions_inheritance: Optional[bool] = payload.get( + "dialing_permissions_inheritance" + ) + self.url: Optional[str] = payload.get("url") + + self._context: Optional[SettingsContext] = None + + @property + def _proxy(self) -> "SettingsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SettingsContext for this SettingsInstance + """ + if self._context is None: + self._context = SettingsContext( + self._version, + ) + return self._context + + def fetch(self) -> "SettingsInstance": + """ + Fetch the SettingsInstance + + + :returns: The fetched SettingsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SettingsInstance": + """ + Asynchronous coroutine to fetch the SettingsInstance + + + :returns: The fetched SettingsInstance + """ + return await self._proxy.fetch_async() + + def update( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> "SettingsInstance": + """ + Update the SettingsInstance + + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. + + :returns: The updated SettingsInstance + """ + return self._proxy.update( + dialing_permissions_inheritance=dialing_permissions_inheritance, + ) + + async def update_async( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> "SettingsInstance": + """ + Asynchronous coroutine to update the SettingsInstance + + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. + + :returns: The updated SettingsInstance + """ + return await self._proxy.update_async( + dialing_permissions_inheritance=dialing_permissions_inheritance, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class SettingsContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the SettingsContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/Settings" + + def fetch(self) -> SettingsInstance: + """ + Fetch the SettingsInstance + + + :returns: The fetched SettingsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SettingsInstance( + self._version, + payload, + ) + + async def fetch_async(self) -> SettingsInstance: + """ + Asynchronous coroutine to fetch the SettingsInstance + + + :returns: The fetched SettingsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SettingsInstance( + self._version, + payload, + ) + + def update( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> SettingsInstance: + """ + Update the SettingsInstance + + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. + + :returns: The updated SettingsInstance + """ + + data = values.of( + { + "DialingPermissionsInheritance": serialize.boolean_to_string( + dialing_permissions_inheritance + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SettingsInstance(self._version, payload) + + async def update_async( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> SettingsInstance: + """ + Asynchronous coroutine to update the SettingsInstance + + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. + + :returns: The updated SettingsInstance + """ + + data = values.of( + { + "DialingPermissionsInheritance": serialize.boolean_to_string( + dialing_permissions_inheritance + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SettingsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class SettingsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SettingsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> SettingsContext: + """ + Constructs a SettingsContext + + """ + return SettingsContext(self._version) + + def __call__(self) -> SettingsContext: + """ + Constructs a SettingsContext + + """ + return SettingsContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/voice/v1/ip_record.py b/venv/Lib/site-packages/twilio/rest/voice/v1/ip_record.py new file mode 100644 index 00000000..05e9741f --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/voice/v1/ip_record.py @@ -0,0 +1,619 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class IpRecordInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IP Record resource. + :ivar sid: The unique string that we created to identify the IP Record resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar ip_address: An IP address in dotted decimal notation, IPv4 only. + :ivar cidr_prefix_length: An integer representing the length of the [CIDR](https://tools.ietf.org/html/rfc4632) prefix to use with this IP address. By default the entire IP address is used, which for IPv4 is value 32. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.ip_address: Optional[str] = payload.get("ip_address") + self.cidr_prefix_length: Optional[int] = deserialize.integer( + payload.get("cidr_prefix_length") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[IpRecordContext] = None + + @property + def _proxy(self) -> "IpRecordContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: IpRecordContext for this IpRecordInstance + """ + if self._context is None: + self._context = IpRecordContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the IpRecordInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpRecordInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "IpRecordInstance": + """ + Fetch the IpRecordInstance + + + :returns: The fetched IpRecordInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "IpRecordInstance": + """ + Asynchronous coroutine to fetch the IpRecordInstance + + + :returns: The fetched IpRecordInstance + """ + return await self._proxy.fetch_async() + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> "IpRecordInstance": + """ + Update the IpRecordInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated IpRecordInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "IpRecordInstance": + """ + Asynchronous coroutine to update the IpRecordInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated IpRecordInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class IpRecordContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the IpRecordContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the IP Record resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/IpRecords/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the IpRecordInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpRecordInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> IpRecordInstance: + """ + Fetch the IpRecordInstance + + + :returns: The fetched IpRecordInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return IpRecordInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> IpRecordInstance: + """ + Asynchronous coroutine to fetch the IpRecordInstance + + + :returns: The fetched IpRecordInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return IpRecordInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> IpRecordInstance: + """ + Update the IpRecordInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated IpRecordInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpRecordInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> IpRecordInstance: + """ + Asynchronous coroutine to update the IpRecordInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated IpRecordInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpRecordInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class IpRecordPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> IpRecordInstance: + """ + Build an instance of IpRecordInstance + + :param payload: Payload response from the API + """ + return IpRecordInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class IpRecordList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the IpRecordList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/IpRecords" + + def create( + self, + ip_address: str, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> IpRecordInstance: + """ + Create the IpRecordInstance + + :param ip_address: An IP address in dotted decimal notation, IPv4 only. + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the [CIDR](https://tools.ietf.org/html/rfc4632) prefix to use with this IP address. By default the entire IP address is used, which for IPv4 is value 32. + + :returns: The created IpRecordInstance + """ + + data = values.of( + { + "IpAddress": ip_address, + "FriendlyName": friendly_name, + "CidrPrefixLength": cidr_prefix_length, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpRecordInstance(self._version, payload) + + async def create_async( + self, + ip_address: str, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> IpRecordInstance: + """ + Asynchronously create the IpRecordInstance + + :param ip_address: An IP address in dotted decimal notation, IPv4 only. + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the [CIDR](https://tools.ietf.org/html/rfc4632) prefix to use with this IP address. By default the entire IP address is used, which for IPv4 is value 32. + + :returns: The created IpRecordInstance + """ + + data = values.of( + { + "IpAddress": ip_address, + "FriendlyName": friendly_name, + "CidrPrefixLength": cidr_prefix_length, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpRecordInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[IpRecordInstance]: + """ + Streams IpRecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IpRecordInstance]: + """ + Asynchronously streams IpRecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpRecordInstance]: + """ + Lists IpRecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpRecordInstance]: + """ + Asynchronously lists IpRecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpRecordPage: + """ + Retrieve a single page of IpRecordInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpRecordInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpRecordPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpRecordPage: + """ + Asynchronously retrieve a single page of IpRecordInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpRecordInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpRecordPage(self._version, response) + + def get_page(self, target_url: str) -> IpRecordPage: + """ + Retrieve a specific page of IpRecordInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpRecordInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return IpRecordPage(self._version, response) + + async def get_page_async(self, target_url: str) -> IpRecordPage: + """ + Asynchronously retrieve a specific page of IpRecordInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpRecordInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return IpRecordPage(self._version, response) + + def get(self, sid: str) -> IpRecordContext: + """ + Constructs a IpRecordContext + + :param sid: The Twilio-provided string that uniquely identifies the IP Record resource to update. + """ + return IpRecordContext(self._version, sid=sid) + + def __call__(self, sid: str) -> IpRecordContext: + """ + Constructs a IpRecordContext + + :param sid: The Twilio-provided string that uniquely identifies the IP Record resource to update. + """ + return IpRecordContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/voice/v1/source_ip_mapping.py b/venv/Lib/site-packages/twilio/rest/voice/v1/source_ip_mapping.py new file mode 100644 index 00000000..749d2b00 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/voice/v1/source_ip_mapping.py @@ -0,0 +1,599 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SourceIpMappingInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the IP Record resource. + :ivar ip_record_sid: The Twilio-provided string that uniquely identifies the IP Record resource to map from. + :ivar sip_domain_sid: The SID of the SIP Domain that the IP Record is mapped to. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.ip_record_sid: Optional[str] = payload.get("ip_record_sid") + self.sip_domain_sid: Optional[str] = payload.get("sip_domain_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SourceIpMappingContext] = None + + @property + def _proxy(self) -> "SourceIpMappingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SourceIpMappingContext for this SourceIpMappingInstance + """ + if self._context is None: + self._context = SourceIpMappingContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SourceIpMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SourceIpMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SourceIpMappingInstance": + """ + Fetch the SourceIpMappingInstance + + + :returns: The fetched SourceIpMappingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SourceIpMappingInstance": + """ + Asynchronous coroutine to fetch the SourceIpMappingInstance + + + :returns: The fetched SourceIpMappingInstance + """ + return await self._proxy.fetch_async() + + def update(self, sip_domain_sid: str) -> "SourceIpMappingInstance": + """ + Update the SourceIpMappingInstance + + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: The updated SourceIpMappingInstance + """ + return self._proxy.update( + sip_domain_sid=sip_domain_sid, + ) + + async def update_async(self, sip_domain_sid: str) -> "SourceIpMappingInstance": + """ + Asynchronous coroutine to update the SourceIpMappingInstance + + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: The updated SourceIpMappingInstance + """ + return await self._proxy.update_async( + sip_domain_sid=sip_domain_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SourceIpMappingContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SourceIpMappingContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the IP Record resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/SourceIpMappings/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the SourceIpMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SourceIpMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SourceIpMappingInstance: + """ + Fetch the SourceIpMappingInstance + + + :returns: The fetched SourceIpMappingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SourceIpMappingInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SourceIpMappingInstance: + """ + Asynchronous coroutine to fetch the SourceIpMappingInstance + + + :returns: The fetched SourceIpMappingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SourceIpMappingInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update(self, sip_domain_sid: str) -> SourceIpMappingInstance: + """ + Update the SourceIpMappingInstance + + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: The updated SourceIpMappingInstance + """ + + data = values.of( + { + "SipDomainSid": sip_domain_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SourceIpMappingInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async(self, sip_domain_sid: str) -> SourceIpMappingInstance: + """ + Asynchronous coroutine to update the SourceIpMappingInstance + + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: The updated SourceIpMappingInstance + """ + + data = values.of( + { + "SipDomainSid": sip_domain_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SourceIpMappingInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SourceIpMappingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SourceIpMappingInstance: + """ + Build an instance of SourceIpMappingInstance + + :param payload: Payload response from the API + """ + return SourceIpMappingInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SourceIpMappingList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SourceIpMappingList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/SourceIpMappings" + + def create( + self, ip_record_sid: str, sip_domain_sid: str + ) -> SourceIpMappingInstance: + """ + Create the SourceIpMappingInstance + + :param ip_record_sid: The Twilio-provided string that uniquely identifies the IP Record resource to map from. + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: The created SourceIpMappingInstance + """ + + data = values.of( + { + "IpRecordSid": ip_record_sid, + "SipDomainSid": sip_domain_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SourceIpMappingInstance(self._version, payload) + + async def create_async( + self, ip_record_sid: str, sip_domain_sid: str + ) -> SourceIpMappingInstance: + """ + Asynchronously create the SourceIpMappingInstance + + :param ip_record_sid: The Twilio-provided string that uniquely identifies the IP Record resource to map from. + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: The created SourceIpMappingInstance + """ + + data = values.of( + { + "IpRecordSid": ip_record_sid, + "SipDomainSid": sip_domain_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SourceIpMappingInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SourceIpMappingInstance]: + """ + Streams SourceIpMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SourceIpMappingInstance]: + """ + Asynchronously streams SourceIpMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SourceIpMappingInstance]: + """ + Lists SourceIpMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SourceIpMappingInstance]: + """ + Asynchronously lists SourceIpMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SourceIpMappingPage: + """ + Retrieve a single page of SourceIpMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SourceIpMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SourceIpMappingPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SourceIpMappingPage: + """ + Asynchronously retrieve a single page of SourceIpMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SourceIpMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SourceIpMappingPage(self._version, response) + + def get_page(self, target_url: str) -> SourceIpMappingPage: + """ + Retrieve a specific page of SourceIpMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SourceIpMappingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SourceIpMappingPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SourceIpMappingPage: + """ + Asynchronously retrieve a specific page of SourceIpMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SourceIpMappingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SourceIpMappingPage(self._version, response) + + def get(self, sid: str) -> SourceIpMappingContext: + """ + Constructs a SourceIpMappingContext + + :param sid: The Twilio-provided string that uniquely identifies the IP Record resource to update. + """ + return SourceIpMappingContext(self._version, sid=sid) + + def __call__(self, sid: str) -> SourceIpMappingContext: + """ + Constructs a SourceIpMappingContext + + :param sid: The Twilio-provided string that uniquely identifies the IP Record resource to update. + """ + return SourceIpMappingContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/wireless/WirelessBase.py b/venv/Lib/site-packages/twilio/rest/wireless/WirelessBase.py new file mode 100644 index 00000000..0228c4d6 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/wireless/WirelessBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.wireless.v1 import V1 + + +class WirelessBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Wireless Domain + + :returns: Domain for Wireless + """ + super().__init__(twilio, "https://wireless.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Wireless + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/wireless/__init__.py b/venv/Lib/site-packages/twilio/rest/wireless/__init__.py new file mode 100644 index 00000000..3b7a4097 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/wireless/__init__.py @@ -0,0 +1,43 @@ +from warnings import warn + +from twilio.rest.wireless.WirelessBase import WirelessBase +from twilio.rest.wireless.v1.command import CommandList +from twilio.rest.wireless.v1.rate_plan import RatePlanList +from twilio.rest.wireless.v1.sim import SimList +from twilio.rest.wireless.v1.usage_record import UsageRecordList + + +class Wireless(WirelessBase): + @property + def usage_records(self) -> UsageRecordList: + warn( + "usage_records is deprecated. Use v1.usage_records instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.usage_records + + @property + def commands(self) -> CommandList: + warn( + "commands is deprecated. Use v1.commands instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.commands + + @property + def rate_plans(self) -> RatePlanList: + warn( + "rate_plans is deprecated. Use v1.rate_plans instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.rate_plans + + @property + def sims(self) -> SimList: + warn( + "sims is deprecated. Use v1.sims instead.", DeprecationWarning, stacklevel=2 + ) + return self.v1.sims diff --git a/venv/Lib/site-packages/twilio/rest/wireless/__pycache__/WirelessBase.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/wireless/__pycache__/WirelessBase.cpython-312.pyc new file mode 100644 index 00000000..aa2a5076 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/wireless/__pycache__/WirelessBase.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/wireless/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/wireless/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..a94f390b Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/wireless/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/wireless/v1/__init__.py b/venv/Lib/site-packages/twilio/rest/wireless/v1/__init__.py new file mode 100644 index 00000000..8f4d0dc5 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/wireless/v1/__init__.py @@ -0,0 +1,67 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Wireless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.wireless.v1.command import CommandList +from twilio.rest.wireless.v1.rate_plan import RatePlanList +from twilio.rest.wireless.v1.sim import SimList +from twilio.rest.wireless.v1.usage_record import UsageRecordList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Wireless + + :param domain: The Twilio.wireless domain + """ + super().__init__(domain, "v1") + self._commands: Optional[CommandList] = None + self._rate_plans: Optional[RatePlanList] = None + self._sims: Optional[SimList] = None + self._usage_records: Optional[UsageRecordList] = None + + @property + def commands(self) -> CommandList: + if self._commands is None: + self._commands = CommandList(self) + return self._commands + + @property + def rate_plans(self) -> RatePlanList: + if self._rate_plans is None: + self._rate_plans = RatePlanList(self) + return self._rate_plans + + @property + def sims(self) -> SimList: + if self._sims is None: + self._sims = SimList(self) + return self._sims + + @property + def usage_records(self) -> UsageRecordList: + if self._usage_records is None: + self._usage_records = UsageRecordList(self) + return self._usage_records + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/wireless/v1/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/wireless/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..392634f0 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/wireless/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/wireless/v1/__pycache__/command.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/wireless/v1/__pycache__/command.cpython-312.pyc new file mode 100644 index 00000000..c6400793 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/wireless/v1/__pycache__/command.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/wireless/v1/__pycache__/rate_plan.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/wireless/v1/__pycache__/rate_plan.cpython-312.pyc new file mode 100644 index 00000000..5b2f144f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/wireless/v1/__pycache__/rate_plan.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/wireless/v1/__pycache__/usage_record.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/wireless/v1/__pycache__/usage_record.cpython-312.pyc new file mode 100644 index 00000000..0995962f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/wireless/v1/__pycache__/usage_record.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/wireless/v1/command.py b/venv/Lib/site-packages/twilio/rest/wireless/v1/command.py new file mode 100644 index 00000000..a6e8f0b3 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/wireless/v1/command.py @@ -0,0 +1,669 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Wireless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CommandInstance(InstanceResource): + + class CommandMode(object): + TEXT = "text" + BINARY = "binary" + + class Direction(object): + FROM_SIM = "from_sim" + TO_SIM = "to_sim" + + class Status(object): + QUEUED = "queued" + SENT = "sent" + DELIVERED = "delivered" + RECEIVED = "received" + FAILED = "failed" + + class Transport(object): + SMS = "sms" + IP = "ip" + + """ + :ivar sid: The unique string that we created to identify the Command resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Command resource. + :ivar sim_sid: The SID of the [Sim resource](https://www.twilio.com/docs/iot/wireless/api/sim-resource) that the Command was sent to or from. + :ivar command: The message being sent to or from the SIM. For text mode messages, this can be up to 160 characters. For binary mode messages, this is a series of up to 140 bytes of data encoded using base64. + :ivar command_mode: + :ivar transport: + :ivar delivery_receipt_requested: Whether to request a delivery receipt. + :ivar status: + :ivar direction: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.command: Optional[str] = payload.get("command") + self.command_mode: Optional["CommandInstance.CommandMode"] = payload.get( + "command_mode" + ) + self.transport: Optional["CommandInstance.Transport"] = payload.get("transport") + self.delivery_receipt_requested: Optional[bool] = payload.get( + "delivery_receipt_requested" + ) + self.status: Optional["CommandInstance.Status"] = payload.get("status") + self.direction: Optional["CommandInstance.Direction"] = payload.get("direction") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CommandContext] = None + + @property + def _proxy(self) -> "CommandContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CommandContext for this CommandInstance + """ + if self._context is None: + self._context = CommandContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CommandInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CommandInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CommandInstance": + """ + Fetch the CommandInstance + + + :returns: The fetched CommandInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CommandInstance": + """ + Asynchronous coroutine to fetch the CommandInstance + + + :returns: The fetched CommandInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CommandContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CommandContext + + :param version: Version that contains the resource + :param sid: The SID of the Command resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Commands/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the CommandInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CommandInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CommandInstance: + """ + Fetch the CommandInstance + + + :returns: The fetched CommandInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CommandInstance: + """ + Asynchronous coroutine to fetch the CommandInstance + + + :returns: The fetched CommandInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CommandPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CommandInstance: + """ + Build an instance of CommandInstance + + :param payload: Payload response from the API + """ + return CommandInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CommandList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CommandList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Commands" + + def create( + self, + command: str, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union["CommandInstance.CommandMode", object] = values.unset, + include_sid: Union[str, object] = values.unset, + delivery_receipt_requested: Union[bool, object] = values.unset, + ) -> CommandInstance: + """ + Create the CommandInstance + + :param command: The message body of the Command. Can be plain text in text mode or a Base64 encoded byte string in binary mode. + :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to send the Command to. + :param callback_method: The HTTP method we use to call `callback_url`. Can be: `POST` or `GET`, and the default is `POST`. + :param callback_url: The URL we call using the `callback_url` when the Command has finished sending, whether the command was delivered or it failed. + :param command_mode: + :param include_sid: Whether to include the SID of the command in the message body. Can be: `none`, `start`, or `end`, and the default behavior is `none`. When sending a Command to a SIM in text mode, we can automatically include the SID of the Command in the message body, which could be used to ensure that the device does not process the same Command more than once. A value of `start` will prepend the message with the Command SID, and `end` will append it to the end, separating the Command SID from the message body with a space. The length of the Command SID is included in the 160 character limit so the SMS body must be 128 characters or less before the Command SID is included. + :param delivery_receipt_requested: Whether to request delivery receipt from the recipient. For Commands that request delivery receipt, the Command state transitions to 'delivered' once the server has received a delivery receipt from the device. The default value is `true`. + + :returns: The created CommandInstance + """ + + data = values.of( + { + "Command": command, + "Sim": sim, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "CommandMode": command_mode, + "IncludeSid": include_sid, + "DeliveryReceiptRequested": serialize.boolean_to_string( + delivery_receipt_requested + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CommandInstance(self._version, payload) + + async def create_async( + self, + command: str, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union["CommandInstance.CommandMode", object] = values.unset, + include_sid: Union[str, object] = values.unset, + delivery_receipt_requested: Union[bool, object] = values.unset, + ) -> CommandInstance: + """ + Asynchronously create the CommandInstance + + :param command: The message body of the Command. Can be plain text in text mode or a Base64 encoded byte string in binary mode. + :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to send the Command to. + :param callback_method: The HTTP method we use to call `callback_url`. Can be: `POST` or `GET`, and the default is `POST`. + :param callback_url: The URL we call using the `callback_url` when the Command has finished sending, whether the command was delivered or it failed. + :param command_mode: + :param include_sid: Whether to include the SID of the command in the message body. Can be: `none`, `start`, or `end`, and the default behavior is `none`. When sending a Command to a SIM in text mode, we can automatically include the SID of the Command in the message body, which could be used to ensure that the device does not process the same Command more than once. A value of `start` will prepend the message with the Command SID, and `end` will append it to the end, separating the Command SID from the message body with a space. The length of the Command SID is included in the 160 character limit so the SMS body must be 128 characters or less before the Command SID is included. + :param delivery_receipt_requested: Whether to request delivery receipt from the recipient. For Commands that request delivery receipt, the Command state transitions to 'delivered' once the server has received a delivery receipt from the device. The default value is `true`. + + :returns: The created CommandInstance + """ + + data = values.of( + { + "Command": command, + "Sim": sim, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "CommandMode": command_mode, + "IncludeSid": include_sid, + "DeliveryReceiptRequested": serialize.boolean_to_string( + delivery_receipt_requested + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CommandInstance(self._version, payload) + + def stream( + self, + sim: Union[str, object] = values.unset, + status: Union["CommandInstance.Status", object] = values.unset, + direction: Union["CommandInstance.Direction", object] = values.unset, + transport: Union["CommandInstance.Transport", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CommandInstance]: + """ + Streams CommandInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. + :param "CommandInstance.Status" status: The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. + :param "CommandInstance.Direction" direction: Only return Commands with this direction value. + :param "CommandInstance.Transport" transport: Only return Commands with this transport value. Can be: `sms` or `ip`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + sim=sim, + status=status, + direction=direction, + transport=transport, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + sim: Union[str, object] = values.unset, + status: Union["CommandInstance.Status", object] = values.unset, + direction: Union["CommandInstance.Direction", object] = values.unset, + transport: Union["CommandInstance.Transport", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CommandInstance]: + """ + Asynchronously streams CommandInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. + :param "CommandInstance.Status" status: The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. + :param "CommandInstance.Direction" direction: Only return Commands with this direction value. + :param "CommandInstance.Transport" transport: Only return Commands with this transport value. Can be: `sms` or `ip`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + sim=sim, + status=status, + direction=direction, + transport=transport, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + sim: Union[str, object] = values.unset, + status: Union["CommandInstance.Status", object] = values.unset, + direction: Union["CommandInstance.Direction", object] = values.unset, + transport: Union["CommandInstance.Transport", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CommandInstance]: + """ + Lists CommandInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. + :param "CommandInstance.Status" status: The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. + :param "CommandInstance.Direction" direction: Only return Commands with this direction value. + :param "CommandInstance.Transport" transport: Only return Commands with this transport value. Can be: `sms` or `ip`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + sim=sim, + status=status, + direction=direction, + transport=transport, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + sim: Union[str, object] = values.unset, + status: Union["CommandInstance.Status", object] = values.unset, + direction: Union["CommandInstance.Direction", object] = values.unset, + transport: Union["CommandInstance.Transport", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CommandInstance]: + """ + Asynchronously lists CommandInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. + :param "CommandInstance.Status" status: The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. + :param "CommandInstance.Direction" direction: Only return Commands with this direction value. + :param "CommandInstance.Transport" transport: Only return Commands with this transport value. Can be: `sms` or `ip`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + sim=sim, + status=status, + direction=direction, + transport=transport, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + sim: Union[str, object] = values.unset, + status: Union["CommandInstance.Status", object] = values.unset, + direction: Union["CommandInstance.Direction", object] = values.unset, + transport: Union["CommandInstance.Transport", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CommandPage: + """ + Retrieve a single page of CommandInstance records from the API. + Request is executed immediately + + :param sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. + :param status: The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. + :param direction: Only return Commands with this direction value. + :param transport: Only return Commands with this transport value. Can be: `sms` or `ip`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CommandInstance + """ + data = values.of( + { + "Sim": sim, + "Status": status, + "Direction": direction, + "Transport": transport, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CommandPage(self._version, response) + + async def page_async( + self, + sim: Union[str, object] = values.unset, + status: Union["CommandInstance.Status", object] = values.unset, + direction: Union["CommandInstance.Direction", object] = values.unset, + transport: Union["CommandInstance.Transport", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CommandPage: + """ + Asynchronously retrieve a single page of CommandInstance records from the API. + Request is executed immediately + + :param sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. + :param status: The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. + :param direction: Only return Commands with this direction value. + :param transport: Only return Commands with this transport value. Can be: `sms` or `ip`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CommandInstance + """ + data = values.of( + { + "Sim": sim, + "Status": status, + "Direction": direction, + "Transport": transport, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CommandPage(self._version, response) + + def get_page(self, target_url: str) -> CommandPage: + """ + Retrieve a specific page of CommandInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CommandInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CommandPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CommandPage: + """ + Asynchronously retrieve a specific page of CommandInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CommandInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CommandPage(self._version, response) + + def get(self, sid: str) -> CommandContext: + """ + Constructs a CommandContext + + :param sid: The SID of the Command resource to fetch. + """ + return CommandContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CommandContext: + """ + Constructs a CommandContext + + :param sid: The SID of the Command resource to fetch. + """ + return CommandContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/wireless/v1/rate_plan.py b/venv/Lib/site-packages/twilio/rest/wireless/v1/rate_plan.py new file mode 100644 index 00000000..23efabe9 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/wireless/v1/rate_plan.py @@ -0,0 +1,728 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Wireless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RatePlanInstance(InstanceResource): + + class DataLimitStrategy(object): + BLOCK = "block" + THROTTLE = "throttle" + + """ + :ivar sid: The unique string that we created to identify the RatePlan resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the RatePlan resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar data_enabled: Whether SIMs can use GPRS/3G/4G/LTE data connectivity. + :ivar data_metering: The model used to meter data usage. Can be: `payg` and `quota-1`, `quota-10`, and `quota-50`. Learn more about the available [data metering models](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#payg-vs-quota-data-plans). + :ivar data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on the home network (T-Mobile USA). The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB. + :ivar messaging_enabled: Whether SIMs can make, send, and receive SMS using [Commands](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :ivar voice_enabled: Deprecated. Whether SIMs can make and receive voice calls. + :ivar national_roaming_enabled: Whether SIMs can roam on networks other than the home network (T-Mobile USA) in the United States. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming). + :ivar national_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on non-home networks in the United States. The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB. + :ivar international_roaming: The list of services that SIMs capable of using GPRS/3G/4G/LTE data connectivity can use outside of the United States. Can contain: `data` and `messaging`. + :ivar international_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month when roaming outside the United States. Can be up to 2TB. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.data_enabled: Optional[bool] = payload.get("data_enabled") + self.data_metering: Optional[str] = payload.get("data_metering") + self.data_limit: Optional[int] = deserialize.integer(payload.get("data_limit")) + self.messaging_enabled: Optional[bool] = payload.get("messaging_enabled") + self.voice_enabled: Optional[bool] = payload.get("voice_enabled") + self.national_roaming_enabled: Optional[bool] = payload.get( + "national_roaming_enabled" + ) + self.national_roaming_data_limit: Optional[int] = deserialize.integer( + payload.get("national_roaming_data_limit") + ) + self.international_roaming: Optional[List[str]] = payload.get( + "international_roaming" + ) + self.international_roaming_data_limit: Optional[int] = deserialize.integer( + payload.get("international_roaming_data_limit") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[RatePlanContext] = None + + @property + def _proxy(self) -> "RatePlanContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RatePlanContext for this RatePlanInstance + """ + if self._context is None: + self._context = RatePlanContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RatePlanInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RatePlanInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RatePlanInstance": + """ + Fetch the RatePlanInstance + + + :returns: The fetched RatePlanInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RatePlanInstance": + """ + Asynchronous coroutine to fetch the RatePlanInstance + + + :returns: The fetched RatePlanInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "RatePlanInstance": + """ + Update the RatePlanInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. + + :returns: The updated RatePlanInstance + """ + return self._proxy.update( + unique_name=unique_name, + friendly_name=friendly_name, + ) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "RatePlanInstance": + """ + Asynchronous coroutine to update the RatePlanInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. + + :returns: The updated RatePlanInstance + """ + return await self._proxy.update_async( + unique_name=unique_name, + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RatePlanContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the RatePlanContext + + :param version: Version that contains the resource + :param sid: The SID of the RatePlan resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/RatePlans/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the RatePlanInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RatePlanInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RatePlanInstance: + """ + Fetch the RatePlanInstance + + + :returns: The fetched RatePlanInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RatePlanInstance: + """ + Asynchronous coroutine to fetch the RatePlanInstance + + + :returns: The fetched RatePlanInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> RatePlanInstance: + """ + Update the RatePlanInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. + + :returns: The updated RatePlanInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> RatePlanInstance: + """ + Asynchronous coroutine to update the RatePlanInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. + + :returns: The updated RatePlanInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RatePlanPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RatePlanInstance: + """ + Build an instance of RatePlanInstance + + :param payload: Payload response from the API + """ + return RatePlanInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RatePlanList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the RatePlanList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/RatePlans" + + def create( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + national_roaming_data_limit: Union[int, object] = values.unset, + international_roaming_data_limit: Union[int, object] = values.unset, + data_limit_strategy: Union[ + "RatePlanInstance.DataLimitStrategy", object + ] = values.unset, + ) -> RatePlanInstance: + """ + Create the RatePlanInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. + :param data_enabled: Whether SIMs can use GPRS/3G/4G/LTE data connectivity. + :param data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on the home network (T-Mobile USA). The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB and the default value is `1000`. + :param data_metering: The model used to meter data usage. Can be: `payg` and `quota-1`, `quota-10`, and `quota-50`. Learn more about the available [data metering models](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#payg-vs-quota-data-plans). + :param messaging_enabled: Whether SIMs can make, send, and receive SMS using [Commands](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_enabled: Deprecated. + :param national_roaming_enabled: Whether SIMs can roam on networks other than the home network (T-Mobile USA) in the United States. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming). + :param international_roaming: The list of services that SIMs capable of using GPRS/3G/4G/LTE data connectivity can use outside of the United States. Can contain: `data` and `messaging`. + :param national_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on non-home networks in the United States. The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming) for more info. + :param international_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month when roaming outside the United States. Can be up to 2TB. + :param data_limit_strategy: + + :returns: The created RatePlanInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + "DataEnabled": serialize.boolean_to_string(data_enabled), + "DataLimit": data_limit, + "DataMetering": data_metering, + "MessagingEnabled": serialize.boolean_to_string(messaging_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "NationalRoamingEnabled": serialize.boolean_to_string( + national_roaming_enabled + ), + "InternationalRoaming": serialize.map( + international_roaming, lambda e: e + ), + "NationalRoamingDataLimit": national_roaming_data_limit, + "InternationalRoamingDataLimit": international_roaming_data_limit, + "DataLimitStrategy": data_limit_strategy, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RatePlanInstance(self._version, payload) + + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + national_roaming_data_limit: Union[int, object] = values.unset, + international_roaming_data_limit: Union[int, object] = values.unset, + data_limit_strategy: Union[ + "RatePlanInstance.DataLimitStrategy", object + ] = values.unset, + ) -> RatePlanInstance: + """ + Asynchronously create the RatePlanInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. + :param data_enabled: Whether SIMs can use GPRS/3G/4G/LTE data connectivity. + :param data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on the home network (T-Mobile USA). The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB and the default value is `1000`. + :param data_metering: The model used to meter data usage. Can be: `payg` and `quota-1`, `quota-10`, and `quota-50`. Learn more about the available [data metering models](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#payg-vs-quota-data-plans). + :param messaging_enabled: Whether SIMs can make, send, and receive SMS using [Commands](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_enabled: Deprecated. + :param national_roaming_enabled: Whether SIMs can roam on networks other than the home network (T-Mobile USA) in the United States. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming). + :param international_roaming: The list of services that SIMs capable of using GPRS/3G/4G/LTE data connectivity can use outside of the United States. Can contain: `data` and `messaging`. + :param national_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on non-home networks in the United States. The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming) for more info. + :param international_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month when roaming outside the United States. Can be up to 2TB. + :param data_limit_strategy: + + :returns: The created RatePlanInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + "DataEnabled": serialize.boolean_to_string(data_enabled), + "DataLimit": data_limit, + "DataMetering": data_metering, + "MessagingEnabled": serialize.boolean_to_string(messaging_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "NationalRoamingEnabled": serialize.boolean_to_string( + national_roaming_enabled + ), + "InternationalRoaming": serialize.map( + international_roaming, lambda e: e + ), + "NationalRoamingDataLimit": national_roaming_data_limit, + "InternationalRoamingDataLimit": international_roaming_data_limit, + "DataLimitStrategy": data_limit_strategy, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RatePlanInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RatePlanInstance]: + """ + Streams RatePlanInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RatePlanInstance]: + """ + Asynchronously streams RatePlanInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RatePlanInstance]: + """ + Lists RatePlanInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RatePlanInstance]: + """ + Asynchronously lists RatePlanInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RatePlanPage: + """ + Retrieve a single page of RatePlanInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RatePlanInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RatePlanPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RatePlanPage: + """ + Asynchronously retrieve a single page of RatePlanInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RatePlanInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RatePlanPage(self._version, response) + + def get_page(self, target_url: str) -> RatePlanPage: + """ + Retrieve a specific page of RatePlanInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RatePlanInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RatePlanPage(self._version, response) + + async def get_page_async(self, target_url: str) -> RatePlanPage: + """ + Asynchronously retrieve a specific page of RatePlanInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RatePlanInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RatePlanPage(self._version, response) + + def get(self, sid: str) -> RatePlanContext: + """ + Constructs a RatePlanContext + + :param sid: The SID of the RatePlan resource to update. + """ + return RatePlanContext(self._version, sid=sid) + + def __call__(self, sid: str) -> RatePlanContext: + """ + Constructs a RatePlanContext + + :param sid: The SID of the RatePlan resource to update. + """ + return RatePlanContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/wireless/v1/sim/__init__.py b/venv/Lib/site-packages/twilio/rest/wireless/v1/sim/__init__.py new file mode 100644 index 00000000..cba0eeec --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/wireless/v1/sim/__init__.py @@ -0,0 +1,942 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Wireless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.wireless.v1.sim.data_session import DataSessionList +from twilio.rest.wireless.v1.sim.usage_record import UsageRecordList + + +class SimInstance(InstanceResource): + + class ResetStatus(object): + RESETTING = "resetting" + + class Status(object): + NEW = "new" + READY = "ready" + ACTIVE = "active" + SUSPENDED = "suspended" + DEACTIVATED = "deactivated" + CANCELED = "canceled" + SCHEDULED = "scheduled" + UPDATING = "updating" + + """ + :ivar sid: The unique string that we created to identify the Sim resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the Sim resource belongs. + :ivar rate_plan_sid: The SID of the [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource) to which the Sim resource is assigned. + :ivar friendly_name: The string that you assigned to describe the Sim resource. + :ivar iccid: The [ICCID](https://en.wikipedia.org/wiki/SIM_card#ICCID) associated with the SIM. + :ivar e_id: Deprecated. + :ivar status: + :ivar reset_status: + :ivar commands_callback_url: The URL we call using the `commands_callback_method` when the SIM originates a machine-to-machine [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :ivar commands_callback_method: The HTTP method we use to call `commands_callback_url`. Can be: `POST` or `GET`. Default is `POST`. + :ivar sms_fallback_method: Deprecated. + :ivar sms_fallback_url: Deprecated. + :ivar sms_method: Deprecated. + :ivar sms_url: Deprecated. + :ivar voice_fallback_method: Deprecated. The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. Default is `POST`. + :ivar voice_fallback_url: Deprecated. The URL we call using the `voice_fallback_method` when an error occurs while retrieving or executing the TwiML requested from `voice_url`. + :ivar voice_method: Deprecated. The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. Default is `POST`. + :ivar voice_url: Deprecated. The URL we call using the `voice_method` when the SIM-connected device makes a voice call. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar date_updated: The date and time in GMT when the Sim resource was last updated specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related subresources. + :ivar ip_address: Deprecated. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.rate_plan_sid: Optional[str] = payload.get("rate_plan_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.iccid: Optional[str] = payload.get("iccid") + self.e_id: Optional[str] = payload.get("e_id") + self.status: Optional["SimInstance.Status"] = payload.get("status") + self.reset_status: Optional["SimInstance.ResetStatus"] = payload.get( + "reset_status" + ) + self.commands_callback_url: Optional[str] = payload.get("commands_callback_url") + self.commands_callback_method: Optional[str] = payload.get( + "commands_callback_method" + ) + self.sms_fallback_method: Optional[str] = payload.get("sms_fallback_method") + self.sms_fallback_url: Optional[str] = payload.get("sms_fallback_url") + self.sms_method: Optional[str] = payload.get("sms_method") + self.sms_url: Optional[str] = payload.get("sms_url") + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_url: Optional[str] = payload.get("voice_url") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.ip_address: Optional[str] = payload.get("ip_address") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SimContext] = None + + @property + def _proxy(self) -> "SimContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SimContext for this SimInstance + """ + if self._context is None: + self._context = SimContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SimInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SimInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SimInstance": + """ + Fetch the SimInstance + + + :returns: The fetched SimInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SimInstance": + """ + Asynchronous coroutine to fetch the SimInstance + + + :returns: The fetched SimInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union["SimInstance.Status", object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + reset_status: Union["SimInstance.ResetStatus", object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> "SimInstance": + """ + Update the SimInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the `sid` in the URL path to address the resource. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param callback_url: The URL we should call using the `callback_url` when the SIM has finished updating. When the SIM transitions from `new` to `ready` or from any status to `deactivated`, we call this URL when the status changes to an intermediate status (`ready` or `deactivated`) and again when the status changes to its final status (`active` or `canceled`). + :param friendly_name: A descriptive string that you create to describe the Sim resource. It does not need to be unique. + :param rate_plan: The SID or unique name of the [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource) to which the Sim resource should be assigned. + :param status: + :param commands_callback_method: The HTTP method we should use to call `commands_callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param commands_callback_url: The URL we should call using the `commands_callback_method` when the SIM sends a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body is ignored. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_fallback_url: The URL we should call using the `sms_fallback_method` when an error occurs while retrieving or executing the TwiML requested from `sms_url`. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_url: The URL we should call using the `sms_method` when the SIM-connected device sends an SMS message that is not a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_fallback_method: Deprecated. + :param voice_fallback_url: Deprecated. + :param voice_method: Deprecated. + :param voice_url: Deprecated. + :param reset_status: + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a [Subaccount](https://www.twilio.com/docs/iam/api/subaccounts) of the requesting Account. Only valid when the Sim resource's status is `new`. For more information, see the [Move SIMs between Subaccounts documentation](https://www.twilio.com/docs/iot/wireless/api/sim-resource#move-sims-between-subaccounts). + + :returns: The updated SimInstance + """ + return self._proxy.update( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + reset_status=reset_status, + account_sid=account_sid, + ) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union["SimInstance.Status", object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + reset_status: Union["SimInstance.ResetStatus", object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> "SimInstance": + """ + Asynchronous coroutine to update the SimInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the `sid` in the URL path to address the resource. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param callback_url: The URL we should call using the `callback_url` when the SIM has finished updating. When the SIM transitions from `new` to `ready` or from any status to `deactivated`, we call this URL when the status changes to an intermediate status (`ready` or `deactivated`) and again when the status changes to its final status (`active` or `canceled`). + :param friendly_name: A descriptive string that you create to describe the Sim resource. It does not need to be unique. + :param rate_plan: The SID or unique name of the [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource) to which the Sim resource should be assigned. + :param status: + :param commands_callback_method: The HTTP method we should use to call `commands_callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param commands_callback_url: The URL we should call using the `commands_callback_method` when the SIM sends a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body is ignored. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_fallback_url: The URL we should call using the `sms_fallback_method` when an error occurs while retrieving or executing the TwiML requested from `sms_url`. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_url: The URL we should call using the `sms_method` when the SIM-connected device sends an SMS message that is not a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_fallback_method: Deprecated. + :param voice_fallback_url: Deprecated. + :param voice_method: Deprecated. + :param voice_url: Deprecated. + :param reset_status: + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a [Subaccount](https://www.twilio.com/docs/iam/api/subaccounts) of the requesting Account. Only valid when the Sim resource's status is `new`. For more information, see the [Move SIMs between Subaccounts documentation](https://www.twilio.com/docs/iot/wireless/api/sim-resource#move-sims-between-subaccounts). + + :returns: The updated SimInstance + """ + return await self._proxy.update_async( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + reset_status=reset_status, + account_sid=account_sid, + ) + + @property + def data_sessions(self) -> DataSessionList: + """ + Access the data_sessions + """ + return self._proxy.data_sessions + + @property + def usage_records(self) -> UsageRecordList: + """ + Access the usage_records + """ + return self._proxy.usage_records + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SimContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SimContext + + :param version: Version that contains the resource + :param sid: The SID or the `unique_name` of the Sim resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Sims/{sid}".format(**self._solution) + + self._data_sessions: Optional[DataSessionList] = None + self._usage_records: Optional[UsageRecordList] = None + + def delete(self) -> bool: + """ + Deletes the SimInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SimInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SimInstance: + """ + Fetch the SimInstance + + + :returns: The fetched SimInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SimInstance: + """ + Asynchronous coroutine to fetch the SimInstance + + + :returns: The fetched SimInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union["SimInstance.Status", object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + reset_status: Union["SimInstance.ResetStatus", object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> SimInstance: + """ + Update the SimInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the `sid` in the URL path to address the resource. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param callback_url: The URL we should call using the `callback_url` when the SIM has finished updating. When the SIM transitions from `new` to `ready` or from any status to `deactivated`, we call this URL when the status changes to an intermediate status (`ready` or `deactivated`) and again when the status changes to its final status (`active` or `canceled`). + :param friendly_name: A descriptive string that you create to describe the Sim resource. It does not need to be unique. + :param rate_plan: The SID or unique name of the [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource) to which the Sim resource should be assigned. + :param status: + :param commands_callback_method: The HTTP method we should use to call `commands_callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param commands_callback_url: The URL we should call using the `commands_callback_method` when the SIM sends a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body is ignored. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_fallback_url: The URL we should call using the `sms_fallback_method` when an error occurs while retrieving or executing the TwiML requested from `sms_url`. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_url: The URL we should call using the `sms_method` when the SIM-connected device sends an SMS message that is not a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_fallback_method: Deprecated. + :param voice_fallback_url: Deprecated. + :param voice_method: Deprecated. + :param voice_url: Deprecated. + :param reset_status: + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a [Subaccount](https://www.twilio.com/docs/iam/api/subaccounts) of the requesting Account. Only valid when the Sim resource's status is `new`. For more information, see the [Move SIMs between Subaccounts documentation](https://www.twilio.com/docs/iot/wireless/api/sim-resource#move-sims-between-subaccounts). + + :returns: The updated SimInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "FriendlyName": friendly_name, + "RatePlan": rate_plan, + "Status": status, + "CommandsCallbackMethod": commands_callback_method, + "CommandsCallbackUrl": commands_callback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "ResetStatus": reset_status, + "AccountSid": account_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SimInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union["SimInstance.Status", object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + reset_status: Union["SimInstance.ResetStatus", object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> SimInstance: + """ + Asynchronous coroutine to update the SimInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the `sid` in the URL path to address the resource. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param callback_url: The URL we should call using the `callback_url` when the SIM has finished updating. When the SIM transitions from `new` to `ready` or from any status to `deactivated`, we call this URL when the status changes to an intermediate status (`ready` or `deactivated`) and again when the status changes to its final status (`active` or `canceled`). + :param friendly_name: A descriptive string that you create to describe the Sim resource. It does not need to be unique. + :param rate_plan: The SID or unique name of the [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource) to which the Sim resource should be assigned. + :param status: + :param commands_callback_method: The HTTP method we should use to call `commands_callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param commands_callback_url: The URL we should call using the `commands_callback_method` when the SIM sends a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body is ignored. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_fallback_url: The URL we should call using the `sms_fallback_method` when an error occurs while retrieving or executing the TwiML requested from `sms_url`. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_url: The URL we should call using the `sms_method` when the SIM-connected device sends an SMS message that is not a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_fallback_method: Deprecated. + :param voice_fallback_url: Deprecated. + :param voice_method: Deprecated. + :param voice_url: Deprecated. + :param reset_status: + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a [Subaccount](https://www.twilio.com/docs/iam/api/subaccounts) of the requesting Account. Only valid when the Sim resource's status is `new`. For more information, see the [Move SIMs between Subaccounts documentation](https://www.twilio.com/docs/iot/wireless/api/sim-resource#move-sims-between-subaccounts). + + :returns: The updated SimInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "FriendlyName": friendly_name, + "RatePlan": rate_plan, + "Status": status, + "CommandsCallbackMethod": commands_callback_method, + "CommandsCallbackUrl": commands_callback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "ResetStatus": reset_status, + "AccountSid": account_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SimInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def data_sessions(self) -> DataSessionList: + """ + Access the data_sessions + """ + if self._data_sessions is None: + self._data_sessions = DataSessionList( + self._version, + self._solution["sid"], + ) + return self._data_sessions + + @property + def usage_records(self) -> UsageRecordList: + """ + Access the usage_records + """ + if self._usage_records is None: + self._usage_records = UsageRecordList( + self._version, + self._solution["sid"], + ) + return self._usage_records + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class SimPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SimInstance: + """ + Build an instance of SimInstance + + :param payload: Payload response from the API + """ + return SimInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SimList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SimList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Sims" + + def stream( + self, + status: Union["SimInstance.Status", object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SimInstance]: + """ + Streams SimInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "SimInstance.Status" status: Only return Sim resources with this status. + :param str iccid: Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. + :param str rate_plan: The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :param str e_id: Deprecated. + :param str sim_registration_code: Only return Sim resources with this registration code. This will return a list with a maximum size of 1. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["SimInstance.Status", object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SimInstance]: + """ + Asynchronously streams SimInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "SimInstance.Status" status: Only return Sim resources with this status. + :param str iccid: Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. + :param str rate_plan: The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :param str e_id: Deprecated. + :param str sim_registration_code: Only return Sim resources with this registration code. This will return a list with a maximum size of 1. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["SimInstance.Status", object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SimInstance]: + """ + Lists SimInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "SimInstance.Status" status: Only return Sim resources with this status. + :param str iccid: Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. + :param str rate_plan: The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :param str e_id: Deprecated. + :param str sim_registration_code: Only return Sim resources with this registration code. This will return a list with a maximum size of 1. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["SimInstance.Status", object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SimInstance]: + """ + Asynchronously lists SimInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "SimInstance.Status" status: Only return Sim resources with this status. + :param str iccid: Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. + :param str rate_plan: The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :param str e_id: Deprecated. + :param str sim_registration_code: Only return Sim resources with this registration code. This will return a list with a maximum size of 1. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["SimInstance.Status", object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SimPage: + """ + Retrieve a single page of SimInstance records from the API. + Request is executed immediately + + :param status: Only return Sim resources with this status. + :param iccid: Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. + :param rate_plan: The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :param e_id: Deprecated. + :param sim_registration_code: Only return Sim resources with this registration code. This will return a list with a maximum size of 1. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SimInstance + """ + data = values.of( + { + "Status": status, + "Iccid": iccid, + "RatePlan": rate_plan, + "EId": e_id, + "SimRegistrationCode": sim_registration_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SimPage(self._version, response) + + async def page_async( + self, + status: Union["SimInstance.Status", object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SimPage: + """ + Asynchronously retrieve a single page of SimInstance records from the API. + Request is executed immediately + + :param status: Only return Sim resources with this status. + :param iccid: Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. + :param rate_plan: The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :param e_id: Deprecated. + :param sim_registration_code: Only return Sim resources with this registration code. This will return a list with a maximum size of 1. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SimInstance + """ + data = values.of( + { + "Status": status, + "Iccid": iccid, + "RatePlan": rate_plan, + "EId": e_id, + "SimRegistrationCode": sim_registration_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SimPage(self._version, response) + + def get_page(self, target_url: str) -> SimPage: + """ + Retrieve a specific page of SimInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SimInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SimPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SimPage: + """ + Asynchronously retrieve a specific page of SimInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SimInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SimPage(self._version, response) + + def get(self, sid: str) -> SimContext: + """ + Constructs a SimContext + + :param sid: The SID or the `unique_name` of the Sim resource to update. + """ + return SimContext(self._version, sid=sid) + + def __call__(self, sid: str) -> SimContext: + """ + Constructs a SimContext + + :param sid: The SID or the `unique_name` of the Sim resource to update. + """ + return SimContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/wireless/v1/sim/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/wireless/v1/sim/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..904abed0 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/wireless/v1/sim/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/wireless/v1/sim/__pycache__/data_session.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/wireless/v1/sim/__pycache__/data_session.cpython-312.pyc new file mode 100644 index 00000000..c103397f Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/wireless/v1/sim/__pycache__/data_session.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/wireless/v1/sim/__pycache__/usage_record.cpython-312.pyc b/venv/Lib/site-packages/twilio/rest/wireless/v1/sim/__pycache__/usage_record.cpython-312.pyc new file mode 100644 index 00000000..93d56041 Binary files /dev/null and b/venv/Lib/site-packages/twilio/rest/wireless/v1/sim/__pycache__/usage_record.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/rest/wireless/v1/sim/data_session.py b/venv/Lib/site-packages/twilio/rest/wireless/v1/sim/data_session.py new file mode 100644 index 00000000..b4c50d60 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/wireless/v1/sim/data_session.py @@ -0,0 +1,327 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Wireless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DataSessionInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the DataSession resource. + :ivar sim_sid: The SID of the [Sim resource](https://www.twilio.com/docs/iot/wireless/api/sim-resource) that the Data Session is for. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the DataSession resource. + :ivar radio_link: The generation of wireless technology that the device was using. + :ivar operator_mcc: The 'mobile country code' is the unique ID of the home country where the Data Session took place. See: [MCC/MNC lookup](http://mcc-mnc.com/). + :ivar operator_mnc: The 'mobile network code' is the unique ID specific to the mobile operator network where the Data Session took place. + :ivar operator_country: The three letter country code representing where the device's Data Session took place. This is determined by looking up the `operator_mcc`. + :ivar operator_name: The friendly name of the mobile operator network that the [SIM](https://www.twilio.com/docs/iot/wireless/api/sim-resource)-connected device is attached to. This is determined by looking up the `operator_mnc`. + :ivar cell_id: The unique ID of the cellular tower that the device was attached to at the moment when the Data Session was last updated. + :ivar cell_location_estimate: An object that describes the estimated location in latitude and longitude where the device's Data Session took place. The location is derived from the `cell_id` when the Data Session was last updated. See [Cell Location Estimate Object](https://www.twilio.com/docs/iot/wireless/api/datasession-resource#cell-location-estimate-object). + :ivar packets_uploaded: The number of packets uploaded by the device between the `start` time and when the Data Session was last updated. + :ivar packets_downloaded: The number of packets downloaded by the device between the `start` time and when the Data Session was last updated. + :ivar last_updated: The date that the resource was last updated, given as GMT in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar start: The date that the Data Session started, given as GMT in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar end: The date that the record ended, given as GMT in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar imei: The 'international mobile equipment identity' is the unique ID of the device using the SIM to connect. An IMEI is a 15-digit string: 14 digits for the device identifier plus a check digit calculated using the Luhn formula. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], sim_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.radio_link: Optional[str] = payload.get("radio_link") + self.operator_mcc: Optional[str] = payload.get("operator_mcc") + self.operator_mnc: Optional[str] = payload.get("operator_mnc") + self.operator_country: Optional[str] = payload.get("operator_country") + self.operator_name: Optional[str] = payload.get("operator_name") + self.cell_id: Optional[str] = payload.get("cell_id") + self.cell_location_estimate: Optional[Dict[str, object]] = payload.get( + "cell_location_estimate" + ) + self.packets_uploaded: Optional[int] = deserialize.integer( + payload.get("packets_uploaded") + ) + self.packets_downloaded: Optional[int] = deserialize.integer( + payload.get("packets_downloaded") + ) + self.last_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("last_updated") + ) + self.start: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start") + ) + self.end: Optional[datetime] = deserialize.iso8601_datetime(payload.get("end")) + self.imei: Optional[str] = payload.get("imei") + + self._solution = { + "sim_sid": sim_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DataSessionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DataSessionInstance: + """ + Build an instance of DataSessionInstance + + :param payload: Payload response from the API + """ + return DataSessionInstance( + self._version, payload, sim_sid=self._solution["sim_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class DataSessionList(ListResource): + + def __init__(self, version: Version, sim_sid: str): + """ + Initialize the DataSessionList + + :param version: Version that contains the resource + :param sim_sid: The SID of the [Sim resource](https://www.twilio.com/docs/iot/wireless/api/sim-resource) with the Data Sessions to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sim_sid": sim_sid, + } + self._uri = "/Sims/{sim_sid}/DataSessions".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DataSessionInstance]: + """ + Streams DataSessionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DataSessionInstance]: + """ + Asynchronously streams DataSessionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DataSessionInstance]: + """ + Lists DataSessionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DataSessionInstance]: + """ + Asynchronously lists DataSessionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DataSessionPage: + """ + Retrieve a single page of DataSessionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DataSessionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DataSessionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DataSessionPage: + """ + Asynchronously retrieve a single page of DataSessionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DataSessionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DataSessionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DataSessionPage: + """ + Retrieve a specific page of DataSessionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DataSessionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DataSessionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DataSessionPage: + """ + Asynchronously retrieve a specific page of DataSessionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DataSessionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DataSessionPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/wireless/v1/sim/usage_record.py b/venv/Lib/site-packages/twilio/rest/wireless/v1/sim/usage_record.py new file mode 100644 index 00000000..1cd26b6c --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/wireless/v1/sim/usage_record.py @@ -0,0 +1,353 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Wireless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UsageRecordInstance(InstanceResource): + + class Granularity(object): + HOURLY = "hourly" + DAILY = "daily" + ALL = "all" + + """ + :ivar sim_sid: The SID of the [Sim resource](https://www.twilio.com/docs/iot/wireless/api/sim-resource) that this Usage Record is for. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resource. + :ivar period: The time period for which the usage is reported. Contains `start` and `end` datetime values given as GMT in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar commands: An object that describes the SIM's usage of Commands during the specified period. See [Commands Usage Object](https://www.twilio.com/docs/iot/wireless/api/sim-usagerecord-resource#commands-usage-object). + :ivar data: An object that describes the SIM's data usage during the specified period. See [Data Usage Object](https://www.twilio.com/docs/iot/wireless/api/sim-usagerecord-resource#data-usage-object). + """ + + def __init__(self, version: Version, payload: Dict[str, Any], sim_sid: str): + super().__init__(version) + + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.period: Optional[Dict[str, object]] = payload.get("period") + self.commands: Optional[Dict[str, object]] = payload.get("commands") + self.data: Optional[Dict[str, object]] = payload.get("data") + + self._solution = { + "sim_sid": sim_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UsageRecordPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UsageRecordInstance: + """ + Build an instance of UsageRecordInstance + + :param payload: Payload response from the API + """ + return UsageRecordInstance( + self._version, payload, sim_sid=self._solution["sim_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class UsageRecordList(ListResource): + + def __init__(self, version: Version, sim_sid: str): + """ + Initialize the UsageRecordList + + :param version: Version that contains the resource + :param sim_sid: The SID of the [Sim resource](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read the usage from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sim_sid": sim_sid, + } + self._uri = "/Sims/{sim_sid}/UsageRecords".format(**self._solution) + + def stream( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UsageRecordInstance]: + """ + Streams UsageRecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param datetime start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UsageRecordInstance]: + """ + Asynchronously streams UsageRecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param datetime start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UsageRecordInstance]: + """ + Lists UsageRecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param datetime start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + end=end, + start=start, + granularity=granularity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UsageRecordInstance]: + """ + Asynchronously lists UsageRecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param datetime start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + end=end, + start=start, + granularity=granularity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UsageRecordPage: + """ + Retrieve a single page of UsageRecordInstance records from the API. + Request is executed immediately + + :param end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UsageRecordInstance + """ + data = values.of( + { + "End": serialize.iso8601_datetime(end), + "Start": serialize.iso8601_datetime(start), + "Granularity": granularity, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsageRecordPage(self._version, response, self._solution) + + async def page_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UsageRecordPage: + """ + Asynchronously retrieve a single page of UsageRecordInstance records from the API. + Request is executed immediately + + :param end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UsageRecordInstance + """ + data = values.of( + { + "End": serialize.iso8601_datetime(end), + "Start": serialize.iso8601_datetime(start), + "Granularity": granularity, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsageRecordPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UsageRecordPage: + """ + Retrieve a specific page of UsageRecordInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UsageRecordInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UsageRecordPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UsageRecordPage: + """ + Asynchronously retrieve a specific page of UsageRecordInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UsageRecordInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UsageRecordPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/rest/wireless/v1/usage_record.py b/venv/Lib/site-packages/twilio/rest/wireless/v1/usage_record.py new file mode 100644 index 00000000..07135cf9 --- /dev/null +++ b/venv/Lib/site-packages/twilio/rest/wireless/v1/usage_record.py @@ -0,0 +1,340 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Wireless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UsageRecordInstance(InstanceResource): + + class Granularity(object): + HOURLY = "hourly" + DAILY = "daily" + ALL = "all" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AccountUsageRecord resource. + :ivar period: The time period for which usage is reported. Contains `start` and `end` properties that describe the period using GMT date-time values specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar commands: An object that describes the aggregated Commands usage for all SIMs during the specified period. See [Commands Usage Object](https://www.twilio.com/docs/iot/wireless/api/account-usagerecord-resource#commands-usage-object). + :ivar data: An object that describes the aggregated Data usage for all SIMs over the period. See [Data Usage Object](https://www.twilio.com/docs/iot/wireless/api/account-usagerecord-resource#data-usage-object). + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.period: Optional[Dict[str, object]] = payload.get("period") + self.commands: Optional[Dict[str, object]] = payload.get("commands") + self.data: Optional[Dict[str, object]] = payload.get("data") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class UsageRecordPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UsageRecordInstance: + """ + Build an instance of UsageRecordInstance + + :param payload: Payload response from the API + """ + return UsageRecordInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class UsageRecordList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the UsageRecordList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/UsageRecords" + + def stream( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UsageRecordInstance]: + """ + Streams UsageRecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime end: Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param datetime start: Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UsageRecordInstance]: + """ + Asynchronously streams UsageRecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime end: Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param datetime start: Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UsageRecordInstance]: + """ + Lists UsageRecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime end: Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param datetime start: Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + end=end, + start=start, + granularity=granularity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UsageRecordInstance]: + """ + Asynchronously lists UsageRecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime end: Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param datetime start: Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + end=end, + start=start, + granularity=granularity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UsageRecordPage: + """ + Retrieve a single page of UsageRecordInstance records from the API. + Request is executed immediately + + :param end: Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param start: Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UsageRecordInstance + """ + data = values.of( + { + "End": serialize.iso8601_datetime(end), + "Start": serialize.iso8601_datetime(start), + "Granularity": granularity, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsageRecordPage(self._version, response) + + async def page_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UsageRecordPage: + """ + Asynchronously retrieve a single page of UsageRecordInstance records from the API. + Request is executed immediately + + :param end: Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param start: Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UsageRecordInstance + """ + data = values.of( + { + "End": serialize.iso8601_datetime(end), + "Start": serialize.iso8601_datetime(start), + "Granularity": granularity, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsageRecordPage(self._version, response) + + def get_page(self, target_url: str) -> UsageRecordPage: + """ + Retrieve a specific page of UsageRecordInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UsageRecordInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UsageRecordPage(self._version, response) + + async def get_page_async(self, target_url: str) -> UsageRecordPage: + """ + Asynchronously retrieve a specific page of UsageRecordInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UsageRecordInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UsageRecordPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/venv/Lib/site-packages/twilio/twiml/__init__.py b/venv/Lib/site-packages/twilio/twiml/__init__.py new file mode 100644 index 00000000..70a4df83 --- /dev/null +++ b/venv/Lib/site-packages/twilio/twiml/__init__.py @@ -0,0 +1,140 @@ +import json +import re +import xml.etree.ElementTree as ET + + +def lower_camel(string): + if not string or "_" not in string: + return string + + result = "".join([x.title() for x in string.split("_")]) + return result[0].lower() + result[1:] + + +def format_language(language): + """ + Attempt to format language parameter as 'ww-WW'. + + :param string language: language parameter + """ + if not language: + return language + + if not re.match("^[a-zA-Z]{2}[_-][a-zA-Z]{2}$", language): + raise TwiMLException("Invalid value for language parameter.") + + return language[0:2].lower() + "-" + language[3:5].upper() + + +class TwiMLException(Exception): + pass + + +class TwiML(object): + MAP = { + "from_": "from", + "xml_lang": "xml:lang", + "interpret_as": "interpret-as", + "for_": "for", + "break_": "break", + } + + def __init__(self, **kwargs): + self.name = self.__class__.__name__ + self.value = None + self.verbs = [] + self.attrs = {} + + for k, v in kwargs.items(): + if v is not None: + self.attrs[lower_camel(self.MAP.get(k, k))] = v + + def __str__(self): + return self.to_xml() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + return False + + def to_xml(self, xml_declaration=True): + """ + Return the contents of this verb as an XML string + + :param bool xml_declaration: Include the XML declaration. Defaults to True + """ + xml = ET.tostring(self.xml(), encoding="utf-8").decode("utf-8") + return ( + '{}'.format(xml) + if xml_declaration + else xml + ) + + def append(self, verb): + """ + Add a TwiML doc + + :param verb: TwiML Document + + :returns: self + """ + self.nest(verb) + return self + + def nest(self, verb): + """ + Add a TwiML doc. Unlike `append()`, this returns the created verb. + + :param verb: TwiML Document + + :returns: the TwiML verb + """ + if not isinstance(verb, TwiML) and not isinstance(verb, str): + raise TwiMLException("Only nesting of TwiML and strings are allowed") + + self.verbs.append(verb) + return verb + + def xml(self): + el = ET.Element(self.name) + + keys = self.attrs.keys() + keys = sorted(keys) + for a in keys: + value = self.attrs[a] + + if isinstance(value, bool): + el.set(a, str(value).lower()) + else: + el.set(a, str(value)) + + if self.value: + if isinstance(self.value, dict): + self.value = json.dumps(self.value) + + el.text = self.value + + last_child = None + + for verb in self.verbs: + if isinstance(verb, str): + if last_child is not None: + last_child.tail = verb + else: + el.text = verb + else: + last_child = verb.xml() + el.append(last_child) + + return el + + def add_child(self, name, value=None, **kwargs): + return self.nest(GenericNode(name, value, **kwargs)) + + +class GenericNode(TwiML): + def __init__(self, name, value, **kwargs): + super(GenericNode, self).__init__(**kwargs) + self.name = name + self.value = value diff --git a/venv/Lib/site-packages/twilio/twiml/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/twilio/twiml/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..72fb18a4 Binary files /dev/null and b/venv/Lib/site-packages/twilio/twiml/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/twiml/__pycache__/fax_response.cpython-312.pyc b/venv/Lib/site-packages/twilio/twiml/__pycache__/fax_response.cpython-312.pyc new file mode 100644 index 00000000..6af6d94e Binary files /dev/null and b/venv/Lib/site-packages/twilio/twiml/__pycache__/fax_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/twiml/__pycache__/messaging_response.cpython-312.pyc b/venv/Lib/site-packages/twilio/twiml/__pycache__/messaging_response.cpython-312.pyc new file mode 100644 index 00000000..b28bc724 Binary files /dev/null and b/venv/Lib/site-packages/twilio/twiml/__pycache__/messaging_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/twiml/__pycache__/voice_response.cpython-312.pyc b/venv/Lib/site-packages/twilio/twiml/__pycache__/voice_response.cpython-312.pyc new file mode 100644 index 00000000..2191c76f Binary files /dev/null and b/venv/Lib/site-packages/twilio/twiml/__pycache__/voice_response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/twilio/twiml/fax_response.py b/venv/Lib/site-packages/twilio/twiml/fax_response.py new file mode 100644 index 00000000..89233bd4 --- /dev/null +++ b/venv/Lib/site-packages/twilio/twiml/fax_response.py @@ -0,0 +1,59 @@ +# coding=utf-8 +r""" +This code was generated by +\ / _ _ _| _ _ + | (_)\/(_)(_|\/| |(/_ v1.0.0 + / / +""" + +from twilio.twiml import ( + TwiML, +) + + +class FaxResponse(TwiML): + """ TwiML for Faxes""" + + def __init__(self, **kwargs): + super(FaxResponse, self).__init__(**kwargs) + self.name = "Response" + + def receive( + self, + action=None, + method=None, + media_type=None, + page_size=None, + store_media=None, + **kwargs + ): + """ + Create a element + + :param action: Receive action URL + :param method: Receive action URL method + :param media_type: The media type used to store media in the fax media store + :param page_size: What size to interpret received pages as + :param store_media: Whether or not to store received media in the fax media store + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Receive( + action=action, + method=method, + media_type=media_type, + page_size=page_size, + store_media=store_media, + **kwargs + ) + ) + + +class Receive(TwiML): + """ TwiML Verb""" + + def __init__(self, **kwargs): + super(Receive, self).__init__(**kwargs) + self.name = "Receive" diff --git a/venv/Lib/site-packages/twilio/twiml/messaging_response.py b/venv/Lib/site-packages/twilio/twiml/messaging_response.py new file mode 100644 index 00000000..ec36c74c --- /dev/null +++ b/venv/Lib/site-packages/twilio/twiml/messaging_response.py @@ -0,0 +1,125 @@ +# coding=utf-8 +r""" +This code was generated by +\ / _ _ _| _ _ + | (_)\/(_)(_|\/| |(/_ v1.0.0 + / / +""" + +from twilio.twiml import ( + TwiML, +) + + +class MessagingResponse(TwiML): + """ TwiML for Messages""" + + def __init__(self, **kwargs): + super(MessagingResponse, self).__init__(**kwargs) + self.name = "Response" + + def message( + self, + body=None, + to=None, + from_=None, + action=None, + method=None, + status_callback=None, + **kwargs + ): + """ + Create a element + + :param body: Message Body + :param to: Phone Number to send Message to + :param from: Phone Number to send Message from + :param action: A URL specifying where Twilio should send status callbacks for the created outbound message. + :param method: Action URL Method + :param status_callback: Status callback URL. Deprecated in favor of action. + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Message( + body=body, + to=to, + from_=from_, + action=action, + method=method, + status_callback=status_callback, + **kwargs + ) + ) + + def redirect(self, url, method=None, **kwargs): + """ + Create a element + + :param url: Redirect URL + :param method: Redirect URL method + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Redirect(url, method=method, **kwargs)) + + +class Redirect(TwiML): + """ TwiML Verb""" + + def __init__(self, url, **kwargs): + super(Redirect, self).__init__(**kwargs) + self.name = "Redirect" + self.value = url + + +class Message(TwiML): + """ TwiML Verb""" + + def __init__(self, body=None, **kwargs): + super(Message, self).__init__(**kwargs) + self.name = "Message" + if body: + self.value = body + + def body(self, message, **kwargs): + """ + Create a element + + :param message: Message Body + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Body(message, **kwargs)) + + def media(self, url, **kwargs): + """ + Create a element + + :param url: Media URL + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Media(url, **kwargs)) + + +class Media(TwiML): + """ TwiML Noun""" + + def __init__(self, url, **kwargs): + super(Media, self).__init__(**kwargs) + self.name = "Media" + self.value = url + + +class Body(TwiML): + """ TwiML Noun""" + + def __init__(self, message, **kwargs): + super(Body, self).__init__(**kwargs) + self.name = "Body" + self.value = message diff --git a/venv/Lib/site-packages/twilio/twiml/voice_response.py b/venv/Lib/site-packages/twilio/twiml/voice_response.py new file mode 100644 index 00000000..18078b90 --- /dev/null +++ b/venv/Lib/site-packages/twilio/twiml/voice_response.py @@ -0,0 +1,3065 @@ +# coding=utf-8 +r""" +This code was generated by +\ / _ _ _| _ _ + | (_)\/(_)(_|\/| |(/_ v1.0.0 + / / +""" + +from twilio.twiml import ( + TwiML, +) + + +class VoiceResponse(TwiML): + """ TwiML for Voice""" + + def __init__(self, **kwargs): + super(VoiceResponse, self).__init__(**kwargs) + self.name = "Response" + + def connect(self, action=None, method=None, **kwargs): + """ + Create a element + + :param action: Action URL + :param method: Action URL method + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Connect(action=action, method=method, **kwargs)) + + def dial( + self, + number=None, + action=None, + method=None, + timeout=None, + hangup_on_star=None, + time_limit=None, + caller_id=None, + record=None, + trim=None, + recording_status_callback=None, + recording_status_callback_method=None, + recording_status_callback_event=None, + answer_on_bridge=None, + ring_tone=None, + recording_track=None, + sequential=None, + refer_url=None, + refer_method=None, + events=None, + **kwargs + ): + """ + Create a element + + :param number: Phone number to dial + :param action: Action URL + :param method: Action URL method + :param timeout: Time to wait for answer + :param hangup_on_star: Hangup call on star press + :param time_limit: Max time length + :param caller_id: Caller ID to display + :param record: Record the call + :param trim: Trim the recording + :param recording_status_callback: Recording status callback URL + :param recording_status_callback_method: Recording status callback URL method + :param recording_status_callback_event: Recording status callback events + :param answer_on_bridge: Preserve the ringing behavior of the inbound call until the Dialed call picks up + :param ring_tone: Ringtone allows you to override the ringback tone that Twilio will play back to the caller while executing the Dial + :param recording_track: To indicate which audio track should be recorded + :param sequential: Used to determine if child TwiML nouns should be dialed in order, one after the other (sequential) or dial all at once (parallel). Default is false, parallel + :param refer_url: Webhook that will receive future SIP REFER requests + :param refer_method: The HTTP method to use for the refer Webhook + :param events: Subscription to events + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Dial( + number=number, + action=action, + method=method, + timeout=timeout, + hangup_on_star=hangup_on_star, + time_limit=time_limit, + caller_id=caller_id, + record=record, + trim=trim, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + recording_status_callback_event=recording_status_callback_event, + answer_on_bridge=answer_on_bridge, + ring_tone=ring_tone, + recording_track=recording_track, + sequential=sequential, + refer_url=refer_url, + refer_method=refer_method, + events=events, + **kwargs + ) + ) + + def echo(self, **kwargs): + """ + Create a element + + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Echo(**kwargs)) + + def enqueue( + self, + name=None, + action=None, + max_queue_size=None, + method=None, + wait_url=None, + wait_url_method=None, + workflow_sid=None, + **kwargs + ): + """ + Create a element + + :param name: Friendly name + :param action: Action URL + :param max_queue_size: Maximum size of queue + :param method: Action URL method + :param wait_url: Wait URL + :param wait_url_method: Wait URL method + :param workflow_sid: TaskRouter Workflow SID + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Enqueue( + name=name, + action=action, + max_queue_size=max_queue_size, + method=method, + wait_url=wait_url, + wait_url_method=wait_url_method, + workflow_sid=workflow_sid, + **kwargs + ) + ) + + def gather( + self, + input=None, + action=None, + method=None, + timeout=None, + speech_timeout=None, + max_speech_time=None, + profanity_filter=None, + finish_on_key=None, + num_digits=None, + partial_result_callback=None, + partial_result_callback_method=None, + language=None, + hints=None, + barge_in=None, + debug=None, + action_on_empty_result=None, + speech_model=None, + enhanced=None, + **kwargs + ): + """ + Create a element + + :param input: Input type Twilio should accept + :param action: Action URL + :param method: Action URL method + :param timeout: Time to wait to gather input + :param speech_timeout: Time to wait to gather speech input and it should be either auto or a positive integer. + :param max_speech_time: Max allowed time for speech input + :param profanity_filter: Profanity Filter on speech + :param finish_on_key: Finish gather on key + :param num_digits: Number of digits to collect + :param partial_result_callback: Partial result callback URL + :param partial_result_callback_method: Partial result callback URL method + :param language: Language to use + :param hints: Speech recognition hints + :param barge_in: Stop playing media upon speech + :param debug: Allow debug for gather + :param action_on_empty_result: Force webhook to the action URL event if there is no input + :param speech_model: Specify the model that is best suited for your use case + :param enhanced: Use enhanced speech model + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Gather( + input=input, + action=action, + method=method, + timeout=timeout, + speech_timeout=speech_timeout, + max_speech_time=max_speech_time, + profanity_filter=profanity_filter, + finish_on_key=finish_on_key, + num_digits=num_digits, + partial_result_callback=partial_result_callback, + partial_result_callback_method=partial_result_callback_method, + language=language, + hints=hints, + barge_in=barge_in, + debug=debug, + action_on_empty_result=action_on_empty_result, + speech_model=speech_model, + enhanced=enhanced, + **kwargs + ) + ) + + def hangup(self, **kwargs): + """ + Create a element + + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Hangup(**kwargs)) + + def leave(self, **kwargs): + """ + Create a element + + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Leave(**kwargs)) + + def pause(self, length=None, **kwargs): + """ + Create a element + + :param length: Length in seconds to pause + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Pause(length=length, **kwargs)) + + def play(self, url=None, loop=None, digits=None, **kwargs): + """ + Create a element + + :param url: Media URL + :param loop: Times to loop media + :param digits: Play DTMF tones for digits + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Play(url=url, loop=loop, digits=digits, **kwargs)) + + def queue( + self, + name, + url=None, + method=None, + reservation_sid=None, + post_work_activity_sid=None, + **kwargs + ): + """ + Create a element + + :param name: Queue name + :param url: Action URL + :param method: Action URL method + :param reservation_sid: TaskRouter Reservation SID + :param post_work_activity_sid: TaskRouter Activity SID + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Queue( + name, + url=url, + method=method, + reservation_sid=reservation_sid, + post_work_activity_sid=post_work_activity_sid, + **kwargs + ) + ) + + def record( + self, + action=None, + method=None, + timeout=None, + finish_on_key=None, + max_length=None, + play_beep=None, + trim=None, + recording_status_callback=None, + recording_status_callback_method=None, + recording_status_callback_event=None, + transcribe=None, + transcribe_callback=None, + **kwargs + ): + """ + Create a element + + :param action: Action URL + :param method: Action URL method + :param timeout: Timeout to begin recording + :param finish_on_key: Finish recording on key + :param max_length: Max time to record in seconds + :param play_beep: Play beep + :param trim: Trim the recording + :param recording_status_callback: Status callback URL + :param recording_status_callback_method: Status callback URL method + :param recording_status_callback_event: Recording status callback events + :param transcribe: Transcribe the recording + :param transcribe_callback: Transcribe callback URL + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Record( + action=action, + method=method, + timeout=timeout, + finish_on_key=finish_on_key, + max_length=max_length, + play_beep=play_beep, + trim=trim, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + recording_status_callback_event=recording_status_callback_event, + transcribe=transcribe, + transcribe_callback=transcribe_callback, + **kwargs + ) + ) + + def redirect(self, url, method=None, **kwargs): + """ + Create a element + + :param url: Redirect URL + :param method: Redirect URL method + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Redirect(url, method=method, **kwargs)) + + def reject(self, reason=None, **kwargs): + """ + Create a element + + :param reason: Rejection reason + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Reject(reason=reason, **kwargs)) + + def say(self, message=None, voice=None, loop=None, language=None, **kwargs): + """ + Create a element + + :param message: Message to say + :param voice: Voice to use + :param loop: Times to loop message + :param language: Message language + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Say(message=message, voice=voice, loop=loop, language=language, **kwargs) + ) + + def sms( + self, + message, + to=None, + from_=None, + action=None, + method=None, + status_callback=None, + **kwargs + ): + """ + Create a element + + :param message: Message body + :param to: Number to send message to + :param from: Number to send message from + :param action: Action URL + :param method: Action URL method + :param status_callback: Status callback URL + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Sms( + message, + to=to, + from_=from_, + action=action, + method=method, + status_callback=status_callback, + **kwargs + ) + ) + + def pay( + self, + input=None, + action=None, + bank_account_type=None, + status_callback=None, + status_callback_method=None, + timeout=None, + max_attempts=None, + security_code=None, + postal_code=None, + min_postal_code_length=None, + payment_connector=None, + payment_method=None, + token_type=None, + charge_amount=None, + currency=None, + description=None, + valid_card_types=None, + language=None, + **kwargs + ): + """ + Create a element + + :param input: Input type Twilio should accept + :param action: Action URL + :param bank_account_type: Bank account type for ach transactions. If set, payment method attribute must be provided and value should be set to ach-debit. defaults to consumer-checking + :param status_callback: Status callback URL + :param status_callback_method: Status callback method + :param timeout: Time to wait to gather input + :param max_attempts: Maximum number of allowed retries when gathering input + :param security_code: Prompt for security code + :param postal_code: Prompt for postal code and it should be true/false or default postal code + :param min_postal_code_length: Prompt for minimum postal code length + :param payment_connector: Unique name for payment connector + :param payment_method: Payment method to be used. defaults to credit-card + :param token_type: Type of token + :param charge_amount: Amount to process. If value is greater than 0 then make the payment else create a payment token + :param currency: Currency of the amount attribute + :param description: Details regarding the payment + :param valid_card_types: Comma separated accepted card types + :param language: Language to use + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Pay( + input=input, + action=action, + bank_account_type=bank_account_type, + status_callback=status_callback, + status_callback_method=status_callback_method, + timeout=timeout, + max_attempts=max_attempts, + security_code=security_code, + postal_code=postal_code, + min_postal_code_length=min_postal_code_length, + payment_connector=payment_connector, + payment_method=payment_method, + token_type=token_type, + charge_amount=charge_amount, + currency=currency, + description=description, + valid_card_types=valid_card_types, + language=language, + **kwargs + ) + ) + + def prompt( + self, + for_=None, + error_type=None, + card_type=None, + attempt=None, + require_matching_inputs=None, + **kwargs + ): + """ + Create a element + + :param for_: Name of the payment source data element + :param error_type: Type of error + :param card_type: Type of the credit card + :param attempt: Current attempt count + :param require_matching_inputs: Require customer to input requested information twice and verify matching. + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Prompt( + for_=for_, + error_type=error_type, + card_type=card_type, + attempt=attempt, + require_matching_inputs=require_matching_inputs, + **kwargs + ) + ) + + def start(self, action=None, method=None, **kwargs): + """ + Create a element + + :param action: Action URL + :param method: Action URL method + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Start(action=action, method=method, **kwargs)) + + def stop(self, **kwargs): + """ + Create a element + + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Stop(**kwargs)) + + def refer(self, action=None, method=None, **kwargs): + """ + Create a element + + :param action: Action URL + :param method: Action URL method + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Refer(action=action, method=method, **kwargs)) + + +class Refer(TwiML): + """ TwiML Verb""" + + def __init__(self, **kwargs): + super(Refer, self).__init__(**kwargs) + self.name = "Refer" + + def sip(self, sip_url, **kwargs): + """ + Create a element + + :param sip_url: SIP URL + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(ReferSip(sip_url, **kwargs)) + + +class ReferSip(TwiML): + """ TwiML Noun used in """ + + def __init__(self, sip_url, **kwargs): + super(ReferSip, self).__init__(**kwargs) + self.name = "Sip" + self.value = sip_url + + +class Stop(TwiML): + """ TwiML Verb""" + + def __init__(self, **kwargs): + super(Stop, self).__init__(**kwargs) + self.name = "Stop" + + def stream( + self, + name=None, + connector_name=None, + url=None, + track=None, + status_callback=None, + status_callback_method=None, + **kwargs + ): + """ + Create a element + + :param name: Friendly name given to the Stream + :param connector_name: Unique name for Stream Connector + :param url: URL of the remote service where the Stream is routed + :param track: Track to be streamed to remote service + :param status_callback: Status Callback URL + :param status_callback_method: Status Callback URL method + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Stream( + name=name, + connector_name=connector_name, + url=url, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + **kwargs + ) + ) + + def siprec( + self, + name=None, + connector_name=None, + track=None, + status_callback=None, + status_callback_method=None, + **kwargs + ): + """ + Create a element + + :param name: Friendly name given to SIPREC + :param connector_name: Unique name for Connector + :param track: Track to be streamed to remote service + :param status_callback: Status Callback URL + :param status_callback_method: Status Callback URL method + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Siprec( + name=name, + connector_name=connector_name, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + **kwargs + ) + ) + + def transcription( + self, + name=None, + track=None, + status_callback_url=None, + status_callback_method=None, + inbound_track_label=None, + outbound_track_label=None, + partial_results=None, + language_code=None, + transcription_engine=None, + profanity_filter=None, + speech_model=None, + hints=None, + enable_automatic_punctuation=None, + intelligence_service=None, + **kwargs + ): + """ + Create a element + + :param name: Friendly name given to the Transcription + :param track: Track to be analyze by the provider + :param status_callback_url: Status Callback URL + :param status_callback_method: Status Callback URL method + :param inbound_track_label: Friendly name given to the Inbound Track + :param outbound_track_label: Friendly name given to the Outbound Track Label + :param partial_results: Indicates if partial results are going to be send to the customer + :param language_code: Language Code used by the transcription engine + :param transcription_engine: Transcription Engine to be used + :param profanity_filter: Enable Profanity Filter + :param speech_model: Speech Model used by the transcription engine + :param hints: Hints to be provided to the transcription engine + :param enable_automatic_punctuation: Enable Automatic Punctuation + :param intelligence_service: The SID or the unique name of the Intelligence Service to be used + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Transcription( + name=name, + track=track, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + inbound_track_label=inbound_track_label, + outbound_track_label=outbound_track_label, + partial_results=partial_results, + language_code=language_code, + transcription_engine=transcription_engine, + profanity_filter=profanity_filter, + speech_model=speech_model, + hints=hints, + enable_automatic_punctuation=enable_automatic_punctuation, + intelligence_service=intelligence_service, + **kwargs + ) + ) + + +class Transcription(TwiML): + """ TwiML Noun""" + + def __init__(self, **kwargs): + super(Transcription, self).__init__(**kwargs) + self.name = "Transcription" + + def config(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom config + :param value: The value of the custom config + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Config(name=name, value=value, **kwargs)) + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Parameter(TwiML): + """ TwiML Noun""" + + def __init__(self, **kwargs): + super(Parameter, self).__init__(**kwargs) + self.name = "Parameter" + + +class Config(TwiML): + """ TwiML Noun""" + + def __init__(self, **kwargs): + super(Config, self).__init__(**kwargs) + self.name = "Config" + + +class Siprec(TwiML): + """ TwiML Noun""" + + def __init__(self, **kwargs): + super(Siprec, self).__init__(**kwargs) + self.name = "Siprec" + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Stream(TwiML): + """ TwiML Noun""" + + def __init__(self, **kwargs): + super(Stream, self).__init__(**kwargs) + self.name = "Stream" + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Start(TwiML): + """ TwiML Verb""" + + def __init__(self, **kwargs): + super(Start, self).__init__(**kwargs) + self.name = "Start" + + def stream( + self, + name=None, + connector_name=None, + url=None, + track=None, + status_callback=None, + status_callback_method=None, + **kwargs + ): + """ + Create a element + + :param name: Friendly name given to the Stream + :param connector_name: Unique name for Stream Connector + :param url: URL of the remote service where the Stream is routed + :param track: Track to be streamed to remote service + :param status_callback: Status Callback URL + :param status_callback_method: Status Callback URL method + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Stream( + name=name, + connector_name=connector_name, + url=url, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + **kwargs + ) + ) + + def siprec( + self, + name=None, + connector_name=None, + track=None, + status_callback=None, + status_callback_method=None, + **kwargs + ): + """ + Create a element + + :param name: Friendly name given to SIPREC + :param connector_name: Unique name for Connector + :param track: Track to be streamed to remote service + :param status_callback: Status Callback URL + :param status_callback_method: Status Callback URL method + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Siprec( + name=name, + connector_name=connector_name, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + **kwargs + ) + ) + + def transcription( + self, + name=None, + track=None, + status_callback_url=None, + status_callback_method=None, + inbound_track_label=None, + outbound_track_label=None, + partial_results=None, + language_code=None, + transcription_engine=None, + profanity_filter=None, + speech_model=None, + hints=None, + enable_automatic_punctuation=None, + intelligence_service=None, + **kwargs + ): + """ + Create a element + + :param name: Friendly name given to the Transcription + :param track: Track to be analyze by the provider + :param status_callback_url: Status Callback URL + :param status_callback_method: Status Callback URL method + :param inbound_track_label: Friendly name given to the Inbound Track + :param outbound_track_label: Friendly name given to the Outbound Track Label + :param partial_results: Indicates if partial results are going to be send to the customer + :param language_code: Language Code used by the transcription engine + :param transcription_engine: Transcription Engine to be used + :param profanity_filter: Enable Profanity Filter + :param speech_model: Speech Model used by the transcription engine + :param hints: Hints to be provided to the transcription engine + :param enable_automatic_punctuation: Enable Automatic Punctuation + :param intelligence_service: The SID or the unique name of the Intelligence Service to be used + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Transcription( + name=name, + track=track, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + inbound_track_label=inbound_track_label, + outbound_track_label=outbound_track_label, + partial_results=partial_results, + language_code=language_code, + transcription_engine=transcription_engine, + profanity_filter=profanity_filter, + speech_model=speech_model, + hints=hints, + enable_automatic_punctuation=enable_automatic_punctuation, + intelligence_service=intelligence_service, + **kwargs + ) + ) + + +class Prompt(TwiML): + """ Twiml Verb""" + + def __init__(self, **kwargs): + super(Prompt, self).__init__(**kwargs) + self.name = "Prompt" + + def say(self, message=None, voice=None, loop=None, language=None, **kwargs): + """ + Create a element + + :param message: Message to say + :param voice: Voice to use + :param loop: Times to loop message + :param language: Message language + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Say(message=message, voice=voice, loop=loop, language=language, **kwargs) + ) + + def play(self, url=None, loop=None, digits=None, **kwargs): + """ + Create a element + + :param url: Media URL + :param loop: Times to loop media + :param digits: Play DTMF tones for digits + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Play(url=url, loop=loop, digits=digits, **kwargs)) + + def pause(self, length=None, **kwargs): + """ + Create a element + + :param length: Length in seconds to pause + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Pause(length=length, **kwargs)) + + +class Pause(TwiML): + """ TwiML Verb""" + + def __init__(self, **kwargs): + super(Pause, self).__init__(**kwargs) + self.name = "Pause" + + +class Play(TwiML): + """ TwiML Verb""" + + def __init__(self, url=None, **kwargs): + super(Play, self).__init__(**kwargs) + self.name = "Play" + if url: + self.value = url + + +class Say(TwiML): + """ TwiML Verb""" + + def __init__(self, message=None, **kwargs): + super(Say, self).__init__(**kwargs) + self.name = "Say" + if message: + self.value = message + + def break_(self, strength=None, time=None, **kwargs): + """ + Create a element + + :param strength: Set a pause based on strength + :param time: Set a pause to a specific length of time in seconds or milliseconds, available values: [number]s, [number]ms + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a element + + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def lang(self, words=None, xml_lang=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param xml:lang: Specify the language + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) + + def p(self, words=None, **kwargs): + """ + Create a

element + + :param words: Words to speak + :param kwargs: additional attributes + + :returns:

element + """ + return self.nest(SsmlP(words=words, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param alphabet: Specify the phonetic alphabet + :param ph: Specifiy the phonetic symbols for pronunciation + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlPhoneme(words, alphabet=alphabet, ph=ph, **kwargs)) + + def prosody(self, words=None, volume=None, rate=None, pitch=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param volume: Specify the volume, available values: default, silent, x-soft, soft, medium, loud, x-loud, +ndB, -ndB + :param rate: Specify the rate, available values: x-slow, slow, medium, fast, x-fast, n% + :param pitch: Specify the pitch, available values: default, x-low, low, medium, high, x-high, +n%, -n% + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) + + def s(self, words=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlS(words=words, **kwargs)) + + def say_as(self, words, interpret_as=None, format=None, **kwargs): + """ + Create a element + + :param words: Words to be interpreted + :param interpret-as: Specify the type of words are spoken + :param format: Specify the format of the date when interpret-as is set to date + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a element + + :param words: Words to be substituted + :param alias: Substitute a different word (or pronunciation) for selected text such as an acronym or abbreviation + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + def w(self, words=None, role=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param role: Customize the pronunciation of words by specifying the word’s part of speech or alternate meaning + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlW(words=words, role=role, **kwargs)) + + +class SsmlW(TwiML): + """Improving Pronunciation by Specifying Parts of Speech in """ + + def __init__(self, words=None, **kwargs): + super(SsmlW, self).__init__(**kwargs) + self.name = "w" + if words: + self.value = words + + def break_(self, strength=None, time=None, **kwargs): + """ + Create a element + + :param strength: Set a pause based on strength + :param time: Set a pause to a specific length of time in seconds or milliseconds, available values: [number]s, [number]ms + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a element + + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param alphabet: Specify the phonetic alphabet + :param ph: Specifiy the phonetic symbols for pronunciation + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlPhoneme(words, alphabet=alphabet, ph=ph, **kwargs)) + + def prosody(self, words=None, volume=None, rate=None, pitch=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param volume: Specify the volume, available values: default, silent, x-soft, soft, medium, loud, x-loud, +ndB, -ndB + :param rate: Specify the rate, available values: x-slow, slow, medium, fast, x-fast, n% + :param pitch: Specify the pitch, available values: default, x-low, low, medium, high, x-high, +n%, -n% + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) + + def say_as(self, words, interpret_as=None, format=None, **kwargs): + """ + Create a element + + :param words: Words to be interpreted + :param interpret-as: Specify the type of words are spoken + :param format: Specify the format of the date when interpret-as is set to date + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a element + + :param words: Words to be substituted + :param alias: Substitute a different word (or pronunciation) for selected text such as an acronym or abbreviation + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + +class SsmlSub(TwiML): + """Pronouncing Acronyms and Abbreviations in """ + + def __init__(self, words, **kwargs): + super(SsmlSub, self).__init__(**kwargs) + self.name = "sub" + self.value = words + + +class SsmlSayAs(TwiML): + """Controlling How Special Types of Words Are Spoken in """ + + def __init__(self, words, **kwargs): + super(SsmlSayAs, self).__init__(**kwargs) + self.name = "say-as" + self.value = words + + +class SsmlProsody(TwiML): + """Controling Volume, Speaking Rate, and Pitch in """ + + def __init__(self, words=None, **kwargs): + super(SsmlProsody, self).__init__(**kwargs) + self.name = "prosody" + if words: + self.value = words + + def break_(self, strength=None, time=None, **kwargs): + """ + Create a element + + :param strength: Set a pause based on strength + :param time: Set a pause to a specific length of time in seconds or milliseconds, available values: [number]s, [number]ms + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a element + + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def lang(self, words=None, xml_lang=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param xml:lang: Specify the language + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) + + def p(self, words=None, **kwargs): + """ + Create a

element + + :param words: Words to speak + :param kwargs: additional attributes + + :returns:

element + """ + return self.nest(SsmlP(words=words, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param alphabet: Specify the phonetic alphabet + :param ph: Specifiy the phonetic symbols for pronunciation + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlPhoneme(words, alphabet=alphabet, ph=ph, **kwargs)) + + def prosody(self, words=None, volume=None, rate=None, pitch=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param volume: Specify the volume, available values: default, silent, x-soft, soft, medium, loud, x-loud, +ndB, -ndB + :param rate: Specify the rate, available values: x-slow, slow, medium, fast, x-fast, n% + :param pitch: Specify the pitch, available values: default, x-low, low, medium, high, x-high, +n%, -n% + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) + + def s(self, words=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlS(words=words, **kwargs)) + + def say_as(self, words, interpret_as=None, format=None, **kwargs): + """ + Create a element + + :param words: Words to be interpreted + :param interpret-as: Specify the type of words are spoken + :param format: Specify the format of the date when interpret-as is set to date + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a element + + :param words: Words to be substituted + :param alias: Substitute a different word (or pronunciation) for selected text such as an acronym or abbreviation + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + def w(self, words=None, role=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param role: Customize the pronunciation of words by specifying the word’s part of speech or alternate meaning + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlW(words=words, role=role, **kwargs)) + + +class SsmlS(TwiML): + """Adding A Pause Between Sentences in """ + + def __init__(self, words=None, **kwargs): + super(SsmlS, self).__init__(**kwargs) + self.name = "s" + if words: + self.value = words + + def break_(self, strength=None, time=None, **kwargs): + """ + Create a element + + :param strength: Set a pause based on strength + :param time: Set a pause to a specific length of time in seconds or milliseconds, available values: [number]s, [number]ms + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a element + + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def lang(self, words=None, xml_lang=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param xml:lang: Specify the language + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param alphabet: Specify the phonetic alphabet + :param ph: Specifiy the phonetic symbols for pronunciation + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlPhoneme(words, alphabet=alphabet, ph=ph, **kwargs)) + + def prosody(self, words=None, volume=None, rate=None, pitch=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param volume: Specify the volume, available values: default, silent, x-soft, soft, medium, loud, x-loud, +ndB, -ndB + :param rate: Specify the rate, available values: x-slow, slow, medium, fast, x-fast, n% + :param pitch: Specify the pitch, available values: default, x-low, low, medium, high, x-high, +n%, -n% + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) + + def say_as(self, words, interpret_as=None, format=None, **kwargs): + """ + Create a element + + :param words: Words to be interpreted + :param interpret-as: Specify the type of words are spoken + :param format: Specify the format of the date when interpret-as is set to date + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a element + + :param words: Words to be substituted + :param alias: Substitute a different word (or pronunciation) for selected text such as an acronym or abbreviation + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + def w(self, words=None, role=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param role: Customize the pronunciation of words by specifying the word’s part of speech or alternate meaning + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlW(words=words, role=role, **kwargs)) + + +class SsmlPhoneme(TwiML): + """Using Phonetic Pronunciation in """ + + def __init__(self, words, **kwargs): + super(SsmlPhoneme, self).__init__(**kwargs) + self.name = "phoneme" + self.value = words + + +class SsmlLang(TwiML): + """Specifying Another Language for Specific Words in """ + + def __init__(self, words=None, **kwargs): + super(SsmlLang, self).__init__(**kwargs) + self.name = "lang" + if words: + self.value = words + + def break_(self, strength=None, time=None, **kwargs): + """ + Create a element + + :param strength: Set a pause based on strength + :param time: Set a pause to a specific length of time in seconds or milliseconds, available values: [number]s, [number]ms + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a element + + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def lang(self, words=None, xml_lang=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param xml:lang: Specify the language + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) + + def p(self, words=None, **kwargs): + """ + Create a

element + + :param words: Words to speak + :param kwargs: additional attributes + + :returns:

element + """ + return self.nest(SsmlP(words=words, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param alphabet: Specify the phonetic alphabet + :param ph: Specifiy the phonetic symbols for pronunciation + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlPhoneme(words, alphabet=alphabet, ph=ph, **kwargs)) + + def prosody(self, words=None, volume=None, rate=None, pitch=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param volume: Specify the volume, available values: default, silent, x-soft, soft, medium, loud, x-loud, +ndB, -ndB + :param rate: Specify the rate, available values: x-slow, slow, medium, fast, x-fast, n% + :param pitch: Specify the pitch, available values: default, x-low, low, medium, high, x-high, +n%, -n% + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) + + def s(self, words=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlS(words=words, **kwargs)) + + def say_as(self, words, interpret_as=None, format=None, **kwargs): + """ + Create a element + + :param words: Words to be interpreted + :param interpret-as: Specify the type of words are spoken + :param format: Specify the format of the date when interpret-as is set to date + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a element + + :param words: Words to be substituted + :param alias: Substitute a different word (or pronunciation) for selected text such as an acronym or abbreviation + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + def w(self, words=None, role=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param role: Customize the pronunciation of words by specifying the word’s part of speech or alternate meaning + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlW(words=words, role=role, **kwargs)) + + +class SsmlP(TwiML): + """Adding a Pause Between Paragraphs in """ + + def __init__(self, words=None, **kwargs): + super(SsmlP, self).__init__(**kwargs) + self.name = "p" + if words: + self.value = words + + def break_(self, strength=None, time=None, **kwargs): + """ + Create a element + + :param strength: Set a pause based on strength + :param time: Set a pause to a specific length of time in seconds or milliseconds, available values: [number]s, [number]ms + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a element + + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def lang(self, words=None, xml_lang=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param xml:lang: Specify the language + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param alphabet: Specify the phonetic alphabet + :param ph: Specifiy the phonetic symbols for pronunciation + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlPhoneme(words, alphabet=alphabet, ph=ph, **kwargs)) + + def prosody(self, words=None, volume=None, rate=None, pitch=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param volume: Specify the volume, available values: default, silent, x-soft, soft, medium, loud, x-loud, +ndB, -ndB + :param rate: Specify the rate, available values: x-slow, slow, medium, fast, x-fast, n% + :param pitch: Specify the pitch, available values: default, x-low, low, medium, high, x-high, +n%, -n% + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) + + def s(self, words=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlS(words=words, **kwargs)) + + def say_as(self, words, interpret_as=None, format=None, **kwargs): + """ + Create a element + + :param words: Words to be interpreted + :param interpret-as: Specify the type of words are spoken + :param format: Specify the format of the date when interpret-as is set to date + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a element + + :param words: Words to be substituted + :param alias: Substitute a different word (or pronunciation) for selected text such as an acronym or abbreviation + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + def w(self, words=None, role=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param role: Customize the pronunciation of words by specifying the word’s part of speech or alternate meaning + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlW(words=words, role=role, **kwargs)) + + +class SsmlEmphasis(TwiML): + """Emphasizing Words in """ + + def __init__(self, words=None, **kwargs): + super(SsmlEmphasis, self).__init__(**kwargs) + self.name = "emphasis" + if words: + self.value = words + + def break_(self, strength=None, time=None, **kwargs): + """ + Create a element + + :param strength: Set a pause based on strength + :param time: Set a pause to a specific length of time in seconds or milliseconds, available values: [number]s, [number]ms + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a element + + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def lang(self, words=None, xml_lang=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param xml:lang: Specify the language + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param alphabet: Specify the phonetic alphabet + :param ph: Specifiy the phonetic symbols for pronunciation + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlPhoneme(words, alphabet=alphabet, ph=ph, **kwargs)) + + def prosody(self, words=None, volume=None, rate=None, pitch=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param volume: Specify the volume, available values: default, silent, x-soft, soft, medium, loud, x-loud, +ndB, -ndB + :param rate: Specify the rate, available values: x-slow, slow, medium, fast, x-fast, n% + :param pitch: Specify the pitch, available values: default, x-low, low, medium, high, x-high, +n%, -n% + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) + + def say_as(self, words, interpret_as=None, format=None, **kwargs): + """ + Create a element + + :param words: Words to be interpreted + :param interpret-as: Specify the type of words are spoken + :param format: Specify the format of the date when interpret-as is set to date + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a element + + :param words: Words to be substituted + :param alias: Substitute a different word (or pronunciation) for selected text such as an acronym or abbreviation + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + def w(self, words=None, role=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param role: Customize the pronunciation of words by specifying the word’s part of speech or alternate meaning + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlW(words=words, role=role, **kwargs)) + + +class SsmlBreak(TwiML): + """Adding a Pause in """ + + def __init__(self, **kwargs): + super(SsmlBreak, self).__init__(**kwargs) + self.name = "break" + + +class Pay(TwiML): + """ Twiml Verb""" + + def __init__(self, **kwargs): + super(Pay, self).__init__(**kwargs) + self.name = "Pay" + + def prompt( + self, + for_=None, + error_type=None, + card_type=None, + attempt=None, + require_matching_inputs=None, + **kwargs + ): + """ + Create a element + + :param for_: Name of the payment source data element + :param error_type: Type of error + :param card_type: Type of the credit card + :param attempt: Current attempt count + :param require_matching_inputs: Require customer to input requested information twice and verify matching. + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Prompt( + for_=for_, + error_type=error_type, + card_type=card_type, + attempt=attempt, + require_matching_inputs=require_matching_inputs, + **kwargs + ) + ) + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Sms(TwiML): + """ TwiML Noun""" + + def __init__(self, message, **kwargs): + super(Sms, self).__init__(**kwargs) + self.name = "Sms" + self.value = message + + +class Reject(TwiML): + """ TwiML Verb""" + + def __init__(self, **kwargs): + super(Reject, self).__init__(**kwargs) + self.name = "Reject" + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Redirect(TwiML): + """ TwiML Verb""" + + def __init__(self, url, **kwargs): + super(Redirect, self).__init__(**kwargs) + self.name = "Redirect" + self.value = url + + +class Record(TwiML): + """ TwiML Verb""" + + def __init__(self, **kwargs): + super(Record, self).__init__(**kwargs) + self.name = "Record" + + +class Queue(TwiML): + """ TwiML Noun""" + + def __init__(self, name, **kwargs): + super(Queue, self).__init__(**kwargs) + self.name = "Queue" + self.value = name + + +class Leave(TwiML): + """ TwiML Verb""" + + def __init__(self, **kwargs): + super(Leave, self).__init__(**kwargs) + self.name = "Leave" + + +class Hangup(TwiML): + """ TwiML Verb""" + + def __init__(self, **kwargs): + super(Hangup, self).__init__(**kwargs) + self.name = "Hangup" + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Gather(TwiML): + """ TwiML Verb""" + + def __init__(self, **kwargs): + super(Gather, self).__init__(**kwargs) + self.name = "Gather" + + def say(self, message=None, voice=None, loop=None, language=None, **kwargs): + """ + Create a element + + :param message: Message to say + :param voice: Voice to use + :param loop: Times to loop message + :param language: Message language + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Say(message=message, voice=voice, loop=loop, language=language, **kwargs) + ) + + def pause(self, length=None, **kwargs): + """ + Create a element + + :param length: Length in seconds to pause + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Pause(length=length, **kwargs)) + + def play(self, url=None, loop=None, digits=None, **kwargs): + """ + Create a element + + :param url: Media URL + :param loop: Times to loop media + :param digits: Play DTMF tones for digits + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Play(url=url, loop=loop, digits=digits, **kwargs)) + + +class Enqueue(TwiML): + """ TwiML Noun""" + + def __init__(self, name=None, **kwargs): + super(Enqueue, self).__init__(**kwargs) + self.name = "Enqueue" + if name: + self.value = name + + def task(self, body, priority=None, timeout=None, **kwargs): + """ + Create a element + + :param body: TaskRouter task attributes + :param priority: Task priority + :param timeout: Timeout associated with task + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Task(body, priority=priority, timeout=timeout, **kwargs)) + + +class Task(TwiML): + """ TwiML Noun""" + + def __init__(self, body, **kwargs): + super(Task, self).__init__(**kwargs) + self.name = "Task" + self.value = body + + +class Echo(TwiML): + """ TwiML Verb""" + + def __init__(self, **kwargs): + super(Echo, self).__init__(**kwargs) + self.name = "Echo" + + +class Dial(TwiML): + """ TwiML Verb""" + + def __init__(self, number=None, **kwargs): + super(Dial, self).__init__(**kwargs) + self.name = "Dial" + if number: + self.value = number + + def client( + self, + identity=None, + url=None, + method=None, + status_callback_event=None, + status_callback=None, + status_callback_method=None, + **kwargs + ): + """ + Create a element + + :param identity: Client identity + :param url: Client URL + :param method: Client URL Method + :param status_callback_event: Events to trigger status callback + :param status_callback: Status Callback URL + :param status_callback_method: Status Callback URL Method + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Client( + identity=identity, + url=url, + method=method, + status_callback_event=status_callback_event, + status_callback=status_callback, + status_callback_method=status_callback_method, + **kwargs + ) + ) + + def conference( + self, + name, + muted=None, + beep=None, + start_conference_on_enter=None, + end_conference_on_exit=None, + wait_url=None, + wait_method=None, + max_participants=None, + record=None, + region=None, + coach=None, + trim=None, + status_callback_event=None, + status_callback=None, + status_callback_method=None, + recording_status_callback=None, + recording_status_callback_method=None, + recording_status_callback_event=None, + event_callback_url=None, + jitter_buffer_size=None, + participant_label=None, + **kwargs + ): + """ + Create a element + + :param name: Conference name + :param muted: Join the conference muted + :param beep: Play beep when joining + :param start_conference_on_enter: Start the conference on enter + :param end_conference_on_exit: End the conferenceon exit + :param wait_url: Wait URL + :param wait_method: Wait URL method + :param max_participants: Maximum number of participants + :param record: Record the conference + :param region: Conference region + :param coach: Call coach + :param trim: Trim the conference recording + :param status_callback_event: Events to call status callback URL + :param status_callback: Status callback URL + :param status_callback_method: Status callback URL method + :param recording_status_callback: Recording status callback URL + :param recording_status_callback_method: Recording status callback URL method + :param recording_status_callback_event: Recording status callback events + :param event_callback_url: Event callback URL + :param jitter_buffer_size: Size of jitter buffer for participant + :param participant_label: A label for participant + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Conference( + name, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + max_participants=max_participants, + record=record, + region=region, + coach=coach, + trim=trim, + status_callback_event=status_callback_event, + status_callback=status_callback, + status_callback_method=status_callback_method, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + recording_status_callback_event=recording_status_callback_event, + event_callback_url=event_callback_url, + jitter_buffer_size=jitter_buffer_size, + participant_label=participant_label, + **kwargs + ) + ) + + def number( + self, + phone_number, + send_digits=None, + url=None, + method=None, + status_callback_event=None, + status_callback=None, + status_callback_method=None, + byoc=None, + machine_detection=None, + amd_status_callback_method=None, + amd_status_callback=None, + machine_detection_timeout=None, + machine_detection_speech_threshold=None, + machine_detection_speech_end_threshold=None, + machine_detection_silence_timeout=None, + **kwargs + ): + """ + Create a element + + :param phone_number: Phone Number to dial + :param send_digits: DTMF tones to play when the call is answered + :param url: TwiML URL + :param method: TwiML URL method + :param status_callback_event: Events to call status callback + :param status_callback: Status callback URL + :param status_callback_method: Status callback URL method + :param byoc: BYOC trunk SID (Beta) + :param machine_detection: Enable machine detection or end of greeting detection + :param amd_status_callback_method: HTTP Method to use with amd_status_callback + :param amd_status_callback: The URL we should call to send amd status information to your application + :param machine_detection_timeout: Number of seconds to wait for machine detection + :param machine_detection_speech_threshold: Number of milliseconds for measuring stick for the length of the speech activity + :param machine_detection_speech_end_threshold: Number of milliseconds of silence after speech activity + :param machine_detection_silence_timeout: Number of milliseconds of initial silence + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Number( + phone_number, + send_digits=send_digits, + url=url, + method=method, + status_callback_event=status_callback_event, + status_callback=status_callback, + status_callback_method=status_callback_method, + byoc=byoc, + machine_detection=machine_detection, + amd_status_callback_method=amd_status_callback_method, + amd_status_callback=amd_status_callback, + machine_detection_timeout=machine_detection_timeout, + machine_detection_speech_threshold=machine_detection_speech_threshold, + machine_detection_speech_end_threshold=machine_detection_speech_end_threshold, + machine_detection_silence_timeout=machine_detection_silence_timeout, + **kwargs + ) + ) + + def queue( + self, + name, + url=None, + method=None, + reservation_sid=None, + post_work_activity_sid=None, + **kwargs + ): + """ + Create a element + + :param name: Queue name + :param url: Action URL + :param method: Action URL method + :param reservation_sid: TaskRouter Reservation SID + :param post_work_activity_sid: TaskRouter Activity SID + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Queue( + name, + url=url, + method=method, + reservation_sid=reservation_sid, + post_work_activity_sid=post_work_activity_sid, + **kwargs + ) + ) + + def sim(self, sim_sid, **kwargs): + """ + Create a element + + :param sim_sid: SIM SID + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Sim(sim_sid, **kwargs)) + + def sip( + self, + sip_url, + username=None, + password=None, + url=None, + method=None, + status_callback_event=None, + status_callback=None, + status_callback_method=None, + machine_detection=None, + amd_status_callback_method=None, + amd_status_callback=None, + machine_detection_timeout=None, + machine_detection_speech_threshold=None, + machine_detection_speech_end_threshold=None, + machine_detection_silence_timeout=None, + **kwargs + ): + """ + Create a element + + :param sip_url: SIP URL + :param username: SIP Username + :param password: SIP Password + :param url: Action URL + :param method: Action URL method + :param status_callback_event: Status callback events + :param status_callback: Status callback URL + :param status_callback_method: Status callback URL method + :param machine_detection: Enable machine detection or end of greeting detection + :param amd_status_callback_method: HTTP Method to use with amd_status_callback + :param amd_status_callback: The URL we should call to send amd status information to your application + :param machine_detection_timeout: Number of seconds to wait for machine detection + :param machine_detection_speech_threshold: Number of milliseconds for measuring stick for the length of the speech activity + :param machine_detection_speech_end_threshold: Number of milliseconds of silence after speech activity + :param machine_detection_silence_timeout: Number of milliseconds of initial silence + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Sip( + sip_url, + username=username, + password=password, + url=url, + method=method, + status_callback_event=status_callback_event, + status_callback=status_callback, + status_callback_method=status_callback_method, + machine_detection=machine_detection, + amd_status_callback_method=amd_status_callback_method, + amd_status_callback=amd_status_callback, + machine_detection_timeout=machine_detection_timeout, + machine_detection_speech_threshold=machine_detection_speech_threshold, + machine_detection_speech_end_threshold=machine_detection_speech_end_threshold, + machine_detection_silence_timeout=machine_detection_silence_timeout, + **kwargs + ) + ) + + def application( + self, + application_sid=None, + url=None, + method=None, + status_callback_event=None, + status_callback=None, + status_callback_method=None, + customer_id=None, + copy_parent_to=None, + **kwargs + ): + """ + Create a element + + :param application_sid: Application sid + :param url: TwiML URL + :param method: TwiML URL Method + :param status_callback_event: Events to trigger status callback + :param status_callback: Status Callback URL + :param status_callback_method: Status Callback URL Method + :param customer_id: Identity of the customer calling application + :param copy_parent_to: Copy parent call To field to called application side, otherwise use the application sid as To field + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Application( + application_sid=application_sid, + url=url, + method=method, + status_callback_event=status_callback_event, + status_callback=status_callback, + status_callback_method=status_callback_method, + customer_id=customer_id, + copy_parent_to=copy_parent_to, + **kwargs + ) + ) + + +class Application(TwiML): + """ TwiML Noun""" + + def __init__(self, application_sid=None, **kwargs): + super(Application, self).__init__(**kwargs) + self.name = "Application" + if application_sid: + self.value = application_sid + + def application_sid(self, sid, **kwargs): + """ + Create a element + + :param sid: Application sid to dial + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(ApplicationSid(sid, **kwargs)) + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class ApplicationSid(TwiML): + """ TwiML Noun""" + + def __init__(self, sid, **kwargs): + super(ApplicationSid, self).__init__(**kwargs) + self.name = "ApplicationSid" + self.value = sid + + +class Sip(TwiML): + """ TwiML Noun""" + + def __init__(self, sip_url, **kwargs): + super(Sip, self).__init__(**kwargs) + self.name = "Sip" + self.value = sip_url + + +class Sim(TwiML): + """ TwiML Noun""" + + def __init__(self, sim_sid, **kwargs): + super(Sim, self).__init__(**kwargs) + self.name = "Sim" + self.value = sim_sid + + +class Number(TwiML): + """ TwiML Noun""" + + def __init__(self, phone_number, **kwargs): + super(Number, self).__init__(**kwargs) + self.name = "Number" + self.value = phone_number + + +class Conference(TwiML): + """ TwiML Noun""" + + def __init__(self, name, **kwargs): + super(Conference, self).__init__(**kwargs) + self.name = "Conference" + self.value = name + + +class Client(TwiML): + """ TwiML Noun""" + + def __init__(self, identity=None, **kwargs): + super(Client, self).__init__(**kwargs) + self.name = "Client" + if identity: + self.value = identity + + def identity(self, client_identity, **kwargs): + """ + Create a element + + :param client_identity: Identity of the client to dial + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Identity(client_identity, **kwargs)) + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Identity(TwiML): + """ TwiML Noun""" + + def __init__(self, client_identity, **kwargs): + super(Identity, self).__init__(**kwargs) + self.name = "Identity" + self.value = client_identity + + +class Connect(TwiML): + """ TwiML Verb""" + + def __init__(self, **kwargs): + super(Connect, self).__init__(**kwargs) + self.name = "Connect" + + def room(self, name, participant_identity=None, **kwargs): + """ + Create a element + + :param name: Room name + :param participant_identity: Participant identity when connecting to the Room + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Room(name, participant_identity=participant_identity, **kwargs) + ) + + def autopilot(self, name, **kwargs): + """ + Create a element + + :param name: Autopilot assistant sid or unique name + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Autopilot(name, **kwargs)) + + def stream( + self, + name=None, + connector_name=None, + url=None, + track=None, + status_callback=None, + status_callback_method=None, + **kwargs + ): + """ + Create a element + + :param name: Friendly name given to the Stream + :param connector_name: Unique name for Stream Connector + :param url: URL of the remote service where the Stream is routed + :param track: Track to be streamed to remote service + :param status_callback: Status Callback URL + :param status_callback_method: Status Callback URL method + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Stream( + name=name, + connector_name=connector_name, + url=url, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + **kwargs + ) + ) + + def virtual_agent( + self, + connector_name=None, + language=None, + sentiment_analysis=None, + status_callback=None, + status_callback_method=None, + **kwargs + ): + """ + Create a element + + :param connector_name: Defines the conversation profile Dialogflow needs to use + :param language: Language to be used by Dialogflow to transcribe speech + :param sentiment_analysis: Whether sentiment analysis needs to be enabled or not + :param status_callback: URL to post status callbacks from Twilio + :param status_callback_method: HTTP method to use when requesting the status callback URL + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + VirtualAgent( + connector_name=connector_name, + language=language, + sentiment_analysis=sentiment_analysis, + status_callback=status_callback, + status_callback_method=status_callback_method, + **kwargs + ) + ) + + def conversation( + self, + service_instance_sid=None, + inbound_autocreation=None, + routing_assignment_timeout=None, + inbound_timeout=None, + url=None, + method=None, + record=None, + trim=None, + recording_status_callback=None, + recording_status_callback_method=None, + recording_status_callback_event=None, + status_callback=None, + status_callback_method=None, + status_callback_event=None, + **kwargs + ): + """ + Create a element + + :param service_instance_sid: Service instance Sid + :param inbound_autocreation: Inbound autocreation + :param routing_assignment_timeout: Routing assignment timeout + :param inbound_timeout: Inbound timeout + :param url: TwiML URL + :param method: TwiML URL method + :param record: Record + :param trim: Trim + :param recording_status_callback: Recording status callback URL + :param recording_status_callback_method: Recording status callback URL method + :param recording_status_callback_event: Recording status callback events + :param status_callback: Status callback URL + :param status_callback_method: Status callback URL method + :param status_callback_event: Events to call status callback URL + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Conversation( + service_instance_sid=service_instance_sid, + inbound_autocreation=inbound_autocreation, + routing_assignment_timeout=routing_assignment_timeout, + inbound_timeout=inbound_timeout, + url=url, + method=method, + record=record, + trim=trim, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + recording_status_callback_event=recording_status_callback_event, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + **kwargs + ) + ) + + def conversation_relay( + self, + url=None, + language=None, + tts_language=None, + transcription_language=None, + tts_provider=None, + voice=None, + transcription_provider=None, + speech_model=None, + profanity_filter=None, + dtmf_detection=None, + welcome_greeting=None, + partial_prompts=None, + welcome_greeting_interruptible=None, + interruptible=None, + preemptible=None, + hints=None, + intelligence_service=None, + report_input_during_agent_speech=None, + elevenlabs_text_normalization=None, + interrupt_sensitivity=None, + debug=None, + **kwargs + ): + """ + Create a element + + :param url: URL of the remote service where the session is connected to + :param language: Language to be used for both text-to-speech and transcription + :param tts_language: Language to be used for text-to-speech + :param transcription_language: Language to be used for transcription + :param tts_provider: Provider to be used for text-to-speech + :param voice: Voice to be used for text-to-speech + :param transcription_provider: Provider to be used for transcription + :param speech_model: Speech model to be used for transcription + :param profanity_filter: Whether profanities should be filtered out of the speech transcription + :param dtmf_detection: Whether DTMF tones should be detected and reported in speech transcription + :param welcome_greeting: The sentence to be played automatically when the session is connected + :param partial_prompts: Whether partial prompts should be reported to WebSocket server before the caller finishes speaking + :param welcome_greeting_interruptible: "Whether and how the input from a caller, such as speaking or DTMF can interrupt the welcome greeting + :param interruptible: Whether and how the input from a caller, such as speaking or DTMF can interrupt the play of text-to-speech + :param preemptible: Whether subsequent text-to-speech or play media can interrupt the on-going play of text-to-speech or media + :param hints: Phrases to help better accuracy in speech recognition of these pharases + :param intelligence_service: The Conversational Intelligence Service id or unique name to be used for the session + :param report_input_during_agent_speech: Whether prompts should be reported to WebSocket server when text-to-speech playing and interrupt is disabled + :param elevenlabs_text_normalization: When using ElevenLabs as TTS provider, this parameter allows you to enable or disable its text normalization feature + :param interrupt_sensitivity: Set the sensitivity of the interrupt feature for speech. The value can be low, medium, or high + :param debug: Multiple debug options to be used for troubleshooting + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + ConversationRelay( + url=url, + language=language, + tts_language=tts_language, + transcription_language=transcription_language, + tts_provider=tts_provider, + voice=voice, + transcription_provider=transcription_provider, + speech_model=speech_model, + profanity_filter=profanity_filter, + dtmf_detection=dtmf_detection, + welcome_greeting=welcome_greeting, + partial_prompts=partial_prompts, + welcome_greeting_interruptible=welcome_greeting_interruptible, + interruptible=interruptible, + preemptible=preemptible, + hints=hints, + intelligence_service=intelligence_service, + report_input_during_agent_speech=report_input_during_agent_speech, + elevenlabs_text_normalization=elevenlabs_text_normalization, + interrupt_sensitivity=interrupt_sensitivity, + debug=debug, + **kwargs + ) + ) + + def assistant( + self, + id=None, + language=None, + tts_language=None, + transcription_language=None, + tts_provider=None, + voice=None, + transcription_provider=None, + speech_model=None, + profanity_filter=None, + dtmf_detection=None, + welcome_greeting=None, + partial_prompts=None, + welcome_greeting_interruptible=None, + interruptible=None, + preemptible=None, + hints=None, + intelligence_service=None, + report_input_during_agent_speech=None, + elevenlabs_text_normalization=None, + interrupt_sensitivity=None, + debug=None, + **kwargs + ): + """ + Create a element + + :param id: The assistant ID of the AI Assistant + :param language: Language to be used for both text-to-speech and transcription + :param tts_language: Language to be used for text-to-speech + :param transcription_language: Language to be used for transcription + :param tts_provider: Provider to be used for text-to-speech + :param voice: Voice to be used for text-to-speech + :param transcription_provider: Provider to be used for transcription + :param speech_model: Speech model to be used for transcription + :param profanity_filter: Whether profanities should be filtered out of the speech transcription + :param dtmf_detection: Whether DTMF tones should be detected and reported in speech transcription + :param welcome_greeting: The sentence to be played automatically when the session is connected + :param partial_prompts: Whether partial prompts should be reported to WebSocket server before the caller finishes speaking + :param welcome_greeting_interruptible: "Whether and how the input from a caller, such as speaking or DTMF can interrupt the welcome greeting + :param interruptible: Whether and how the input from a caller, such as speaking or DTMF can interrupt the play of text-to-speech + :param preemptible: Whether subsequent text-to-speech or play media can interrupt the on-going play of text-to-speech or media + :param hints: Phrases to help better accuracy in speech recognition of these pharases + :param intelligence_service: The Conversational Intelligence Service id or unique name to be used for the session + :param report_input_during_agent_speech: Whether prompts should be reported to WebSocket server when text-to-speech playing and interrupt is disabled + :param elevenlabs_text_normalization: When using ElevenLabs as TTS provider, this parameter allows you to enable or disable its text normalization feature + :param interrupt_sensitivity: Set the sensitivity of the interrupt feature for speech. The value can be low, medium, or high + :param debug: Multiple debug options to be used for troubleshooting + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Assistant( + id=id, + language=language, + tts_language=tts_language, + transcription_language=transcription_language, + tts_provider=tts_provider, + voice=voice, + transcription_provider=transcription_provider, + speech_model=speech_model, + profanity_filter=profanity_filter, + dtmf_detection=dtmf_detection, + welcome_greeting=welcome_greeting, + partial_prompts=partial_prompts, + welcome_greeting_interruptible=welcome_greeting_interruptible, + interruptible=interruptible, + preemptible=preemptible, + hints=hints, + intelligence_service=intelligence_service, + report_input_during_agent_speech=report_input_during_agent_speech, + elevenlabs_text_normalization=elevenlabs_text_normalization, + interrupt_sensitivity=interrupt_sensitivity, + debug=debug, + **kwargs + ) + ) + + +class Assistant(TwiML): + """ TwiML Noun""" + + def __init__(self, **kwargs): + super(Assistant, self).__init__(**kwargs) + self.name = "Assistant" + + def language( + self, + code=None, + tts_provider=None, + voice=None, + transcription_provider=None, + speech_model=None, + **kwargs + ): + """ + Create a element + + :param code: Language code of this language setting is for + :param tts_provider: Provider to be used for text-to-speech of this language + :param voice: Voice to be used for text-to-speech of this language + :param transcription_provider: Provider to be used for transcription of this language + :param speech_model: Speech model to be used for transcription of this language + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Language( + code=code, + tts_provider=tts_provider, + voice=voice, + transcription_provider=transcription_provider, + speech_model=speech_model, + **kwargs + ) + ) + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Language(TwiML): + """ TwiML Noun""" + + def __init__(self, **kwargs): + super(Language, self).__init__(**kwargs) + self.name = "Language" + + +class ConversationRelay(TwiML): + """ TwiML Noun""" + + def __init__(self, **kwargs): + super(ConversationRelay, self).__init__(**kwargs) + self.name = "ConversationRelay" + + def language( + self, + code=None, + tts_provider=None, + voice=None, + transcription_provider=None, + speech_model=None, + **kwargs + ): + """ + Create a element + + :param code: Language code of this language setting is for + :param tts_provider: Provider to be used for text-to-speech of this language + :param voice: Voice to be used for text-to-speech of this language + :param transcription_provider: Provider to be used for transcription of this language + :param speech_model: Speech model to be used for transcription of this language + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Language( + code=code, + tts_provider=tts_provider, + voice=voice, + transcription_provider=transcription_provider, + speech_model=speech_model, + **kwargs + ) + ) + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Conversation(TwiML): + """ TwiML Noun""" + + def __init__(self, **kwargs): + super(Conversation, self).__init__(**kwargs) + self.name = "Conversation" + + +class VirtualAgent(TwiML): + """ TwiML Noun""" + + def __init__(self, **kwargs): + super(VirtualAgent, self).__init__(**kwargs) + self.name = "VirtualAgent" + + def config(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom config + :param value: The value of the custom config + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Config(name=name, value=value, **kwargs)) + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Autopilot(TwiML): + """ TwiML Noun""" + + def __init__(self, name, **kwargs): + super(Autopilot, self).__init__(**kwargs) + self.name = "Autopilot" + self.value = name + + +class Room(TwiML): + """ TwiML Noun""" + + def __init__(self, name, **kwargs): + super(Room, self).__init__(**kwargs) + self.name = "Room" + self.value = name diff --git a/venv/Lib/site-packages/typing_inspection/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/typing_inspection/__pycache__/__init__.cpython-312.pyc index 1b41296b..e247cb6a 100644 Binary files a/venv/Lib/site-packages/typing_inspection/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/typing_inspection/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/typing_inspection/__pycache__/introspection.cpython-312.pyc b/venv/Lib/site-packages/typing_inspection/__pycache__/introspection.cpython-312.pyc index 80aed293..cb755feb 100644 Binary files a/venv/Lib/site-packages/typing_inspection/__pycache__/introspection.cpython-312.pyc and b/venv/Lib/site-packages/typing_inspection/__pycache__/introspection.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/typing_inspection/__pycache__/typing_objects.cpython-312.pyc b/venv/Lib/site-packages/typing_inspection/__pycache__/typing_objects.cpython-312.pyc index 51de3b3d..30b645dc 100644 Binary files a/venv/Lib/site-packages/typing_inspection/__pycache__/typing_objects.cpython-312.pyc and b/venv/Lib/site-packages/typing_inspection/__pycache__/typing_objects.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3-2.5.0.dist-info/INSTALLER b/venv/Lib/site-packages/urllib3-2.5.0.dist-info/INSTALLER new file mode 100644 index 00000000..a1b589e3 --- /dev/null +++ b/venv/Lib/site-packages/urllib3-2.5.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/Lib/site-packages/urllib3-2.5.0.dist-info/METADATA b/venv/Lib/site-packages/urllib3-2.5.0.dist-info/METADATA new file mode 100644 index 00000000..15116c78 --- /dev/null +++ b/venv/Lib/site-packages/urllib3-2.5.0.dist-info/METADATA @@ -0,0 +1,154 @@ +Metadata-Version: 2.4 +Name: urllib3 +Version: 2.5.0 +Summary: HTTP library with thread-safe connection pooling, file post, and more. +Project-URL: Changelog, https://github.com/urllib3/urllib3/blob/main/CHANGES.rst +Project-URL: Documentation, https://urllib3.readthedocs.io +Project-URL: Code, https://github.com/urllib3/urllib3 +Project-URL: Issue tracker, https://github.com/urllib3/urllib3/issues +Author-email: Andrey Petrov +Maintainer-email: Seth Michael Larson , Quentin Pradet , Illia Volochii +License-Expression: MIT +License-File: LICENSE.txt +Keywords: filepost,http,httplib,https,pooling,ssl,threadsafe,urllib +Classifier: Environment :: Web Environment +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Internet :: WWW/HTTP +Classifier: Topic :: Software Development :: Libraries +Requires-Python: >=3.9 +Provides-Extra: brotli +Requires-Dist: brotli>=1.0.9; (platform_python_implementation == 'CPython') and extra == 'brotli' +Requires-Dist: brotlicffi>=0.8.0; (platform_python_implementation != 'CPython') and extra == 'brotli' +Provides-Extra: h2 +Requires-Dist: h2<5,>=4; extra == 'h2' +Provides-Extra: socks +Requires-Dist: pysocks!=1.5.7,<2.0,>=1.5.6; extra == 'socks' +Provides-Extra: zstd +Requires-Dist: zstandard>=0.18.0; extra == 'zstd' +Description-Content-Type: text/markdown + +

+ +![urllib3](https://github.com/urllib3/urllib3/raw/main/docs/_static/banner_github.svg) + +

+ +

+ PyPI Version + Python Versions + Join our Discord + Coverage Status + Build Status on GitHub + Documentation Status
+ OpenSSF Scorecard + SLSA 3 + CII Best Practices +

+ +urllib3 is a powerful, *user-friendly* HTTP client for Python. Much of the +Python ecosystem already uses urllib3 and you should too. +urllib3 brings many critical features that are missing from the Python +standard libraries: + +- Thread safety. +- Connection pooling. +- Client-side SSL/TLS verification. +- File uploads with multipart encoding. +- Helpers for retrying requests and dealing with HTTP redirects. +- Support for gzip, deflate, brotli, and zstd encoding. +- Proxy support for HTTP and SOCKS. +- 100% test coverage. + +urllib3 is powerful and easy to use: + +```python3 +>>> import urllib3 +>>> resp = urllib3.request("GET", "http://httpbin.org/robots.txt") +>>> resp.status +200 +>>> resp.data +b"User-agent: *\nDisallow: /deny\n" +``` + +## Installing + +urllib3 can be installed with [pip](https://pip.pypa.io): + +```bash +$ python -m pip install urllib3 +``` + +Alternatively, you can grab the latest source code from [GitHub](https://github.com/urllib3/urllib3): + +```bash +$ git clone https://github.com/urllib3/urllib3.git +$ cd urllib3 +$ pip install . +``` + + +## Documentation + +urllib3 has usage and reference documentation at [urllib3.readthedocs.io](https://urllib3.readthedocs.io). + + +## Community + +urllib3 has a [community Discord channel](https://discord.gg/urllib3) for asking questions and +collaborating with other contributors. Drop by and say hello 👋 + + +## Contributing + +urllib3 happily accepts contributions. Please see our +[contributing documentation](https://urllib3.readthedocs.io/en/latest/contributing.html) +for some tips on getting started. + + +## Security Disclosures + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure with maintainers. + + +## Maintainers + +- [@sethmlarson](https://github.com/sethmlarson) (Seth M. Larson) +- [@pquentin](https://github.com/pquentin) (Quentin Pradet) +- [@illia-v](https://github.com/illia-v) (Illia Volochii) +- [@theacodes](https://github.com/theacodes) (Thea Flowers) +- [@haikuginger](https://github.com/haikuginger) (Jess Shapiro) +- [@lukasa](https://github.com/lukasa) (Cory Benfield) +- [@sigmavirus24](https://github.com/sigmavirus24) (Ian Stapleton Cordasco) +- [@shazow](https://github.com/shazow) (Andrey Petrov) + +👋 + + +## Sponsorship + +If your company benefits from this library, please consider [sponsoring its +development](https://urllib3.readthedocs.io/en/latest/sponsors.html). + + +## For Enterprise + +Professional support for urllib3 is available as part of the [Tidelift +Subscription][1]. Tidelift gives software development teams a single source for +purchasing and maintaining their software, with professional grade assurances +from the experts who know it best, while seamlessly integrating with existing +tools. + +[1]: https://tidelift.com/subscription/pkg/pypi-urllib3?utm_source=pypi-urllib3&utm_medium=referral&utm_campaign=readme diff --git a/venv/Lib/site-packages/urllib3-2.5.0.dist-info/RECORD b/venv/Lib/site-packages/urllib3-2.5.0.dist-info/RECORD new file mode 100644 index 00000000..91383f14 --- /dev/null +++ b/venv/Lib/site-packages/urllib3-2.5.0.dist-info/RECORD @@ -0,0 +1,79 @@ +urllib3-2.5.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +urllib3-2.5.0.dist-info/METADATA,sha256=maYkTIZt0a-lkEC-hMZWbCBmcGZyJcYOeRk4_nuTrNc,6461 +urllib3-2.5.0.dist-info/RECORD,, +urllib3-2.5.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +urllib3-2.5.0.dist-info/licenses/LICENSE.txt,sha256=Ew46ZNX91dCWp1JpRjSn2d8oRGnehuVzIQAmgEHj1oY,1093 +urllib3/__init__.py,sha256=JMo1tg1nIV1AeJ2vENC_Txfl0e5h6Gzl9DGVk1rWRbo,6979 +urllib3/__pycache__/__init__.cpython-312.pyc,, +urllib3/__pycache__/_base_connection.cpython-312.pyc,, +urllib3/__pycache__/_collections.cpython-312.pyc,, +urllib3/__pycache__/_request_methods.cpython-312.pyc,, +urllib3/__pycache__/_version.cpython-312.pyc,, +urllib3/__pycache__/connection.cpython-312.pyc,, +urllib3/__pycache__/connectionpool.cpython-312.pyc,, +urllib3/__pycache__/exceptions.cpython-312.pyc,, +urllib3/__pycache__/fields.cpython-312.pyc,, +urllib3/__pycache__/filepost.cpython-312.pyc,, +urllib3/__pycache__/poolmanager.cpython-312.pyc,, +urllib3/__pycache__/response.cpython-312.pyc,, +urllib3/_base_connection.py,sha256=T1cwH3RhzsrBh6Bz3AOGVDboRsE7veijqZPXXQTR2Rg,5568 +urllib3/_collections.py,sha256=tM7c6J1iKtWZYV_QGYb8-r7Nr1524Dehnsa0Ufh6_mU,17295 +urllib3/_request_methods.py,sha256=gCeF85SO_UU4WoPwYHIoz_tw-eM_EVOkLFp8OFsC7DA,9931 +urllib3/_version.py,sha256=ZlSUkBo_Pd90B6pM0GDO7l2vitQD3QCK3xPR_K0zFJA,511 +urllib3/connection.py,sha256=iP4pgSJtpusXyYlejzNn-gih_wWCxMU-qy6OU1kaapc,42613 +urllib3/connectionpool.py,sha256=ZEhudsa8BIubD2M0XoxBBsjxbsXwMgUScH7oQ9i-j1Y,43371 +urllib3/contrib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +urllib3/contrib/__pycache__/__init__.cpython-312.pyc,, +urllib3/contrib/__pycache__/pyopenssl.cpython-312.pyc,, +urllib3/contrib/__pycache__/socks.cpython-312.pyc,, +urllib3/contrib/emscripten/__init__.py,sha256=u6KNgzjlFZbuAAXa_ybCR7gQ71VJESnF-IIdDA73brw,733 +urllib3/contrib/emscripten/__pycache__/__init__.cpython-312.pyc,, +urllib3/contrib/emscripten/__pycache__/connection.cpython-312.pyc,, +urllib3/contrib/emscripten/__pycache__/fetch.cpython-312.pyc,, +urllib3/contrib/emscripten/__pycache__/request.cpython-312.pyc,, +urllib3/contrib/emscripten/__pycache__/response.cpython-312.pyc,, +urllib3/contrib/emscripten/connection.py,sha256=j8DR_flE7hsoFhNfiqHLiaPaCsVbzG44jgahwvsQ52A,8771 +urllib3/contrib/emscripten/emscripten_fetch_worker.js,sha256=CDfYF_9CDobtx2lGidyJ1zjDEvwNT5F-dchmVWXDh0E,3655 +urllib3/contrib/emscripten/fetch.py,sha256=kco06lWoQ-fdFfN51-nzeTywPVBEHg89WIst33H3xcg,23484 +urllib3/contrib/emscripten/request.py,sha256=mL28szy1KvE3NJhWor5jNmarp8gwplDU-7gwGZY5g0Q,566 +urllib3/contrib/emscripten/response.py,sha256=7oVPENYZHuzEGRtG40HonpH5tAIYHsGcHPbJt2Z0U-Y,9507 +urllib3/contrib/pyopenssl.py,sha256=Xp5Ym05VgXGhHa0C4wlutvHxY8SnKSS6WLb2t5Miu0s,19720 +urllib3/contrib/socks.py,sha256=-iardc61GypsJzD6W6yuRS7KVCyfowcQrl_719H7lIM,7549 +urllib3/exceptions.py,sha256=pziumHf0Vwx3z4gvUy7ou8nlM2yIYX0N3l3znEdeF5U,9938 +urllib3/fields.py,sha256=FCf7UULSkf10cuTRUWTQESzxgl1WT8e2aCy3kfyZins,10829 +urllib3/filepost.py,sha256=U8eNZ-mpKKHhrlbHEEiTxxgK16IejhEa7uz42yqA_dI,2388 +urllib3/http2/__init__.py,sha256=xzrASH7R5ANRkPJOot5lGnATOq3KKuyXzI42rcnwmqs,1741 +urllib3/http2/__pycache__/__init__.cpython-312.pyc,, +urllib3/http2/__pycache__/connection.cpython-312.pyc,, +urllib3/http2/__pycache__/probe.cpython-312.pyc,, +urllib3/http2/connection.py,sha256=4DB0DkZEC3yIkhGjUDIHB17wrYCLaL0Ag5bDW2_mGPI,12694 +urllib3/http2/probe.py,sha256=nnAkqbhAakOiF75rz7W0udZ38Eeh_uD8fjV74N73FEI,3014 +urllib3/poolmanager.py,sha256=oKsgP1EsAI4OVgK9-9D3AYXZS5HYV8yKUSog-QbJ8Ts,23866 +urllib3/py.typed,sha256=UaCuPFa3H8UAakbt-5G8SPacldTOGvJv18pPjUJ5gDY,93 +urllib3/response.py,sha256=TVTSu6Q1U0U7hoHYMIRxxuh4zroeMo8b5EI4DOA13Eo,46480 +urllib3/util/__init__.py,sha256=-qeS0QceivazvBEKDNFCAI-6ACcdDOE4TMvo7SLNlAQ,1001 +urllib3/util/__pycache__/__init__.cpython-312.pyc,, +urllib3/util/__pycache__/connection.cpython-312.pyc,, +urllib3/util/__pycache__/proxy.cpython-312.pyc,, +urllib3/util/__pycache__/request.cpython-312.pyc,, +urllib3/util/__pycache__/response.cpython-312.pyc,, +urllib3/util/__pycache__/retry.cpython-312.pyc,, +urllib3/util/__pycache__/ssl_.cpython-312.pyc,, +urllib3/util/__pycache__/ssl_match_hostname.cpython-312.pyc,, +urllib3/util/__pycache__/ssltransport.cpython-312.pyc,, +urllib3/util/__pycache__/timeout.cpython-312.pyc,, +urllib3/util/__pycache__/url.cpython-312.pyc,, +urllib3/util/__pycache__/util.cpython-312.pyc,, +urllib3/util/__pycache__/wait.cpython-312.pyc,, +urllib3/util/connection.py,sha256=JjO722lzHlzLXPTkr9ZWBdhseXnMVjMSb1DJLVrXSnQ,4444 +urllib3/util/proxy.py,sha256=seP8-Q5B6bB0dMtwPj-YcZZQ30vHuLqRu-tI0JZ2fzs,1148 +urllib3/util/request.py,sha256=XuAsEBT58DAZYUTwpMH5Hr3A1OPoMNvNIYIunbIqbc8,8411 +urllib3/util/response.py,sha256=vQE639uoEhj1vpjEdxu5lNIhJCSUZkd7pqllUI0BZOA,3374 +urllib3/util/retry.py,sha256=bj-2YUqblxLlv8THg5fxww-DM54XCbjgZXIQ71XioCY,18459 +urllib3/util/ssl_.py,sha256=jxnQ3msYkVaokJVWqHNnAVdVtDdidrTHDeyk50gwqaQ,19786 +urllib3/util/ssl_match_hostname.py,sha256=Di7DU7zokoltapT_F0Sj21ffYxwaS_cE5apOtwueeyA,5845 +urllib3/util/ssltransport.py,sha256=Ez4O8pR_vT8dan_FvqBYS6dgDfBXEMfVfrzcdUoWfi4,8847 +urllib3/util/timeout.py,sha256=4eT1FVeZZU7h7mYD1Jq2OXNe4fxekdNvhoWUkZusRpA,10346 +urllib3/util/url.py,sha256=WRh-TMYXosmgp8m8lT4H5spoHw5yUjlcMCfU53AkoAs,15205 +urllib3/util/util.py,sha256=j3lbZK1jPyiwD34T8IgJzdWEZVT-4E-0vYIJi9UjeNA,1146 +urllib3/util/wait.py,sha256=_ph8IrUR3sqPqi0OopQgJUlH4wzkGeM5CiyA7XGGtmI,4423 diff --git a/venv/Lib/site-packages/urllib3-2.5.0.dist-info/WHEEL b/venv/Lib/site-packages/urllib3-2.5.0.dist-info/WHEEL new file mode 100644 index 00000000..12228d41 --- /dev/null +++ b/venv/Lib/site-packages/urllib3-2.5.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/venv/Lib/site-packages/urllib3-2.5.0.dist-info/licenses/LICENSE.txt b/venv/Lib/site-packages/urllib3-2.5.0.dist-info/licenses/LICENSE.txt new file mode 100644 index 00000000..e6183d02 --- /dev/null +++ b/venv/Lib/site-packages/urllib3-2.5.0.dist-info/licenses/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2008-2020 Andrey Petrov and contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/venv/Lib/site-packages/urllib3/__init__.py b/venv/Lib/site-packages/urllib3/__init__.py new file mode 100644 index 00000000..3fe782c8 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/__init__.py @@ -0,0 +1,211 @@ +""" +Python HTTP library with thread-safe connection pooling, file post support, user friendly, and more +""" + +from __future__ import annotations + +# Set default logging handler to avoid "No handler found" warnings. +import logging +import sys +import typing +import warnings +from logging import NullHandler + +from . import exceptions +from ._base_connection import _TYPE_BODY +from ._collections import HTTPHeaderDict +from ._version import __version__ +from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, connection_from_url +from .filepost import _TYPE_FIELDS, encode_multipart_formdata +from .poolmanager import PoolManager, ProxyManager, proxy_from_url +from .response import BaseHTTPResponse, HTTPResponse +from .util.request import make_headers +from .util.retry import Retry +from .util.timeout import Timeout + +# Ensure that Python is compiled with OpenSSL 1.1.1+ +# If the 'ssl' module isn't available at all that's +# fine, we only care if the module is available. +try: + import ssl +except ImportError: + pass +else: + if not ssl.OPENSSL_VERSION.startswith("OpenSSL "): # Defensive: + warnings.warn( + "urllib3 v2 only supports OpenSSL 1.1.1+, currently " + f"the 'ssl' module is compiled with {ssl.OPENSSL_VERSION!r}. " + "See: https://github.com/urllib3/urllib3/issues/3020", + exceptions.NotOpenSSLWarning, + ) + elif ssl.OPENSSL_VERSION_INFO < (1, 1, 1): # Defensive: + raise ImportError( + "urllib3 v2 only supports OpenSSL 1.1.1+, currently " + f"the 'ssl' module is compiled with {ssl.OPENSSL_VERSION!r}. " + "See: https://github.com/urllib3/urllib3/issues/2168" + ) + +__author__ = "Andrey Petrov (andrey.petrov@shazow.net)" +__license__ = "MIT" +__version__ = __version__ + +__all__ = ( + "HTTPConnectionPool", + "HTTPHeaderDict", + "HTTPSConnectionPool", + "PoolManager", + "ProxyManager", + "HTTPResponse", + "Retry", + "Timeout", + "add_stderr_logger", + "connection_from_url", + "disable_warnings", + "encode_multipart_formdata", + "make_headers", + "proxy_from_url", + "request", + "BaseHTTPResponse", +) + +logging.getLogger(__name__).addHandler(NullHandler()) + + +def add_stderr_logger( + level: int = logging.DEBUG, +) -> logging.StreamHandler[typing.TextIO]: + """ + Helper for quickly adding a StreamHandler to the logger. Useful for + debugging. + + Returns the handler after adding it. + """ + # This method needs to be in this __init__.py to get the __name__ correct + # even if urllib3 is vendored within another package. + logger = logging.getLogger(__name__) + handler = logging.StreamHandler() + handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s")) + logger.addHandler(handler) + logger.setLevel(level) + logger.debug("Added a stderr logging handler to logger: %s", __name__) + return handler + + +# ... Clean up. +del NullHandler + + +# All warning filters *must* be appended unless you're really certain that they +# shouldn't be: otherwise, it's very hard for users to use most Python +# mechanisms to silence them. +# SecurityWarning's always go off by default. +warnings.simplefilter("always", exceptions.SecurityWarning, append=True) +# InsecurePlatformWarning's don't vary between requests, so we keep it default. +warnings.simplefilter("default", exceptions.InsecurePlatformWarning, append=True) + + +def disable_warnings(category: type[Warning] = exceptions.HTTPWarning) -> None: + """ + Helper for quickly disabling all urllib3 warnings. + """ + warnings.simplefilter("ignore", category) + + +_DEFAULT_POOL = PoolManager() + + +def request( + method: str, + url: str, + *, + body: _TYPE_BODY | None = None, + fields: _TYPE_FIELDS | None = None, + headers: typing.Mapping[str, str] | None = None, + preload_content: bool | None = True, + decode_content: bool | None = True, + redirect: bool | None = True, + retries: Retry | bool | int | None = None, + timeout: Timeout | float | int | None = 3, + json: typing.Any | None = None, +) -> BaseHTTPResponse: + """ + A convenience, top-level request method. It uses a module-global ``PoolManager`` instance. + Therefore, its side effects could be shared across dependencies relying on it. + To avoid side effects create a new ``PoolManager`` instance and use it instead. + The method does not accept low-level ``**urlopen_kw`` keyword arguments. + + :param method: + HTTP request method (such as GET, POST, PUT, etc.) + + :param url: + The URL to perform the request on. + + :param body: + Data to send in the request body, either :class:`str`, :class:`bytes`, + an iterable of :class:`str`/:class:`bytes`, or a file-like object. + + :param fields: + Data to encode and send in the request body. + + :param headers: + Dictionary of custom headers to send, such as User-Agent, + If-None-Match, etc. + + :param bool preload_content: + If True, the response's body will be preloaded into memory. + + :param bool decode_content: + If True, will attempt to decode the body based on the + 'content-encoding' header. + + :param redirect: + If True, automatically handle redirects (status codes 301, 302, + 303, 307, 308). Each redirect counts as a retry. Disabling retries + will disable redirect, too. + + :param retries: + Configure the number of retries to allow before raising a + :class:`~urllib3.exceptions.MaxRetryError` exception. + + If ``None`` (default) will retry 3 times, see ``Retry.DEFAULT``. Pass a + :class:`~urllib3.util.retry.Retry` object for fine-grained control + over different types of retries. + Pass an integer number to retry connection errors that many times, + but no other types of errors. Pass zero to never retry. + + If ``False``, then retries are disabled and any exception is raised + immediately. Also, instead of raising a MaxRetryError on redirects, + the redirect response will be returned. + + :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int. + + :param timeout: + If specified, overrides the default timeout for this one + request. It may be a float (in seconds) or an instance of + :class:`urllib3.util.Timeout`. + + :param json: + Data to encode and send as JSON with UTF-encoded in the request body. + The ``"Content-Type"`` header will be set to ``"application/json"`` + unless specified otherwise. + """ + + return _DEFAULT_POOL.request( + method, + url, + body=body, + fields=fields, + headers=headers, + preload_content=preload_content, + decode_content=decode_content, + redirect=redirect, + retries=retries, + timeout=timeout, + json=json, + ) + + +if sys.platform == "emscripten": + from .contrib.emscripten import inject_into_urllib3 # noqa: 401 + + inject_into_urllib3() diff --git a/venv/Lib/site-packages/urllib3/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/urllib3/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..514facda Binary files /dev/null and b/venv/Lib/site-packages/urllib3/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/__pycache__/_base_connection.cpython-312.pyc b/venv/Lib/site-packages/urllib3/__pycache__/_base_connection.cpython-312.pyc new file mode 100644 index 00000000..2e4935e4 Binary files /dev/null and b/venv/Lib/site-packages/urllib3/__pycache__/_base_connection.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/__pycache__/_collections.cpython-312.pyc b/venv/Lib/site-packages/urllib3/__pycache__/_collections.cpython-312.pyc new file mode 100644 index 00000000..de477217 Binary files /dev/null and b/venv/Lib/site-packages/urllib3/__pycache__/_collections.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/__pycache__/_request_methods.cpython-312.pyc b/venv/Lib/site-packages/urllib3/__pycache__/_request_methods.cpython-312.pyc new file mode 100644 index 00000000..46e43504 Binary files /dev/null and b/venv/Lib/site-packages/urllib3/__pycache__/_request_methods.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/__pycache__/_version.cpython-312.pyc b/venv/Lib/site-packages/urllib3/__pycache__/_version.cpython-312.pyc new file mode 100644 index 00000000..c1841800 Binary files /dev/null and b/venv/Lib/site-packages/urllib3/__pycache__/_version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/__pycache__/connection.cpython-312.pyc b/venv/Lib/site-packages/urllib3/__pycache__/connection.cpython-312.pyc new file mode 100644 index 00000000..c92f0efb Binary files /dev/null and b/venv/Lib/site-packages/urllib3/__pycache__/connection.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/__pycache__/connectionpool.cpython-312.pyc b/venv/Lib/site-packages/urllib3/__pycache__/connectionpool.cpython-312.pyc new file mode 100644 index 00000000..0e223adf Binary files /dev/null and b/venv/Lib/site-packages/urllib3/__pycache__/connectionpool.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/__pycache__/exceptions.cpython-312.pyc b/venv/Lib/site-packages/urllib3/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 00000000..909d4653 Binary files /dev/null and b/venv/Lib/site-packages/urllib3/__pycache__/exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/__pycache__/fields.cpython-312.pyc b/venv/Lib/site-packages/urllib3/__pycache__/fields.cpython-312.pyc new file mode 100644 index 00000000..f45a079f Binary files /dev/null and b/venv/Lib/site-packages/urllib3/__pycache__/fields.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/__pycache__/filepost.cpython-312.pyc b/venv/Lib/site-packages/urllib3/__pycache__/filepost.cpython-312.pyc new file mode 100644 index 00000000..fa7f514b Binary files /dev/null and b/venv/Lib/site-packages/urllib3/__pycache__/filepost.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/__pycache__/poolmanager.cpython-312.pyc b/venv/Lib/site-packages/urllib3/__pycache__/poolmanager.cpython-312.pyc new file mode 100644 index 00000000..161da73d Binary files /dev/null and b/venv/Lib/site-packages/urllib3/__pycache__/poolmanager.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/__pycache__/response.cpython-312.pyc b/venv/Lib/site-packages/urllib3/__pycache__/response.cpython-312.pyc new file mode 100644 index 00000000..f69216dc Binary files /dev/null and b/venv/Lib/site-packages/urllib3/__pycache__/response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/_base_connection.py b/venv/Lib/site-packages/urllib3/_base_connection.py new file mode 100644 index 00000000..dc0f318c --- /dev/null +++ b/venv/Lib/site-packages/urllib3/_base_connection.py @@ -0,0 +1,165 @@ +from __future__ import annotations + +import typing + +from .util.connection import _TYPE_SOCKET_OPTIONS +from .util.timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT +from .util.url import Url + +_TYPE_BODY = typing.Union[bytes, typing.IO[typing.Any], typing.Iterable[bytes], str] + + +class ProxyConfig(typing.NamedTuple): + ssl_context: ssl.SSLContext | None + use_forwarding_for_https: bool + assert_hostname: None | str | typing.Literal[False] + assert_fingerprint: str | None + + +class _ResponseOptions(typing.NamedTuple): + # TODO: Remove this in favor of a better + # HTTP request/response lifecycle tracking. + request_method: str + request_url: str + preload_content: bool + decode_content: bool + enforce_content_length: bool + + +if typing.TYPE_CHECKING: + import ssl + from typing import Protocol + + from .response import BaseHTTPResponse + + class BaseHTTPConnection(Protocol): + default_port: typing.ClassVar[int] + default_socket_options: typing.ClassVar[_TYPE_SOCKET_OPTIONS] + + host: str + port: int + timeout: None | ( + float + ) # Instance doesn't store _DEFAULT_TIMEOUT, must be resolved. + blocksize: int + source_address: tuple[str, int] | None + socket_options: _TYPE_SOCKET_OPTIONS | None + + proxy: Url | None + proxy_config: ProxyConfig | None + + is_verified: bool + proxy_is_verified: bool | None + + def __init__( + self, + host: str, + port: int | None = None, + *, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + blocksize: int = 8192, + socket_options: _TYPE_SOCKET_OPTIONS | None = ..., + proxy: Url | None = None, + proxy_config: ProxyConfig | None = None, + ) -> None: ... + + def set_tunnel( + self, + host: str, + port: int | None = None, + headers: typing.Mapping[str, str] | None = None, + scheme: str = "http", + ) -> None: ... + + def connect(self) -> None: ... + + def request( + self, + method: str, + url: str, + body: _TYPE_BODY | None = None, + headers: typing.Mapping[str, str] | None = None, + # We know *at least* botocore is depending on the order of the + # first 3 parameters so to be safe we only mark the later ones + # as keyword-only to ensure we have space to extend. + *, + chunked: bool = False, + preload_content: bool = True, + decode_content: bool = True, + enforce_content_length: bool = True, + ) -> None: ... + + def getresponse(self) -> BaseHTTPResponse: ... + + def close(self) -> None: ... + + @property + def is_closed(self) -> bool: + """Whether the connection either is brand new or has been previously closed. + If this property is True then both ``is_connected`` and ``has_connected_to_proxy`` + properties must be False. + """ + + @property + def is_connected(self) -> bool: + """Whether the connection is actively connected to any origin (proxy or target)""" + + @property + def has_connected_to_proxy(self) -> bool: + """Whether the connection has successfully connected to its proxy. + This returns False if no proxy is in use. Used to determine whether + errors are coming from the proxy layer or from tunnelling to the target origin. + """ + + class BaseHTTPSConnection(BaseHTTPConnection, Protocol): + default_port: typing.ClassVar[int] + default_socket_options: typing.ClassVar[_TYPE_SOCKET_OPTIONS] + + # Certificate verification methods + cert_reqs: int | str | None + assert_hostname: None | str | typing.Literal[False] + assert_fingerprint: str | None + ssl_context: ssl.SSLContext | None + + # Trusted CAs + ca_certs: str | None + ca_cert_dir: str | None + ca_cert_data: None | str | bytes + + # TLS version + ssl_minimum_version: int | None + ssl_maximum_version: int | None + ssl_version: int | str | None # Deprecated + + # Client certificates + cert_file: str | None + key_file: str | None + key_password: str | None + + def __init__( + self, + host: str, + port: int | None = None, + *, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + blocksize: int = 16384, + socket_options: _TYPE_SOCKET_OPTIONS | None = ..., + proxy: Url | None = None, + proxy_config: ProxyConfig | None = None, + cert_reqs: int | str | None = None, + assert_hostname: None | str | typing.Literal[False] = None, + assert_fingerprint: str | None = None, + server_hostname: str | None = None, + ssl_context: ssl.SSLContext | None = None, + ca_certs: str | None = None, + ca_cert_dir: str | None = None, + ca_cert_data: None | str | bytes = None, + ssl_minimum_version: int | None = None, + ssl_maximum_version: int | None = None, + ssl_version: int | str | None = None, # Deprecated + cert_file: str | None = None, + key_file: str | None = None, + key_password: str | None = None, + ) -> None: ... diff --git a/venv/Lib/site-packages/urllib3/_collections.py b/venv/Lib/site-packages/urllib3/_collections.py new file mode 100644 index 00000000..1b6c1364 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/_collections.py @@ -0,0 +1,479 @@ +from __future__ import annotations + +import typing +from collections import OrderedDict +from enum import Enum, auto +from threading import RLock + +if typing.TYPE_CHECKING: + # We can only import Protocol if TYPE_CHECKING because it's a development + # dependency, and is not available at runtime. + from typing import Protocol + + from typing_extensions import Self + + class HasGettableStringKeys(Protocol): + def keys(self) -> typing.Iterator[str]: ... + + def __getitem__(self, key: str) -> str: ... + + +__all__ = ["RecentlyUsedContainer", "HTTPHeaderDict"] + + +# Key type +_KT = typing.TypeVar("_KT") +# Value type +_VT = typing.TypeVar("_VT") +# Default type +_DT = typing.TypeVar("_DT") + +ValidHTTPHeaderSource = typing.Union[ + "HTTPHeaderDict", + typing.Mapping[str, str], + typing.Iterable[tuple[str, str]], + "HasGettableStringKeys", +] + + +class _Sentinel(Enum): + not_passed = auto() + + +def ensure_can_construct_http_header_dict( + potential: object, +) -> ValidHTTPHeaderSource | None: + if isinstance(potential, HTTPHeaderDict): + return potential + elif isinstance(potential, typing.Mapping): + # Full runtime checking of the contents of a Mapping is expensive, so for the + # purposes of typechecking, we assume that any Mapping is the right shape. + return typing.cast(typing.Mapping[str, str], potential) + elif isinstance(potential, typing.Iterable): + # Similarly to Mapping, full runtime checking of the contents of an Iterable is + # expensive, so for the purposes of typechecking, we assume that any Iterable + # is the right shape. + return typing.cast(typing.Iterable[tuple[str, str]], potential) + elif hasattr(potential, "keys") and hasattr(potential, "__getitem__"): + return typing.cast("HasGettableStringKeys", potential) + else: + return None + + +class RecentlyUsedContainer(typing.Generic[_KT, _VT], typing.MutableMapping[_KT, _VT]): + """ + Provides a thread-safe dict-like container which maintains up to + ``maxsize`` keys while throwing away the least-recently-used keys beyond + ``maxsize``. + + :param maxsize: + Maximum number of recent elements to retain. + + :param dispose_func: + Every time an item is evicted from the container, + ``dispose_func(value)`` is called. Callback which will get called + """ + + _container: typing.OrderedDict[_KT, _VT] + _maxsize: int + dispose_func: typing.Callable[[_VT], None] | None + lock: RLock + + def __init__( + self, + maxsize: int = 10, + dispose_func: typing.Callable[[_VT], None] | None = None, + ) -> None: + super().__init__() + self._maxsize = maxsize + self.dispose_func = dispose_func + self._container = OrderedDict() + self.lock = RLock() + + def __getitem__(self, key: _KT) -> _VT: + # Re-insert the item, moving it to the end of the eviction line. + with self.lock: + item = self._container.pop(key) + self._container[key] = item + return item + + def __setitem__(self, key: _KT, value: _VT) -> None: + evicted_item = None + with self.lock: + # Possibly evict the existing value of 'key' + try: + # If the key exists, we'll overwrite it, which won't change the + # size of the pool. Because accessing a key should move it to + # the end of the eviction line, we pop it out first. + evicted_item = key, self._container.pop(key) + self._container[key] = value + except KeyError: + # When the key does not exist, we insert the value first so that + # evicting works in all cases, including when self._maxsize is 0 + self._container[key] = value + if len(self._container) > self._maxsize: + # If we didn't evict an existing value, and we've hit our maximum + # size, then we have to evict the least recently used item from + # the beginning of the container. + evicted_item = self._container.popitem(last=False) + + # After releasing the lock on the pool, dispose of any evicted value. + if evicted_item is not None and self.dispose_func: + _, evicted_value = evicted_item + self.dispose_func(evicted_value) + + def __delitem__(self, key: _KT) -> None: + with self.lock: + value = self._container.pop(key) + + if self.dispose_func: + self.dispose_func(value) + + def __len__(self) -> int: + with self.lock: + return len(self._container) + + def __iter__(self) -> typing.NoReturn: + raise NotImplementedError( + "Iteration over this class is unlikely to be threadsafe." + ) + + def clear(self) -> None: + with self.lock: + # Copy pointers to all values, then wipe the mapping + values = list(self._container.values()) + self._container.clear() + + if self.dispose_func: + for value in values: + self.dispose_func(value) + + def keys(self) -> set[_KT]: # type: ignore[override] + with self.lock: + return set(self._container.keys()) + + +class HTTPHeaderDictItemView(set[tuple[str, str]]): + """ + HTTPHeaderDict is unusual for a Mapping[str, str] in that it has two modes of + address. + + If we directly try to get an item with a particular name, we will get a string + back that is the concatenated version of all the values: + + >>> d['X-Header-Name'] + 'Value1, Value2, Value3' + + However, if we iterate over an HTTPHeaderDict's items, we will optionally combine + these values based on whether combine=True was called when building up the dictionary + + >>> d = HTTPHeaderDict({"A": "1", "B": "foo"}) + >>> d.add("A", "2", combine=True) + >>> d.add("B", "bar") + >>> list(d.items()) + [ + ('A', '1, 2'), + ('B', 'foo'), + ('B', 'bar'), + ] + + This class conforms to the interface required by the MutableMapping ABC while + also giving us the nonstandard iteration behavior we want; items with duplicate + keys, ordered by time of first insertion. + """ + + _headers: HTTPHeaderDict + + def __init__(self, headers: HTTPHeaderDict) -> None: + self._headers = headers + + def __len__(self) -> int: + return len(list(self._headers.iteritems())) + + def __iter__(self) -> typing.Iterator[tuple[str, str]]: + return self._headers.iteritems() + + def __contains__(self, item: object) -> bool: + if isinstance(item, tuple) and len(item) == 2: + passed_key, passed_val = item + if isinstance(passed_key, str) and isinstance(passed_val, str): + return self._headers._has_value_for_header(passed_key, passed_val) + return False + + +class HTTPHeaderDict(typing.MutableMapping[str, str]): + """ + :param headers: + An iterable of field-value pairs. Must not contain multiple field names + when compared case-insensitively. + + :param kwargs: + Additional field-value pairs to pass in to ``dict.update``. + + A ``dict`` like container for storing HTTP Headers. + + Field names are stored and compared case-insensitively in compliance with + RFC 7230. Iteration provides the first case-sensitive key seen for each + case-insensitive pair. + + Using ``__setitem__`` syntax overwrites fields that compare equal + case-insensitively in order to maintain ``dict``'s api. For fields that + compare equal, instead create a new ``HTTPHeaderDict`` and use ``.add`` + in a loop. + + If multiple fields that are equal case-insensitively are passed to the + constructor or ``.update``, the behavior is undefined and some will be + lost. + + >>> headers = HTTPHeaderDict() + >>> headers.add('Set-Cookie', 'foo=bar') + >>> headers.add('set-cookie', 'baz=quxx') + >>> headers['content-length'] = '7' + >>> headers['SET-cookie'] + 'foo=bar, baz=quxx' + >>> headers['Content-Length'] + '7' + """ + + _container: typing.MutableMapping[str, list[str]] + + def __init__(self, headers: ValidHTTPHeaderSource | None = None, **kwargs: str): + super().__init__() + self._container = {} # 'dict' is insert-ordered + if headers is not None: + if isinstance(headers, HTTPHeaderDict): + self._copy_from(headers) + else: + self.extend(headers) + if kwargs: + self.extend(kwargs) + + def __setitem__(self, key: str, val: str) -> None: + # avoid a bytes/str comparison by decoding before httplib + if isinstance(key, bytes): + key = key.decode("latin-1") + self._container[key.lower()] = [key, val] + + def __getitem__(self, key: str) -> str: + val = self._container[key.lower()] + return ", ".join(val[1:]) + + def __delitem__(self, key: str) -> None: + del self._container[key.lower()] + + def __contains__(self, key: object) -> bool: + if isinstance(key, str): + return key.lower() in self._container + return False + + def setdefault(self, key: str, default: str = "") -> str: + return super().setdefault(key, default) + + def __eq__(self, other: object) -> bool: + maybe_constructable = ensure_can_construct_http_header_dict(other) + if maybe_constructable is None: + return False + else: + other_as_http_header_dict = type(self)(maybe_constructable) + + return {k.lower(): v for k, v in self.itermerged()} == { + k.lower(): v for k, v in other_as_http_header_dict.itermerged() + } + + def __ne__(self, other: object) -> bool: + return not self.__eq__(other) + + def __len__(self) -> int: + return len(self._container) + + def __iter__(self) -> typing.Iterator[str]: + # Only provide the originally cased names + for vals in self._container.values(): + yield vals[0] + + def discard(self, key: str) -> None: + try: + del self[key] + except KeyError: + pass + + def add(self, key: str, val: str, *, combine: bool = False) -> None: + """Adds a (name, value) pair, doesn't overwrite the value if it already + exists. + + If this is called with combine=True, instead of adding a new header value + as a distinct item during iteration, this will instead append the value to + any existing header value with a comma. If no existing header value exists + for the key, then the value will simply be added, ignoring the combine parameter. + + >>> headers = HTTPHeaderDict(foo='bar') + >>> headers.add('Foo', 'baz') + >>> headers['foo'] + 'bar, baz' + >>> list(headers.items()) + [('foo', 'bar'), ('foo', 'baz')] + >>> headers.add('foo', 'quz', combine=True) + >>> list(headers.items()) + [('foo', 'bar, baz, quz')] + """ + # avoid a bytes/str comparison by decoding before httplib + if isinstance(key, bytes): + key = key.decode("latin-1") + key_lower = key.lower() + new_vals = [key, val] + # Keep the common case aka no item present as fast as possible + vals = self._container.setdefault(key_lower, new_vals) + if new_vals is not vals: + # if there are values here, then there is at least the initial + # key/value pair + assert len(vals) >= 2 + if combine: + vals[-1] = vals[-1] + ", " + val + else: + vals.append(val) + + def extend(self, *args: ValidHTTPHeaderSource, **kwargs: str) -> None: + """Generic import function for any type of header-like object. + Adapted version of MutableMapping.update in order to insert items + with self.add instead of self.__setitem__ + """ + if len(args) > 1: + raise TypeError( + f"extend() takes at most 1 positional arguments ({len(args)} given)" + ) + other = args[0] if len(args) >= 1 else () + + if isinstance(other, HTTPHeaderDict): + for key, val in other.iteritems(): + self.add(key, val) + elif isinstance(other, typing.Mapping): + for key, val in other.items(): + self.add(key, val) + elif isinstance(other, typing.Iterable): + other = typing.cast(typing.Iterable[tuple[str, str]], other) + for key, value in other: + self.add(key, value) + elif hasattr(other, "keys") and hasattr(other, "__getitem__"): + # THIS IS NOT A TYPESAFE BRANCH + # In this branch, the object has a `keys` attr but is not a Mapping or any of + # the other types indicated in the method signature. We do some stuff with + # it as though it partially implements the Mapping interface, but we're not + # doing that stuff safely AT ALL. + for key in other.keys(): + self.add(key, other[key]) + + for key, value in kwargs.items(): + self.add(key, value) + + @typing.overload + def getlist(self, key: str) -> list[str]: ... + + @typing.overload + def getlist(self, key: str, default: _DT) -> list[str] | _DT: ... + + def getlist( + self, key: str, default: _Sentinel | _DT = _Sentinel.not_passed + ) -> list[str] | _DT: + """Returns a list of all the values for the named field. Returns an + empty list if the key doesn't exist.""" + try: + vals = self._container[key.lower()] + except KeyError: + if default is _Sentinel.not_passed: + # _DT is unbound; empty list is instance of List[str] + return [] + # _DT is bound; default is instance of _DT + return default + else: + # _DT may or may not be bound; vals[1:] is instance of List[str], which + # meets our external interface requirement of `Union[List[str], _DT]`. + return vals[1:] + + def _prepare_for_method_change(self) -> Self: + """ + Remove content-specific header fields before changing the request + method to GET or HEAD according to RFC 9110, Section 15.4. + """ + content_specific_headers = [ + "Content-Encoding", + "Content-Language", + "Content-Location", + "Content-Type", + "Content-Length", + "Digest", + "Last-Modified", + ] + for header in content_specific_headers: + self.discard(header) + return self + + # Backwards compatibility for httplib + getheaders = getlist + getallmatchingheaders = getlist + iget = getlist + + # Backwards compatibility for http.cookiejar + get_all = getlist + + def __repr__(self) -> str: + return f"{type(self).__name__}({dict(self.itermerged())})" + + def _copy_from(self, other: HTTPHeaderDict) -> None: + for key in other: + val = other.getlist(key) + self._container[key.lower()] = [key, *val] + + def copy(self) -> Self: + clone = type(self)() + clone._copy_from(self) + return clone + + def iteritems(self) -> typing.Iterator[tuple[str, str]]: + """Iterate over all header lines, including duplicate ones.""" + for key in self: + vals = self._container[key.lower()] + for val in vals[1:]: + yield vals[0], val + + def itermerged(self) -> typing.Iterator[tuple[str, str]]: + """Iterate over all headers, merging duplicate ones together.""" + for key in self: + val = self._container[key.lower()] + yield val[0], ", ".join(val[1:]) + + def items(self) -> HTTPHeaderDictItemView: # type: ignore[override] + return HTTPHeaderDictItemView(self) + + def _has_value_for_header(self, header_name: str, potential_value: str) -> bool: + if header_name in self: + return potential_value in self._container[header_name.lower()][1:] + return False + + def __ior__(self, other: object) -> HTTPHeaderDict: + # Supports extending a header dict in-place using operator |= + # combining items with add instead of __setitem__ + maybe_constructable = ensure_can_construct_http_header_dict(other) + if maybe_constructable is None: + return NotImplemented + self.extend(maybe_constructable) + return self + + def __or__(self, other: object) -> Self: + # Supports merging header dicts using operator | + # combining items with add instead of __setitem__ + maybe_constructable = ensure_can_construct_http_header_dict(other) + if maybe_constructable is None: + return NotImplemented + result = self.copy() + result.extend(maybe_constructable) + return result + + def __ror__(self, other: object) -> Self: + # Supports merging header dicts using operator | when other is on left side + # combining items with add instead of __setitem__ + maybe_constructable = ensure_can_construct_http_header_dict(other) + if maybe_constructable is None: + return NotImplemented + result = type(self)(maybe_constructable) + result.extend(self) + return result diff --git a/venv/Lib/site-packages/urllib3/_request_methods.py b/venv/Lib/site-packages/urllib3/_request_methods.py new file mode 100644 index 00000000..297c271b --- /dev/null +++ b/venv/Lib/site-packages/urllib3/_request_methods.py @@ -0,0 +1,278 @@ +from __future__ import annotations + +import json as _json +import typing +from urllib.parse import urlencode + +from ._base_connection import _TYPE_BODY +from ._collections import HTTPHeaderDict +from .filepost import _TYPE_FIELDS, encode_multipart_formdata +from .response import BaseHTTPResponse + +__all__ = ["RequestMethods"] + +_TYPE_ENCODE_URL_FIELDS = typing.Union[ + typing.Sequence[tuple[str, typing.Union[str, bytes]]], + typing.Mapping[str, typing.Union[str, bytes]], +] + + +class RequestMethods: + """ + Convenience mixin for classes who implement a :meth:`urlopen` method, such + as :class:`urllib3.HTTPConnectionPool` and + :class:`urllib3.PoolManager`. + + Provides behavior for making common types of HTTP request methods and + decides which type of request field encoding to use. + + Specifically, + + :meth:`.request_encode_url` is for sending requests whose fields are + encoded in the URL (such as GET, HEAD, DELETE). + + :meth:`.request_encode_body` is for sending requests whose fields are + encoded in the *body* of the request using multipart or www-form-urlencoded + (such as for POST, PUT, PATCH). + + :meth:`.request` is for making any kind of request, it will look up the + appropriate encoding format and use one of the above two methods to make + the request. + + Initializer parameters: + + :param headers: + Headers to include with all requests, unless other headers are given + explicitly. + """ + + _encode_url_methods = {"DELETE", "GET", "HEAD", "OPTIONS"} + + def __init__(self, headers: typing.Mapping[str, str] | None = None) -> None: + self.headers = headers or {} + + def urlopen( + self, + method: str, + url: str, + body: _TYPE_BODY | None = None, + headers: typing.Mapping[str, str] | None = None, + encode_multipart: bool = True, + multipart_boundary: str | None = None, + **kw: typing.Any, + ) -> BaseHTTPResponse: # Abstract + raise NotImplementedError( + "Classes extending RequestMethods must implement " + "their own ``urlopen`` method." + ) + + def request( + self, + method: str, + url: str, + body: _TYPE_BODY | None = None, + fields: _TYPE_FIELDS | None = None, + headers: typing.Mapping[str, str] | None = None, + json: typing.Any | None = None, + **urlopen_kw: typing.Any, + ) -> BaseHTTPResponse: + """ + Make a request using :meth:`urlopen` with the appropriate encoding of + ``fields`` based on the ``method`` used. + + This is a convenience method that requires the least amount of manual + effort. It can be used in most situations, while still having the + option to drop down to more specific methods when necessary, such as + :meth:`request_encode_url`, :meth:`request_encode_body`, + or even the lowest level :meth:`urlopen`. + + :param method: + HTTP request method (such as GET, POST, PUT, etc.) + + :param url: + The URL to perform the request on. + + :param body: + Data to send in the request body, either :class:`str`, :class:`bytes`, + an iterable of :class:`str`/:class:`bytes`, or a file-like object. + + :param fields: + Data to encode and send in the URL or request body, depending on ``method``. + + :param headers: + Dictionary of custom headers to send, such as User-Agent, + If-None-Match, etc. If None, pool headers are used. If provided, + these headers completely replace any pool-specific headers. + + :param json: + Data to encode and send as JSON with UTF-encoded in the request body. + The ``"Content-Type"`` header will be set to ``"application/json"`` + unless specified otherwise. + """ + method = method.upper() + + if json is not None and body is not None: + raise TypeError( + "request got values for both 'body' and 'json' parameters which are mutually exclusive" + ) + + if json is not None: + if headers is None: + headers = self.headers + + if not ("content-type" in map(str.lower, headers.keys())): + headers = HTTPHeaderDict(headers) + headers["Content-Type"] = "application/json" + + body = _json.dumps(json, separators=(",", ":"), ensure_ascii=False).encode( + "utf-8" + ) + + if body is not None: + urlopen_kw["body"] = body + + if method in self._encode_url_methods: + return self.request_encode_url( + method, + url, + fields=fields, # type: ignore[arg-type] + headers=headers, + **urlopen_kw, + ) + else: + return self.request_encode_body( + method, url, fields=fields, headers=headers, **urlopen_kw + ) + + def request_encode_url( + self, + method: str, + url: str, + fields: _TYPE_ENCODE_URL_FIELDS | None = None, + headers: typing.Mapping[str, str] | None = None, + **urlopen_kw: str, + ) -> BaseHTTPResponse: + """ + Make a request using :meth:`urlopen` with the ``fields`` encoded in + the url. This is useful for request methods like GET, HEAD, DELETE, etc. + + :param method: + HTTP request method (such as GET, POST, PUT, etc.) + + :param url: + The URL to perform the request on. + + :param fields: + Data to encode and send in the URL. + + :param headers: + Dictionary of custom headers to send, such as User-Agent, + If-None-Match, etc. If None, pool headers are used. If provided, + these headers completely replace any pool-specific headers. + """ + if headers is None: + headers = self.headers + + extra_kw: dict[str, typing.Any] = {"headers": headers} + extra_kw.update(urlopen_kw) + + if fields: + url += "?" + urlencode(fields) + + return self.urlopen(method, url, **extra_kw) + + def request_encode_body( + self, + method: str, + url: str, + fields: _TYPE_FIELDS | None = None, + headers: typing.Mapping[str, str] | None = None, + encode_multipart: bool = True, + multipart_boundary: str | None = None, + **urlopen_kw: str, + ) -> BaseHTTPResponse: + """ + Make a request using :meth:`urlopen` with the ``fields`` encoded in + the body. This is useful for request methods like POST, PUT, PATCH, etc. + + When ``encode_multipart=True`` (default), then + :func:`urllib3.encode_multipart_formdata` is used to encode + the payload with the appropriate content type. Otherwise + :func:`urllib.parse.urlencode` is used with the + 'application/x-www-form-urlencoded' content type. + + Multipart encoding must be used when posting files, and it's reasonably + safe to use it in other times too. However, it may break request + signing, such as with OAuth. + + Supports an optional ``fields`` parameter of key/value strings AND + key/filetuple. A filetuple is a (filename, data, MIME type) tuple where + the MIME type is optional. For example:: + + fields = { + 'foo': 'bar', + 'fakefile': ('foofile.txt', 'contents of foofile'), + 'realfile': ('barfile.txt', open('realfile').read()), + 'typedfile': ('bazfile.bin', open('bazfile').read(), + 'image/jpeg'), + 'nonamefile': 'contents of nonamefile field', + } + + When uploading a file, providing a filename (the first parameter of the + tuple) is optional but recommended to best mimic behavior of browsers. + + Note that if ``headers`` are supplied, the 'Content-Type' header will + be overwritten because it depends on the dynamic random boundary string + which is used to compose the body of the request. The random boundary + string can be explicitly set with the ``multipart_boundary`` parameter. + + :param method: + HTTP request method (such as GET, POST, PUT, etc.) + + :param url: + The URL to perform the request on. + + :param fields: + Data to encode and send in the request body. + + :param headers: + Dictionary of custom headers to send, such as User-Agent, + If-None-Match, etc. If None, pool headers are used. If provided, + these headers completely replace any pool-specific headers. + + :param encode_multipart: + If True, encode the ``fields`` using the multipart/form-data MIME + format. + + :param multipart_boundary: + If not specified, then a random boundary will be generated using + :func:`urllib3.filepost.choose_boundary`. + """ + if headers is None: + headers = self.headers + + extra_kw: dict[str, typing.Any] = {"headers": HTTPHeaderDict(headers)} + body: bytes | str + + if fields: + if "body" in urlopen_kw: + raise TypeError( + "request got values for both 'fields' and 'body', can only specify one." + ) + + if encode_multipart: + body, content_type = encode_multipart_formdata( + fields, boundary=multipart_boundary + ) + else: + body, content_type = ( + urlencode(fields), # type: ignore[arg-type] + "application/x-www-form-urlencoded", + ) + + extra_kw["body"] = body + extra_kw["headers"].setdefault("Content-Type", content_type) + + extra_kw.update(urlopen_kw) + + return self.urlopen(method, url, **extra_kw) diff --git a/venv/Lib/site-packages/urllib3/_version.py b/venv/Lib/site-packages/urllib3/_version.py new file mode 100644 index 00000000..49707ce5 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/_version.py @@ -0,0 +1,21 @@ +# file generated by setuptools-scm +# don't change, don't track in version control + +__all__ = ["__version__", "__version_tuple__", "version", "version_tuple"] + +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import Tuple + from typing import Union + + VERSION_TUPLE = Tuple[Union[int, str], ...] +else: + VERSION_TUPLE = object + +version: str +__version__: str +__version_tuple__: VERSION_TUPLE +version_tuple: VERSION_TUPLE + +__version__ = version = '2.5.0' +__version_tuple__ = version_tuple = (2, 5, 0) diff --git a/venv/Lib/site-packages/urllib3/connection.py b/venv/Lib/site-packages/urllib3/connection.py new file mode 100644 index 00000000..8082387d --- /dev/null +++ b/venv/Lib/site-packages/urllib3/connection.py @@ -0,0 +1,1093 @@ +from __future__ import annotations + +import datetime +import http.client +import logging +import os +import re +import socket +import sys +import threading +import typing +import warnings +from http.client import HTTPConnection as _HTTPConnection +from http.client import HTTPException as HTTPException # noqa: F401 +from http.client import ResponseNotReady +from socket import timeout as SocketTimeout + +if typing.TYPE_CHECKING: + from .response import HTTPResponse + from .util.ssl_ import _TYPE_PEER_CERT_RET_DICT + from .util.ssltransport import SSLTransport + +from ._collections import HTTPHeaderDict +from .http2 import probe as http2_probe +from .util.response import assert_header_parsing +from .util.timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT, Timeout +from .util.util import to_str +from .util.wait import wait_for_read + +try: # Compiled with SSL? + import ssl + + BaseSSLError = ssl.SSLError +except (ImportError, AttributeError): + ssl = None # type: ignore[assignment] + + class BaseSSLError(BaseException): # type: ignore[no-redef] + pass + + +from ._base_connection import _TYPE_BODY +from ._base_connection import ProxyConfig as ProxyConfig +from ._base_connection import _ResponseOptions as _ResponseOptions +from ._version import __version__ +from .exceptions import ( + ConnectTimeoutError, + HeaderParsingError, + NameResolutionError, + NewConnectionError, + ProxyError, + SystemTimeWarning, +) +from .util import SKIP_HEADER, SKIPPABLE_HEADERS, connection, ssl_ +from .util.request import body_to_chunks +from .util.ssl_ import assert_fingerprint as _assert_fingerprint +from .util.ssl_ import ( + create_urllib3_context, + is_ipaddress, + resolve_cert_reqs, + resolve_ssl_version, + ssl_wrap_socket, +) +from .util.ssl_match_hostname import CertificateError, match_hostname +from .util.url import Url + +# Not a no-op, we're adding this to the namespace so it can be imported. +ConnectionError = ConnectionError +BrokenPipeError = BrokenPipeError + + +log = logging.getLogger(__name__) + +port_by_scheme = {"http": 80, "https": 443} + +# When it comes time to update this value as a part of regular maintenance +# (ie test_recent_date is failing) update it to ~6 months before the current date. +RECENT_DATE = datetime.date(2025, 1, 1) + +_CONTAINS_CONTROL_CHAR_RE = re.compile(r"[^-!#$%&'*+.^_`|~0-9a-zA-Z]") + + +class HTTPConnection(_HTTPConnection): + """ + Based on :class:`http.client.HTTPConnection` but provides an extra constructor + backwards-compatibility layer between older and newer Pythons. + + Additional keyword parameters are used to configure attributes of the connection. + Accepted parameters include: + + - ``source_address``: Set the source address for the current connection. + - ``socket_options``: Set specific options on the underlying socket. If not specified, then + defaults are loaded from ``HTTPConnection.default_socket_options`` which includes disabling + Nagle's algorithm (sets TCP_NODELAY to 1) unless the connection is behind a proxy. + + For example, if you wish to enable TCP Keep Alive in addition to the defaults, + you might pass: + + .. code-block:: python + + HTTPConnection.default_socket_options + [ + (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1), + ] + + Or you may want to disable the defaults by passing an empty list (e.g., ``[]``). + """ + + default_port: typing.ClassVar[int] = port_by_scheme["http"] # type: ignore[misc] + + #: Disable Nagle's algorithm by default. + #: ``[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]`` + default_socket_options: typing.ClassVar[connection._TYPE_SOCKET_OPTIONS] = [ + (socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + ] + + #: Whether this connection verifies the host's certificate. + is_verified: bool = False + + #: Whether this proxy connection verified the proxy host's certificate. + # If no proxy is currently connected to the value will be ``None``. + proxy_is_verified: bool | None = None + + blocksize: int + source_address: tuple[str, int] | None + socket_options: connection._TYPE_SOCKET_OPTIONS | None + + _has_connected_to_proxy: bool + _response_options: _ResponseOptions | None + _tunnel_host: str | None + _tunnel_port: int | None + _tunnel_scheme: str | None + + def __init__( + self, + host: str, + port: int | None = None, + *, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + blocksize: int = 16384, + socket_options: None | ( + connection._TYPE_SOCKET_OPTIONS + ) = default_socket_options, + proxy: Url | None = None, + proxy_config: ProxyConfig | None = None, + ) -> None: + super().__init__( + host=host, + port=port, + timeout=Timeout.resolve_default_timeout(timeout), + source_address=source_address, + blocksize=blocksize, + ) + self.socket_options = socket_options + self.proxy = proxy + self.proxy_config = proxy_config + + self._has_connected_to_proxy = False + self._response_options = None + self._tunnel_host: str | None = None + self._tunnel_port: int | None = None + self._tunnel_scheme: str | None = None + + @property + def host(self) -> str: + """ + Getter method to remove any trailing dots that indicate the hostname is an FQDN. + + In general, SSL certificates don't include the trailing dot indicating a + fully-qualified domain name, and thus, they don't validate properly when + checked against a domain name that includes the dot. In addition, some + servers may not expect to receive the trailing dot when provided. + + However, the hostname with trailing dot is critical to DNS resolution; doing a + lookup with the trailing dot will properly only resolve the appropriate FQDN, + whereas a lookup without a trailing dot will search the system's search domain + list. Thus, it's important to keep the original host around for use only in + those cases where it's appropriate (i.e., when doing DNS lookup to establish the + actual TCP connection across which we're going to send HTTP requests). + """ + return self._dns_host.rstrip(".") + + @host.setter + def host(self, value: str) -> None: + """ + Setter for the `host` property. + + We assume that only urllib3 uses the _dns_host attribute; httplib itself + only uses `host`, and it seems reasonable that other libraries follow suit. + """ + self._dns_host = value + + def _new_conn(self) -> socket.socket: + """Establish a socket connection and set nodelay settings on it. + + :return: New socket connection. + """ + try: + sock = connection.create_connection( + (self._dns_host, self.port), + self.timeout, + source_address=self.source_address, + socket_options=self.socket_options, + ) + except socket.gaierror as e: + raise NameResolutionError(self.host, self, e) from e + except SocketTimeout as e: + raise ConnectTimeoutError( + self, + f"Connection to {self.host} timed out. (connect timeout={self.timeout})", + ) from e + + except OSError as e: + raise NewConnectionError( + self, f"Failed to establish a new connection: {e}" + ) from e + + sys.audit("http.client.connect", self, self.host, self.port) + + return sock + + def set_tunnel( + self, + host: str, + port: int | None = None, + headers: typing.Mapping[str, str] | None = None, + scheme: str = "http", + ) -> None: + if scheme not in ("http", "https"): + raise ValueError( + f"Invalid proxy scheme for tunneling: {scheme!r}, must be either 'http' or 'https'" + ) + super().set_tunnel(host, port=port, headers=headers) + self._tunnel_scheme = scheme + + if sys.version_info < (3, 11, 9) or ((3, 12) <= sys.version_info < (3, 12, 3)): + # Taken from python/cpython#100986 which was backported in 3.11.9 and 3.12.3. + # When using connection_from_host, host will come without brackets. + def _wrap_ipv6(self, ip: bytes) -> bytes: + if b":" in ip and ip[0] != b"["[0]: + return b"[" + ip + b"]" + return ip + + if sys.version_info < (3, 11, 9): + # `_tunnel` copied from 3.11.13 backporting + # https://github.com/python/cpython/commit/0d4026432591d43185568dd31cef6a034c4b9261 + # and https://github.com/python/cpython/commit/6fbc61070fda2ffb8889e77e3b24bca4249ab4d1 + def _tunnel(self) -> None: + _MAXLINE = http.client._MAXLINE # type: ignore[attr-defined] + connect = b"CONNECT %s:%d HTTP/1.0\r\n" % ( # type: ignore[str-format] + self._wrap_ipv6(self._tunnel_host.encode("ascii")), # type: ignore[union-attr] + self._tunnel_port, + ) + headers = [connect] + for header, value in self._tunnel_headers.items(): # type: ignore[attr-defined] + headers.append(f"{header}: {value}\r\n".encode("latin-1")) + headers.append(b"\r\n") + # Making a single send() call instead of one per line encourages + # the host OS to use a more optimal packet size instead of + # potentially emitting a series of small packets. + self.send(b"".join(headers)) + del headers + + response = self.response_class(self.sock, method=self._method) # type: ignore[attr-defined] + try: + (version, code, message) = response._read_status() # type: ignore[attr-defined] + + if code != http.HTTPStatus.OK: + self.close() + raise OSError( + f"Tunnel connection failed: {code} {message.strip()}" + ) + while True: + line = response.fp.readline(_MAXLINE + 1) + if len(line) > _MAXLINE: + raise http.client.LineTooLong("header line") + if not line: + # for sites which EOF without sending a trailer + break + if line in (b"\r\n", b"\n", b""): + break + + if self.debuglevel > 0: + print("header:", line.decode()) + finally: + response.close() + + elif (3, 12) <= sys.version_info < (3, 12, 3): + # `_tunnel` copied from 3.12.11 backporting + # https://github.com/python/cpython/commit/23aef575c7629abcd4aaf028ebd226fb41a4b3c8 + def _tunnel(self) -> None: # noqa: F811 + connect = b"CONNECT %s:%d HTTP/1.1\r\n" % ( # type: ignore[str-format] + self._wrap_ipv6(self._tunnel_host.encode("idna")), # type: ignore[union-attr] + self._tunnel_port, + ) + headers = [connect] + for header, value in self._tunnel_headers.items(): # type: ignore[attr-defined] + headers.append(f"{header}: {value}\r\n".encode("latin-1")) + headers.append(b"\r\n") + # Making a single send() call instead of one per line encourages + # the host OS to use a more optimal packet size instead of + # potentially emitting a series of small packets. + self.send(b"".join(headers)) + del headers + + response = self.response_class(self.sock, method=self._method) # type: ignore[attr-defined] + try: + (version, code, message) = response._read_status() # type: ignore[attr-defined] + + self._raw_proxy_headers = http.client._read_headers(response.fp) # type: ignore[attr-defined] + + if self.debuglevel > 0: + for header in self._raw_proxy_headers: + print("header:", header.decode()) + + if code != http.HTTPStatus.OK: + self.close() + raise OSError( + f"Tunnel connection failed: {code} {message.strip()}" + ) + + finally: + response.close() + + def connect(self) -> None: + self.sock = self._new_conn() + if self._tunnel_host: + # If we're tunneling it means we're connected to our proxy. + self._has_connected_to_proxy = True + + # TODO: Fix tunnel so it doesn't depend on self.sock state. + self._tunnel() + + # If there's a proxy to be connected to we are fully connected. + # This is set twice (once above and here) due to forwarding proxies + # not using tunnelling. + self._has_connected_to_proxy = bool(self.proxy) + + if self._has_connected_to_proxy: + self.proxy_is_verified = False + + @property + def is_closed(self) -> bool: + return self.sock is None + + @property + def is_connected(self) -> bool: + if self.sock is None: + return False + return not wait_for_read(self.sock, timeout=0.0) + + @property + def has_connected_to_proxy(self) -> bool: + return self._has_connected_to_proxy + + @property + def proxy_is_forwarding(self) -> bool: + """ + Return True if a forwarding proxy is configured, else return False + """ + return bool(self.proxy) and self._tunnel_host is None + + @property + def proxy_is_tunneling(self) -> bool: + """ + Return True if a tunneling proxy is configured, else return False + """ + return self._tunnel_host is not None + + def close(self) -> None: + try: + super().close() + finally: + # Reset all stateful properties so connection + # can be re-used without leaking prior configs. + self.sock = None + self.is_verified = False + self.proxy_is_verified = None + self._has_connected_to_proxy = False + self._response_options = None + self._tunnel_host = None + self._tunnel_port = None + self._tunnel_scheme = None + + def putrequest( + self, + method: str, + url: str, + skip_host: bool = False, + skip_accept_encoding: bool = False, + ) -> None: + """""" + # Empty docstring because the indentation of CPython's implementation + # is broken but we don't want this method in our documentation. + match = _CONTAINS_CONTROL_CHAR_RE.search(method) + if match: + raise ValueError( + f"Method cannot contain non-token characters {method!r} (found at least {match.group()!r})" + ) + + return super().putrequest( + method, url, skip_host=skip_host, skip_accept_encoding=skip_accept_encoding + ) + + def putheader(self, header: str, *values: str) -> None: # type: ignore[override] + """""" + if not any(isinstance(v, str) and v == SKIP_HEADER for v in values): + super().putheader(header, *values) + elif to_str(header.lower()) not in SKIPPABLE_HEADERS: + skippable_headers = "', '".join( + [str.title(header) for header in sorted(SKIPPABLE_HEADERS)] + ) + raise ValueError( + f"urllib3.util.SKIP_HEADER only supports '{skippable_headers}'" + ) + + # `request` method's signature intentionally violates LSP. + # urllib3's API is different from `http.client.HTTPConnection` and the subclassing is only incidental. + def request( # type: ignore[override] + self, + method: str, + url: str, + body: _TYPE_BODY | None = None, + headers: typing.Mapping[str, str] | None = None, + *, + chunked: bool = False, + preload_content: bool = True, + decode_content: bool = True, + enforce_content_length: bool = True, + ) -> None: + # Update the inner socket's timeout value to send the request. + # This only triggers if the connection is re-used. + if self.sock is not None: + self.sock.settimeout(self.timeout) + + # Store these values to be fed into the HTTPResponse + # object later. TODO: Remove this in favor of a real + # HTTP lifecycle mechanism. + + # We have to store these before we call .request() + # because sometimes we can still salvage a response + # off the wire even if we aren't able to completely + # send the request body. + self._response_options = _ResponseOptions( + request_method=method, + request_url=url, + preload_content=preload_content, + decode_content=decode_content, + enforce_content_length=enforce_content_length, + ) + + if headers is None: + headers = {} + header_keys = frozenset(to_str(k.lower()) for k in headers) + skip_accept_encoding = "accept-encoding" in header_keys + skip_host = "host" in header_keys + self.putrequest( + method, url, skip_accept_encoding=skip_accept_encoding, skip_host=skip_host + ) + + # Transform the body into an iterable of sendall()-able chunks + # and detect if an explicit Content-Length is doable. + chunks_and_cl = body_to_chunks(body, method=method, blocksize=self.blocksize) + chunks = chunks_and_cl.chunks + content_length = chunks_and_cl.content_length + + # When chunked is explicit set to 'True' we respect that. + if chunked: + if "transfer-encoding" not in header_keys: + self.putheader("Transfer-Encoding", "chunked") + else: + # Detect whether a framing mechanism is already in use. If so + # we respect that value, otherwise we pick chunked vs content-length + # depending on the type of 'body'. + if "content-length" in header_keys: + chunked = False + elif "transfer-encoding" in header_keys: + chunked = True + + # Otherwise we go off the recommendation of 'body_to_chunks()'. + else: + chunked = False + if content_length is None: + if chunks is not None: + chunked = True + self.putheader("Transfer-Encoding", "chunked") + else: + self.putheader("Content-Length", str(content_length)) + + # Now that framing headers are out of the way we send all the other headers. + if "user-agent" not in header_keys: + self.putheader("User-Agent", _get_default_user_agent()) + for header, value in headers.items(): + self.putheader(header, value) + self.endheaders() + + # If we're given a body we start sending that in chunks. + if chunks is not None: + for chunk in chunks: + # Sending empty chunks isn't allowed for TE: chunked + # as it indicates the end of the body. + if not chunk: + continue + if isinstance(chunk, str): + chunk = chunk.encode("utf-8") + if chunked: + self.send(b"%x\r\n%b\r\n" % (len(chunk), chunk)) + else: + self.send(chunk) + + # Regardless of whether we have a body or not, if we're in + # chunked mode we want to send an explicit empty chunk. + if chunked: + self.send(b"0\r\n\r\n") + + def request_chunked( + self, + method: str, + url: str, + body: _TYPE_BODY | None = None, + headers: typing.Mapping[str, str] | None = None, + ) -> None: + """ + Alternative to the common request method, which sends the + body with chunked encoding and not as one block + """ + warnings.warn( + "HTTPConnection.request_chunked() is deprecated and will be removed " + "in urllib3 v2.1.0. Instead use HTTPConnection.request(..., chunked=True).", + category=DeprecationWarning, + stacklevel=2, + ) + self.request(method, url, body=body, headers=headers, chunked=True) + + def getresponse( # type: ignore[override] + self, + ) -> HTTPResponse: + """ + Get the response from the server. + + If the HTTPConnection is in the correct state, returns an instance of HTTPResponse or of whatever object is returned by the response_class variable. + + If a request has not been sent or if a previous response has not be handled, ResponseNotReady is raised. If the HTTP response indicates that the connection should be closed, then it will be closed before the response is returned. When the connection is closed, the underlying socket is closed. + """ + # Raise the same error as http.client.HTTPConnection + if self._response_options is None: + raise ResponseNotReady() + + # Reset this attribute for being used again. + resp_options = self._response_options + self._response_options = None + + # Since the connection's timeout value may have been updated + # we need to set the timeout on the socket. + self.sock.settimeout(self.timeout) + + # This is needed here to avoid circular import errors + from .response import HTTPResponse + + # Save a reference to the shutdown function before ownership is passed + # to httplib_response + # TODO should we implement it everywhere? + _shutdown = getattr(self.sock, "shutdown", None) + + # Get the response from http.client.HTTPConnection + httplib_response = super().getresponse() + + try: + assert_header_parsing(httplib_response.msg) + except (HeaderParsingError, TypeError) as hpe: + log.warning( + "Failed to parse headers (url=%s): %s", + _url_from_connection(self, resp_options.request_url), + hpe, + exc_info=True, + ) + + headers = HTTPHeaderDict(httplib_response.msg.items()) + + response = HTTPResponse( + body=httplib_response, + headers=headers, + status=httplib_response.status, + version=httplib_response.version, + version_string=getattr(self, "_http_vsn_str", "HTTP/?"), + reason=httplib_response.reason, + preload_content=resp_options.preload_content, + decode_content=resp_options.decode_content, + original_response=httplib_response, + enforce_content_length=resp_options.enforce_content_length, + request_method=resp_options.request_method, + request_url=resp_options.request_url, + sock_shutdown=_shutdown, + ) + return response + + +class HTTPSConnection(HTTPConnection): + """ + Many of the parameters to this constructor are passed to the underlying SSL + socket by means of :py:func:`urllib3.util.ssl_wrap_socket`. + """ + + default_port = port_by_scheme["https"] # type: ignore[misc] + + cert_reqs: int | str | None = None + ca_certs: str | None = None + ca_cert_dir: str | None = None + ca_cert_data: None | str | bytes = None + ssl_version: int | str | None = None + ssl_minimum_version: int | None = None + ssl_maximum_version: int | None = None + assert_fingerprint: str | None = None + _connect_callback: typing.Callable[..., None] | None = None + + def __init__( + self, + host: str, + port: int | None = None, + *, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + blocksize: int = 16384, + socket_options: None | ( + connection._TYPE_SOCKET_OPTIONS + ) = HTTPConnection.default_socket_options, + proxy: Url | None = None, + proxy_config: ProxyConfig | None = None, + cert_reqs: int | str | None = None, + assert_hostname: None | str | typing.Literal[False] = None, + assert_fingerprint: str | None = None, + server_hostname: str | None = None, + ssl_context: ssl.SSLContext | None = None, + ca_certs: str | None = None, + ca_cert_dir: str | None = None, + ca_cert_data: None | str | bytes = None, + ssl_minimum_version: int | None = None, + ssl_maximum_version: int | None = None, + ssl_version: int | str | None = None, # Deprecated + cert_file: str | None = None, + key_file: str | None = None, + key_password: str | None = None, + ) -> None: + super().__init__( + host, + port=port, + timeout=timeout, + source_address=source_address, + blocksize=blocksize, + socket_options=socket_options, + proxy=proxy, + proxy_config=proxy_config, + ) + + self.key_file = key_file + self.cert_file = cert_file + self.key_password = key_password + self.ssl_context = ssl_context + self.server_hostname = server_hostname + self.assert_hostname = assert_hostname + self.assert_fingerprint = assert_fingerprint + self.ssl_version = ssl_version + self.ssl_minimum_version = ssl_minimum_version + self.ssl_maximum_version = ssl_maximum_version + self.ca_certs = ca_certs and os.path.expanduser(ca_certs) + self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir) + self.ca_cert_data = ca_cert_data + + # cert_reqs depends on ssl_context so calculate last. + if cert_reqs is None: + if self.ssl_context is not None: + cert_reqs = self.ssl_context.verify_mode + else: + cert_reqs = resolve_cert_reqs(None) + self.cert_reqs = cert_reqs + self._connect_callback = None + + def set_cert( + self, + key_file: str | None = None, + cert_file: str | None = None, + cert_reqs: int | str | None = None, + key_password: str | None = None, + ca_certs: str | None = None, + assert_hostname: None | str | typing.Literal[False] = None, + assert_fingerprint: str | None = None, + ca_cert_dir: str | None = None, + ca_cert_data: None | str | bytes = None, + ) -> None: + """ + This method should only be called once, before the connection is used. + """ + warnings.warn( + "HTTPSConnection.set_cert() is deprecated and will be removed " + "in urllib3 v2.1.0. Instead provide the parameters to the " + "HTTPSConnection constructor.", + category=DeprecationWarning, + stacklevel=2, + ) + + # If cert_reqs is not provided we'll assume CERT_REQUIRED unless we also + # have an SSLContext object in which case we'll use its verify_mode. + if cert_reqs is None: + if self.ssl_context is not None: + cert_reqs = self.ssl_context.verify_mode + else: + cert_reqs = resolve_cert_reqs(None) + + self.key_file = key_file + self.cert_file = cert_file + self.cert_reqs = cert_reqs + self.key_password = key_password + self.assert_hostname = assert_hostname + self.assert_fingerprint = assert_fingerprint + self.ca_certs = ca_certs and os.path.expanduser(ca_certs) + self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir) + self.ca_cert_data = ca_cert_data + + def connect(self) -> None: + # Today we don't need to be doing this step before the /actual/ socket + # connection, however in the future we'll need to decide whether to + # create a new socket or re-use an existing "shared" socket as a part + # of the HTTP/2 handshake dance. + if self._tunnel_host is not None and self._tunnel_port is not None: + probe_http2_host = self._tunnel_host + probe_http2_port = self._tunnel_port + else: + probe_http2_host = self.host + probe_http2_port = self.port + + # Check if the target origin supports HTTP/2. + # If the value comes back as 'None' it means that the current thread + # is probing for HTTP/2 support. Otherwise, we're waiting for another + # probe to complete, or we get a value right away. + target_supports_http2: bool | None + if "h2" in ssl_.ALPN_PROTOCOLS: + target_supports_http2 = http2_probe.acquire_and_get( + host=probe_http2_host, port=probe_http2_port + ) + else: + # If HTTP/2 isn't going to be offered it doesn't matter if + # the target supports HTTP/2. Don't want to make a probe. + target_supports_http2 = False + + if self._connect_callback is not None: + self._connect_callback( + "before connect", + thread_id=threading.get_ident(), + target_supports_http2=target_supports_http2, + ) + + try: + sock: socket.socket | ssl.SSLSocket + self.sock = sock = self._new_conn() + server_hostname: str = self.host + tls_in_tls = False + + # Do we need to establish a tunnel? + if self.proxy_is_tunneling: + # We're tunneling to an HTTPS origin so need to do TLS-in-TLS. + if self._tunnel_scheme == "https": + # _connect_tls_proxy will verify and assign proxy_is_verified + self.sock = sock = self._connect_tls_proxy(self.host, sock) + tls_in_tls = True + elif self._tunnel_scheme == "http": + self.proxy_is_verified = False + + # If we're tunneling it means we're connected to our proxy. + self._has_connected_to_proxy = True + + self._tunnel() + # Override the host with the one we're requesting data from. + server_hostname = typing.cast(str, self._tunnel_host) + + if self.server_hostname is not None: + server_hostname = self.server_hostname + + is_time_off = datetime.date.today() < RECENT_DATE + if is_time_off: + warnings.warn( + ( + f"System time is way off (before {RECENT_DATE}). This will probably " + "lead to SSL verification errors" + ), + SystemTimeWarning, + ) + + # Remove trailing '.' from fqdn hostnames to allow certificate validation + server_hostname_rm_dot = server_hostname.rstrip(".") + + sock_and_verified = _ssl_wrap_socket_and_match_hostname( + sock=sock, + cert_reqs=self.cert_reqs, + ssl_version=self.ssl_version, + ssl_minimum_version=self.ssl_minimum_version, + ssl_maximum_version=self.ssl_maximum_version, + ca_certs=self.ca_certs, + ca_cert_dir=self.ca_cert_dir, + ca_cert_data=self.ca_cert_data, + cert_file=self.cert_file, + key_file=self.key_file, + key_password=self.key_password, + server_hostname=server_hostname_rm_dot, + ssl_context=self.ssl_context, + tls_in_tls=tls_in_tls, + assert_hostname=self.assert_hostname, + assert_fingerprint=self.assert_fingerprint, + ) + self.sock = sock_and_verified.socket + + # If an error occurs during connection/handshake we may need to release + # our lock so another connection can probe the origin. + except BaseException: + if self._connect_callback is not None: + self._connect_callback( + "after connect failure", + thread_id=threading.get_ident(), + target_supports_http2=target_supports_http2, + ) + + if target_supports_http2 is None: + http2_probe.set_and_release( + host=probe_http2_host, port=probe_http2_port, supports_http2=None + ) + raise + + # If this connection doesn't know if the origin supports HTTP/2 + # we report back to the HTTP/2 probe our result. + if target_supports_http2 is None: + supports_http2 = sock_and_verified.socket.selected_alpn_protocol() == "h2" + http2_probe.set_and_release( + host=probe_http2_host, + port=probe_http2_port, + supports_http2=supports_http2, + ) + + # Forwarding proxies can never have a verified target since + # the proxy is the one doing the verification. Should instead + # use a CONNECT tunnel in order to verify the target. + # See: https://github.com/urllib3/urllib3/issues/3267. + if self.proxy_is_forwarding: + self.is_verified = False + else: + self.is_verified = sock_and_verified.is_verified + + # If there's a proxy to be connected to we are fully connected. + # This is set twice (once above and here) due to forwarding proxies + # not using tunnelling. + self._has_connected_to_proxy = bool(self.proxy) + + # Set `self.proxy_is_verified` unless it's already set while + # establishing a tunnel. + if self._has_connected_to_proxy and self.proxy_is_verified is None: + self.proxy_is_verified = sock_and_verified.is_verified + + def _connect_tls_proxy(self, hostname: str, sock: socket.socket) -> ssl.SSLSocket: + """ + Establish a TLS connection to the proxy using the provided SSL context. + """ + # `_connect_tls_proxy` is called when self._tunnel_host is truthy. + proxy_config = typing.cast(ProxyConfig, self.proxy_config) + ssl_context = proxy_config.ssl_context + sock_and_verified = _ssl_wrap_socket_and_match_hostname( + sock, + cert_reqs=self.cert_reqs, + ssl_version=self.ssl_version, + ssl_minimum_version=self.ssl_minimum_version, + ssl_maximum_version=self.ssl_maximum_version, + ca_certs=self.ca_certs, + ca_cert_dir=self.ca_cert_dir, + ca_cert_data=self.ca_cert_data, + server_hostname=hostname, + ssl_context=ssl_context, + assert_hostname=proxy_config.assert_hostname, + assert_fingerprint=proxy_config.assert_fingerprint, + # Features that aren't implemented for proxies yet: + cert_file=None, + key_file=None, + key_password=None, + tls_in_tls=False, + ) + self.proxy_is_verified = sock_and_verified.is_verified + return sock_and_verified.socket # type: ignore[return-value] + + +class _WrappedAndVerifiedSocket(typing.NamedTuple): + """ + Wrapped socket and whether the connection is + verified after the TLS handshake + """ + + socket: ssl.SSLSocket | SSLTransport + is_verified: bool + + +def _ssl_wrap_socket_and_match_hostname( + sock: socket.socket, + *, + cert_reqs: None | str | int, + ssl_version: None | str | int, + ssl_minimum_version: int | None, + ssl_maximum_version: int | None, + cert_file: str | None, + key_file: str | None, + key_password: str | None, + ca_certs: str | None, + ca_cert_dir: str | None, + ca_cert_data: None | str | bytes, + assert_hostname: None | str | typing.Literal[False], + assert_fingerprint: str | None, + server_hostname: str | None, + ssl_context: ssl.SSLContext | None, + tls_in_tls: bool = False, +) -> _WrappedAndVerifiedSocket: + """Logic for constructing an SSLContext from all TLS parameters, passing + that down into ssl_wrap_socket, and then doing certificate verification + either via hostname or fingerprint. This function exists to guarantee + that both proxies and targets have the same behavior when connecting via TLS. + """ + default_ssl_context = False + if ssl_context is None: + default_ssl_context = True + context = create_urllib3_context( + ssl_version=resolve_ssl_version(ssl_version), + ssl_minimum_version=ssl_minimum_version, + ssl_maximum_version=ssl_maximum_version, + cert_reqs=resolve_cert_reqs(cert_reqs), + ) + else: + context = ssl_context + + context.verify_mode = resolve_cert_reqs(cert_reqs) + + # In some cases, we want to verify hostnames ourselves + if ( + # `ssl` can't verify fingerprints or alternate hostnames + assert_fingerprint + or assert_hostname + # assert_hostname can be set to False to disable hostname checking + or assert_hostname is False + # We still support OpenSSL 1.0.2, which prevents us from verifying + # hostnames easily: https://github.com/pyca/pyopenssl/pull/933 + or ssl_.IS_PYOPENSSL + or not ssl_.HAS_NEVER_CHECK_COMMON_NAME + ): + context.check_hostname = False + + # Try to load OS default certs if none are given. We need to do the hasattr() check + # for custom pyOpenSSL SSLContext objects because they don't support + # load_default_certs(). + if ( + not ca_certs + and not ca_cert_dir + and not ca_cert_data + and default_ssl_context + and hasattr(context, "load_default_certs") + ): + context.load_default_certs() + + # Ensure that IPv6 addresses are in the proper format and don't have a + # scope ID. Python's SSL module fails to recognize scoped IPv6 addresses + # and interprets them as DNS hostnames. + if server_hostname is not None: + normalized = server_hostname.strip("[]") + if "%" in normalized: + normalized = normalized[: normalized.rfind("%")] + if is_ipaddress(normalized): + server_hostname = normalized + + ssl_sock = ssl_wrap_socket( + sock=sock, + keyfile=key_file, + certfile=cert_file, + key_password=key_password, + ca_certs=ca_certs, + ca_cert_dir=ca_cert_dir, + ca_cert_data=ca_cert_data, + server_hostname=server_hostname, + ssl_context=context, + tls_in_tls=tls_in_tls, + ) + + try: + if assert_fingerprint: + _assert_fingerprint( + ssl_sock.getpeercert(binary_form=True), assert_fingerprint + ) + elif ( + context.verify_mode != ssl.CERT_NONE + and not context.check_hostname + and assert_hostname is not False + ): + cert: _TYPE_PEER_CERT_RET_DICT = ssl_sock.getpeercert() # type: ignore[assignment] + + # Need to signal to our match_hostname whether to use 'commonName' or not. + # If we're using our own constructed SSLContext we explicitly set 'False' + # because PyPy hard-codes 'True' from SSLContext.hostname_checks_common_name. + if default_ssl_context: + hostname_checks_common_name = False + else: + hostname_checks_common_name = ( + getattr(context, "hostname_checks_common_name", False) or False + ) + + _match_hostname( + cert, + assert_hostname or server_hostname, # type: ignore[arg-type] + hostname_checks_common_name, + ) + + return _WrappedAndVerifiedSocket( + socket=ssl_sock, + is_verified=context.verify_mode == ssl.CERT_REQUIRED + or bool(assert_fingerprint), + ) + except BaseException: + ssl_sock.close() + raise + + +def _match_hostname( + cert: _TYPE_PEER_CERT_RET_DICT | None, + asserted_hostname: str, + hostname_checks_common_name: bool = False, +) -> None: + # Our upstream implementation of ssl.match_hostname() + # only applies this normalization to IP addresses so it doesn't + # match DNS SANs so we do the same thing! + stripped_hostname = asserted_hostname.strip("[]") + if is_ipaddress(stripped_hostname): + asserted_hostname = stripped_hostname + + try: + match_hostname(cert, asserted_hostname, hostname_checks_common_name) + except CertificateError as e: + log.warning( + "Certificate did not match expected hostname: %s. Certificate: %s", + asserted_hostname, + cert, + ) + # Add cert to exception and reraise so client code can inspect + # the cert when catching the exception, if they want to + e._peer_cert = cert # type: ignore[attr-defined] + raise + + +def _wrap_proxy_error(err: Exception, proxy_scheme: str | None) -> ProxyError: + # Look for the phrase 'wrong version number', if found + # then we should warn the user that we're very sure that + # this proxy is HTTP-only and they have a configuration issue. + error_normalized = " ".join(re.split("[^a-z]", str(err).lower())) + is_likely_http_proxy = ( + "wrong version number" in error_normalized + or "unknown protocol" in error_normalized + or "record layer failure" in error_normalized + ) + http_proxy_warning = ( + ". Your proxy appears to only use HTTP and not HTTPS, " + "try changing your proxy URL to be HTTP. See: " + "https://urllib3.readthedocs.io/en/latest/advanced-usage.html" + "#https-proxy-error-http-proxy" + ) + new_err = ProxyError( + f"Unable to connect to proxy" + f"{http_proxy_warning if is_likely_http_proxy and proxy_scheme == 'https' else ''}", + err, + ) + new_err.__cause__ = err + return new_err + + +def _get_default_user_agent() -> str: + return f"python-urllib3/{__version__}" + + +class DummyConnection: + """Used to detect a failed ConnectionCls import.""" + + +if not ssl: + HTTPSConnection = DummyConnection # type: ignore[misc, assignment] # noqa: F811 + + +VerifiedHTTPSConnection = HTTPSConnection + + +def _url_from_connection( + conn: HTTPConnection | HTTPSConnection, path: str | None = None +) -> str: + """Returns the URL from a given connection. This is mainly used for testing and logging.""" + + scheme = "https" if isinstance(conn, HTTPSConnection) else "http" + + return Url(scheme=scheme, host=conn.host, port=conn.port, path=path).url diff --git a/venv/Lib/site-packages/urllib3/connectionpool.py b/venv/Lib/site-packages/urllib3/connectionpool.py new file mode 100644 index 00000000..3a0685b4 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/connectionpool.py @@ -0,0 +1,1178 @@ +from __future__ import annotations + +import errno +import logging +import queue +import sys +import typing +import warnings +import weakref +from socket import timeout as SocketTimeout +from types import TracebackType + +from ._base_connection import _TYPE_BODY +from ._collections import HTTPHeaderDict +from ._request_methods import RequestMethods +from .connection import ( + BaseSSLError, + BrokenPipeError, + DummyConnection, + HTTPConnection, + HTTPException, + HTTPSConnection, + ProxyConfig, + _wrap_proxy_error, +) +from .connection import port_by_scheme as port_by_scheme +from .exceptions import ( + ClosedPoolError, + EmptyPoolError, + FullPoolError, + HostChangedError, + InsecureRequestWarning, + LocationValueError, + MaxRetryError, + NewConnectionError, + ProtocolError, + ProxyError, + ReadTimeoutError, + SSLError, + TimeoutError, +) +from .response import BaseHTTPResponse +from .util.connection import is_connection_dropped +from .util.proxy import connection_requires_http_tunnel +from .util.request import _TYPE_BODY_POSITION, set_file_position +from .util.retry import Retry +from .util.ssl_match_hostname import CertificateError +from .util.timeout import _DEFAULT_TIMEOUT, _TYPE_DEFAULT, Timeout +from .util.url import Url, _encode_target +from .util.url import _normalize_host as normalize_host +from .util.url import parse_url +from .util.util import to_str + +if typing.TYPE_CHECKING: + import ssl + + from typing_extensions import Self + + from ._base_connection import BaseHTTPConnection, BaseHTTPSConnection + +log = logging.getLogger(__name__) + +_TYPE_TIMEOUT = typing.Union[Timeout, float, _TYPE_DEFAULT, None] + + +# Pool objects +class ConnectionPool: + """ + Base class for all connection pools, such as + :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`. + + .. note:: + ConnectionPool.urlopen() does not normalize or percent-encode target URIs + which is useful if your target server doesn't support percent-encoded + target URIs. + """ + + scheme: str | None = None + QueueCls = queue.LifoQueue + + def __init__(self, host: str, port: int | None = None) -> None: + if not host: + raise LocationValueError("No host specified.") + + self.host = _normalize_host(host, scheme=self.scheme) + self.port = port + + # This property uses 'normalize_host()' (not '_normalize_host()') + # to avoid removing square braces around IPv6 addresses. + # This value is sent to `HTTPConnection.set_tunnel()` if called + # because square braces are required for HTTP CONNECT tunneling. + self._tunnel_host = normalize_host(host, scheme=self.scheme).lower() + + def __str__(self) -> str: + return f"{type(self).__name__}(host={self.host!r}, port={self.port!r})" + + def __enter__(self) -> Self: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> typing.Literal[False]: + self.close() + # Return False to re-raise any potential exceptions + return False + + def close(self) -> None: + """ + Close all pooled connections and disable the pool. + """ + + +# This is taken from http://hg.python.org/cpython/file/7aaba721ebc0/Lib/socket.py#l252 +_blocking_errnos = {errno.EAGAIN, errno.EWOULDBLOCK} + + +class HTTPConnectionPool(ConnectionPool, RequestMethods): + """ + Thread-safe connection pool for one host. + + :param host: + Host used for this HTTP Connection (e.g. "localhost"), passed into + :class:`http.client.HTTPConnection`. + + :param port: + Port used for this HTTP Connection (None is equivalent to 80), passed + into :class:`http.client.HTTPConnection`. + + :param timeout: + Socket timeout in seconds for each individual connection. This can + be a float or integer, which sets the timeout for the HTTP request, + or an instance of :class:`urllib3.util.Timeout` which gives you more + fine-grained control over request timeouts. After the constructor has + been parsed, this is always a `urllib3.util.Timeout` object. + + :param maxsize: + Number of connections to save that can be reused. More than 1 is useful + in multithreaded situations. If ``block`` is set to False, more + connections will be created but they will not be saved once they've + been used. + + :param block: + If set to True, no more than ``maxsize`` connections will be used at + a time. When no free connections are available, the call will block + until a connection has been released. This is a useful side effect for + particular multithreaded situations where one does not want to use more + than maxsize connections per host to prevent flooding. + + :param headers: + Headers to include with all requests, unless other headers are given + explicitly. + + :param retries: + Retry configuration to use by default with requests in this pool. + + :param _proxy: + Parsed proxy URL, should not be used directly, instead, see + :class:`urllib3.ProxyManager` + + :param _proxy_headers: + A dictionary with proxy headers, should not be used directly, + instead, see :class:`urllib3.ProxyManager` + + :param \\**conn_kw: + Additional parameters are used to create fresh :class:`urllib3.connection.HTTPConnection`, + :class:`urllib3.connection.HTTPSConnection` instances. + """ + + scheme = "http" + ConnectionCls: type[BaseHTTPConnection] | type[BaseHTTPSConnection] = HTTPConnection + + def __init__( + self, + host: str, + port: int | None = None, + timeout: _TYPE_TIMEOUT | None = _DEFAULT_TIMEOUT, + maxsize: int = 1, + block: bool = False, + headers: typing.Mapping[str, str] | None = None, + retries: Retry | bool | int | None = None, + _proxy: Url | None = None, + _proxy_headers: typing.Mapping[str, str] | None = None, + _proxy_config: ProxyConfig | None = None, + **conn_kw: typing.Any, + ): + ConnectionPool.__init__(self, host, port) + RequestMethods.__init__(self, headers) + + if not isinstance(timeout, Timeout): + timeout = Timeout.from_float(timeout) + + if retries is None: + retries = Retry.DEFAULT + + self.timeout = timeout + self.retries = retries + + self.pool: queue.LifoQueue[typing.Any] | None = self.QueueCls(maxsize) + self.block = block + + self.proxy = _proxy + self.proxy_headers = _proxy_headers or {} + self.proxy_config = _proxy_config + + # Fill the queue up so that doing get() on it will block properly + for _ in range(maxsize): + self.pool.put(None) + + # These are mostly for testing and debugging purposes. + self.num_connections = 0 + self.num_requests = 0 + self.conn_kw = conn_kw + + if self.proxy: + # Enable Nagle's algorithm for proxies, to avoid packet fragmentation. + # We cannot know if the user has added default socket options, so we cannot replace the + # list. + self.conn_kw.setdefault("socket_options", []) + + self.conn_kw["proxy"] = self.proxy + self.conn_kw["proxy_config"] = self.proxy_config + + # Do not pass 'self' as callback to 'finalize'. + # Then the 'finalize' would keep an endless living (leak) to self. + # By just passing a reference to the pool allows the garbage collector + # to free self if nobody else has a reference to it. + pool = self.pool + + # Close all the HTTPConnections in the pool before the + # HTTPConnectionPool object is garbage collected. + weakref.finalize(self, _close_pool_connections, pool) + + def _new_conn(self) -> BaseHTTPConnection: + """ + Return a fresh :class:`HTTPConnection`. + """ + self.num_connections += 1 + log.debug( + "Starting new HTTP connection (%d): %s:%s", + self.num_connections, + self.host, + self.port or "80", + ) + + conn = self.ConnectionCls( + host=self.host, + port=self.port, + timeout=self.timeout.connect_timeout, + **self.conn_kw, + ) + return conn + + def _get_conn(self, timeout: float | None = None) -> BaseHTTPConnection: + """ + Get a connection. Will return a pooled connection if one is available. + + If no connections are available and :prop:`.block` is ``False``, then a + fresh connection is returned. + + :param timeout: + Seconds to wait before giving up and raising + :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and + :prop:`.block` is ``True``. + """ + conn = None + + if self.pool is None: + raise ClosedPoolError(self, "Pool is closed.") + + try: + conn = self.pool.get(block=self.block, timeout=timeout) + + except AttributeError: # self.pool is None + raise ClosedPoolError(self, "Pool is closed.") from None # Defensive: + + except queue.Empty: + if self.block: + raise EmptyPoolError( + self, + "Pool is empty and a new connection can't be opened due to blocking mode.", + ) from None + pass # Oh well, we'll create a new connection then + + # If this is a persistent connection, check if it got disconnected + if conn and is_connection_dropped(conn): + log.debug("Resetting dropped connection: %s", self.host) + conn.close() + + return conn or self._new_conn() + + def _put_conn(self, conn: BaseHTTPConnection | None) -> None: + """ + Put a connection back into the pool. + + :param conn: + Connection object for the current host and port as returned by + :meth:`._new_conn` or :meth:`._get_conn`. + + If the pool is already full, the connection is closed and discarded + because we exceeded maxsize. If connections are discarded frequently, + then maxsize should be increased. + + If the pool is closed, then the connection will be closed and discarded. + """ + if self.pool is not None: + try: + self.pool.put(conn, block=False) + return # Everything is dandy, done. + except AttributeError: + # self.pool is None. + pass + except queue.Full: + # Connection never got put back into the pool, close it. + if conn: + conn.close() + + if self.block: + # This should never happen if you got the conn from self._get_conn + raise FullPoolError( + self, + "Pool reached maximum size and no more connections are allowed.", + ) from None + + log.warning( + "Connection pool is full, discarding connection: %s. Connection pool size: %s", + self.host, + self.pool.qsize(), + ) + + # Connection never got put back into the pool, close it. + if conn: + conn.close() + + def _validate_conn(self, conn: BaseHTTPConnection) -> None: + """ + Called right before a request is made, after the socket is created. + """ + + def _prepare_proxy(self, conn: BaseHTTPConnection) -> None: + # Nothing to do for HTTP connections. + pass + + def _get_timeout(self, timeout: _TYPE_TIMEOUT) -> Timeout: + """Helper that always returns a :class:`urllib3.util.Timeout`""" + if timeout is _DEFAULT_TIMEOUT: + return self.timeout.clone() + + if isinstance(timeout, Timeout): + return timeout.clone() + else: + # User passed us an int/float. This is for backwards compatibility, + # can be removed later + return Timeout.from_float(timeout) + + def _raise_timeout( + self, + err: BaseSSLError | OSError | SocketTimeout, + url: str, + timeout_value: _TYPE_TIMEOUT | None, + ) -> None: + """Is the error actually a timeout? Will raise a ReadTimeout or pass""" + + if isinstance(err, SocketTimeout): + raise ReadTimeoutError( + self, url, f"Read timed out. (read timeout={timeout_value})" + ) from err + + # See the above comment about EAGAIN in Python 3. + if hasattr(err, "errno") and err.errno in _blocking_errnos: + raise ReadTimeoutError( + self, url, f"Read timed out. (read timeout={timeout_value})" + ) from err + + def _make_request( + self, + conn: BaseHTTPConnection, + method: str, + url: str, + body: _TYPE_BODY | None = None, + headers: typing.Mapping[str, str] | None = None, + retries: Retry | None = None, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + chunked: bool = False, + response_conn: BaseHTTPConnection | None = None, + preload_content: bool = True, + decode_content: bool = True, + enforce_content_length: bool = True, + ) -> BaseHTTPResponse: + """ + Perform a request on a given urllib connection object taken from our + pool. + + :param conn: + a connection from one of our connection pools + + :param method: + HTTP request method (such as GET, POST, PUT, etc.) + + :param url: + The URL to perform the request on. + + :param body: + Data to send in the request body, either :class:`str`, :class:`bytes`, + an iterable of :class:`str`/:class:`bytes`, or a file-like object. + + :param headers: + Dictionary of custom headers to send, such as User-Agent, + If-None-Match, etc. If None, pool headers are used. If provided, + these headers completely replace any pool-specific headers. + + :param retries: + Configure the number of retries to allow before raising a + :class:`~urllib3.exceptions.MaxRetryError` exception. + + Pass ``None`` to retry until you receive a response. Pass a + :class:`~urllib3.util.retry.Retry` object for fine-grained control + over different types of retries. + Pass an integer number to retry connection errors that many times, + but no other types of errors. Pass zero to never retry. + + If ``False``, then retries are disabled and any exception is raised + immediately. Also, instead of raising a MaxRetryError on redirects, + the redirect response will be returned. + + :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int. + + :param timeout: + If specified, overrides the default timeout for this one + request. It may be a float (in seconds) or an instance of + :class:`urllib3.util.Timeout`. + + :param chunked: + If True, urllib3 will send the body using chunked transfer + encoding. Otherwise, urllib3 will send the body using the standard + content-length form. Defaults to False. + + :param response_conn: + Set this to ``None`` if you will handle releasing the connection or + set the connection to have the response release it. + + :param preload_content: + If True, the response's body will be preloaded during construction. + + :param decode_content: + If True, will attempt to decode the body based on the + 'content-encoding' header. + + :param enforce_content_length: + Enforce content length checking. Body returned by server must match + value of Content-Length header, if present. Otherwise, raise error. + """ + self.num_requests += 1 + + timeout_obj = self._get_timeout(timeout) + timeout_obj.start_connect() + conn.timeout = Timeout.resolve_default_timeout(timeout_obj.connect_timeout) + + try: + # Trigger any extra validation we need to do. + try: + self._validate_conn(conn) + except (SocketTimeout, BaseSSLError) as e: + self._raise_timeout(err=e, url=url, timeout_value=conn.timeout) + raise + + # _validate_conn() starts the connection to an HTTPS proxy + # so we need to wrap errors with 'ProxyError' here too. + except ( + OSError, + NewConnectionError, + TimeoutError, + BaseSSLError, + CertificateError, + SSLError, + ) as e: + new_e: Exception = e + if isinstance(e, (BaseSSLError, CertificateError)): + new_e = SSLError(e) + # If the connection didn't successfully connect to it's proxy + # then there + if isinstance( + new_e, (OSError, NewConnectionError, TimeoutError, SSLError) + ) and (conn and conn.proxy and not conn.has_connected_to_proxy): + new_e = _wrap_proxy_error(new_e, conn.proxy.scheme) + raise new_e + + # conn.request() calls http.client.*.request, not the method in + # urllib3.request. It also calls makefile (recv) on the socket. + try: + conn.request( + method, + url, + body=body, + headers=headers, + chunked=chunked, + preload_content=preload_content, + decode_content=decode_content, + enforce_content_length=enforce_content_length, + ) + + # We are swallowing BrokenPipeError (errno.EPIPE) since the server is + # legitimately able to close the connection after sending a valid response. + # With this behaviour, the received response is still readable. + except BrokenPipeError: + pass + except OSError as e: + # MacOS/Linux + # EPROTOTYPE and ECONNRESET are needed on macOS + # https://erickt.github.io/blog/2014/11/19/adventures-in-debugging-a-potential-osx-kernel-bug/ + # Condition changed later to emit ECONNRESET instead of only EPROTOTYPE. + if e.errno != errno.EPROTOTYPE and e.errno != errno.ECONNRESET: + raise + + # Reset the timeout for the recv() on the socket + read_timeout = timeout_obj.read_timeout + + if not conn.is_closed: + # In Python 3 socket.py will catch EAGAIN and return None when you + # try and read into the file pointer created by http.client, which + # instead raises a BadStatusLine exception. Instead of catching + # the exception and assuming all BadStatusLine exceptions are read + # timeouts, check for a zero timeout before making the request. + if read_timeout == 0: + raise ReadTimeoutError( + self, url, f"Read timed out. (read timeout={read_timeout})" + ) + conn.timeout = read_timeout + + # Receive the response from the server + try: + response = conn.getresponse() + except (BaseSSLError, OSError) as e: + self._raise_timeout(err=e, url=url, timeout_value=read_timeout) + raise + + # Set properties that are used by the pooling layer. + response.retries = retries + response._connection = response_conn # type: ignore[attr-defined] + response._pool = self # type: ignore[attr-defined] + + log.debug( + '%s://%s:%s "%s %s %s" %s %s', + self.scheme, + self.host, + self.port, + method, + url, + response.version_string, + response.status, + response.length_remaining, + ) + + return response + + def close(self) -> None: + """ + Close all pooled connections and disable the pool. + """ + if self.pool is None: + return + # Disable access to the pool + old_pool, self.pool = self.pool, None + + # Close all the HTTPConnections in the pool. + _close_pool_connections(old_pool) + + def is_same_host(self, url: str) -> bool: + """ + Check if the given ``url`` is a member of the same host as this + connection pool. + """ + if url.startswith("/"): + return True + + # TODO: Add optional support for socket.gethostbyname checking. + scheme, _, host, port, *_ = parse_url(url) + scheme = scheme or "http" + if host is not None: + host = _normalize_host(host, scheme=scheme) + + # Use explicit default port for comparison when none is given + if self.port and not port: + port = port_by_scheme.get(scheme) + elif not self.port and port == port_by_scheme.get(scheme): + port = None + + return (scheme, host, port) == (self.scheme, self.host, self.port) + + def urlopen( # type: ignore[override] + self, + method: str, + url: str, + body: _TYPE_BODY | None = None, + headers: typing.Mapping[str, str] | None = None, + retries: Retry | bool | int | None = None, + redirect: bool = True, + assert_same_host: bool = True, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + pool_timeout: int | None = None, + release_conn: bool | None = None, + chunked: bool = False, + body_pos: _TYPE_BODY_POSITION | None = None, + preload_content: bool = True, + decode_content: bool = True, + **response_kw: typing.Any, + ) -> BaseHTTPResponse: + """ + Get a connection from the pool and perform an HTTP request. This is the + lowest level call for making a request, so you'll need to specify all + the raw details. + + .. note:: + + More commonly, it's appropriate to use a convenience method + such as :meth:`request`. + + .. note:: + + `release_conn` will only behave as expected if + `preload_content=False` because we want to make + `preload_content=False` the default behaviour someday soon without + breaking backwards compatibility. + + :param method: + HTTP request method (such as GET, POST, PUT, etc.) + + :param url: + The URL to perform the request on. + + :param body: + Data to send in the request body, either :class:`str`, :class:`bytes`, + an iterable of :class:`str`/:class:`bytes`, or a file-like object. + + :param headers: + Dictionary of custom headers to send, such as User-Agent, + If-None-Match, etc. If None, pool headers are used. If provided, + these headers completely replace any pool-specific headers. + + :param retries: + Configure the number of retries to allow before raising a + :class:`~urllib3.exceptions.MaxRetryError` exception. + + If ``None`` (default) will retry 3 times, see ``Retry.DEFAULT``. Pass a + :class:`~urllib3.util.retry.Retry` object for fine-grained control + over different types of retries. + Pass an integer number to retry connection errors that many times, + but no other types of errors. Pass zero to never retry. + + If ``False``, then retries are disabled and any exception is raised + immediately. Also, instead of raising a MaxRetryError on redirects, + the redirect response will be returned. + + :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int. + + :param redirect: + If True, automatically handle redirects (status codes 301, 302, + 303, 307, 308). Each redirect counts as a retry. Disabling retries + will disable redirect, too. + + :param assert_same_host: + If ``True``, will make sure that the host of the pool requests is + consistent else will raise HostChangedError. When ``False``, you can + use the pool on an HTTP proxy and request foreign hosts. + + :param timeout: + If specified, overrides the default timeout for this one + request. It may be a float (in seconds) or an instance of + :class:`urllib3.util.Timeout`. + + :param pool_timeout: + If set and the pool is set to block=True, then this method will + block for ``pool_timeout`` seconds and raise EmptyPoolError if no + connection is available within the time period. + + :param bool preload_content: + If True, the response's body will be preloaded into memory. + + :param bool decode_content: + If True, will attempt to decode the body based on the + 'content-encoding' header. + + :param release_conn: + If False, then the urlopen call will not release the connection + back into the pool once a response is received (but will release if + you read the entire contents of the response such as when + `preload_content=True`). This is useful if you're not preloading + the response's content immediately. You will need to call + ``r.release_conn()`` on the response ``r`` to return the connection + back into the pool. If None, it takes the value of ``preload_content`` + which defaults to ``True``. + + :param bool chunked: + If True, urllib3 will send the body using chunked transfer + encoding. Otherwise, urllib3 will send the body using the standard + content-length form. Defaults to False. + + :param int body_pos: + Position to seek to in file-like body in the event of a retry or + redirect. Typically this won't need to be set because urllib3 will + auto-populate the value when needed. + """ + parsed_url = parse_url(url) + destination_scheme = parsed_url.scheme + + if headers is None: + headers = self.headers + + if not isinstance(retries, Retry): + retries = Retry.from_int(retries, redirect=redirect, default=self.retries) + + if release_conn is None: + release_conn = preload_content + + # Check host + if assert_same_host and not self.is_same_host(url): + raise HostChangedError(self, url, retries) + + # Ensure that the URL we're connecting to is properly encoded + if url.startswith("/"): + url = to_str(_encode_target(url)) + else: + url = to_str(parsed_url.url) + + conn = None + + # Track whether `conn` needs to be released before + # returning/raising/recursing. Update this variable if necessary, and + # leave `release_conn` constant throughout the function. That way, if + # the function recurses, the original value of `release_conn` will be + # passed down into the recursive call, and its value will be respected. + # + # See issue #651 [1] for details. + # + # [1] + release_this_conn = release_conn + + http_tunnel_required = connection_requires_http_tunnel( + self.proxy, self.proxy_config, destination_scheme + ) + + # Merge the proxy headers. Only done when not using HTTP CONNECT. We + # have to copy the headers dict so we can safely change it without those + # changes being reflected in anyone else's copy. + if not http_tunnel_required: + headers = headers.copy() # type: ignore[attr-defined] + headers.update(self.proxy_headers) # type: ignore[union-attr] + + # Must keep the exception bound to a separate variable or else Python 3 + # complains about UnboundLocalError. + err = None + + # Keep track of whether we cleanly exited the except block. This + # ensures we do proper cleanup in finally. + clean_exit = False + + # Rewind body position, if needed. Record current position + # for future rewinds in the event of a redirect/retry. + body_pos = set_file_position(body, body_pos) + + try: + # Request a connection from the queue. + timeout_obj = self._get_timeout(timeout) + conn = self._get_conn(timeout=pool_timeout) + + conn.timeout = timeout_obj.connect_timeout # type: ignore[assignment] + + # Is this a closed/new connection that requires CONNECT tunnelling? + if self.proxy is not None and http_tunnel_required and conn.is_closed: + try: + self._prepare_proxy(conn) + except (BaseSSLError, OSError, SocketTimeout) as e: + self._raise_timeout( + err=e, url=self.proxy.url, timeout_value=conn.timeout + ) + raise + + # If we're going to release the connection in ``finally:``, then + # the response doesn't need to know about the connection. Otherwise + # it will also try to release it and we'll have a double-release + # mess. + response_conn = conn if not release_conn else None + + # Make the request on the HTTPConnection object + response = self._make_request( + conn, + method, + url, + timeout=timeout_obj, + body=body, + headers=headers, + chunked=chunked, + retries=retries, + response_conn=response_conn, + preload_content=preload_content, + decode_content=decode_content, + **response_kw, + ) + + # Everything went great! + clean_exit = True + + except EmptyPoolError: + # Didn't get a connection from the pool, no need to clean up + clean_exit = True + release_this_conn = False + raise + + except ( + TimeoutError, + HTTPException, + OSError, + ProtocolError, + BaseSSLError, + SSLError, + CertificateError, + ProxyError, + ) as e: + # Discard the connection for these exceptions. It will be + # replaced during the next _get_conn() call. + clean_exit = False + new_e: Exception = e + if isinstance(e, (BaseSSLError, CertificateError)): + new_e = SSLError(e) + if isinstance( + new_e, + ( + OSError, + NewConnectionError, + TimeoutError, + SSLError, + HTTPException, + ), + ) and (conn and conn.proxy and not conn.has_connected_to_proxy): + new_e = _wrap_proxy_error(new_e, conn.proxy.scheme) + elif isinstance(new_e, (OSError, HTTPException)): + new_e = ProtocolError("Connection aborted.", new_e) + + retries = retries.increment( + method, url, error=new_e, _pool=self, _stacktrace=sys.exc_info()[2] + ) + retries.sleep() + + # Keep track of the error for the retry warning. + err = e + + finally: + if not clean_exit: + # We hit some kind of exception, handled or otherwise. We need + # to throw the connection away unless explicitly told not to. + # Close the connection, set the variable to None, and make sure + # we put the None back in the pool to avoid leaking it. + if conn: + conn.close() + conn = None + release_this_conn = True + + if release_this_conn: + # Put the connection back to be reused. If the connection is + # expired then it will be None, which will get replaced with a + # fresh connection during _get_conn. + self._put_conn(conn) + + if not conn: + # Try again + log.warning( + "Retrying (%r) after connection broken by '%r': %s", retries, err, url + ) + return self.urlopen( + method, + url, + body, + headers, + retries, + redirect, + assert_same_host, + timeout=timeout, + pool_timeout=pool_timeout, + release_conn=release_conn, + chunked=chunked, + body_pos=body_pos, + preload_content=preload_content, + decode_content=decode_content, + **response_kw, + ) + + # Handle redirect? + redirect_location = redirect and response.get_redirect_location() + if redirect_location: + if response.status == 303: + # Change the method according to RFC 9110, Section 15.4.4. + method = "GET" + # And lose the body not to transfer anything sensitive. + body = None + headers = HTTPHeaderDict(headers)._prepare_for_method_change() + + try: + retries = retries.increment(method, url, response=response, _pool=self) + except MaxRetryError: + if retries.raise_on_redirect: + response.drain_conn() + raise + return response + + response.drain_conn() + retries.sleep_for_retry(response) + log.debug("Redirecting %s -> %s", url, redirect_location) + return self.urlopen( + method, + redirect_location, + body, + headers, + retries=retries, + redirect=redirect, + assert_same_host=assert_same_host, + timeout=timeout, + pool_timeout=pool_timeout, + release_conn=release_conn, + chunked=chunked, + body_pos=body_pos, + preload_content=preload_content, + decode_content=decode_content, + **response_kw, + ) + + # Check if we should retry the HTTP response. + has_retry_after = bool(response.headers.get("Retry-After")) + if retries.is_retry(method, response.status, has_retry_after): + try: + retries = retries.increment(method, url, response=response, _pool=self) + except MaxRetryError: + if retries.raise_on_status: + response.drain_conn() + raise + return response + + response.drain_conn() + retries.sleep(response) + log.debug("Retry: %s", url) + return self.urlopen( + method, + url, + body, + headers, + retries=retries, + redirect=redirect, + assert_same_host=assert_same_host, + timeout=timeout, + pool_timeout=pool_timeout, + release_conn=release_conn, + chunked=chunked, + body_pos=body_pos, + preload_content=preload_content, + decode_content=decode_content, + **response_kw, + ) + + return response + + +class HTTPSConnectionPool(HTTPConnectionPool): + """ + Same as :class:`.HTTPConnectionPool`, but HTTPS. + + :class:`.HTTPSConnection` uses one of ``assert_fingerprint``, + ``assert_hostname`` and ``host`` in this order to verify connections. + If ``assert_hostname`` is False, no verification is done. + + The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs``, + ``ca_cert_dir``, ``ssl_version``, ``key_password`` are only used if :mod:`ssl` + is available and are fed into :meth:`urllib3.util.ssl_wrap_socket` to upgrade + the connection socket into an SSL socket. + """ + + scheme = "https" + ConnectionCls: type[BaseHTTPSConnection] = HTTPSConnection + + def __init__( + self, + host: str, + port: int | None = None, + timeout: _TYPE_TIMEOUT | None = _DEFAULT_TIMEOUT, + maxsize: int = 1, + block: bool = False, + headers: typing.Mapping[str, str] | None = None, + retries: Retry | bool | int | None = None, + _proxy: Url | None = None, + _proxy_headers: typing.Mapping[str, str] | None = None, + key_file: str | None = None, + cert_file: str | None = None, + cert_reqs: int | str | None = None, + key_password: str | None = None, + ca_certs: str | None = None, + ssl_version: int | str | None = None, + ssl_minimum_version: ssl.TLSVersion | None = None, + ssl_maximum_version: ssl.TLSVersion | None = None, + assert_hostname: str | typing.Literal[False] | None = None, + assert_fingerprint: str | None = None, + ca_cert_dir: str | None = None, + **conn_kw: typing.Any, + ) -> None: + super().__init__( + host, + port, + timeout, + maxsize, + block, + headers, + retries, + _proxy, + _proxy_headers, + **conn_kw, + ) + + self.key_file = key_file + self.cert_file = cert_file + self.cert_reqs = cert_reqs + self.key_password = key_password + self.ca_certs = ca_certs + self.ca_cert_dir = ca_cert_dir + self.ssl_version = ssl_version + self.ssl_minimum_version = ssl_minimum_version + self.ssl_maximum_version = ssl_maximum_version + self.assert_hostname = assert_hostname + self.assert_fingerprint = assert_fingerprint + + def _prepare_proxy(self, conn: HTTPSConnection) -> None: # type: ignore[override] + """Establishes a tunnel connection through HTTP CONNECT.""" + if self.proxy and self.proxy.scheme == "https": + tunnel_scheme = "https" + else: + tunnel_scheme = "http" + + conn.set_tunnel( + scheme=tunnel_scheme, + host=self._tunnel_host, + port=self.port, + headers=self.proxy_headers, + ) + conn.connect() + + def _new_conn(self) -> BaseHTTPSConnection: + """ + Return a fresh :class:`urllib3.connection.HTTPConnection`. + """ + self.num_connections += 1 + log.debug( + "Starting new HTTPS connection (%d): %s:%s", + self.num_connections, + self.host, + self.port or "443", + ) + + if not self.ConnectionCls or self.ConnectionCls is DummyConnection: # type: ignore[comparison-overlap] + raise ImportError( + "Can't connect to HTTPS URL because the SSL module is not available." + ) + + actual_host: str = self.host + actual_port = self.port + if self.proxy is not None and self.proxy.host is not None: + actual_host = self.proxy.host + actual_port = self.proxy.port + + return self.ConnectionCls( + host=actual_host, + port=actual_port, + timeout=self.timeout.connect_timeout, + cert_file=self.cert_file, + key_file=self.key_file, + key_password=self.key_password, + cert_reqs=self.cert_reqs, + ca_certs=self.ca_certs, + ca_cert_dir=self.ca_cert_dir, + assert_hostname=self.assert_hostname, + assert_fingerprint=self.assert_fingerprint, + ssl_version=self.ssl_version, + ssl_minimum_version=self.ssl_minimum_version, + ssl_maximum_version=self.ssl_maximum_version, + **self.conn_kw, + ) + + def _validate_conn(self, conn: BaseHTTPConnection) -> None: + """ + Called right before a request is made, after the socket is created. + """ + super()._validate_conn(conn) + + # Force connect early to allow us to validate the connection. + if conn.is_closed: + conn.connect() + + # TODO revise this, see https://github.com/urllib3/urllib3/issues/2791 + if not conn.is_verified and not conn.proxy_is_verified: + warnings.warn( + ( + f"Unverified HTTPS request is being made to host '{conn.host}'. " + "Adding certificate verification is strongly advised. See: " + "https://urllib3.readthedocs.io/en/latest/advanced-usage.html" + "#tls-warnings" + ), + InsecureRequestWarning, + ) + + +def connection_from_url(url: str, **kw: typing.Any) -> HTTPConnectionPool: + """ + Given a url, return an :class:`.ConnectionPool` instance of its host. + + This is a shortcut for not having to parse out the scheme, host, and port + of the url before creating an :class:`.ConnectionPool` instance. + + :param url: + Absolute URL string that must include the scheme. Port is optional. + + :param \\**kw: + Passes additional parameters to the constructor of the appropriate + :class:`.ConnectionPool`. Useful for specifying things like + timeout, maxsize, headers, etc. + + Example:: + + >>> conn = connection_from_url('http://google.com/') + >>> r = conn.request('GET', '/') + """ + scheme, _, host, port, *_ = parse_url(url) + scheme = scheme or "http" + port = port or port_by_scheme.get(scheme, 80) + if scheme == "https": + return HTTPSConnectionPool(host, port=port, **kw) # type: ignore[arg-type] + else: + return HTTPConnectionPool(host, port=port, **kw) # type: ignore[arg-type] + + +@typing.overload +def _normalize_host(host: None, scheme: str | None) -> None: ... + + +@typing.overload +def _normalize_host(host: str, scheme: str | None) -> str: ... + + +def _normalize_host(host: str | None, scheme: str | None) -> str | None: + """ + Normalize hosts for comparisons and use with sockets. + """ + + host = normalize_host(host, scheme) + + # httplib doesn't like it when we include brackets in IPv6 addresses + # Specifically, if we include brackets but also pass the port then + # httplib crazily doubles up the square brackets on the Host header. + # Instead, we need to make sure we never pass ``None`` as the port. + # However, for backward compatibility reasons we can't actually + # *assert* that. See http://bugs.python.org/issue28539 + if host and host.startswith("[") and host.endswith("]"): + host = host[1:-1] + return host + + +def _url_from_pool( + pool: HTTPConnectionPool | HTTPSConnectionPool, path: str | None = None +) -> str: + """Returns the URL from a given connection pool. This is mainly used for testing and logging.""" + return Url(scheme=pool.scheme, host=pool.host, port=pool.port, path=path).url + + +def _close_pool_connections(pool: queue.LifoQueue[typing.Any]) -> None: + """Drains a queue of connections and closes each one.""" + try: + while True: + conn = pool.get(block=False) + if conn: + conn.close() + except queue.Empty: + pass # Done. diff --git a/venv/Lib/site-packages/urllib3/contrib/__init__.py b/venv/Lib/site-packages/urllib3/contrib/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/venv/Lib/site-packages/urllib3/contrib/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/urllib3/contrib/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..bdeabfac Binary files /dev/null and b/venv/Lib/site-packages/urllib3/contrib/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/contrib/__pycache__/pyopenssl.cpython-312.pyc b/venv/Lib/site-packages/urllib3/contrib/__pycache__/pyopenssl.cpython-312.pyc new file mode 100644 index 00000000..bee76ab5 Binary files /dev/null and b/venv/Lib/site-packages/urllib3/contrib/__pycache__/pyopenssl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/contrib/__pycache__/socks.cpython-312.pyc b/venv/Lib/site-packages/urllib3/contrib/__pycache__/socks.cpython-312.pyc new file mode 100644 index 00000000..a0ae17ba Binary files /dev/null and b/venv/Lib/site-packages/urllib3/contrib/__pycache__/socks.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/contrib/emscripten/__init__.py b/venv/Lib/site-packages/urllib3/contrib/emscripten/__init__.py new file mode 100644 index 00000000..8a3c5beb --- /dev/null +++ b/venv/Lib/site-packages/urllib3/contrib/emscripten/__init__.py @@ -0,0 +1,16 @@ +from __future__ import annotations + +import urllib3.connection + +from ...connectionpool import HTTPConnectionPool, HTTPSConnectionPool +from .connection import EmscriptenHTTPConnection, EmscriptenHTTPSConnection + + +def inject_into_urllib3() -> None: + # override connection classes to use emscripten specific classes + # n.b. mypy complains about the overriding of classes below + # if it isn't ignored + HTTPConnectionPool.ConnectionCls = EmscriptenHTTPConnection + HTTPSConnectionPool.ConnectionCls = EmscriptenHTTPSConnection + urllib3.connection.HTTPConnection = EmscriptenHTTPConnection # type: ignore[misc,assignment] + urllib3.connection.HTTPSConnection = EmscriptenHTTPSConnection # type: ignore[misc,assignment] diff --git a/venv/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..2a9930a6 Binary files /dev/null and b/venv/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/connection.cpython-312.pyc b/venv/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/connection.cpython-312.pyc new file mode 100644 index 00000000..7dedcdad Binary files /dev/null and b/venv/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/connection.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/fetch.cpython-312.pyc b/venv/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/fetch.cpython-312.pyc new file mode 100644 index 00000000..3d924eb4 Binary files /dev/null and b/venv/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/fetch.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/request.cpython-312.pyc b/venv/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/request.cpython-312.pyc new file mode 100644 index 00000000..a53285e1 Binary files /dev/null and b/venv/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/request.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/response.cpython-312.pyc b/venv/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/response.cpython-312.pyc new file mode 100644 index 00000000..f2dc0620 Binary files /dev/null and b/venv/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/contrib/emscripten/connection.py b/venv/Lib/site-packages/urllib3/contrib/emscripten/connection.py new file mode 100644 index 00000000..41bfd279 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/contrib/emscripten/connection.py @@ -0,0 +1,255 @@ +from __future__ import annotations + +import os +import typing + +# use http.client.HTTPException for consistency with non-emscripten +from http.client import HTTPException as HTTPException # noqa: F401 +from http.client import ResponseNotReady + +from ..._base_connection import _TYPE_BODY +from ...connection import HTTPConnection, ProxyConfig, port_by_scheme +from ...exceptions import TimeoutError +from ...response import BaseHTTPResponse +from ...util.connection import _TYPE_SOCKET_OPTIONS +from ...util.timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT +from ...util.url import Url +from .fetch import _RequestError, _TimeoutError, send_request, send_streaming_request +from .request import EmscriptenRequest +from .response import EmscriptenHttpResponseWrapper, EmscriptenResponse + +if typing.TYPE_CHECKING: + from ..._base_connection import BaseHTTPConnection, BaseHTTPSConnection + + +class EmscriptenHTTPConnection: + default_port: typing.ClassVar[int] = port_by_scheme["http"] + default_socket_options: typing.ClassVar[_TYPE_SOCKET_OPTIONS] + + timeout: None | (float) + + host: str + port: int + blocksize: int + source_address: tuple[str, int] | None + socket_options: _TYPE_SOCKET_OPTIONS | None + + proxy: Url | None + proxy_config: ProxyConfig | None + + is_verified: bool = False + proxy_is_verified: bool | None = None + + _response: EmscriptenResponse | None + + def __init__( + self, + host: str, + port: int = 0, + *, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + blocksize: int = 8192, + socket_options: _TYPE_SOCKET_OPTIONS | None = None, + proxy: Url | None = None, + proxy_config: ProxyConfig | None = None, + ) -> None: + self.host = host + self.port = port + self.timeout = timeout if isinstance(timeout, float) else 0.0 + self.scheme = "http" + self._closed = True + self._response = None + # ignore these things because we don't + # have control over that stuff + self.proxy = None + self.proxy_config = None + self.blocksize = blocksize + self.source_address = None + self.socket_options = None + self.is_verified = False + + def set_tunnel( + self, + host: str, + port: int | None = 0, + headers: typing.Mapping[str, str] | None = None, + scheme: str = "http", + ) -> None: + pass + + def connect(self) -> None: + pass + + def request( + self, + method: str, + url: str, + body: _TYPE_BODY | None = None, + headers: typing.Mapping[str, str] | None = None, + # We know *at least* botocore is depending on the order of the + # first 3 parameters so to be safe we only mark the later ones + # as keyword-only to ensure we have space to extend. + *, + chunked: bool = False, + preload_content: bool = True, + decode_content: bool = True, + enforce_content_length: bool = True, + ) -> None: + self._closed = False + if url.startswith("/"): + # no scheme / host / port included, make a full url + url = f"{self.scheme}://{self.host}:{self.port}" + url + request = EmscriptenRequest( + url=url, + method=method, + timeout=self.timeout if self.timeout else 0, + decode_content=decode_content, + ) + request.set_body(body) + if headers: + for k, v in headers.items(): + request.set_header(k, v) + self._response = None + try: + if not preload_content: + self._response = send_streaming_request(request) + if self._response is None: + self._response = send_request(request) + except _TimeoutError as e: + raise TimeoutError(e.message) from e + except _RequestError as e: + raise HTTPException(e.message) from e + + def getresponse(self) -> BaseHTTPResponse: + if self._response is not None: + return EmscriptenHttpResponseWrapper( + internal_response=self._response, + url=self._response.request.url, + connection=self, + ) + else: + raise ResponseNotReady() + + def close(self) -> None: + self._closed = True + self._response = None + + @property + def is_closed(self) -> bool: + """Whether the connection either is brand new or has been previously closed. + If this property is True then both ``is_connected`` and ``has_connected_to_proxy`` + properties must be False. + """ + return self._closed + + @property + def is_connected(self) -> bool: + """Whether the connection is actively connected to any origin (proxy or target)""" + return True + + @property + def has_connected_to_proxy(self) -> bool: + """Whether the connection has successfully connected to its proxy. + This returns False if no proxy is in use. Used to determine whether + errors are coming from the proxy layer or from tunnelling to the target origin. + """ + return False + + +class EmscriptenHTTPSConnection(EmscriptenHTTPConnection): + default_port = port_by_scheme["https"] + # all this is basically ignored, as browser handles https + cert_reqs: int | str | None = None + ca_certs: str | None = None + ca_cert_dir: str | None = None + ca_cert_data: None | str | bytes = None + cert_file: str | None + key_file: str | None + key_password: str | None + ssl_context: typing.Any | None + ssl_version: int | str | None = None + ssl_minimum_version: int | None = None + ssl_maximum_version: int | None = None + assert_hostname: None | str | typing.Literal[False] + assert_fingerprint: str | None = None + + def __init__( + self, + host: str, + port: int = 0, + *, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + blocksize: int = 16384, + socket_options: ( + None | _TYPE_SOCKET_OPTIONS + ) = HTTPConnection.default_socket_options, + proxy: Url | None = None, + proxy_config: ProxyConfig | None = None, + cert_reqs: int | str | None = None, + assert_hostname: None | str | typing.Literal[False] = None, + assert_fingerprint: str | None = None, + server_hostname: str | None = None, + ssl_context: typing.Any | None = None, + ca_certs: str | None = None, + ca_cert_dir: str | None = None, + ca_cert_data: None | str | bytes = None, + ssl_minimum_version: int | None = None, + ssl_maximum_version: int | None = None, + ssl_version: int | str | None = None, # Deprecated + cert_file: str | None = None, + key_file: str | None = None, + key_password: str | None = None, + ) -> None: + super().__init__( + host, + port=port, + timeout=timeout, + source_address=source_address, + blocksize=blocksize, + socket_options=socket_options, + proxy=proxy, + proxy_config=proxy_config, + ) + self.scheme = "https" + + self.key_file = key_file + self.cert_file = cert_file + self.key_password = key_password + self.ssl_context = ssl_context + self.server_hostname = server_hostname + self.assert_hostname = assert_hostname + self.assert_fingerprint = assert_fingerprint + self.ssl_version = ssl_version + self.ssl_minimum_version = ssl_minimum_version + self.ssl_maximum_version = ssl_maximum_version + self.ca_certs = ca_certs and os.path.expanduser(ca_certs) + self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir) + self.ca_cert_data = ca_cert_data + + self.cert_reqs = None + + # The browser will automatically verify all requests. + # We have no control over that setting. + self.is_verified = True + + def set_cert( + self, + key_file: str | None = None, + cert_file: str | None = None, + cert_reqs: int | str | None = None, + key_password: str | None = None, + ca_certs: str | None = None, + assert_hostname: None | str | typing.Literal[False] = None, + assert_fingerprint: str | None = None, + ca_cert_dir: str | None = None, + ca_cert_data: None | str | bytes = None, + ) -> None: + pass + + +# verify that this class implements BaseHTTP(s) connection correctly +if typing.TYPE_CHECKING: + _supports_http_protocol: BaseHTTPConnection = EmscriptenHTTPConnection("", 0) + _supports_https_protocol: BaseHTTPSConnection = EmscriptenHTTPSConnection("", 0) diff --git a/venv/Lib/site-packages/urllib3/contrib/emscripten/emscripten_fetch_worker.js b/venv/Lib/site-packages/urllib3/contrib/emscripten/emscripten_fetch_worker.js new file mode 100644 index 00000000..243b8622 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/contrib/emscripten/emscripten_fetch_worker.js @@ -0,0 +1,110 @@ +let Status = { + SUCCESS_HEADER: -1, + SUCCESS_EOF: -2, + ERROR_TIMEOUT: -3, + ERROR_EXCEPTION: -4, +}; + +let connections = {}; +let nextConnectionID = 1; +const encoder = new TextEncoder(); + +self.addEventListener("message", async function (event) { + if (event.data.close) { + let connectionID = event.data.close; + delete connections[connectionID]; + return; + } else if (event.data.getMore) { + let connectionID = event.data.getMore; + let { curOffset, value, reader, intBuffer, byteBuffer } = + connections[connectionID]; + // if we still have some in buffer, then just send it back straight away + if (!value || curOffset >= value.length) { + // read another buffer if required + try { + let readResponse = await reader.read(); + + if (readResponse.done) { + // read everything - clear connection and return + delete connections[connectionID]; + Atomics.store(intBuffer, 0, Status.SUCCESS_EOF); + Atomics.notify(intBuffer, 0); + // finished reading successfully + // return from event handler + return; + } + curOffset = 0; + connections[connectionID].value = readResponse.value; + value = readResponse.value; + } catch (error) { + console.log("Request exception:", error); + let errorBytes = encoder.encode(error.message); + let written = errorBytes.length; + byteBuffer.set(errorBytes); + intBuffer[1] = written; + Atomics.store(intBuffer, 0, Status.ERROR_EXCEPTION); + Atomics.notify(intBuffer, 0); + } + } + + // send as much buffer as we can + let curLen = value.length - curOffset; + if (curLen > byteBuffer.length) { + curLen = byteBuffer.length; + } + byteBuffer.set(value.subarray(curOffset, curOffset + curLen), 0); + + Atomics.store(intBuffer, 0, curLen); // store current length in bytes + Atomics.notify(intBuffer, 0); + curOffset += curLen; + connections[connectionID].curOffset = curOffset; + + return; + } else { + // start fetch + let connectionID = nextConnectionID; + nextConnectionID += 1; + const intBuffer = new Int32Array(event.data.buffer); + const byteBuffer = new Uint8Array(event.data.buffer, 8); + try { + const response = await fetch(event.data.url, event.data.fetchParams); + // return the headers first via textencoder + var headers = []; + for (const pair of response.headers.entries()) { + headers.push([pair[0], pair[1]]); + } + let headerObj = { + headers: headers, + status: response.status, + connectionID, + }; + const headerText = JSON.stringify(headerObj); + let headerBytes = encoder.encode(headerText); + let written = headerBytes.length; + byteBuffer.set(headerBytes); + intBuffer[1] = written; + // make a connection + connections[connectionID] = { + reader: response.body.getReader(), + intBuffer: intBuffer, + byteBuffer: byteBuffer, + value: undefined, + curOffset: 0, + }; + // set header ready + Atomics.store(intBuffer, 0, Status.SUCCESS_HEADER); + Atomics.notify(intBuffer, 0); + // all fetching after this goes through a new postmessage call with getMore + // this allows for parallel requests + } catch (error) { + console.log("Request exception:", error); + let errorBytes = encoder.encode(error.message); + let written = errorBytes.length; + byteBuffer.set(errorBytes); + intBuffer[1] = written; + Atomics.store(intBuffer, 0, Status.ERROR_EXCEPTION); + Atomics.notify(intBuffer, 0); + } + } +}); +self.postMessage({ inited: true }); diff --git a/venv/Lib/site-packages/urllib3/contrib/emscripten/fetch.py b/venv/Lib/site-packages/urllib3/contrib/emscripten/fetch.py new file mode 100644 index 00000000..66958217 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/contrib/emscripten/fetch.py @@ -0,0 +1,728 @@ +""" +Support for streaming http requests in emscripten. + +A few caveats - + +If your browser (or Node.js) has WebAssembly JavaScript Promise Integration enabled +https://github.com/WebAssembly/js-promise-integration/blob/main/proposals/js-promise-integration/Overview.md +*and* you launch pyodide using `pyodide.runPythonAsync`, this will fetch data using the +JavaScript asynchronous fetch api (wrapped via `pyodide.ffi.call_sync`). In this case +timeouts and streaming should just work. + +Otherwise, it uses a combination of XMLHttpRequest and a web-worker for streaming. + +This approach has several caveats: + +Firstly, you can't do streaming http in the main UI thread, because atomics.wait isn't allowed. +Streaming only works if you're running pyodide in a web worker. + +Secondly, this uses an extra web worker and SharedArrayBuffer to do the asynchronous fetch +operation, so it requires that you have crossOriginIsolation enabled, by serving over https +(or from localhost) with the two headers below set: + + Cross-Origin-Opener-Policy: same-origin + Cross-Origin-Embedder-Policy: require-corp + +You can tell if cross origin isolation is successfully enabled by looking at the global crossOriginIsolated variable in +JavaScript console. If it isn't, streaming requests will fallback to XMLHttpRequest, i.e. getting the whole +request into a buffer and then returning it. it shows a warning in the JavaScript console in this case. + +Finally, the webworker which does the streaming fetch is created on initial import, but will only be started once +control is returned to javascript. Call `await wait_for_streaming_ready()` to wait for streaming fetch. + +NB: in this code, there are a lot of JavaScript objects. They are named js_* +to make it clear what type of object they are. +""" + +from __future__ import annotations + +import io +import json +from email.parser import Parser +from importlib.resources import files +from typing import TYPE_CHECKING, Any + +import js # type: ignore[import-not-found] +from pyodide.ffi import ( # type: ignore[import-not-found] + JsArray, + JsException, + JsProxy, + to_js, +) + +if TYPE_CHECKING: + from typing_extensions import Buffer + +from .request import EmscriptenRequest +from .response import EmscriptenResponse + +""" +There are some headers that trigger unintended CORS preflight requests. +See also https://github.com/koenvo/pyodide-http/issues/22 +""" +HEADERS_TO_IGNORE = ("user-agent",) + +SUCCESS_HEADER = -1 +SUCCESS_EOF = -2 +ERROR_TIMEOUT = -3 +ERROR_EXCEPTION = -4 + +_STREAMING_WORKER_CODE = ( + files(__package__) + .joinpath("emscripten_fetch_worker.js") + .read_text(encoding="utf-8") +) + + +class _RequestError(Exception): + def __init__( + self, + message: str | None = None, + *, + request: EmscriptenRequest | None = None, + response: EmscriptenResponse | None = None, + ): + self.request = request + self.response = response + self.message = message + super().__init__(self.message) + + +class _StreamingError(_RequestError): + pass + + +class _TimeoutError(_RequestError): + pass + + +def _obj_from_dict(dict_val: dict[str, Any]) -> JsProxy: + return to_js(dict_val, dict_converter=js.Object.fromEntries) + + +class _ReadStream(io.RawIOBase): + def __init__( + self, + int_buffer: JsArray, + byte_buffer: JsArray, + timeout: float, + worker: JsProxy, + connection_id: int, + request: EmscriptenRequest, + ): + self.int_buffer = int_buffer + self.byte_buffer = byte_buffer + self.read_pos = 0 + self.read_len = 0 + self.connection_id = connection_id + self.worker = worker + self.timeout = int(1000 * timeout) if timeout > 0 else None + self.is_live = True + self._is_closed = False + self.request: EmscriptenRequest | None = request + + def __del__(self) -> None: + self.close() + + # this is compatible with _base_connection + def is_closed(self) -> bool: + return self._is_closed + + # for compatibility with RawIOBase + @property + def closed(self) -> bool: + return self.is_closed() + + def close(self) -> None: + if self.is_closed(): + return + self.read_len = 0 + self.read_pos = 0 + self.int_buffer = None + self.byte_buffer = None + self._is_closed = True + self.request = None + if self.is_live: + self.worker.postMessage(_obj_from_dict({"close": self.connection_id})) + self.is_live = False + super().close() + + def readable(self) -> bool: + return True + + def writable(self) -> bool: + return False + + def seekable(self) -> bool: + return False + + def readinto(self, byte_obj: Buffer) -> int: + if not self.int_buffer: + raise _StreamingError( + "No buffer for stream in _ReadStream.readinto", + request=self.request, + response=None, + ) + if self.read_len == 0: + # wait for the worker to send something + js.Atomics.store(self.int_buffer, 0, ERROR_TIMEOUT) + self.worker.postMessage(_obj_from_dict({"getMore": self.connection_id})) + if ( + js.Atomics.wait(self.int_buffer, 0, ERROR_TIMEOUT, self.timeout) + == "timed-out" + ): + raise _TimeoutError + data_len = self.int_buffer[0] + if data_len > 0: + self.read_len = data_len + self.read_pos = 0 + elif data_len == ERROR_EXCEPTION: + string_len = self.int_buffer[1] + # decode the error string + js_decoder = js.TextDecoder.new() + json_str = js_decoder.decode(self.byte_buffer.slice(0, string_len)) + raise _StreamingError( + f"Exception thrown in fetch: {json_str}", + request=self.request, + response=None, + ) + else: + # EOF, free the buffers and return zero + # and free the request + self.is_live = False + self.close() + return 0 + # copy from int32array to python bytes + ret_length = min(self.read_len, len(memoryview(byte_obj))) + subarray = self.byte_buffer.subarray( + self.read_pos, self.read_pos + ret_length + ).to_py() + memoryview(byte_obj)[0:ret_length] = subarray + self.read_len -= ret_length + self.read_pos += ret_length + return ret_length + + +class _StreamingFetcher: + def __init__(self) -> None: + # make web-worker and data buffer on startup + self.streaming_ready = False + + js_data_blob = js.Blob.new( + to_js([_STREAMING_WORKER_CODE], create_pyproxies=False), + _obj_from_dict({"type": "application/javascript"}), + ) + + def promise_resolver(js_resolve_fn: JsProxy, js_reject_fn: JsProxy) -> None: + def onMsg(e: JsProxy) -> None: + self.streaming_ready = True + js_resolve_fn(e) + + def onErr(e: JsProxy) -> None: + js_reject_fn(e) # Defensive: never happens in ci + + self.js_worker.onmessage = onMsg + self.js_worker.onerror = onErr + + js_data_url = js.URL.createObjectURL(js_data_blob) + self.js_worker = js.globalThis.Worker.new(js_data_url) + self.js_worker_ready_promise = js.globalThis.Promise.new(promise_resolver) + + def send(self, request: EmscriptenRequest) -> EmscriptenResponse: + headers = { + k: v for k, v in request.headers.items() if k not in HEADERS_TO_IGNORE + } + + body = request.body + fetch_data = {"headers": headers, "body": to_js(body), "method": request.method} + # start the request off in the worker + timeout = int(1000 * request.timeout) if request.timeout > 0 else None + js_shared_buffer = js.SharedArrayBuffer.new(1048576) + js_int_buffer = js.Int32Array.new(js_shared_buffer) + js_byte_buffer = js.Uint8Array.new(js_shared_buffer, 8) + + js.Atomics.store(js_int_buffer, 0, ERROR_TIMEOUT) + js.Atomics.notify(js_int_buffer, 0) + js_absolute_url = js.URL.new(request.url, js.location).href + self.js_worker.postMessage( + _obj_from_dict( + { + "buffer": js_shared_buffer, + "url": js_absolute_url, + "fetchParams": fetch_data, + } + ) + ) + # wait for the worker to send something + js.Atomics.wait(js_int_buffer, 0, ERROR_TIMEOUT, timeout) + if js_int_buffer[0] == ERROR_TIMEOUT: + raise _TimeoutError( + "Timeout connecting to streaming request", + request=request, + response=None, + ) + elif js_int_buffer[0] == SUCCESS_HEADER: + # got response + # header length is in second int of intBuffer + string_len = js_int_buffer[1] + # decode the rest to a JSON string + js_decoder = js.TextDecoder.new() + # this does a copy (the slice) because decode can't work on shared array + # for some silly reason + json_str = js_decoder.decode(js_byte_buffer.slice(0, string_len)) + # get it as an object + response_obj = json.loads(json_str) + return EmscriptenResponse( + request=request, + status_code=response_obj["status"], + headers=response_obj["headers"], + body=_ReadStream( + js_int_buffer, + js_byte_buffer, + request.timeout, + self.js_worker, + response_obj["connectionID"], + request, + ), + ) + elif js_int_buffer[0] == ERROR_EXCEPTION: + string_len = js_int_buffer[1] + # decode the error string + js_decoder = js.TextDecoder.new() + json_str = js_decoder.decode(js_byte_buffer.slice(0, string_len)) + raise _StreamingError( + f"Exception thrown in fetch: {json_str}", request=request, response=None + ) + else: + raise _StreamingError( + f"Unknown status from worker in fetch: {js_int_buffer[0]}", + request=request, + response=None, + ) + + +class _JSPIReadStream(io.RawIOBase): + """ + A read stream that uses pyodide.ffi.run_sync to read from a JavaScript fetch + response. This requires support for WebAssembly JavaScript Promise Integration + in the containing browser, and for pyodide to be launched via runPythonAsync. + + :param js_read_stream: + The JavaScript stream reader + + :param timeout: + Timeout in seconds + + :param request: + The request we're handling + + :param response: + The response this stream relates to + + :param js_abort_controller: + A JavaScript AbortController object, used for timeouts + """ + + def __init__( + self, + js_read_stream: Any, + timeout: float, + request: EmscriptenRequest, + response: EmscriptenResponse, + js_abort_controller: Any, # JavaScript AbortController for timeouts + ): + self.js_read_stream = js_read_stream + self.timeout = timeout + self._is_closed = False + self._is_done = False + self.request: EmscriptenRequest | None = request + self.response: EmscriptenResponse | None = response + self.current_buffer = None + self.current_buffer_pos = 0 + self.js_abort_controller = js_abort_controller + + def __del__(self) -> None: + self.close() + + # this is compatible with _base_connection + def is_closed(self) -> bool: + return self._is_closed + + # for compatibility with RawIOBase + @property + def closed(self) -> bool: + return self.is_closed() + + def close(self) -> None: + if self.is_closed(): + return + self.read_len = 0 + self.read_pos = 0 + self.js_read_stream.cancel() + self.js_read_stream = None + self._is_closed = True + self._is_done = True + self.request = None + self.response = None + super().close() + + def readable(self) -> bool: + return True + + def writable(self) -> bool: + return False + + def seekable(self) -> bool: + return False + + def _get_next_buffer(self) -> bool: + result_js = _run_sync_with_timeout( + self.js_read_stream.read(), + self.timeout, + self.js_abort_controller, + request=self.request, + response=self.response, + ) + if result_js.done: + self._is_done = True + return False + else: + self.current_buffer = result_js.value.to_py() + self.current_buffer_pos = 0 + return True + + def readinto(self, byte_obj: Buffer) -> int: + if self.current_buffer is None: + if not self._get_next_buffer() or self.current_buffer is None: + self.close() + return 0 + ret_length = min( + len(byte_obj), len(self.current_buffer) - self.current_buffer_pos + ) + byte_obj[0:ret_length] = self.current_buffer[ + self.current_buffer_pos : self.current_buffer_pos + ret_length + ] + self.current_buffer_pos += ret_length + if self.current_buffer_pos == len(self.current_buffer): + self.current_buffer = None + return ret_length + + +# check if we are in a worker or not +def is_in_browser_main_thread() -> bool: + return hasattr(js, "window") and hasattr(js, "self") and js.self == js.window + + +def is_cross_origin_isolated() -> bool: + return hasattr(js, "crossOriginIsolated") and js.crossOriginIsolated + + +def is_in_node() -> bool: + return ( + hasattr(js, "process") + and hasattr(js.process, "release") + and hasattr(js.process.release, "name") + and js.process.release.name == "node" + ) + + +def is_worker_available() -> bool: + return hasattr(js, "Worker") and hasattr(js, "Blob") + + +_fetcher: _StreamingFetcher | None = None + +if is_worker_available() and ( + (is_cross_origin_isolated() and not is_in_browser_main_thread()) + and (not is_in_node()) +): + _fetcher = _StreamingFetcher() +else: + _fetcher = None + + +NODE_JSPI_ERROR = ( + "urllib3 only works in Node.js with pyodide.runPythonAsync" + " and requires the flag --experimental-wasm-stack-switching in " + " versions of node <24." +) + + +def send_streaming_request(request: EmscriptenRequest) -> EmscriptenResponse | None: + if has_jspi(): + return send_jspi_request(request, True) + elif is_in_node(): + raise _RequestError( + message=NODE_JSPI_ERROR, + request=request, + response=None, + ) + + if _fetcher and streaming_ready(): + return _fetcher.send(request) + else: + _show_streaming_warning() + return None + + +_SHOWN_TIMEOUT_WARNING = False + + +def _show_timeout_warning() -> None: + global _SHOWN_TIMEOUT_WARNING + if not _SHOWN_TIMEOUT_WARNING: + _SHOWN_TIMEOUT_WARNING = True + message = "Warning: Timeout is not available on main browser thread" + js.console.warn(message) + + +_SHOWN_STREAMING_WARNING = False + + +def _show_streaming_warning() -> None: + global _SHOWN_STREAMING_WARNING + if not _SHOWN_STREAMING_WARNING: + _SHOWN_STREAMING_WARNING = True + message = "Can't stream HTTP requests because: \n" + if not is_cross_origin_isolated(): + message += " Page is not cross-origin isolated\n" + if is_in_browser_main_thread(): + message += " Python is running in main browser thread\n" + if not is_worker_available(): + message += " Worker or Blob classes are not available in this environment." # Defensive: this is always False in browsers that we test in + if streaming_ready() is False: + message += """ Streaming fetch worker isn't ready. If you want to be sure that streaming fetch +is working, you need to call: 'await urllib3.contrib.emscripten.fetch.wait_for_streaming_ready()`""" + from js import console + + console.warn(message) + + +def send_request(request: EmscriptenRequest) -> EmscriptenResponse: + if has_jspi(): + return send_jspi_request(request, False) + elif is_in_node(): + raise _RequestError( + message=NODE_JSPI_ERROR, + request=request, + response=None, + ) + try: + js_xhr = js.XMLHttpRequest.new() + + if not is_in_browser_main_thread(): + js_xhr.responseType = "arraybuffer" + if request.timeout: + js_xhr.timeout = int(request.timeout * 1000) + else: + js_xhr.overrideMimeType("text/plain; charset=ISO-8859-15") + if request.timeout: + # timeout isn't available on the main thread - show a warning in console + # if it is set + _show_timeout_warning() + + js_xhr.open(request.method, request.url, False) + for name, value in request.headers.items(): + if name.lower() not in HEADERS_TO_IGNORE: + js_xhr.setRequestHeader(name, value) + + js_xhr.send(to_js(request.body)) + + headers = dict(Parser().parsestr(js_xhr.getAllResponseHeaders())) + + if not is_in_browser_main_thread(): + body = js_xhr.response.to_py().tobytes() + else: + body = js_xhr.response.encode("ISO-8859-15") + return EmscriptenResponse( + status_code=js_xhr.status, headers=headers, body=body, request=request + ) + except JsException as err: + if err.name == "TimeoutError": + raise _TimeoutError(err.message, request=request) + elif err.name == "NetworkError": + raise _RequestError(err.message, request=request) + else: + # general http error + raise _RequestError(err.message, request=request) + + +def send_jspi_request( + request: EmscriptenRequest, streaming: bool +) -> EmscriptenResponse: + """ + Send a request using WebAssembly JavaScript Promise Integration + to wrap the asynchronous JavaScript fetch api (experimental). + + :param request: + Request to send + + :param streaming: + Whether to stream the response + + :return: The response object + :rtype: EmscriptenResponse + """ + timeout = request.timeout + js_abort_controller = js.AbortController.new() + headers = {k: v for k, v in request.headers.items() if k not in HEADERS_TO_IGNORE} + req_body = request.body + fetch_data = { + "headers": headers, + "body": to_js(req_body), + "method": request.method, + "signal": js_abort_controller.signal, + } + # Node.js returns the whole response (unlike opaqueredirect in browsers), + # so urllib3 can set `redirect: manual` to control redirects itself. + # https://stackoverflow.com/a/78524615 + if _is_node_js(): + fetch_data["redirect"] = "manual" + # Call JavaScript fetch (async api, returns a promise) + fetcher_promise_js = js.fetch(request.url, _obj_from_dict(fetch_data)) + # Now suspend WebAssembly until we resolve that promise + # or time out. + response_js = _run_sync_with_timeout( + fetcher_promise_js, + timeout, + js_abort_controller, + request=request, + response=None, + ) + headers = {} + header_iter = response_js.headers.entries() + while True: + iter_value_js = header_iter.next() + if getattr(iter_value_js, "done", False): + break + else: + headers[str(iter_value_js.value[0])] = str(iter_value_js.value[1]) + status_code = response_js.status + body: bytes | io.RawIOBase = b"" + + response = EmscriptenResponse( + status_code=status_code, headers=headers, body=b"", request=request + ) + if streaming: + # get via inputstream + if response_js.body is not None: + # get a reader from the fetch response + body_stream_js = response_js.body.getReader() + body = _JSPIReadStream( + body_stream_js, timeout, request, response, js_abort_controller + ) + else: + # get directly via arraybuffer + # n.b. this is another async JavaScript call. + body = _run_sync_with_timeout( + response_js.arrayBuffer(), + timeout, + js_abort_controller, + request=request, + response=response, + ).to_py() + response.body = body + return response + + +def _run_sync_with_timeout( + promise: Any, + timeout: float, + js_abort_controller: Any, + request: EmscriptenRequest | None, + response: EmscriptenResponse | None, +) -> Any: + """ + Await a JavaScript promise synchronously with a timeout which is implemented + via the AbortController + + :param promise: + Javascript promise to await + + :param timeout: + Timeout in seconds + + :param js_abort_controller: + A JavaScript AbortController object, used on timeout + + :param request: + The request being handled + + :param response: + The response being handled (if it exists yet) + + :raises _TimeoutError: If the request times out + :raises _RequestError: If the request raises a JavaScript exception + + :return: The result of awaiting the promise. + """ + timer_id = None + if timeout > 0: + timer_id = js.setTimeout( + js_abort_controller.abort.bind(js_abort_controller), int(timeout * 1000) + ) + try: + from pyodide.ffi import run_sync + + # run_sync here uses WebAssembly JavaScript Promise Integration to + # suspend python until the JavaScript promise resolves. + return run_sync(promise) + except JsException as err: + if err.name == "AbortError": + raise _TimeoutError( + message="Request timed out", request=request, response=response + ) + else: + raise _RequestError(message=err.message, request=request, response=response) + finally: + if timer_id is not None: + js.clearTimeout(timer_id) + + +def has_jspi() -> bool: + """ + Return true if jspi can be used. + + This requires both browser support and also WebAssembly + to be in the correct state - i.e. that the javascript + call into python was async not sync. + + :return: True if jspi can be used. + :rtype: bool + """ + try: + from pyodide.ffi import can_run_sync, run_sync # noqa: F401 + + return bool(can_run_sync()) + except ImportError: + return False + + +def _is_node_js() -> bool: + """ + Check if we are in Node.js. + + :return: True if we are in Node.js. + :rtype: bool + """ + return ( + hasattr(js, "process") + and hasattr(js.process, "release") + # According to the Node.js documentation, the release name is always "node". + and js.process.release.name == "node" + ) + + +def streaming_ready() -> bool | None: + if _fetcher: + return _fetcher.streaming_ready + else: + return None # no fetcher, return None to signify that + + +async def wait_for_streaming_ready() -> bool: + if _fetcher: + await _fetcher.js_worker_ready_promise + return True + else: + return False diff --git a/venv/Lib/site-packages/urllib3/contrib/emscripten/request.py b/venv/Lib/site-packages/urllib3/contrib/emscripten/request.py new file mode 100644 index 00000000..e692e692 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/contrib/emscripten/request.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +from dataclasses import dataclass, field + +from ..._base_connection import _TYPE_BODY + + +@dataclass +class EmscriptenRequest: + method: str + url: str + params: dict[str, str] | None = None + body: _TYPE_BODY | None = None + headers: dict[str, str] = field(default_factory=dict) + timeout: float = 0 + decode_content: bool = True + + def set_header(self, name: str, value: str) -> None: + self.headers[name.capitalize()] = value + + def set_body(self, body: _TYPE_BODY | None) -> None: + self.body = body diff --git a/venv/Lib/site-packages/urllib3/contrib/emscripten/response.py b/venv/Lib/site-packages/urllib3/contrib/emscripten/response.py new file mode 100644 index 00000000..cb1088a1 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/contrib/emscripten/response.py @@ -0,0 +1,277 @@ +from __future__ import annotations + +import json as _json +import logging +import typing +from contextlib import contextmanager +from dataclasses import dataclass +from http.client import HTTPException as HTTPException +from io import BytesIO, IOBase + +from ...exceptions import InvalidHeader, TimeoutError +from ...response import BaseHTTPResponse +from ...util.retry import Retry +from .request import EmscriptenRequest + +if typing.TYPE_CHECKING: + from ..._base_connection import BaseHTTPConnection, BaseHTTPSConnection + +log = logging.getLogger(__name__) + + +@dataclass +class EmscriptenResponse: + status_code: int + headers: dict[str, str] + body: IOBase | bytes + request: EmscriptenRequest + + +class EmscriptenHttpResponseWrapper(BaseHTTPResponse): + def __init__( + self, + internal_response: EmscriptenResponse, + url: str | None = None, + connection: BaseHTTPConnection | BaseHTTPSConnection | None = None, + ): + self._pool = None # set by pool class + self._body = None + self._response = internal_response + self._url = url + self._connection = connection + self._closed = False + super().__init__( + headers=internal_response.headers, + status=internal_response.status_code, + request_url=url, + version=0, + version_string="HTTP/?", + reason="", + decode_content=True, + ) + self.length_remaining = self._init_length(self._response.request.method) + self.length_is_certain = False + + @property + def url(self) -> str | None: + return self._url + + @url.setter + def url(self, url: str | None) -> None: + self._url = url + + @property + def connection(self) -> BaseHTTPConnection | BaseHTTPSConnection | None: + return self._connection + + @property + def retries(self) -> Retry | None: + return self._retries + + @retries.setter + def retries(self, retries: Retry | None) -> None: + # Override the request_url if retries has a redirect location. + self._retries = retries + + def stream( + self, amt: int | None = 2**16, decode_content: bool | None = None + ) -> typing.Generator[bytes]: + """ + A generator wrapper for the read() method. A call will block until + ``amt`` bytes have been read from the connection or until the + connection is closed. + + :param amt: + How much of the content to read. The generator will return up to + much data per iteration, but may return less. This is particularly + likely when using compressed data. However, the empty string will + never be returned. + + :param decode_content: + If True, will attempt to decode the body based on the + 'content-encoding' header. + """ + while True: + data = self.read(amt=amt, decode_content=decode_content) + + if data: + yield data + else: + break + + def _init_length(self, request_method: str | None) -> int | None: + length: int | None + content_length: str | None = self.headers.get("content-length") + + if content_length is not None: + try: + # RFC 7230 section 3.3.2 specifies multiple content lengths can + # be sent in a single Content-Length header + # (e.g. Content-Length: 42, 42). This line ensures the values + # are all valid ints and that as long as the `set` length is 1, + # all values are the same. Otherwise, the header is invalid. + lengths = {int(val) for val in content_length.split(",")} + if len(lengths) > 1: + raise InvalidHeader( + "Content-Length contained multiple " + "unmatching values (%s)" % content_length + ) + length = lengths.pop() + except ValueError: + length = None + else: + if length < 0: + length = None + + else: # if content_length is None + length = None + + # Check for responses that shouldn't include a body + if ( + self.status in (204, 304) + or 100 <= self.status < 200 + or request_method == "HEAD" + ): + length = 0 + + return length + + def read( + self, + amt: int | None = None, + decode_content: bool | None = None, # ignored because browser decodes always + cache_content: bool = False, + ) -> bytes: + if ( + self._closed + or self._response is None + or (isinstance(self._response.body, IOBase) and self._response.body.closed) + ): + return b"" + + with self._error_catcher(): + # body has been preloaded as a string by XmlHttpRequest + if not isinstance(self._response.body, IOBase): + self.length_remaining = len(self._response.body) + self.length_is_certain = True + # wrap body in IOStream + self._response.body = BytesIO(self._response.body) + if amt is not None and amt >= 0: + # don't cache partial content + cache_content = False + data = self._response.body.read(amt) + else: # read all we can (and cache it) + data = self._response.body.read() + if cache_content: + self._body = data + if self.length_remaining is not None: + self.length_remaining = max(self.length_remaining - len(data), 0) + if len(data) == 0 or ( + self.length_is_certain and self.length_remaining == 0 + ): + # definitely finished reading, close response stream + self._response.body.close() + return typing.cast(bytes, data) + + def read_chunked( + self, + amt: int | None = None, + decode_content: bool | None = None, + ) -> typing.Generator[bytes]: + # chunked is handled by browser + while True: + bytes = self.read(amt, decode_content) + if not bytes: + break + yield bytes + + def release_conn(self) -> None: + if not self._pool or not self._connection: + return None + + self._pool._put_conn(self._connection) + self._connection = None + + def drain_conn(self) -> None: + self.close() + + @property + def data(self) -> bytes: + if self._body: + return self._body + else: + return self.read(cache_content=True) + + def json(self) -> typing.Any: + """ + Deserializes the body of the HTTP response as a Python object. + + The body of the HTTP response must be encoded using UTF-8, as per + `RFC 8529 Section 8.1 `_. + + To use a custom JSON decoder pass the result of :attr:`HTTPResponse.data` to + your custom decoder instead. + + If the body of the HTTP response is not decodable to UTF-8, a + `UnicodeDecodeError` will be raised. If the body of the HTTP response is not a + valid JSON document, a `json.JSONDecodeError` will be raised. + + Read more :ref:`here `. + + :returns: The body of the HTTP response as a Python object. + """ + data = self.data.decode("utf-8") + return _json.loads(data) + + def close(self) -> None: + if not self._closed: + if isinstance(self._response.body, IOBase): + self._response.body.close() + if self._connection: + self._connection.close() + self._connection = None + self._closed = True + + @contextmanager + def _error_catcher(self) -> typing.Generator[None]: + """ + Catch Emscripten specific exceptions thrown by fetch.py, + instead re-raising urllib3 variants, so that low-level exceptions + are not leaked in the high-level api. + + On exit, release the connection back to the pool. + """ + from .fetch import _RequestError, _TimeoutError # avoid circular import + + clean_exit = False + + try: + yield + # If no exception is thrown, we should avoid cleaning up + # unnecessarily. + clean_exit = True + except _TimeoutError as e: + raise TimeoutError(str(e)) + except _RequestError as e: + raise HTTPException(str(e)) + finally: + # If we didn't terminate cleanly, we need to throw away our + # connection. + if not clean_exit: + # The response may not be closed but we're not going to use it + # anymore so close it now + if ( + isinstance(self._response.body, IOBase) + and not self._response.body.closed + ): + self._response.body.close() + # release the connection back to the pool + self.release_conn() + else: + # If we have read everything from the response stream, + # return the connection back to the pool. + if ( + isinstance(self._response.body, IOBase) + and self._response.body.closed + ): + self.release_conn() diff --git a/venv/Lib/site-packages/urllib3/contrib/pyopenssl.py b/venv/Lib/site-packages/urllib3/contrib/pyopenssl.py new file mode 100644 index 00000000..3714500e --- /dev/null +++ b/venv/Lib/site-packages/urllib3/contrib/pyopenssl.py @@ -0,0 +1,564 @@ +""" +Module for using pyOpenSSL as a TLS backend. This module was relevant before +the standard library ``ssl`` module supported SNI, but now that we've dropped +support for Python 2.7 all relevant Python versions support SNI so +**this module is no longer recommended**. + +This needs the following packages installed: + +* `pyOpenSSL`_ (tested with 16.0.0) +* `cryptography`_ (minimum 1.3.4, from pyopenssl) +* `idna`_ (minimum 2.0) + +However, pyOpenSSL depends on cryptography, so while we use all three directly here we +end up having relatively few packages required. + +You can install them with the following command: + +.. code-block:: bash + + $ python -m pip install pyopenssl cryptography idna + +To activate certificate checking, call +:func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code +before you begin making HTTP requests. This can be done in a ``sitecustomize`` +module, or at any other time before your application begins using ``urllib3``, +like this: + +.. code-block:: python + + try: + import urllib3.contrib.pyopenssl + urllib3.contrib.pyopenssl.inject_into_urllib3() + except ImportError: + pass + +.. _pyopenssl: https://www.pyopenssl.org +.. _cryptography: https://cryptography.io +.. _idna: https://github.com/kjd/idna +""" + +from __future__ import annotations + +import OpenSSL.SSL # type: ignore[import-untyped] +from cryptography import x509 + +try: + from cryptography.x509 import UnsupportedExtension # type: ignore[attr-defined] +except ImportError: + # UnsupportedExtension is gone in cryptography >= 2.1.0 + class UnsupportedExtension(Exception): # type: ignore[no-redef] + pass + + +import logging +import ssl +import typing +from io import BytesIO +from socket import socket as socket_cls +from socket import timeout + +from .. import util + +if typing.TYPE_CHECKING: + from OpenSSL.crypto import X509 # type: ignore[import-untyped] + + +__all__ = ["inject_into_urllib3", "extract_from_urllib3"] + +# Map from urllib3 to PyOpenSSL compatible parameter-values. +_openssl_versions: dict[int, int] = { + util.ssl_.PROTOCOL_TLS: OpenSSL.SSL.SSLv23_METHOD, # type: ignore[attr-defined] + util.ssl_.PROTOCOL_TLS_CLIENT: OpenSSL.SSL.SSLv23_METHOD, # type: ignore[attr-defined] + ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD, +} + +if hasattr(ssl, "PROTOCOL_TLSv1_1") and hasattr(OpenSSL.SSL, "TLSv1_1_METHOD"): + _openssl_versions[ssl.PROTOCOL_TLSv1_1] = OpenSSL.SSL.TLSv1_1_METHOD + +if hasattr(ssl, "PROTOCOL_TLSv1_2") and hasattr(OpenSSL.SSL, "TLSv1_2_METHOD"): + _openssl_versions[ssl.PROTOCOL_TLSv1_2] = OpenSSL.SSL.TLSv1_2_METHOD + + +_stdlib_to_openssl_verify = { + ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE, + ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER, + ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER + + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT, +} +_openssl_to_stdlib_verify = {v: k for k, v in _stdlib_to_openssl_verify.items()} + +# The SSLvX values are the most likely to be missing in the future +# but we check them all just to be sure. +_OP_NO_SSLv2_OR_SSLv3: int = getattr(OpenSSL.SSL, "OP_NO_SSLv2", 0) | getattr( + OpenSSL.SSL, "OP_NO_SSLv3", 0 +) +_OP_NO_TLSv1: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1", 0) +_OP_NO_TLSv1_1: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1_1", 0) +_OP_NO_TLSv1_2: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1_2", 0) +_OP_NO_TLSv1_3: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1_3", 0) + +_openssl_to_ssl_minimum_version: dict[int, int] = { + ssl.TLSVersion.MINIMUM_SUPPORTED: _OP_NO_SSLv2_OR_SSLv3, + ssl.TLSVersion.TLSv1: _OP_NO_SSLv2_OR_SSLv3, + ssl.TLSVersion.TLSv1_1: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1, + ssl.TLSVersion.TLSv1_2: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1 | _OP_NO_TLSv1_1, + ssl.TLSVersion.TLSv1_3: ( + _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1 | _OP_NO_TLSv1_1 | _OP_NO_TLSv1_2 + ), + ssl.TLSVersion.MAXIMUM_SUPPORTED: ( + _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1 | _OP_NO_TLSv1_1 | _OP_NO_TLSv1_2 + ), +} +_openssl_to_ssl_maximum_version: dict[int, int] = { + ssl.TLSVersion.MINIMUM_SUPPORTED: ( + _OP_NO_SSLv2_OR_SSLv3 + | _OP_NO_TLSv1 + | _OP_NO_TLSv1_1 + | _OP_NO_TLSv1_2 + | _OP_NO_TLSv1_3 + ), + ssl.TLSVersion.TLSv1: ( + _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1_1 | _OP_NO_TLSv1_2 | _OP_NO_TLSv1_3 + ), + ssl.TLSVersion.TLSv1_1: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1_2 | _OP_NO_TLSv1_3, + ssl.TLSVersion.TLSv1_2: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1_3, + ssl.TLSVersion.TLSv1_3: _OP_NO_SSLv2_OR_SSLv3, + ssl.TLSVersion.MAXIMUM_SUPPORTED: _OP_NO_SSLv2_OR_SSLv3, +} + +# OpenSSL will only write 16K at a time +SSL_WRITE_BLOCKSIZE = 16384 + +orig_util_SSLContext = util.ssl_.SSLContext + + +log = logging.getLogger(__name__) + + +def inject_into_urllib3() -> None: + "Monkey-patch urllib3 with PyOpenSSL-backed SSL-support." + + _validate_dependencies_met() + + util.SSLContext = PyOpenSSLContext # type: ignore[assignment] + util.ssl_.SSLContext = PyOpenSSLContext # type: ignore[assignment] + util.IS_PYOPENSSL = True + util.ssl_.IS_PYOPENSSL = True + + +def extract_from_urllib3() -> None: + "Undo monkey-patching by :func:`inject_into_urllib3`." + + util.SSLContext = orig_util_SSLContext + util.ssl_.SSLContext = orig_util_SSLContext + util.IS_PYOPENSSL = False + util.ssl_.IS_PYOPENSSL = False + + +def _validate_dependencies_met() -> None: + """ + Verifies that PyOpenSSL's package-level dependencies have been met. + Throws `ImportError` if they are not met. + """ + # Method added in `cryptography==1.1`; not available in older versions + from cryptography.x509.extensions import Extensions + + if getattr(Extensions, "get_extension_for_class", None) is None: + raise ImportError( + "'cryptography' module missing required functionality. " + "Try upgrading to v1.3.4 or newer." + ) + + # pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509 + # attribute is only present on those versions. + from OpenSSL.crypto import X509 + + x509 = X509() + if getattr(x509, "_x509", None) is None: + raise ImportError( + "'pyOpenSSL' module missing required functionality. " + "Try upgrading to v0.14 or newer." + ) + + +def _dnsname_to_stdlib(name: str) -> str | None: + """ + Converts a dNSName SubjectAlternativeName field to the form used by the + standard library on the given Python version. + + Cryptography produces a dNSName as a unicode string that was idna-decoded + from ASCII bytes. We need to idna-encode that string to get it back, and + then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib + uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8). + + If the name cannot be idna-encoded then we return None signalling that + the name given should be skipped. + """ + + def idna_encode(name: str) -> bytes | None: + """ + Borrowed wholesale from the Python Cryptography Project. It turns out + that we can't just safely call `idna.encode`: it can explode for + wildcard names. This avoids that problem. + """ + import idna + + try: + for prefix in ["*.", "."]: + if name.startswith(prefix): + name = name[len(prefix) :] + return prefix.encode("ascii") + idna.encode(name) + return idna.encode(name) + except idna.core.IDNAError: + return None + + # Don't send IPv6 addresses through the IDNA encoder. + if ":" in name: + return name + + encoded_name = idna_encode(name) + if encoded_name is None: + return None + return encoded_name.decode("utf-8") + + +def get_subj_alt_name(peer_cert: X509) -> list[tuple[str, str]]: + """ + Given an PyOpenSSL certificate, provides all the subject alternative names. + """ + cert = peer_cert.to_cryptography() + + # We want to find the SAN extension. Ask Cryptography to locate it (it's + # faster than looping in Python) + try: + ext = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value + except x509.ExtensionNotFound: + # No such extension, return the empty list. + return [] + except ( + x509.DuplicateExtension, + UnsupportedExtension, + x509.UnsupportedGeneralNameType, + UnicodeError, + ) as e: + # A problem has been found with the quality of the certificate. Assume + # no SAN field is present. + log.warning( + "A problem was encountered with the certificate that prevented " + "urllib3 from finding the SubjectAlternativeName field. This can " + "affect certificate validation. The error was %s", + e, + ) + return [] + + # We want to return dNSName and iPAddress fields. We need to cast the IPs + # back to strings because the match_hostname function wants them as + # strings. + # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 + # decoded. This is pretty frustrating, but that's what the standard library + # does with certificates, and so we need to attempt to do the same. + # We also want to skip over names which cannot be idna encoded. + names = [ + ("DNS", name) + for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName)) + if name is not None + ] + names.extend( + ("IP Address", str(name)) for name in ext.get_values_for_type(x509.IPAddress) + ) + + return names + + +class WrappedSocket: + """API-compatibility wrapper for Python OpenSSL's Connection-class.""" + + def __init__( + self, + connection: OpenSSL.SSL.Connection, + socket: socket_cls, + suppress_ragged_eofs: bool = True, + ) -> None: + self.connection = connection + self.socket = socket + self.suppress_ragged_eofs = suppress_ragged_eofs + self._io_refs = 0 + self._closed = False + + def fileno(self) -> int: + return self.socket.fileno() + + # Copy-pasted from Python 3.5 source code + def _decref_socketios(self) -> None: + if self._io_refs > 0: + self._io_refs -= 1 + if self._closed: + self.close() + + def recv(self, *args: typing.Any, **kwargs: typing.Any) -> bytes: + try: + data = self.connection.recv(*args, **kwargs) + except OpenSSL.SSL.SysCallError as e: + if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"): + return b"" + else: + raise OSError(e.args[0], str(e)) from e + except OpenSSL.SSL.ZeroReturnError: + if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: + return b"" + else: + raise + except OpenSSL.SSL.WantReadError as e: + if not util.wait_for_read(self.socket, self.socket.gettimeout()): + raise timeout("The read operation timed out") from e + else: + return self.recv(*args, **kwargs) + + # TLS 1.3 post-handshake authentication + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"read error: {e!r}") from e + else: + return data # type: ignore[no-any-return] + + def recv_into(self, *args: typing.Any, **kwargs: typing.Any) -> int: + try: + return self.connection.recv_into(*args, **kwargs) # type: ignore[no-any-return] + except OpenSSL.SSL.SysCallError as e: + if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"): + return 0 + else: + raise OSError(e.args[0], str(e)) from e + except OpenSSL.SSL.ZeroReturnError: + if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: + return 0 + else: + raise + except OpenSSL.SSL.WantReadError as e: + if not util.wait_for_read(self.socket, self.socket.gettimeout()): + raise timeout("The read operation timed out") from e + else: + return self.recv_into(*args, **kwargs) + + # TLS 1.3 post-handshake authentication + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"read error: {e!r}") from e + + def settimeout(self, timeout: float) -> None: + return self.socket.settimeout(timeout) + + def _send_until_done(self, data: bytes) -> int: + while True: + try: + return self.connection.send(data) # type: ignore[no-any-return] + except OpenSSL.SSL.WantWriteError as e: + if not util.wait_for_write(self.socket, self.socket.gettimeout()): + raise timeout() from e + continue + except OpenSSL.SSL.SysCallError as e: + raise OSError(e.args[0], str(e)) from e + + def sendall(self, data: bytes) -> None: + total_sent = 0 + while total_sent < len(data): + sent = self._send_until_done( + data[total_sent : total_sent + SSL_WRITE_BLOCKSIZE] + ) + total_sent += sent + + def shutdown(self, how: int) -> None: + try: + self.connection.shutdown() + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"shutdown error: {e!r}") from e + + def close(self) -> None: + self._closed = True + if self._io_refs <= 0: + self._real_close() + + def _real_close(self) -> None: + try: + return self.connection.close() # type: ignore[no-any-return] + except OpenSSL.SSL.Error: + return + + def getpeercert( + self, binary_form: bool = False + ) -> dict[str, list[typing.Any]] | None: + x509 = self.connection.get_peer_certificate() + + if not x509: + return x509 # type: ignore[no-any-return] + + if binary_form: + return OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, x509) # type: ignore[no-any-return] + + return { + "subject": ((("commonName", x509.get_subject().CN),),), # type: ignore[dict-item] + "subjectAltName": get_subj_alt_name(x509), + } + + def version(self) -> str: + return self.connection.get_protocol_version_name() # type: ignore[no-any-return] + + def selected_alpn_protocol(self) -> str | None: + alpn_proto = self.connection.get_alpn_proto_negotiated() + return alpn_proto.decode() if alpn_proto else None + + +WrappedSocket.makefile = socket_cls.makefile # type: ignore[attr-defined] + + +class PyOpenSSLContext: + """ + I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible + for translating the interface of the standard library ``SSLContext`` object + to calls into PyOpenSSL. + """ + + def __init__(self, protocol: int) -> None: + self.protocol = _openssl_versions[protocol] + self._ctx = OpenSSL.SSL.Context(self.protocol) + self._options = 0 + self.check_hostname = False + self._minimum_version: int = ssl.TLSVersion.MINIMUM_SUPPORTED + self._maximum_version: int = ssl.TLSVersion.MAXIMUM_SUPPORTED + self._verify_flags: int = ssl.VERIFY_X509_TRUSTED_FIRST + + @property + def options(self) -> int: + return self._options + + @options.setter + def options(self, value: int) -> None: + self._options = value + self._set_ctx_options() + + @property + def verify_flags(self) -> int: + return self._verify_flags + + @verify_flags.setter + def verify_flags(self, value: int) -> None: + self._verify_flags = value + self._ctx.get_cert_store().set_flags(self._verify_flags) + + @property + def verify_mode(self) -> int: + return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()] + + @verify_mode.setter + def verify_mode(self, value: ssl.VerifyMode) -> None: + self._ctx.set_verify(_stdlib_to_openssl_verify[value], _verify_callback) + + def set_default_verify_paths(self) -> None: + self._ctx.set_default_verify_paths() + + def set_ciphers(self, ciphers: bytes | str) -> None: + if isinstance(ciphers, str): + ciphers = ciphers.encode("utf-8") + self._ctx.set_cipher_list(ciphers) + + def load_verify_locations( + self, + cafile: str | None = None, + capath: str | None = None, + cadata: bytes | None = None, + ) -> None: + if cafile is not None: + cafile = cafile.encode("utf-8") # type: ignore[assignment] + if capath is not None: + capath = capath.encode("utf-8") # type: ignore[assignment] + try: + self._ctx.load_verify_locations(cafile, capath) + if cadata is not None: + self._ctx.load_verify_locations(BytesIO(cadata)) + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"unable to load trusted certificates: {e!r}") from e + + def load_cert_chain( + self, + certfile: str, + keyfile: str | None = None, + password: str | None = None, + ) -> None: + try: + self._ctx.use_certificate_chain_file(certfile) + if password is not None: + if not isinstance(password, bytes): + password = password.encode("utf-8") # type: ignore[assignment] + self._ctx.set_passwd_cb(lambda *_: password) + self._ctx.use_privatekey_file(keyfile or certfile) + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"Unable to load certificate chain: {e!r}") from e + + def set_alpn_protocols(self, protocols: list[bytes | str]) -> None: + protocols = [util.util.to_bytes(p, "ascii") for p in protocols] + return self._ctx.set_alpn_protos(protocols) # type: ignore[no-any-return] + + def wrap_socket( + self, + sock: socket_cls, + server_side: bool = False, + do_handshake_on_connect: bool = True, + suppress_ragged_eofs: bool = True, + server_hostname: bytes | str | None = None, + ) -> WrappedSocket: + cnx = OpenSSL.SSL.Connection(self._ctx, sock) + + # If server_hostname is an IP, don't use it for SNI, per RFC6066 Section 3 + if server_hostname and not util.ssl_.is_ipaddress(server_hostname): + if isinstance(server_hostname, str): + server_hostname = server_hostname.encode("utf-8") + cnx.set_tlsext_host_name(server_hostname) + + cnx.set_connect_state() + + while True: + try: + cnx.do_handshake() + except OpenSSL.SSL.WantReadError as e: + if not util.wait_for_read(sock, sock.gettimeout()): + raise timeout("select timed out") from e + continue + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"bad handshake: {e!r}") from e + break + + return WrappedSocket(cnx, sock) + + def _set_ctx_options(self) -> None: + self._ctx.set_options( + self._options + | _openssl_to_ssl_minimum_version[self._minimum_version] + | _openssl_to_ssl_maximum_version[self._maximum_version] + ) + + @property + def minimum_version(self) -> int: + return self._minimum_version + + @minimum_version.setter + def minimum_version(self, minimum_version: int) -> None: + self._minimum_version = minimum_version + self._set_ctx_options() + + @property + def maximum_version(self) -> int: + return self._maximum_version + + @maximum_version.setter + def maximum_version(self, maximum_version: int) -> None: + self._maximum_version = maximum_version + self._set_ctx_options() + + +def _verify_callback( + cnx: OpenSSL.SSL.Connection, + x509: X509, + err_no: int, + err_depth: int, + return_code: int, +) -> bool: + return err_no == 0 diff --git a/venv/Lib/site-packages/urllib3/contrib/socks.py b/venv/Lib/site-packages/urllib3/contrib/socks.py new file mode 100644 index 00000000..c62b5e03 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/contrib/socks.py @@ -0,0 +1,228 @@ +""" +This module contains provisional support for SOCKS proxies from within +urllib3. This module supports SOCKS4, SOCKS4A (an extension of SOCKS4), and +SOCKS5. To enable its functionality, either install PySocks or install this +module with the ``socks`` extra. + +The SOCKS implementation supports the full range of urllib3 features. It also +supports the following SOCKS features: + +- SOCKS4A (``proxy_url='socks4a://...``) +- SOCKS4 (``proxy_url='socks4://...``) +- SOCKS5 with remote DNS (``proxy_url='socks5h://...``) +- SOCKS5 with local DNS (``proxy_url='socks5://...``) +- Usernames and passwords for the SOCKS proxy + +.. note:: + It is recommended to use ``socks5h://`` or ``socks4a://`` schemes in + your ``proxy_url`` to ensure that DNS resolution is done from the remote + server instead of client-side when connecting to a domain name. + +SOCKS4 supports IPv4 and domain names with the SOCKS4A extension. SOCKS5 +supports IPv4, IPv6, and domain names. + +When connecting to a SOCKS4 proxy the ``username`` portion of the ``proxy_url`` +will be sent as the ``userid`` section of the SOCKS request: + +.. code-block:: python + + proxy_url="socks4a://@proxy-host" + +When connecting to a SOCKS5 proxy the ``username`` and ``password`` portion +of the ``proxy_url`` will be sent as the username/password to authenticate +with the proxy: + +.. code-block:: python + + proxy_url="socks5h://:@proxy-host" + +""" + +from __future__ import annotations + +try: + import socks # type: ignore[import-not-found] +except ImportError: + import warnings + + from ..exceptions import DependencyWarning + + warnings.warn( + ( + "SOCKS support in urllib3 requires the installation of optional " + "dependencies: specifically, PySocks. For more information, see " + "https://urllib3.readthedocs.io/en/latest/advanced-usage.html#socks-proxies" + ), + DependencyWarning, + ) + raise + +import typing +from socket import timeout as SocketTimeout + +from ..connection import HTTPConnection, HTTPSConnection +from ..connectionpool import HTTPConnectionPool, HTTPSConnectionPool +from ..exceptions import ConnectTimeoutError, NewConnectionError +from ..poolmanager import PoolManager +from ..util.url import parse_url + +try: + import ssl +except ImportError: + ssl = None # type: ignore[assignment] + + +class _TYPE_SOCKS_OPTIONS(typing.TypedDict): + socks_version: int + proxy_host: str | None + proxy_port: str | None + username: str | None + password: str | None + rdns: bool + + +class SOCKSConnection(HTTPConnection): + """ + A plain-text HTTP connection that connects via a SOCKS proxy. + """ + + def __init__( + self, + _socks_options: _TYPE_SOCKS_OPTIONS, + *args: typing.Any, + **kwargs: typing.Any, + ) -> None: + self._socks_options = _socks_options + super().__init__(*args, **kwargs) + + def _new_conn(self) -> socks.socksocket: + """ + Establish a new connection via the SOCKS proxy. + """ + extra_kw: dict[str, typing.Any] = {} + if self.source_address: + extra_kw["source_address"] = self.source_address + + if self.socket_options: + extra_kw["socket_options"] = self.socket_options + + try: + conn = socks.create_connection( + (self.host, self.port), + proxy_type=self._socks_options["socks_version"], + proxy_addr=self._socks_options["proxy_host"], + proxy_port=self._socks_options["proxy_port"], + proxy_username=self._socks_options["username"], + proxy_password=self._socks_options["password"], + proxy_rdns=self._socks_options["rdns"], + timeout=self.timeout, + **extra_kw, + ) + + except SocketTimeout as e: + raise ConnectTimeoutError( + self, + f"Connection to {self.host} timed out. (connect timeout={self.timeout})", + ) from e + + except socks.ProxyError as e: + # This is fragile as hell, but it seems to be the only way to raise + # useful errors here. + if e.socket_err: + error = e.socket_err + if isinstance(error, SocketTimeout): + raise ConnectTimeoutError( + self, + f"Connection to {self.host} timed out. (connect timeout={self.timeout})", + ) from e + else: + # Adding `from e` messes with coverage somehow, so it's omitted. + # See #2386. + raise NewConnectionError( + self, f"Failed to establish a new connection: {error}" + ) + else: + raise NewConnectionError( + self, f"Failed to establish a new connection: {e}" + ) from e + + except OSError as e: # Defensive: PySocks should catch all these. + raise NewConnectionError( + self, f"Failed to establish a new connection: {e}" + ) from e + + return conn + + +# We don't need to duplicate the Verified/Unverified distinction from +# urllib3/connection.py here because the HTTPSConnection will already have been +# correctly set to either the Verified or Unverified form by that module. This +# means the SOCKSHTTPSConnection will automatically be the correct type. +class SOCKSHTTPSConnection(SOCKSConnection, HTTPSConnection): + pass + + +class SOCKSHTTPConnectionPool(HTTPConnectionPool): + ConnectionCls = SOCKSConnection + + +class SOCKSHTTPSConnectionPool(HTTPSConnectionPool): + ConnectionCls = SOCKSHTTPSConnection + + +class SOCKSProxyManager(PoolManager): + """ + A version of the urllib3 ProxyManager that routes connections via the + defined SOCKS proxy. + """ + + pool_classes_by_scheme = { + "http": SOCKSHTTPConnectionPool, + "https": SOCKSHTTPSConnectionPool, + } + + def __init__( + self, + proxy_url: str, + username: str | None = None, + password: str | None = None, + num_pools: int = 10, + headers: typing.Mapping[str, str] | None = None, + **connection_pool_kw: typing.Any, + ): + parsed = parse_url(proxy_url) + + if username is None and password is None and parsed.auth is not None: + split = parsed.auth.split(":") + if len(split) == 2: + username, password = split + if parsed.scheme == "socks5": + socks_version = socks.PROXY_TYPE_SOCKS5 + rdns = False + elif parsed.scheme == "socks5h": + socks_version = socks.PROXY_TYPE_SOCKS5 + rdns = True + elif parsed.scheme == "socks4": + socks_version = socks.PROXY_TYPE_SOCKS4 + rdns = False + elif parsed.scheme == "socks4a": + socks_version = socks.PROXY_TYPE_SOCKS4 + rdns = True + else: + raise ValueError(f"Unable to determine SOCKS version from {proxy_url}") + + self.proxy_url = proxy_url + + socks_options = { + "socks_version": socks_version, + "proxy_host": parsed.host, + "proxy_port": parsed.port, + "username": username, + "password": password, + "rdns": rdns, + } + connection_pool_kw["_socks_options"] = socks_options + + super().__init__(num_pools, headers, **connection_pool_kw) + + self.pool_classes_by_scheme = SOCKSProxyManager.pool_classes_by_scheme diff --git a/venv/Lib/site-packages/urllib3/exceptions.py b/venv/Lib/site-packages/urllib3/exceptions.py new file mode 100644 index 00000000..a0de9d6c --- /dev/null +++ b/venv/Lib/site-packages/urllib3/exceptions.py @@ -0,0 +1,335 @@ +from __future__ import annotations + +import socket +import typing +import warnings +from email.errors import MessageDefect +from http.client import IncompleteRead as httplib_IncompleteRead + +if typing.TYPE_CHECKING: + from .connection import HTTPConnection + from .connectionpool import ConnectionPool + from .response import HTTPResponse + from .util.retry import Retry + +# Base Exceptions + + +class HTTPError(Exception): + """Base exception used by this module.""" + + +class HTTPWarning(Warning): + """Base warning used by this module.""" + + +_TYPE_REDUCE_RESULT = tuple[typing.Callable[..., object], tuple[object, ...]] + + +class PoolError(HTTPError): + """Base exception for errors caused within a pool.""" + + def __init__(self, pool: ConnectionPool, message: str) -> None: + self.pool = pool + self._message = message + super().__init__(f"{pool}: {message}") + + def __reduce__(self) -> _TYPE_REDUCE_RESULT: + # For pickling purposes. + return self.__class__, (None, self._message) + + +class RequestError(PoolError): + """Base exception for PoolErrors that have associated URLs.""" + + def __init__(self, pool: ConnectionPool, url: str, message: str) -> None: + self.url = url + super().__init__(pool, message) + + def __reduce__(self) -> _TYPE_REDUCE_RESULT: + # For pickling purposes. + return self.__class__, (None, self.url, self._message) + + +class SSLError(HTTPError): + """Raised when SSL certificate fails in an HTTPS connection.""" + + +class ProxyError(HTTPError): + """Raised when the connection to a proxy fails.""" + + # The original error is also available as __cause__. + original_error: Exception + + def __init__(self, message: str, error: Exception) -> None: + super().__init__(message, error) + self.original_error = error + + +class DecodeError(HTTPError): + """Raised when automatic decoding based on Content-Type fails.""" + + +class ProtocolError(HTTPError): + """Raised when something unexpected happens mid-request/response.""" + + +#: Renamed to ProtocolError but aliased for backwards compatibility. +ConnectionError = ProtocolError + + +# Leaf Exceptions + + +class MaxRetryError(RequestError): + """Raised when the maximum number of retries is exceeded. + + :param pool: The connection pool + :type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool` + :param str url: The requested Url + :param reason: The underlying error + :type reason: :class:`Exception` + + """ + + def __init__( + self, pool: ConnectionPool, url: str, reason: Exception | None = None + ) -> None: + self.reason = reason + + message = f"Max retries exceeded with url: {url} (Caused by {reason!r})" + + super().__init__(pool, url, message) + + def __reduce__(self) -> _TYPE_REDUCE_RESULT: + # For pickling purposes. + return self.__class__, (None, self.url, self.reason) + + +class HostChangedError(RequestError): + """Raised when an existing pool gets a request for a foreign host.""" + + def __init__( + self, pool: ConnectionPool, url: str, retries: Retry | int = 3 + ) -> None: + message = f"Tried to open a foreign host with url: {url}" + super().__init__(pool, url, message) + self.retries = retries + + +class TimeoutStateError(HTTPError): + """Raised when passing an invalid state to a timeout""" + + +class TimeoutError(HTTPError): + """Raised when a socket timeout error occurs. + + Catching this error will catch both :exc:`ReadTimeoutErrors + ` and :exc:`ConnectTimeoutErrors `. + """ + + +class ReadTimeoutError(TimeoutError, RequestError): + """Raised when a socket timeout occurs while receiving data from a server""" + + +# This timeout error does not have a URL attached and needs to inherit from the +# base HTTPError +class ConnectTimeoutError(TimeoutError): + """Raised when a socket timeout occurs while connecting to a server""" + + +class NewConnectionError(ConnectTimeoutError, HTTPError): + """Raised when we fail to establish a new connection. Usually ECONNREFUSED.""" + + def __init__(self, conn: HTTPConnection, message: str) -> None: + self.conn = conn + self._message = message + super().__init__(f"{conn}: {message}") + + def __reduce__(self) -> _TYPE_REDUCE_RESULT: + # For pickling purposes. + return self.__class__, (None, self._message) + + @property + def pool(self) -> HTTPConnection: + warnings.warn( + "The 'pool' property is deprecated and will be removed " + "in urllib3 v2.1.0. Use 'conn' instead.", + DeprecationWarning, + stacklevel=2, + ) + + return self.conn + + +class NameResolutionError(NewConnectionError): + """Raised when host name resolution fails.""" + + def __init__(self, host: str, conn: HTTPConnection, reason: socket.gaierror): + message = f"Failed to resolve '{host}' ({reason})" + self._host = host + self._reason = reason + super().__init__(conn, message) + + def __reduce__(self) -> _TYPE_REDUCE_RESULT: + # For pickling purposes. + return self.__class__, (self._host, None, self._reason) + + +class EmptyPoolError(PoolError): + """Raised when a pool runs out of connections and no more are allowed.""" + + +class FullPoolError(PoolError): + """Raised when we try to add a connection to a full pool in blocking mode.""" + + +class ClosedPoolError(PoolError): + """Raised when a request enters a pool after the pool has been closed.""" + + +class LocationValueError(ValueError, HTTPError): + """Raised when there is something wrong with a given URL input.""" + + +class LocationParseError(LocationValueError): + """Raised when get_host or similar fails to parse the URL input.""" + + def __init__(self, location: str) -> None: + message = f"Failed to parse: {location}" + super().__init__(message) + + self.location = location + + +class URLSchemeUnknown(LocationValueError): + """Raised when a URL input has an unsupported scheme.""" + + def __init__(self, scheme: str): + message = f"Not supported URL scheme {scheme}" + super().__init__(message) + + self.scheme = scheme + + +class ResponseError(HTTPError): + """Used as a container for an error reason supplied in a MaxRetryError.""" + + GENERIC_ERROR = "too many error responses" + SPECIFIC_ERROR = "too many {status_code} error responses" + + +class SecurityWarning(HTTPWarning): + """Warned when performing security reducing actions""" + + +class InsecureRequestWarning(SecurityWarning): + """Warned when making an unverified HTTPS request.""" + + +class NotOpenSSLWarning(SecurityWarning): + """Warned when using unsupported SSL library""" + + +class SystemTimeWarning(SecurityWarning): + """Warned when system time is suspected to be wrong""" + + +class InsecurePlatformWarning(SecurityWarning): + """Warned when certain TLS/SSL configuration is not available on a platform.""" + + +class DependencyWarning(HTTPWarning): + """ + Warned when an attempt is made to import a module with missing optional + dependencies. + """ + + +class ResponseNotChunked(ProtocolError, ValueError): + """Response needs to be chunked in order to read it as chunks.""" + + +class BodyNotHttplibCompatible(HTTPError): + """ + Body should be :class:`http.client.HTTPResponse` like + (have an fp attribute which returns raw chunks) for read_chunked(). + """ + + +class IncompleteRead(HTTPError, httplib_IncompleteRead): + """ + Response length doesn't match expected Content-Length + + Subclass of :class:`http.client.IncompleteRead` to allow int value + for ``partial`` to avoid creating large objects on streamed reads. + """ + + partial: int # type: ignore[assignment] + expected: int + + def __init__(self, partial: int, expected: int) -> None: + self.partial = partial + self.expected = expected + + def __repr__(self) -> str: + return "IncompleteRead(%i bytes read, %i more expected)" % ( + self.partial, + self.expected, + ) + + +class InvalidChunkLength(HTTPError, httplib_IncompleteRead): + """Invalid chunk length in a chunked response.""" + + def __init__(self, response: HTTPResponse, length: bytes) -> None: + self.partial: int = response.tell() # type: ignore[assignment] + self.expected: int | None = response.length_remaining + self.response = response + self.length = length + + def __repr__(self) -> str: + return "InvalidChunkLength(got length %r, %i bytes read)" % ( + self.length, + self.partial, + ) + + +class InvalidHeader(HTTPError): + """The header provided was somehow invalid.""" + + +class ProxySchemeUnknown(AssertionError, URLSchemeUnknown): + """ProxyManager does not support the supplied scheme""" + + # TODO(t-8ch): Stop inheriting from AssertionError in v2.0. + + def __init__(self, scheme: str | None) -> None: + # 'localhost' is here because our URL parser parses + # localhost:8080 -> scheme=localhost, remove if we fix this. + if scheme == "localhost": + scheme = None + if scheme is None: + message = "Proxy URL had no scheme, should start with http:// or https://" + else: + message = f"Proxy URL had unsupported scheme {scheme}, should use http:// or https://" + super().__init__(message) + + +class ProxySchemeUnsupported(ValueError): + """Fetching HTTPS resources through HTTPS proxies is unsupported""" + + +class HeaderParsingError(HTTPError): + """Raised by assert_header_parsing, but we convert it to a log.warning statement.""" + + def __init__( + self, defects: list[MessageDefect], unparsed_data: bytes | str | None + ) -> None: + message = f"{defects or 'Unknown'}, unparsed data: {unparsed_data!r}" + super().__init__(message) + + +class UnrewindableBodyError(HTTPError): + """urllib3 encountered an error when trying to rewind a body""" diff --git a/venv/Lib/site-packages/urllib3/fields.py b/venv/Lib/site-packages/urllib3/fields.py new file mode 100644 index 00000000..97c4730c --- /dev/null +++ b/venv/Lib/site-packages/urllib3/fields.py @@ -0,0 +1,341 @@ +from __future__ import annotations + +import email.utils +import mimetypes +import typing + +_TYPE_FIELD_VALUE = typing.Union[str, bytes] +_TYPE_FIELD_VALUE_TUPLE = typing.Union[ + _TYPE_FIELD_VALUE, + tuple[str, _TYPE_FIELD_VALUE], + tuple[str, _TYPE_FIELD_VALUE, str], +] + + +def guess_content_type( + filename: str | None, default: str = "application/octet-stream" +) -> str: + """ + Guess the "Content-Type" of a file. + + :param filename: + The filename to guess the "Content-Type" of using :mod:`mimetypes`. + :param default: + If no "Content-Type" can be guessed, default to `default`. + """ + if filename: + return mimetypes.guess_type(filename)[0] or default + return default + + +def format_header_param_rfc2231(name: str, value: _TYPE_FIELD_VALUE) -> str: + """ + Helper function to format and quote a single header parameter using the + strategy defined in RFC 2231. + + Particularly useful for header parameters which might contain + non-ASCII values, like file names. This follows + `RFC 2388 Section 4.4 `_. + + :param name: + The name of the parameter, a string expected to be ASCII only. + :param value: + The value of the parameter, provided as ``bytes`` or `str``. + :returns: + An RFC-2231-formatted unicode string. + + .. deprecated:: 2.0.0 + Will be removed in urllib3 v2.1.0. This is not valid for + ``multipart/form-data`` header parameters. + """ + import warnings + + warnings.warn( + "'format_header_param_rfc2231' is deprecated and will be " + "removed in urllib3 v2.1.0. This is not valid for " + "multipart/form-data header parameters.", + DeprecationWarning, + stacklevel=2, + ) + + if isinstance(value, bytes): + value = value.decode("utf-8") + + if not any(ch in value for ch in '"\\\r\n'): + result = f'{name}="{value}"' + try: + result.encode("ascii") + except (UnicodeEncodeError, UnicodeDecodeError): + pass + else: + return result + + value = email.utils.encode_rfc2231(value, "utf-8") + value = f"{name}*={value}" + + return value + + +def format_multipart_header_param(name: str, value: _TYPE_FIELD_VALUE) -> str: + """ + Format and quote a single multipart header parameter. + + This follows the `WHATWG HTML Standard`_ as of 2021/06/10, matching + the behavior of current browser and curl versions. Values are + assumed to be UTF-8. The ``\\n``, ``\\r``, and ``"`` characters are + percent encoded. + + .. _WHATWG HTML Standard: + https://html.spec.whatwg.org/multipage/ + form-control-infrastructure.html#multipart-form-data + + :param name: + The name of the parameter, an ASCII-only ``str``. + :param value: + The value of the parameter, a ``str`` or UTF-8 encoded + ``bytes``. + :returns: + A string ``name="value"`` with the escaped value. + + .. versionchanged:: 2.0.0 + Matches the WHATWG HTML Standard as of 2021/06/10. Control + characters are no longer percent encoded. + + .. versionchanged:: 2.0.0 + Renamed from ``format_header_param_html5`` and + ``format_header_param``. The old names will be removed in + urllib3 v2.1.0. + """ + if isinstance(value, bytes): + value = value.decode("utf-8") + + # percent encode \n \r " + value = value.translate({10: "%0A", 13: "%0D", 34: "%22"}) + return f'{name}="{value}"' + + +def format_header_param_html5(name: str, value: _TYPE_FIELD_VALUE) -> str: + """ + .. deprecated:: 2.0.0 + Renamed to :func:`format_multipart_header_param`. Will be + removed in urllib3 v2.1.0. + """ + import warnings + + warnings.warn( + "'format_header_param_html5' has been renamed to " + "'format_multipart_header_param'. The old name will be " + "removed in urllib3 v2.1.0.", + DeprecationWarning, + stacklevel=2, + ) + return format_multipart_header_param(name, value) + + +def format_header_param(name: str, value: _TYPE_FIELD_VALUE) -> str: + """ + .. deprecated:: 2.0.0 + Renamed to :func:`format_multipart_header_param`. Will be + removed in urllib3 v2.1.0. + """ + import warnings + + warnings.warn( + "'format_header_param' has been renamed to " + "'format_multipart_header_param'. The old name will be " + "removed in urllib3 v2.1.0.", + DeprecationWarning, + stacklevel=2, + ) + return format_multipart_header_param(name, value) + + +class RequestField: + """ + A data container for request body parameters. + + :param name: + The name of this request field. Must be unicode. + :param data: + The data/value body. + :param filename: + An optional filename of the request field. Must be unicode. + :param headers: + An optional dict-like object of headers to initially use for the field. + + .. versionchanged:: 2.0.0 + The ``header_formatter`` parameter is deprecated and will + be removed in urllib3 v2.1.0. + """ + + def __init__( + self, + name: str, + data: _TYPE_FIELD_VALUE, + filename: str | None = None, + headers: typing.Mapping[str, str] | None = None, + header_formatter: typing.Callable[[str, _TYPE_FIELD_VALUE], str] | None = None, + ): + self._name = name + self._filename = filename + self.data = data + self.headers: dict[str, str | None] = {} + if headers: + self.headers = dict(headers) + + if header_formatter is not None: + import warnings + + warnings.warn( + "The 'header_formatter' parameter is deprecated and " + "will be removed in urllib3 v2.1.0.", + DeprecationWarning, + stacklevel=2, + ) + self.header_formatter = header_formatter + else: + self.header_formatter = format_multipart_header_param + + @classmethod + def from_tuples( + cls, + fieldname: str, + value: _TYPE_FIELD_VALUE_TUPLE, + header_formatter: typing.Callable[[str, _TYPE_FIELD_VALUE], str] | None = None, + ) -> RequestField: + """ + A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters. + + Supports constructing :class:`~urllib3.fields.RequestField` from + parameter of key/value strings AND key/filetuple. A filetuple is a + (filename, data, MIME type) tuple where the MIME type is optional. + For example:: + + 'foo': 'bar', + 'fakefile': ('foofile.txt', 'contents of foofile'), + 'realfile': ('barfile.txt', open('realfile').read()), + 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), + 'nonamefile': 'contents of nonamefile field', + + Field names and filenames must be unicode. + """ + filename: str | None + content_type: str | None + data: _TYPE_FIELD_VALUE + + if isinstance(value, tuple): + if len(value) == 3: + filename, data, content_type = value + else: + filename, data = value + content_type = guess_content_type(filename) + else: + filename = None + content_type = None + data = value + + request_param = cls( + fieldname, data, filename=filename, header_formatter=header_formatter + ) + request_param.make_multipart(content_type=content_type) + + return request_param + + def _render_part(self, name: str, value: _TYPE_FIELD_VALUE) -> str: + """ + Override this method to change how each multipart header + parameter is formatted. By default, this calls + :func:`format_multipart_header_param`. + + :param name: + The name of the parameter, an ASCII-only ``str``. + :param value: + The value of the parameter, a ``str`` or UTF-8 encoded + ``bytes``. + + :meta public: + """ + return self.header_formatter(name, value) + + def _render_parts( + self, + header_parts: ( + dict[str, _TYPE_FIELD_VALUE | None] + | typing.Sequence[tuple[str, _TYPE_FIELD_VALUE | None]] + ), + ) -> str: + """ + Helper function to format and quote a single header. + + Useful for single headers that are composed of multiple items. E.g., + 'Content-Disposition' fields. + + :param header_parts: + A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format + as `k1="v1"; k2="v2"; ...`. + """ + iterable: typing.Iterable[tuple[str, _TYPE_FIELD_VALUE | None]] + + parts = [] + if isinstance(header_parts, dict): + iterable = header_parts.items() + else: + iterable = header_parts + + for name, value in iterable: + if value is not None: + parts.append(self._render_part(name, value)) + + return "; ".join(parts) + + def render_headers(self) -> str: + """ + Renders the headers for this request field. + """ + lines = [] + + sort_keys = ["Content-Disposition", "Content-Type", "Content-Location"] + for sort_key in sort_keys: + if self.headers.get(sort_key, False): + lines.append(f"{sort_key}: {self.headers[sort_key]}") + + for header_name, header_value in self.headers.items(): + if header_name not in sort_keys: + if header_value: + lines.append(f"{header_name}: {header_value}") + + lines.append("\r\n") + return "\r\n".join(lines) + + def make_multipart( + self, + content_disposition: str | None = None, + content_type: str | None = None, + content_location: str | None = None, + ) -> None: + """ + Makes this request field into a multipart request field. + + This method overrides "Content-Disposition", "Content-Type" and + "Content-Location" headers to the request parameter. + + :param content_disposition: + The 'Content-Disposition' of the request body. Defaults to 'form-data' + :param content_type: + The 'Content-Type' of the request body. + :param content_location: + The 'Content-Location' of the request body. + + """ + content_disposition = (content_disposition or "form-data") + "; ".join( + [ + "", + self._render_parts( + (("name", self._name), ("filename", self._filename)) + ), + ] + ) + + self.headers["Content-Disposition"] = content_disposition + self.headers["Content-Type"] = content_type + self.headers["Content-Location"] = content_location diff --git a/venv/Lib/site-packages/urllib3/filepost.py b/venv/Lib/site-packages/urllib3/filepost.py new file mode 100644 index 00000000..14f70b05 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/filepost.py @@ -0,0 +1,89 @@ +from __future__ import annotations + +import binascii +import codecs +import os +import typing +from io import BytesIO + +from .fields import _TYPE_FIELD_VALUE_TUPLE, RequestField + +writer = codecs.lookup("utf-8")[3] + +_TYPE_FIELDS_SEQUENCE = typing.Sequence[ + typing.Union[tuple[str, _TYPE_FIELD_VALUE_TUPLE], RequestField] +] +_TYPE_FIELDS = typing.Union[ + _TYPE_FIELDS_SEQUENCE, + typing.Mapping[str, _TYPE_FIELD_VALUE_TUPLE], +] + + +def choose_boundary() -> str: + """ + Our embarrassingly-simple replacement for mimetools.choose_boundary. + """ + return binascii.hexlify(os.urandom(16)).decode() + + +def iter_field_objects(fields: _TYPE_FIELDS) -> typing.Iterable[RequestField]: + """ + Iterate over fields. + + Supports list of (k, v) tuples and dicts, and lists of + :class:`~urllib3.fields.RequestField`. + + """ + iterable: typing.Iterable[RequestField | tuple[str, _TYPE_FIELD_VALUE_TUPLE]] + + if isinstance(fields, typing.Mapping): + iterable = fields.items() + else: + iterable = fields + + for field in iterable: + if isinstance(field, RequestField): + yield field + else: + yield RequestField.from_tuples(*field) + + +def encode_multipart_formdata( + fields: _TYPE_FIELDS, boundary: str | None = None +) -> tuple[bytes, str]: + """ + Encode a dictionary of ``fields`` using the multipart/form-data MIME format. + + :param fields: + Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`). + Values are processed by :func:`urllib3.fields.RequestField.from_tuples`. + + :param boundary: + If not specified, then a random boundary will be generated using + :func:`urllib3.filepost.choose_boundary`. + """ + body = BytesIO() + if boundary is None: + boundary = choose_boundary() + + for field in iter_field_objects(fields): + body.write(f"--{boundary}\r\n".encode("latin-1")) + + writer(body).write(field.render_headers()) + data = field.data + + if isinstance(data, int): + data = str(data) # Backwards compatibility + + if isinstance(data, str): + writer(body).write(data) + else: + body.write(data) + + body.write(b"\r\n") + + body.write(f"--{boundary}--\r\n".encode("latin-1")) + + content_type = f"multipart/form-data; boundary={boundary}" + + return body.getvalue(), content_type diff --git a/venv/Lib/site-packages/urllib3/http2/__init__.py b/venv/Lib/site-packages/urllib3/http2/__init__.py new file mode 100644 index 00000000..133e1d8f --- /dev/null +++ b/venv/Lib/site-packages/urllib3/http2/__init__.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +from importlib.metadata import version + +__all__ = [ + "inject_into_urllib3", + "extract_from_urllib3", +] + +import typing + +orig_HTTPSConnection: typing.Any = None + + +def inject_into_urllib3() -> None: + # First check if h2 version is valid + h2_version = version("h2") + if not h2_version.startswith("4."): + raise ImportError( + "urllib3 v2 supports h2 version 4.x.x, currently " + f"the 'h2' module is compiled with {h2_version!r}. " + "See: https://github.com/urllib3/urllib3/issues/3290" + ) + + # Import here to avoid circular dependencies. + from .. import connection as urllib3_connection + from .. import util as urllib3_util + from ..connectionpool import HTTPSConnectionPool + from ..util import ssl_ as urllib3_util_ssl + from .connection import HTTP2Connection + + global orig_HTTPSConnection + orig_HTTPSConnection = urllib3_connection.HTTPSConnection + + HTTPSConnectionPool.ConnectionCls = HTTP2Connection + urllib3_connection.HTTPSConnection = HTTP2Connection # type: ignore[misc] + + # TODO: Offer 'http/1.1' as well, but for testing purposes this is handy. + urllib3_util.ALPN_PROTOCOLS = ["h2"] + urllib3_util_ssl.ALPN_PROTOCOLS = ["h2"] + + +def extract_from_urllib3() -> None: + from .. import connection as urllib3_connection + from .. import util as urllib3_util + from ..connectionpool import HTTPSConnectionPool + from ..util import ssl_ as urllib3_util_ssl + + HTTPSConnectionPool.ConnectionCls = orig_HTTPSConnection + urllib3_connection.HTTPSConnection = orig_HTTPSConnection # type: ignore[misc] + + urllib3_util.ALPN_PROTOCOLS = ["http/1.1"] + urllib3_util_ssl.ALPN_PROTOCOLS = ["http/1.1"] diff --git a/venv/Lib/site-packages/urllib3/http2/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/urllib3/http2/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..83beb849 Binary files /dev/null and b/venv/Lib/site-packages/urllib3/http2/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/http2/__pycache__/connection.cpython-312.pyc b/venv/Lib/site-packages/urllib3/http2/__pycache__/connection.cpython-312.pyc new file mode 100644 index 00000000..12ce20dc Binary files /dev/null and b/venv/Lib/site-packages/urllib3/http2/__pycache__/connection.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/http2/__pycache__/probe.cpython-312.pyc b/venv/Lib/site-packages/urllib3/http2/__pycache__/probe.cpython-312.pyc new file mode 100644 index 00000000..bd703af1 Binary files /dev/null and b/venv/Lib/site-packages/urllib3/http2/__pycache__/probe.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/http2/connection.py b/venv/Lib/site-packages/urllib3/http2/connection.py new file mode 100644 index 00000000..d0822391 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/http2/connection.py @@ -0,0 +1,356 @@ +from __future__ import annotations + +import logging +import re +import threading +import types +import typing + +import h2.config # type: ignore[import-untyped] +import h2.connection # type: ignore[import-untyped] +import h2.events # type: ignore[import-untyped] + +from .._base_connection import _TYPE_BODY +from .._collections import HTTPHeaderDict +from ..connection import HTTPSConnection, _get_default_user_agent +from ..exceptions import ConnectionError +from ..response import BaseHTTPResponse + +orig_HTTPSConnection = HTTPSConnection + +T = typing.TypeVar("T") + +log = logging.getLogger(__name__) + +RE_IS_LEGAL_HEADER_NAME = re.compile(rb"^[!#$%&'*+\-.^_`|~0-9a-z]+$") +RE_IS_ILLEGAL_HEADER_VALUE = re.compile(rb"[\0\x00\x0a\x0d\r\n]|^[ \r\n\t]|[ \r\n\t]$") + + +def _is_legal_header_name(name: bytes) -> bool: + """ + "An implementation that validates fields according to the definitions in Sections + 5.1 and 5.5 of [HTTP] only needs an additional check that field names do not + include uppercase characters." (https://httpwg.org/specs/rfc9113.html#n-field-validity) + + `http.client._is_legal_header_name` does not validate the field name according to the + HTTP 1.1 spec, so we do that here, in addition to checking for uppercase characters. + + This does not allow for the `:` character in the header name, so should not + be used to validate pseudo-headers. + """ + return bool(RE_IS_LEGAL_HEADER_NAME.match(name)) + + +def _is_illegal_header_value(value: bytes) -> bool: + """ + "A field value MUST NOT contain the zero value (ASCII NUL, 0x00), line feed + (ASCII LF, 0x0a), or carriage return (ASCII CR, 0x0d) at any position. A field + value MUST NOT start or end with an ASCII whitespace character (ASCII SP or HTAB, + 0x20 or 0x09)." (https://httpwg.org/specs/rfc9113.html#n-field-validity) + """ + return bool(RE_IS_ILLEGAL_HEADER_VALUE.search(value)) + + +class _LockedObject(typing.Generic[T]): + """ + A wrapper class that hides a specific object behind a lock. + The goal here is to provide a simple way to protect access to an object + that cannot safely be simultaneously accessed from multiple threads. The + intended use of this class is simple: take hold of it with a context + manager, which returns the protected object. + """ + + __slots__ = ( + "lock", + "_obj", + ) + + def __init__(self, obj: T): + self.lock = threading.RLock() + self._obj = obj + + def __enter__(self) -> T: + self.lock.acquire() + return self._obj + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: types.TracebackType | None, + ) -> None: + self.lock.release() + + +class HTTP2Connection(HTTPSConnection): + def __init__( + self, host: str, port: int | None = None, **kwargs: typing.Any + ) -> None: + self._h2_conn = self._new_h2_conn() + self._h2_stream: int | None = None + self._headers: list[tuple[bytes, bytes]] = [] + + if "proxy" in kwargs or "proxy_config" in kwargs: # Defensive: + raise NotImplementedError("Proxies aren't supported with HTTP/2") + + super().__init__(host, port, **kwargs) + + if self._tunnel_host is not None: + raise NotImplementedError("Tunneling isn't supported with HTTP/2") + + def _new_h2_conn(self) -> _LockedObject[h2.connection.H2Connection]: + config = h2.config.H2Configuration(client_side=True) + return _LockedObject(h2.connection.H2Connection(config=config)) + + def connect(self) -> None: + super().connect() + with self._h2_conn as conn: + conn.initiate_connection() + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + + def putrequest( # type: ignore[override] + self, + method: str, + url: str, + **kwargs: typing.Any, + ) -> None: + """putrequest + This deviates from the HTTPConnection method signature since we never need to override + sending accept-encoding headers or the host header. + """ + if "skip_host" in kwargs: + raise NotImplementedError("`skip_host` isn't supported") + if "skip_accept_encoding" in kwargs: + raise NotImplementedError("`skip_accept_encoding` isn't supported") + + self._request_url = url or "/" + self._validate_path(url) # type: ignore[attr-defined] + + if ":" in self.host: + authority = f"[{self.host}]:{self.port or 443}" + else: + authority = f"{self.host}:{self.port or 443}" + + self._headers.append((b":scheme", b"https")) + self._headers.append((b":method", method.encode())) + self._headers.append((b":authority", authority.encode())) + self._headers.append((b":path", url.encode())) + + with self._h2_conn as conn: + self._h2_stream = conn.get_next_available_stream_id() + + def putheader(self, header: str | bytes, *values: str | bytes) -> None: # type: ignore[override] + # TODO SKIPPABLE_HEADERS from urllib3 are ignored. + header = header.encode() if isinstance(header, str) else header + header = header.lower() # A lot of upstream code uses capitalized headers. + if not _is_legal_header_name(header): + raise ValueError(f"Illegal header name {str(header)}") + + for value in values: + value = value.encode() if isinstance(value, str) else value + if _is_illegal_header_value(value): + raise ValueError(f"Illegal header value {str(value)}") + self._headers.append((header, value)) + + def endheaders(self, message_body: typing.Any = None) -> None: # type: ignore[override] + if self._h2_stream is None: + raise ConnectionError("Must call `putrequest` first.") + + with self._h2_conn as conn: + conn.send_headers( + stream_id=self._h2_stream, + headers=self._headers, + end_stream=(message_body is None), + ) + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + self._headers = [] # Reset headers for the next request. + + def send(self, data: typing.Any) -> None: + """Send data to the server. + `data` can be: `str`, `bytes`, an iterable, or file-like objects + that support a .read() method. + """ + if self._h2_stream is None: + raise ConnectionError("Must call `putrequest` first.") + + with self._h2_conn as conn: + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + + if hasattr(data, "read"): # file-like objects + while True: + chunk = data.read(self.blocksize) + if not chunk: + break + if isinstance(chunk, str): + chunk = chunk.encode() # pragma: no cover + conn.send_data(self._h2_stream, chunk, end_stream=False) + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + conn.end_stream(self._h2_stream) + return + + if isinstance(data, str): # str -> bytes + data = data.encode() + + try: + if isinstance(data, bytes): + conn.send_data(self._h2_stream, data, end_stream=True) + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + else: + for chunk in data: + conn.send_data(self._h2_stream, chunk, end_stream=False) + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + conn.end_stream(self._h2_stream) + except TypeError: + raise TypeError( + "`data` should be str, bytes, iterable, or file. got %r" + % type(data) + ) + + def set_tunnel( + self, + host: str, + port: int | None = None, + headers: typing.Mapping[str, str] | None = None, + scheme: str = "http", + ) -> None: + raise NotImplementedError( + "HTTP/2 does not support setting up a tunnel through a proxy" + ) + + def getresponse( # type: ignore[override] + self, + ) -> HTTP2Response: + status = None + data = bytearray() + with self._h2_conn as conn: + end_stream = False + while not end_stream: + # TODO: Arbitrary read value. + if received_data := self.sock.recv(65535): + events = conn.receive_data(received_data) + for event in events: + if isinstance(event, h2.events.ResponseReceived): + headers = HTTPHeaderDict() + for header, value in event.headers: + if header == b":status": + status = int(value.decode()) + else: + headers.add( + header.decode("ascii"), value.decode("ascii") + ) + + elif isinstance(event, h2.events.DataReceived): + data += event.data + conn.acknowledge_received_data( + event.flow_controlled_length, event.stream_id + ) + + elif isinstance(event, h2.events.StreamEnded): + end_stream = True + + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + + assert status is not None + return HTTP2Response( + status=status, + headers=headers, + request_url=self._request_url, + data=bytes(data), + ) + + def request( # type: ignore[override] + self, + method: str, + url: str, + body: _TYPE_BODY | None = None, + headers: typing.Mapping[str, str] | None = None, + *, + preload_content: bool = True, + decode_content: bool = True, + enforce_content_length: bool = True, + **kwargs: typing.Any, + ) -> None: + """Send an HTTP/2 request""" + if "chunked" in kwargs: + # TODO this is often present from upstream. + # raise NotImplementedError("`chunked` isn't supported with HTTP/2") + pass + + if self.sock is not None: + self.sock.settimeout(self.timeout) + + self.putrequest(method, url) + + headers = headers or {} + for k, v in headers.items(): + if k.lower() == "transfer-encoding" and v == "chunked": + continue + else: + self.putheader(k, v) + + if b"user-agent" not in dict(self._headers): + self.putheader(b"user-agent", _get_default_user_agent()) + + if body: + self.endheaders(message_body=body) + self.send(body) + else: + self.endheaders() + + def close(self) -> None: + with self._h2_conn as conn: + try: + conn.close_connection() + if data := conn.data_to_send(): + self.sock.sendall(data) + except Exception: + pass + + # Reset all our HTTP/2 connection state. + self._h2_conn = self._new_h2_conn() + self._h2_stream = None + self._headers = [] + + super().close() + + +class HTTP2Response(BaseHTTPResponse): + # TODO: This is a woefully incomplete response object, but works for non-streaming. + def __init__( + self, + status: int, + headers: HTTPHeaderDict, + request_url: str, + data: bytes, + decode_content: bool = False, # TODO: support decoding + ) -> None: + super().__init__( + status=status, + headers=headers, + # Following CPython, we map HTTP versions to major * 10 + minor integers + version=20, + version_string="HTTP/2", + # No reason phrase in HTTP/2 + reason=None, + decode_content=decode_content, + request_url=request_url, + ) + self._data = data + self.length_remaining = 0 + + @property + def data(self) -> bytes: + return self._data + + def get_redirect_location(self) -> None: + return None + + def close(self) -> None: + pass diff --git a/venv/Lib/site-packages/urllib3/http2/probe.py b/venv/Lib/site-packages/urllib3/http2/probe.py new file mode 100644 index 00000000..9ea90076 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/http2/probe.py @@ -0,0 +1,87 @@ +from __future__ import annotations + +import threading + + +class _HTTP2ProbeCache: + __slots__ = ( + "_lock", + "_cache_locks", + "_cache_values", + ) + + def __init__(self) -> None: + self._lock = threading.Lock() + self._cache_locks: dict[tuple[str, int], threading.RLock] = {} + self._cache_values: dict[tuple[str, int], bool | None] = {} + + def acquire_and_get(self, host: str, port: int) -> bool | None: + # By the end of this block we know that + # _cache_[values,locks] is available. + value = None + with self._lock: + key = (host, port) + try: + value = self._cache_values[key] + # If it's a known value we return right away. + if value is not None: + return value + except KeyError: + self._cache_locks[key] = threading.RLock() + self._cache_values[key] = None + + # If the value is unknown, we acquire the lock to signal + # to the requesting thread that the probe is in progress + # or that the current thread needs to return their findings. + key_lock = self._cache_locks[key] + key_lock.acquire() + try: + # If the by the time we get the lock the value has been + # updated we want to return the updated value. + value = self._cache_values[key] + + # In case an exception like KeyboardInterrupt is raised here. + except BaseException as e: # Defensive: + assert not isinstance(e, KeyError) # KeyError shouldn't be possible. + key_lock.release() + raise + + return value + + def set_and_release( + self, host: str, port: int, supports_http2: bool | None + ) -> None: + key = (host, port) + key_lock = self._cache_locks[key] + with key_lock: # Uses an RLock, so can be locked again from same thread. + if supports_http2 is None and self._cache_values[key] is not None: + raise ValueError( + "Cannot reset HTTP/2 support for origin after value has been set." + ) # Defensive: not expected in normal usage + + self._cache_values[key] = supports_http2 + key_lock.release() + + def _values(self) -> dict[tuple[str, int], bool | None]: + """This function is for testing purposes only. Gets the current state of the probe cache""" + with self._lock: + return {k: v for k, v in self._cache_values.items()} + + def _reset(self) -> None: + """This function is for testing purposes only. Reset the cache values""" + with self._lock: + self._cache_locks = {} + self._cache_values = {} + + +_HTTP2_PROBE_CACHE = _HTTP2ProbeCache() + +set_and_release = _HTTP2_PROBE_CACHE.set_and_release +acquire_and_get = _HTTP2_PROBE_CACHE.acquire_and_get +_values = _HTTP2_PROBE_CACHE._values +_reset = _HTTP2_PROBE_CACHE._reset + +__all__ = [ + "set_and_release", + "acquire_and_get", +] diff --git a/venv/Lib/site-packages/urllib3/poolmanager.py b/venv/Lib/site-packages/urllib3/poolmanager.py new file mode 100644 index 00000000..5763fea8 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/poolmanager.py @@ -0,0 +1,653 @@ +from __future__ import annotations + +import functools +import logging +import typing +import warnings +from types import TracebackType +from urllib.parse import urljoin + +from ._collections import HTTPHeaderDict, RecentlyUsedContainer +from ._request_methods import RequestMethods +from .connection import ProxyConfig +from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, port_by_scheme +from .exceptions import ( + LocationValueError, + MaxRetryError, + ProxySchemeUnknown, + URLSchemeUnknown, +) +from .response import BaseHTTPResponse +from .util.connection import _TYPE_SOCKET_OPTIONS +from .util.proxy import connection_requires_http_tunnel +from .util.retry import Retry +from .util.timeout import Timeout +from .util.url import Url, parse_url + +if typing.TYPE_CHECKING: + import ssl + + from typing_extensions import Self + +__all__ = ["PoolManager", "ProxyManager", "proxy_from_url"] + + +log = logging.getLogger(__name__) + +SSL_KEYWORDS = ( + "key_file", + "cert_file", + "cert_reqs", + "ca_certs", + "ca_cert_data", + "ssl_version", + "ssl_minimum_version", + "ssl_maximum_version", + "ca_cert_dir", + "ssl_context", + "key_password", + "server_hostname", +) +# Default value for `blocksize` - a new parameter introduced to +# http.client.HTTPConnection & http.client.HTTPSConnection in Python 3.7 +_DEFAULT_BLOCKSIZE = 16384 + + +class PoolKey(typing.NamedTuple): + """ + All known keyword arguments that could be provided to the pool manager, its + pools, or the underlying connections. + + All custom key schemes should include the fields in this key at a minimum. + """ + + key_scheme: str + key_host: str + key_port: int | None + key_timeout: Timeout | float | int | None + key_retries: Retry | bool | int | None + key_block: bool | None + key_source_address: tuple[str, int] | None + key_key_file: str | None + key_key_password: str | None + key_cert_file: str | None + key_cert_reqs: str | None + key_ca_certs: str | None + key_ca_cert_data: str | bytes | None + key_ssl_version: int | str | None + key_ssl_minimum_version: ssl.TLSVersion | None + key_ssl_maximum_version: ssl.TLSVersion | None + key_ca_cert_dir: str | None + key_ssl_context: ssl.SSLContext | None + key_maxsize: int | None + key_headers: frozenset[tuple[str, str]] | None + key__proxy: Url | None + key__proxy_headers: frozenset[tuple[str, str]] | None + key__proxy_config: ProxyConfig | None + key_socket_options: _TYPE_SOCKET_OPTIONS | None + key__socks_options: frozenset[tuple[str, str]] | None + key_assert_hostname: bool | str | None + key_assert_fingerprint: str | None + key_server_hostname: str | None + key_blocksize: int | None + + +def _default_key_normalizer( + key_class: type[PoolKey], request_context: dict[str, typing.Any] +) -> PoolKey: + """ + Create a pool key out of a request context dictionary. + + According to RFC 3986, both the scheme and host are case-insensitive. + Therefore, this function normalizes both before constructing the pool + key for an HTTPS request. If you wish to change this behaviour, provide + alternate callables to ``key_fn_by_scheme``. + + :param key_class: + The class to use when constructing the key. This should be a namedtuple + with the ``scheme`` and ``host`` keys at a minimum. + :type key_class: namedtuple + :param request_context: + A dictionary-like object that contain the context for a request. + :type request_context: dict + + :return: A namedtuple that can be used as a connection pool key. + :rtype: PoolKey + """ + # Since we mutate the dictionary, make a copy first + context = request_context.copy() + context["scheme"] = context["scheme"].lower() + context["host"] = context["host"].lower() + + # These are both dictionaries and need to be transformed into frozensets + for key in ("headers", "_proxy_headers", "_socks_options"): + if key in context and context[key] is not None: + context[key] = frozenset(context[key].items()) + + # The socket_options key may be a list and needs to be transformed into a + # tuple. + socket_opts = context.get("socket_options") + if socket_opts is not None: + context["socket_options"] = tuple(socket_opts) + + # Map the kwargs to the names in the namedtuple - this is necessary since + # namedtuples can't have fields starting with '_'. + for key in list(context.keys()): + context["key_" + key] = context.pop(key) + + # Default to ``None`` for keys missing from the context + for field in key_class._fields: + if field not in context: + context[field] = None + + # Default key_blocksize to _DEFAULT_BLOCKSIZE if missing from the context + if context.get("key_blocksize") is None: + context["key_blocksize"] = _DEFAULT_BLOCKSIZE + + return key_class(**context) + + +#: A dictionary that maps a scheme to a callable that creates a pool key. +#: This can be used to alter the way pool keys are constructed, if desired. +#: Each PoolManager makes a copy of this dictionary so they can be configured +#: globally here, or individually on the instance. +key_fn_by_scheme = { + "http": functools.partial(_default_key_normalizer, PoolKey), + "https": functools.partial(_default_key_normalizer, PoolKey), +} + +pool_classes_by_scheme = {"http": HTTPConnectionPool, "https": HTTPSConnectionPool} + + +class PoolManager(RequestMethods): + """ + Allows for arbitrary requests while transparently keeping track of + necessary connection pools for you. + + :param num_pools: + Number of connection pools to cache before discarding the least + recently used pool. + + :param headers: + Headers to include with all requests, unless other headers are given + explicitly. + + :param \\**connection_pool_kw: + Additional parameters are used to create fresh + :class:`urllib3.connectionpool.ConnectionPool` instances. + + Example: + + .. code-block:: python + + import urllib3 + + http = urllib3.PoolManager(num_pools=2) + + resp1 = http.request("GET", "https://google.com/") + resp2 = http.request("GET", "https://google.com/mail") + resp3 = http.request("GET", "https://yahoo.com/") + + print(len(http.pools)) + # 2 + + """ + + proxy: Url | None = None + proxy_config: ProxyConfig | None = None + + def __init__( + self, + num_pools: int = 10, + headers: typing.Mapping[str, str] | None = None, + **connection_pool_kw: typing.Any, + ) -> None: + super().__init__(headers) + if "retries" in connection_pool_kw: + retries = connection_pool_kw["retries"] + if not isinstance(retries, Retry): + # When Retry is initialized, raise_on_redirect is based + # on a redirect boolean value. + # But requests made via a pool manager always set + # redirect to False, and raise_on_redirect always ends + # up being False consequently. + # Here we fix the issue by setting raise_on_redirect to + # a value needed by the pool manager without considering + # the redirect boolean. + raise_on_redirect = retries is not False + retries = Retry.from_int(retries, redirect=False) + retries.raise_on_redirect = raise_on_redirect + connection_pool_kw = connection_pool_kw.copy() + connection_pool_kw["retries"] = retries + self.connection_pool_kw = connection_pool_kw + + self.pools: RecentlyUsedContainer[PoolKey, HTTPConnectionPool] + self.pools = RecentlyUsedContainer(num_pools) + + # Locally set the pool classes and keys so other PoolManagers can + # override them. + self.pool_classes_by_scheme = pool_classes_by_scheme + self.key_fn_by_scheme = key_fn_by_scheme.copy() + + def __enter__(self) -> Self: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> typing.Literal[False]: + self.clear() + # Return False to re-raise any potential exceptions + return False + + def _new_pool( + self, + scheme: str, + host: str, + port: int, + request_context: dict[str, typing.Any] | None = None, + ) -> HTTPConnectionPool: + """ + Create a new :class:`urllib3.connectionpool.ConnectionPool` based on host, port, scheme, and + any additional pool keyword arguments. + + If ``request_context`` is provided, it is provided as keyword arguments + to the pool class used. This method is used to actually create the + connection pools handed out by :meth:`connection_from_url` and + companion methods. It is intended to be overridden for customization. + """ + pool_cls: type[HTTPConnectionPool] = self.pool_classes_by_scheme[scheme] + if request_context is None: + request_context = self.connection_pool_kw.copy() + + # Default blocksize to _DEFAULT_BLOCKSIZE if missing or explicitly + # set to 'None' in the request_context. + if request_context.get("blocksize") is None: + request_context["blocksize"] = _DEFAULT_BLOCKSIZE + + # Although the context has everything necessary to create the pool, + # this function has historically only used the scheme, host, and port + # in the positional args. When an API change is acceptable these can + # be removed. + for key in ("scheme", "host", "port"): + request_context.pop(key, None) + + if scheme == "http": + for kw in SSL_KEYWORDS: + request_context.pop(kw, None) + + return pool_cls(host, port, **request_context) + + def clear(self) -> None: + """ + Empty our store of pools and direct them all to close. + + This will not affect in-flight connections, but they will not be + re-used after completion. + """ + self.pools.clear() + + def connection_from_host( + self, + host: str | None, + port: int | None = None, + scheme: str | None = "http", + pool_kwargs: dict[str, typing.Any] | None = None, + ) -> HTTPConnectionPool: + """ + Get a :class:`urllib3.connectionpool.ConnectionPool` based on the host, port, and scheme. + + If ``port`` isn't given, it will be derived from the ``scheme`` using + ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is + provided, it is merged with the instance's ``connection_pool_kw`` + variable and used to create the new connection pool, if one is + needed. + """ + + if not host: + raise LocationValueError("No host specified.") + + request_context = self._merge_pool_kwargs(pool_kwargs) + request_context["scheme"] = scheme or "http" + if not port: + port = port_by_scheme.get(request_context["scheme"].lower(), 80) + request_context["port"] = port + request_context["host"] = host + + return self.connection_from_context(request_context) + + def connection_from_context( + self, request_context: dict[str, typing.Any] + ) -> HTTPConnectionPool: + """ + Get a :class:`urllib3.connectionpool.ConnectionPool` based on the request context. + + ``request_context`` must at least contain the ``scheme`` key and its + value must be a key in ``key_fn_by_scheme`` instance variable. + """ + if "strict" in request_context: + warnings.warn( + "The 'strict' parameter is no longer needed on Python 3+. " + "This will raise an error in urllib3 v2.1.0.", + DeprecationWarning, + ) + request_context.pop("strict") + + scheme = request_context["scheme"].lower() + pool_key_constructor = self.key_fn_by_scheme.get(scheme) + if not pool_key_constructor: + raise URLSchemeUnknown(scheme) + pool_key = pool_key_constructor(request_context) + + return self.connection_from_pool_key(pool_key, request_context=request_context) + + def connection_from_pool_key( + self, pool_key: PoolKey, request_context: dict[str, typing.Any] + ) -> HTTPConnectionPool: + """ + Get a :class:`urllib3.connectionpool.ConnectionPool` based on the provided pool key. + + ``pool_key`` should be a namedtuple that only contains immutable + objects. At a minimum it must have the ``scheme``, ``host``, and + ``port`` fields. + """ + with self.pools.lock: + # If the scheme, host, or port doesn't match existing open + # connections, open a new ConnectionPool. + pool = self.pools.get(pool_key) + if pool: + return pool + + # Make a fresh ConnectionPool of the desired type + scheme = request_context["scheme"] + host = request_context["host"] + port = request_context["port"] + pool = self._new_pool(scheme, host, port, request_context=request_context) + self.pools[pool_key] = pool + + return pool + + def connection_from_url( + self, url: str, pool_kwargs: dict[str, typing.Any] | None = None + ) -> HTTPConnectionPool: + """ + Similar to :func:`urllib3.connectionpool.connection_from_url`. + + If ``pool_kwargs`` is not provided and a new pool needs to be + constructed, ``self.connection_pool_kw`` is used to initialize + the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs`` + is provided, it is used instead. Note that if a new pool does not + need to be created for the request, the provided ``pool_kwargs`` are + not used. + """ + u = parse_url(url) + return self.connection_from_host( + u.host, port=u.port, scheme=u.scheme, pool_kwargs=pool_kwargs + ) + + def _merge_pool_kwargs( + self, override: dict[str, typing.Any] | None + ) -> dict[str, typing.Any]: + """ + Merge a dictionary of override values for self.connection_pool_kw. + + This does not modify self.connection_pool_kw and returns a new dict. + Any keys in the override dictionary with a value of ``None`` are + removed from the merged dictionary. + """ + base_pool_kwargs = self.connection_pool_kw.copy() + if override: + for key, value in override.items(): + if value is None: + try: + del base_pool_kwargs[key] + except KeyError: + pass + else: + base_pool_kwargs[key] = value + return base_pool_kwargs + + def _proxy_requires_url_absolute_form(self, parsed_url: Url) -> bool: + """ + Indicates if the proxy requires the complete destination URL in the + request. Normally this is only needed when not using an HTTP CONNECT + tunnel. + """ + if self.proxy is None: + return False + + return not connection_requires_http_tunnel( + self.proxy, self.proxy_config, parsed_url.scheme + ) + + def urlopen( # type: ignore[override] + self, method: str, url: str, redirect: bool = True, **kw: typing.Any + ) -> BaseHTTPResponse: + """ + Same as :meth:`urllib3.HTTPConnectionPool.urlopen` + with custom cross-host redirect logic and only sends the request-uri + portion of the ``url``. + + The given ``url`` parameter must be absolute, such that an appropriate + :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it. + """ + u = parse_url(url) + + if u.scheme is None: + warnings.warn( + "URLs without a scheme (ie 'https://') are deprecated and will raise an error " + "in a future version of urllib3. To avoid this DeprecationWarning ensure all URLs " + "start with 'https://' or 'http://'. Read more in this issue: " + "https://github.com/urllib3/urllib3/issues/2920", + category=DeprecationWarning, + stacklevel=2, + ) + + conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme) + + kw["assert_same_host"] = False + kw["redirect"] = False + + if "headers" not in kw: + kw["headers"] = self.headers + + if self._proxy_requires_url_absolute_form(u): + response = conn.urlopen(method, url, **kw) + else: + response = conn.urlopen(method, u.request_uri, **kw) + + redirect_location = redirect and response.get_redirect_location() + if not redirect_location: + return response + + # Support relative URLs for redirecting. + redirect_location = urljoin(url, redirect_location) + + if response.status == 303: + # Change the method according to RFC 9110, Section 15.4.4. + method = "GET" + # And lose the body not to transfer anything sensitive. + kw["body"] = None + kw["headers"] = HTTPHeaderDict(kw["headers"])._prepare_for_method_change() + + retries = kw.get("retries", response.retries) + if not isinstance(retries, Retry): + retries = Retry.from_int(retries, redirect=redirect) + + # Strip headers marked as unsafe to forward to the redirected location. + # Check remove_headers_on_redirect to avoid a potential network call within + # conn.is_same_host() which may use socket.gethostbyname() in the future. + if retries.remove_headers_on_redirect and not conn.is_same_host( + redirect_location + ): + new_headers = kw["headers"].copy() + for header in kw["headers"]: + if header.lower() in retries.remove_headers_on_redirect: + new_headers.pop(header, None) + kw["headers"] = new_headers + + try: + retries = retries.increment(method, url, response=response, _pool=conn) + except MaxRetryError: + if retries.raise_on_redirect: + response.drain_conn() + raise + return response + + kw["retries"] = retries + kw["redirect"] = redirect + + log.info("Redirecting %s -> %s", url, redirect_location) + + response.drain_conn() + return self.urlopen(method, redirect_location, **kw) + + +class ProxyManager(PoolManager): + """ + Behaves just like :class:`PoolManager`, but sends all requests through + the defined proxy, using the CONNECT method for HTTPS URLs. + + :param proxy_url: + The URL of the proxy to be used. + + :param proxy_headers: + A dictionary containing headers that will be sent to the proxy. In case + of HTTP they are being sent with each request, while in the + HTTPS/CONNECT case they are sent only once. Could be used for proxy + authentication. + + :param proxy_ssl_context: + The proxy SSL context is used to establish the TLS connection to the + proxy when using HTTPS proxies. + + :param use_forwarding_for_https: + (Defaults to False) If set to True will forward requests to the HTTPS + proxy to be made on behalf of the client instead of creating a TLS + tunnel via the CONNECT method. **Enabling this flag means that request + and response headers and content will be visible from the HTTPS proxy** + whereas tunneling keeps request and response headers and content + private. IP address, target hostname, SNI, and port are always visible + to an HTTPS proxy even when this flag is disabled. + + :param proxy_assert_hostname: + The hostname of the certificate to verify against. + + :param proxy_assert_fingerprint: + The fingerprint of the certificate to verify against. + + Example: + + .. code-block:: python + + import urllib3 + + proxy = urllib3.ProxyManager("https://localhost:3128/") + + resp1 = proxy.request("GET", "https://google.com/") + resp2 = proxy.request("GET", "https://httpbin.org/") + + print(len(proxy.pools)) + # 1 + + resp3 = proxy.request("GET", "https://httpbin.org/") + resp4 = proxy.request("GET", "https://twitter.com/") + + print(len(proxy.pools)) + # 3 + + """ + + def __init__( + self, + proxy_url: str, + num_pools: int = 10, + headers: typing.Mapping[str, str] | None = None, + proxy_headers: typing.Mapping[str, str] | None = None, + proxy_ssl_context: ssl.SSLContext | None = None, + use_forwarding_for_https: bool = False, + proxy_assert_hostname: None | str | typing.Literal[False] = None, + proxy_assert_fingerprint: str | None = None, + **connection_pool_kw: typing.Any, + ) -> None: + if isinstance(proxy_url, HTTPConnectionPool): + str_proxy_url = f"{proxy_url.scheme}://{proxy_url.host}:{proxy_url.port}" + else: + str_proxy_url = proxy_url + proxy = parse_url(str_proxy_url) + + if proxy.scheme not in ("http", "https"): + raise ProxySchemeUnknown(proxy.scheme) + + if not proxy.port: + port = port_by_scheme.get(proxy.scheme, 80) + proxy = proxy._replace(port=port) + + self.proxy = proxy + self.proxy_headers = proxy_headers or {} + self.proxy_ssl_context = proxy_ssl_context + self.proxy_config = ProxyConfig( + proxy_ssl_context, + use_forwarding_for_https, + proxy_assert_hostname, + proxy_assert_fingerprint, + ) + + connection_pool_kw["_proxy"] = self.proxy + connection_pool_kw["_proxy_headers"] = self.proxy_headers + connection_pool_kw["_proxy_config"] = self.proxy_config + + super().__init__(num_pools, headers, **connection_pool_kw) + + def connection_from_host( + self, + host: str | None, + port: int | None = None, + scheme: str | None = "http", + pool_kwargs: dict[str, typing.Any] | None = None, + ) -> HTTPConnectionPool: + if scheme == "https": + return super().connection_from_host( + host, port, scheme, pool_kwargs=pool_kwargs + ) + + return super().connection_from_host( + self.proxy.host, self.proxy.port, self.proxy.scheme, pool_kwargs=pool_kwargs # type: ignore[union-attr] + ) + + def _set_proxy_headers( + self, url: str, headers: typing.Mapping[str, str] | None = None + ) -> typing.Mapping[str, str]: + """ + Sets headers needed by proxies: specifically, the Accept and Host + headers. Only sets headers not provided by the user. + """ + headers_ = {"Accept": "*/*"} + + netloc = parse_url(url).netloc + if netloc: + headers_["Host"] = netloc + + if headers: + headers_.update(headers) + return headers_ + + def urlopen( # type: ignore[override] + self, method: str, url: str, redirect: bool = True, **kw: typing.Any + ) -> BaseHTTPResponse: + "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute." + u = parse_url(url) + if not connection_requires_http_tunnel(self.proxy, self.proxy_config, u.scheme): + # For connections using HTTP CONNECT, httplib sets the necessary + # headers on the CONNECT to the proxy. If we're not using CONNECT, + # we'll definitely need to set 'Host' at the very least. + headers = kw.get("headers", self.headers) + kw["headers"] = self._set_proxy_headers(url, headers) + + return super().urlopen(method, url, redirect=redirect, **kw) + + +def proxy_from_url(url: str, **kw: typing.Any) -> ProxyManager: + return ProxyManager(proxy_url=url, **kw) diff --git a/venv/Lib/site-packages/urllib3/py.typed b/venv/Lib/site-packages/urllib3/py.typed new file mode 100644 index 00000000..5f3ea3d9 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/py.typed @@ -0,0 +1,2 @@ +# Instruct type checkers to look for inline type annotations in this package. +# See PEP 561. diff --git a/venv/Lib/site-packages/urllib3/response.py b/venv/Lib/site-packages/urllib3/response.py new file mode 100644 index 00000000..5632dab3 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/response.py @@ -0,0 +1,1307 @@ +from __future__ import annotations + +import collections +import io +import json as _json +import logging +import re +import socket +import sys +import typing +import warnings +import zlib +from contextlib import contextmanager +from http.client import HTTPMessage as _HttplibHTTPMessage +from http.client import HTTPResponse as _HttplibHTTPResponse +from socket import timeout as SocketTimeout + +if typing.TYPE_CHECKING: + from ._base_connection import BaseHTTPConnection + +try: + try: + import brotlicffi as brotli # type: ignore[import-not-found] + except ImportError: + import brotli # type: ignore[import-not-found] +except ImportError: + brotli = None + +from . import util +from ._base_connection import _TYPE_BODY +from ._collections import HTTPHeaderDict +from .connection import BaseSSLError, HTTPConnection, HTTPException +from .exceptions import ( + BodyNotHttplibCompatible, + DecodeError, + HTTPError, + IncompleteRead, + InvalidChunkLength, + InvalidHeader, + ProtocolError, + ReadTimeoutError, + ResponseNotChunked, + SSLError, +) +from .util.response import is_fp_closed, is_response_to_head +from .util.retry import Retry + +if typing.TYPE_CHECKING: + from .connectionpool import HTTPConnectionPool + +log = logging.getLogger(__name__) + + +class ContentDecoder: + def decompress(self, data: bytes) -> bytes: + raise NotImplementedError() + + def flush(self) -> bytes: + raise NotImplementedError() + + +class DeflateDecoder(ContentDecoder): + def __init__(self) -> None: + self._first_try = True + self._data = b"" + self._obj = zlib.decompressobj() + + def decompress(self, data: bytes) -> bytes: + if not data: + return data + + if not self._first_try: + return self._obj.decompress(data) + + self._data += data + try: + decompressed = self._obj.decompress(data) + if decompressed: + self._first_try = False + self._data = None # type: ignore[assignment] + return decompressed + except zlib.error: + self._first_try = False + self._obj = zlib.decompressobj(-zlib.MAX_WBITS) + try: + return self.decompress(self._data) + finally: + self._data = None # type: ignore[assignment] + + def flush(self) -> bytes: + return self._obj.flush() + + +class GzipDecoderState: + FIRST_MEMBER = 0 + OTHER_MEMBERS = 1 + SWALLOW_DATA = 2 + + +class GzipDecoder(ContentDecoder): + def __init__(self) -> None: + self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS) + self._state = GzipDecoderState.FIRST_MEMBER + + def decompress(self, data: bytes) -> bytes: + ret = bytearray() + if self._state == GzipDecoderState.SWALLOW_DATA or not data: + return bytes(ret) + while True: + try: + ret += self._obj.decompress(data) + except zlib.error: + previous_state = self._state + # Ignore data after the first error + self._state = GzipDecoderState.SWALLOW_DATA + if previous_state == GzipDecoderState.OTHER_MEMBERS: + # Allow trailing garbage acceptable in other gzip clients + return bytes(ret) + raise + data = self._obj.unused_data + if not data: + return bytes(ret) + self._state = GzipDecoderState.OTHER_MEMBERS + self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS) + + def flush(self) -> bytes: + return self._obj.flush() + + +if brotli is not None: + + class BrotliDecoder(ContentDecoder): + # Supports both 'brotlipy' and 'Brotli' packages + # since they share an import name. The top branches + # are for 'brotlipy' and bottom branches for 'Brotli' + def __init__(self) -> None: + self._obj = brotli.Decompressor() + if hasattr(self._obj, "decompress"): + setattr(self, "decompress", self._obj.decompress) + else: + setattr(self, "decompress", self._obj.process) + + def flush(self) -> bytes: + if hasattr(self._obj, "flush"): + return self._obj.flush() # type: ignore[no-any-return] + return b"" + + +try: + # Python 3.14+ + from compression import zstd # type: ignore[import-not-found] # noqa: F401 + + HAS_ZSTD = True + + class ZstdDecoder(ContentDecoder): + def __init__(self) -> None: + self._obj = zstd.ZstdDecompressor() + + def decompress(self, data: bytes) -> bytes: + if not data: + return b"" + data_parts = [self._obj.decompress(data)] + while self._obj.eof and self._obj.unused_data: + unused_data = self._obj.unused_data + self._obj = zstd.ZstdDecompressor() + data_parts.append(self._obj.decompress(unused_data)) + return b"".join(data_parts) + + def flush(self) -> bytes: + if not self._obj.eof: + raise DecodeError("Zstandard data is incomplete") + return b"" + +except ImportError: + try: + # Python 3.13 and earlier require the 'zstandard' module. + import zstandard as zstd + + # The package 'zstandard' added the 'eof' property starting + # in v0.18.0 which we require to ensure a complete and + # valid zstd stream was fed into the ZstdDecoder. + # See: https://github.com/urllib3/urllib3/pull/2624 + _zstd_version = tuple( + map(int, re.search(r"^([0-9]+)\.([0-9]+)", zstd.__version__).groups()) # type: ignore[union-attr] + ) + if _zstd_version < (0, 18): # Defensive: + raise ImportError("zstandard module doesn't have eof") + except (AttributeError, ImportError, ValueError): # Defensive: + HAS_ZSTD = False + else: + HAS_ZSTD = True + + class ZstdDecoder(ContentDecoder): # type: ignore[no-redef] + def __init__(self) -> None: + self._obj = zstd.ZstdDecompressor().decompressobj() + + def decompress(self, data: bytes) -> bytes: + if not data: + return b"" + data_parts = [self._obj.decompress(data)] + while self._obj.eof and self._obj.unused_data: + unused_data = self._obj.unused_data + self._obj = zstd.ZstdDecompressor().decompressobj() + data_parts.append(self._obj.decompress(unused_data)) + return b"".join(data_parts) + + def flush(self) -> bytes: + ret = self._obj.flush() # note: this is a no-op + if not self._obj.eof: + raise DecodeError("Zstandard data is incomplete") + return ret # type: ignore[no-any-return] + + +class MultiDecoder(ContentDecoder): + """ + From RFC7231: + If one or more encodings have been applied to a representation, the + sender that applied the encodings MUST generate a Content-Encoding + header field that lists the content codings in the order in which + they were applied. + """ + + def __init__(self, modes: str) -> None: + self._decoders = [_get_decoder(m.strip()) for m in modes.split(",")] + + def flush(self) -> bytes: + return self._decoders[0].flush() + + def decompress(self, data: bytes) -> bytes: + for d in reversed(self._decoders): + data = d.decompress(data) + return data + + +def _get_decoder(mode: str) -> ContentDecoder: + if "," in mode: + return MultiDecoder(mode) + + # According to RFC 9110 section 8.4.1.3, recipients should + # consider x-gzip equivalent to gzip + if mode in ("gzip", "x-gzip"): + return GzipDecoder() + + if brotli is not None and mode == "br": + return BrotliDecoder() + + if HAS_ZSTD and mode == "zstd": + return ZstdDecoder() + + return DeflateDecoder() + + +class BytesQueueBuffer: + """Memory-efficient bytes buffer + + To return decoded data in read() and still follow the BufferedIOBase API, we need a + buffer to always return the correct amount of bytes. + + This buffer should be filled using calls to put() + + Our maximum memory usage is determined by the sum of the size of: + + * self.buffer, which contains the full data + * the largest chunk that we will copy in get() + + The worst case scenario is a single chunk, in which case we'll make a full copy of + the data inside get(). + """ + + def __init__(self) -> None: + self.buffer: typing.Deque[bytes] = collections.deque() + self._size: int = 0 + + def __len__(self) -> int: + return self._size + + def put(self, data: bytes) -> None: + self.buffer.append(data) + self._size += len(data) + + def get(self, n: int) -> bytes: + if n == 0: + return b"" + elif not self.buffer: + raise RuntimeError("buffer is empty") + elif n < 0: + raise ValueError("n should be > 0") + + fetched = 0 + ret = io.BytesIO() + while fetched < n: + remaining = n - fetched + chunk = self.buffer.popleft() + chunk_length = len(chunk) + if remaining < chunk_length: + left_chunk, right_chunk = chunk[:remaining], chunk[remaining:] + ret.write(left_chunk) + self.buffer.appendleft(right_chunk) + self._size -= remaining + break + else: + ret.write(chunk) + self._size -= chunk_length + fetched += chunk_length + + if not self.buffer: + break + + return ret.getvalue() + + def get_all(self) -> bytes: + buffer = self.buffer + if not buffer: + assert self._size == 0 + return b"" + if len(buffer) == 1: + result = buffer.pop() + else: + ret = io.BytesIO() + ret.writelines(buffer.popleft() for _ in range(len(buffer))) + result = ret.getvalue() + self._size = 0 + return result + + +class BaseHTTPResponse(io.IOBase): + CONTENT_DECODERS = ["gzip", "x-gzip", "deflate"] + if brotli is not None: + CONTENT_DECODERS += ["br"] + if HAS_ZSTD: + CONTENT_DECODERS += ["zstd"] + REDIRECT_STATUSES = [301, 302, 303, 307, 308] + + DECODER_ERROR_CLASSES: tuple[type[Exception], ...] = (IOError, zlib.error) + if brotli is not None: + DECODER_ERROR_CLASSES += (brotli.error,) + + if HAS_ZSTD: + DECODER_ERROR_CLASSES += (zstd.ZstdError,) + + def __init__( + self, + *, + headers: typing.Mapping[str, str] | typing.Mapping[bytes, bytes] | None = None, + status: int, + version: int, + version_string: str, + reason: str | None, + decode_content: bool, + request_url: str | None, + retries: Retry | None = None, + ) -> None: + if isinstance(headers, HTTPHeaderDict): + self.headers = headers + else: + self.headers = HTTPHeaderDict(headers) # type: ignore[arg-type] + self.status = status + self.version = version + self.version_string = version_string + self.reason = reason + self.decode_content = decode_content + self._has_decoded_content = False + self._request_url: str | None = request_url + self.retries = retries + + self.chunked = False + tr_enc = self.headers.get("transfer-encoding", "").lower() + # Don't incur the penalty of creating a list and then discarding it + encodings = (enc.strip() for enc in tr_enc.split(",")) + if "chunked" in encodings: + self.chunked = True + + self._decoder: ContentDecoder | None = None + self.length_remaining: int | None + + def get_redirect_location(self) -> str | None | typing.Literal[False]: + """ + Should we redirect and where to? + + :returns: Truthy redirect location string if we got a redirect status + code and valid location. ``None`` if redirect status and no + location. ``False`` if not a redirect status code. + """ + if self.status in self.REDIRECT_STATUSES: + return self.headers.get("location") + return False + + @property + def data(self) -> bytes: + raise NotImplementedError() + + def json(self) -> typing.Any: + """ + Deserializes the body of the HTTP response as a Python object. + + The body of the HTTP response must be encoded using UTF-8, as per + `RFC 8529 Section 8.1 `_. + + To use a custom JSON decoder pass the result of :attr:`HTTPResponse.data` to + your custom decoder instead. + + If the body of the HTTP response is not decodable to UTF-8, a + `UnicodeDecodeError` will be raised. If the body of the HTTP response is not a + valid JSON document, a `json.JSONDecodeError` will be raised. + + Read more :ref:`here `. + + :returns: The body of the HTTP response as a Python object. + """ + data = self.data.decode("utf-8") + return _json.loads(data) + + @property + def url(self) -> str | None: + raise NotImplementedError() + + @url.setter + def url(self, url: str | None) -> None: + raise NotImplementedError() + + @property + def connection(self) -> BaseHTTPConnection | None: + raise NotImplementedError() + + @property + def retries(self) -> Retry | None: + return self._retries + + @retries.setter + def retries(self, retries: Retry | None) -> None: + # Override the request_url if retries has a redirect location. + if retries is not None and retries.history: + self.url = retries.history[-1].redirect_location + self._retries = retries + + def stream( + self, amt: int | None = 2**16, decode_content: bool | None = None + ) -> typing.Iterator[bytes]: + raise NotImplementedError() + + def read( + self, + amt: int | None = None, + decode_content: bool | None = None, + cache_content: bool = False, + ) -> bytes: + raise NotImplementedError() + + def read1( + self, + amt: int | None = None, + decode_content: bool | None = None, + ) -> bytes: + raise NotImplementedError() + + def read_chunked( + self, + amt: int | None = None, + decode_content: bool | None = None, + ) -> typing.Iterator[bytes]: + raise NotImplementedError() + + def release_conn(self) -> None: + raise NotImplementedError() + + def drain_conn(self) -> None: + raise NotImplementedError() + + def shutdown(self) -> None: + raise NotImplementedError() + + def close(self) -> None: + raise NotImplementedError() + + def _init_decoder(self) -> None: + """ + Set-up the _decoder attribute if necessary. + """ + # Note: content-encoding value should be case-insensitive, per RFC 7230 + # Section 3.2 + content_encoding = self.headers.get("content-encoding", "").lower() + if self._decoder is None: + if content_encoding in self.CONTENT_DECODERS: + self._decoder = _get_decoder(content_encoding) + elif "," in content_encoding: + encodings = [ + e.strip() + for e in content_encoding.split(",") + if e.strip() in self.CONTENT_DECODERS + ] + if encodings: + self._decoder = _get_decoder(content_encoding) + + def _decode( + self, data: bytes, decode_content: bool | None, flush_decoder: bool + ) -> bytes: + """ + Decode the data passed in and potentially flush the decoder. + """ + if not decode_content: + if self._has_decoded_content: + raise RuntimeError( + "Calling read(decode_content=False) is not supported after " + "read(decode_content=True) was called." + ) + return data + + try: + if self._decoder: + data = self._decoder.decompress(data) + self._has_decoded_content = True + except self.DECODER_ERROR_CLASSES as e: + content_encoding = self.headers.get("content-encoding", "").lower() + raise DecodeError( + "Received response with content-encoding: %s, but " + "failed to decode it." % content_encoding, + e, + ) from e + if flush_decoder: + data += self._flush_decoder() + + return data + + def _flush_decoder(self) -> bytes: + """ + Flushes the decoder. Should only be called if the decoder is actually + being used. + """ + if self._decoder: + return self._decoder.decompress(b"") + self._decoder.flush() + return b"" + + # Compatibility methods for `io` module + def readinto(self, b: bytearray) -> int: + temp = self.read(len(b)) + if len(temp) == 0: + return 0 + else: + b[: len(temp)] = temp + return len(temp) + + # Compatibility methods for http.client.HTTPResponse + def getheaders(self) -> HTTPHeaderDict: + warnings.warn( + "HTTPResponse.getheaders() is deprecated and will be removed " + "in urllib3 v2.6.0. Instead access HTTPResponse.headers directly.", + category=DeprecationWarning, + stacklevel=2, + ) + return self.headers + + def getheader(self, name: str, default: str | None = None) -> str | None: + warnings.warn( + "HTTPResponse.getheader() is deprecated and will be removed " + "in urllib3 v2.6.0. Instead use HTTPResponse.headers.get(name, default).", + category=DeprecationWarning, + stacklevel=2, + ) + return self.headers.get(name, default) + + # Compatibility method for http.cookiejar + def info(self) -> HTTPHeaderDict: + return self.headers + + def geturl(self) -> str | None: + return self.url + + +class HTTPResponse(BaseHTTPResponse): + """ + HTTP Response container. + + Backwards-compatible with :class:`http.client.HTTPResponse` but the response ``body`` is + loaded and decoded on-demand when the ``data`` property is accessed. This + class is also compatible with the Python standard library's :mod:`io` + module, and can hence be treated as a readable object in the context of that + framework. + + Extra parameters for behaviour not present in :class:`http.client.HTTPResponse`: + + :param preload_content: + If True, the response's body will be preloaded during construction. + + :param decode_content: + If True, will attempt to decode the body based on the + 'content-encoding' header. + + :param original_response: + When this HTTPResponse wrapper is generated from an :class:`http.client.HTTPResponse` + object, it's convenient to include the original for debug purposes. It's + otherwise unused. + + :param retries: + The retries contains the last :class:`~urllib3.util.retry.Retry` that + was used during the request. + + :param enforce_content_length: + Enforce content length checking. Body returned by server must match + value of Content-Length header, if present. Otherwise, raise error. + """ + + def __init__( + self, + body: _TYPE_BODY = "", + headers: typing.Mapping[str, str] | typing.Mapping[bytes, bytes] | None = None, + status: int = 0, + version: int = 0, + version_string: str = "HTTP/?", + reason: str | None = None, + preload_content: bool = True, + decode_content: bool = True, + original_response: _HttplibHTTPResponse | None = None, + pool: HTTPConnectionPool | None = None, + connection: HTTPConnection | None = None, + msg: _HttplibHTTPMessage | None = None, + retries: Retry | None = None, + enforce_content_length: bool = True, + request_method: str | None = None, + request_url: str | None = None, + auto_close: bool = True, + sock_shutdown: typing.Callable[[int], None] | None = None, + ) -> None: + super().__init__( + headers=headers, + status=status, + version=version, + version_string=version_string, + reason=reason, + decode_content=decode_content, + request_url=request_url, + retries=retries, + ) + + self.enforce_content_length = enforce_content_length + self.auto_close = auto_close + + self._body = None + self._fp: _HttplibHTTPResponse | None = None + self._original_response = original_response + self._fp_bytes_read = 0 + self.msg = msg + + if body and isinstance(body, (str, bytes)): + self._body = body + + self._pool = pool + self._connection = connection + + if hasattr(body, "read"): + self._fp = body # type: ignore[assignment] + self._sock_shutdown = sock_shutdown + + # Are we using the chunked-style of transfer encoding? + self.chunk_left: int | None = None + + # Determine length of response + self.length_remaining = self._init_length(request_method) + + # Used to return the correct amount of bytes for partial read()s + self._decoded_buffer = BytesQueueBuffer() + + # If requested, preload the body. + if preload_content and not self._body: + self._body = self.read(decode_content=decode_content) + + def release_conn(self) -> None: + if not self._pool or not self._connection: + return None + + self._pool._put_conn(self._connection) + self._connection = None + + def drain_conn(self) -> None: + """ + Read and discard any remaining HTTP response data in the response connection. + + Unread data in the HTTPResponse connection blocks the connection from being released back to the pool. + """ + try: + self.read() + except (HTTPError, OSError, BaseSSLError, HTTPException): + pass + + @property + def data(self) -> bytes: + # For backwards-compat with earlier urllib3 0.4 and earlier. + if self._body: + return self._body # type: ignore[return-value] + + if self._fp: + return self.read(cache_content=True) + + return None # type: ignore[return-value] + + @property + def connection(self) -> HTTPConnection | None: + return self._connection + + def isclosed(self) -> bool: + return is_fp_closed(self._fp) + + def tell(self) -> int: + """ + Obtain the number of bytes pulled over the wire so far. May differ from + the amount of content returned by :meth:``urllib3.response.HTTPResponse.read`` + if bytes are encoded on the wire (e.g, compressed). + """ + return self._fp_bytes_read + + def _init_length(self, request_method: str | None) -> int | None: + """ + Set initial length value for Response content if available. + """ + length: int | None + content_length: str | None = self.headers.get("content-length") + + if content_length is not None: + if self.chunked: + # This Response will fail with an IncompleteRead if it can't be + # received as chunked. This method falls back to attempt reading + # the response before raising an exception. + log.warning( + "Received response with both Content-Length and " + "Transfer-Encoding set. This is expressly forbidden " + "by RFC 7230 sec 3.3.2. Ignoring Content-Length and " + "attempting to process response as Transfer-Encoding: " + "chunked." + ) + return None + + try: + # RFC 7230 section 3.3.2 specifies multiple content lengths can + # be sent in a single Content-Length header + # (e.g. Content-Length: 42, 42). This line ensures the values + # are all valid ints and that as long as the `set` length is 1, + # all values are the same. Otherwise, the header is invalid. + lengths = {int(val) for val in content_length.split(",")} + if len(lengths) > 1: + raise InvalidHeader( + "Content-Length contained multiple " + "unmatching values (%s)" % content_length + ) + length = lengths.pop() + except ValueError: + length = None + else: + if length < 0: + length = None + + else: # if content_length is None + length = None + + # Convert status to int for comparison + # In some cases, httplib returns a status of "_UNKNOWN" + try: + status = int(self.status) + except ValueError: + status = 0 + + # Check for responses that shouldn't include a body + if status in (204, 304) or 100 <= status < 200 or request_method == "HEAD": + length = 0 + + return length + + @contextmanager + def _error_catcher(self) -> typing.Generator[None]: + """ + Catch low-level python exceptions, instead re-raising urllib3 + variants, so that low-level exceptions are not leaked in the + high-level api. + + On exit, release the connection back to the pool. + """ + clean_exit = False + + try: + try: + yield + + except SocketTimeout as e: + # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but + # there is yet no clean way to get at it from this context. + raise ReadTimeoutError(self._pool, None, "Read timed out.") from e # type: ignore[arg-type] + + except BaseSSLError as e: + # FIXME: Is there a better way to differentiate between SSLErrors? + if "read operation timed out" not in str(e): + # SSL errors related to framing/MAC get wrapped and reraised here + raise SSLError(e) from e + + raise ReadTimeoutError(self._pool, None, "Read timed out.") from e # type: ignore[arg-type] + + except IncompleteRead as e: + if ( + e.expected is not None + and e.partial is not None + and e.expected == -e.partial + ): + arg = "Response may not contain content." + else: + arg = f"Connection broken: {e!r}" + raise ProtocolError(arg, e) from e + + except (HTTPException, OSError) as e: + raise ProtocolError(f"Connection broken: {e!r}", e) from e + + # If no exception is thrown, we should avoid cleaning up + # unnecessarily. + clean_exit = True + finally: + # If we didn't terminate cleanly, we need to throw away our + # connection. + if not clean_exit: + # The response may not be closed but we're not going to use it + # anymore so close it now to ensure that the connection is + # released back to the pool. + if self._original_response: + self._original_response.close() + + # Closing the response may not actually be sufficient to close + # everything, so if we have a hold of the connection close that + # too. + if self._connection: + self._connection.close() + + # If we hold the original response but it's closed now, we should + # return the connection back to the pool. + if self._original_response and self._original_response.isclosed(): + self.release_conn() + + def _fp_read( + self, + amt: int | None = None, + *, + read1: bool = False, + ) -> bytes: + """ + Read a response with the thought that reading the number of bytes + larger than can fit in a 32-bit int at a time via SSL in some + known cases leads to an overflow error that has to be prevented + if `amt` or `self.length_remaining` indicate that a problem may + happen. + + The known cases: + * CPython < 3.9.7 because of a bug + https://github.com/urllib3/urllib3/issues/2513#issuecomment-1152559900. + * urllib3 injected with pyOpenSSL-backed SSL-support. + * CPython < 3.10 only when `amt` does not fit 32-bit int. + """ + assert self._fp + c_int_max = 2**31 - 1 + if ( + (amt and amt > c_int_max) + or ( + amt is None + and self.length_remaining + and self.length_remaining > c_int_max + ) + ) and (util.IS_PYOPENSSL or sys.version_info < (3, 10)): + if read1: + return self._fp.read1(c_int_max) + buffer = io.BytesIO() + # Besides `max_chunk_amt` being a maximum chunk size, it + # affects memory overhead of reading a response by this + # method in CPython. + # `c_int_max` equal to 2 GiB - 1 byte is the actual maximum + # chunk size that does not lead to an overflow error, but + # 256 MiB is a compromise. + max_chunk_amt = 2**28 + while amt is None or amt != 0: + if amt is not None: + chunk_amt = min(amt, max_chunk_amt) + amt -= chunk_amt + else: + chunk_amt = max_chunk_amt + data = self._fp.read(chunk_amt) + if not data: + break + buffer.write(data) + del data # to reduce peak memory usage by `max_chunk_amt`. + return buffer.getvalue() + elif read1: + return self._fp.read1(amt) if amt is not None else self._fp.read1() + else: + # StringIO doesn't like amt=None + return self._fp.read(amt) if amt is not None else self._fp.read() + + def _raw_read( + self, + amt: int | None = None, + *, + read1: bool = False, + ) -> bytes: + """ + Reads `amt` of bytes from the socket. + """ + if self._fp is None: + return None # type: ignore[return-value] + + fp_closed = getattr(self._fp, "closed", False) + + with self._error_catcher(): + data = self._fp_read(amt, read1=read1) if not fp_closed else b"" + if amt is not None and amt != 0 and not data: + # Platform-specific: Buggy versions of Python. + # Close the connection when no data is returned + # + # This is redundant to what httplib/http.client _should_ + # already do. However, versions of python released before + # December 15, 2012 (http://bugs.python.org/issue16298) do + # not properly close the connection in all cases. There is + # no harm in redundantly calling close. + self._fp.close() + if ( + self.enforce_content_length + and self.length_remaining is not None + and self.length_remaining != 0 + ): + # This is an edge case that httplib failed to cover due + # to concerns of backward compatibility. We're + # addressing it here to make sure IncompleteRead is + # raised during streaming, so all calls with incorrect + # Content-Length are caught. + raise IncompleteRead(self._fp_bytes_read, self.length_remaining) + elif read1 and ( + (amt != 0 and not data) or self.length_remaining == len(data) + ): + # All data has been read, but `self._fp.read1` in + # CPython 3.12 and older doesn't always close + # `http.client.HTTPResponse`, so we close it here. + # See https://github.com/python/cpython/issues/113199 + self._fp.close() + + if data: + self._fp_bytes_read += len(data) + if self.length_remaining is not None: + self.length_remaining -= len(data) + return data + + def read( + self, + amt: int | None = None, + decode_content: bool | None = None, + cache_content: bool = False, + ) -> bytes: + """ + Similar to :meth:`http.client.HTTPResponse.read`, but with two additional + parameters: ``decode_content`` and ``cache_content``. + + :param amt: + How much of the content to read. If specified, caching is skipped + because it doesn't make sense to cache partial content as the full + response. + + :param decode_content: + If True, will attempt to decode the body based on the + 'content-encoding' header. + + :param cache_content: + If True, will save the returned data such that the same result is + returned despite of the state of the underlying file object. This + is useful if you want the ``.data`` property to continue working + after having ``.read()`` the file object. (Overridden if ``amt`` is + set.) + """ + self._init_decoder() + if decode_content is None: + decode_content = self.decode_content + + if amt and amt < 0: + # Negative numbers and `None` should be treated the same. + amt = None + elif amt is not None: + cache_content = False + + if len(self._decoded_buffer) >= amt: + return self._decoded_buffer.get(amt) + + data = self._raw_read(amt) + + flush_decoder = amt is None or (amt != 0 and not data) + + if not data and len(self._decoded_buffer) == 0: + return data + + if amt is None: + data = self._decode(data, decode_content, flush_decoder) + if cache_content: + self._body = data + else: + # do not waste memory on buffer when not decoding + if not decode_content: + if self._has_decoded_content: + raise RuntimeError( + "Calling read(decode_content=False) is not supported after " + "read(decode_content=True) was called." + ) + return data + + decoded_data = self._decode(data, decode_content, flush_decoder) + self._decoded_buffer.put(decoded_data) + + while len(self._decoded_buffer) < amt and data: + # TODO make sure to initially read enough data to get past the headers + # For example, the GZ file header takes 10 bytes, we don't want to read + # it one byte at a time + data = self._raw_read(amt) + decoded_data = self._decode(data, decode_content, flush_decoder) + self._decoded_buffer.put(decoded_data) + data = self._decoded_buffer.get(amt) + + return data + + def read1( + self, + amt: int | None = None, + decode_content: bool | None = None, + ) -> bytes: + """ + Similar to ``http.client.HTTPResponse.read1`` and documented + in :meth:`io.BufferedReader.read1`, but with an additional parameter: + ``decode_content``. + + :param amt: + How much of the content to read. + + :param decode_content: + If True, will attempt to decode the body based on the + 'content-encoding' header. + """ + if decode_content is None: + decode_content = self.decode_content + if amt and amt < 0: + # Negative numbers and `None` should be treated the same. + amt = None + # try and respond without going to the network + if self._has_decoded_content: + if not decode_content: + raise RuntimeError( + "Calling read1(decode_content=False) is not supported after " + "read1(decode_content=True) was called." + ) + if len(self._decoded_buffer) > 0: + if amt is None: + return self._decoded_buffer.get_all() + return self._decoded_buffer.get(amt) + if amt == 0: + return b"" + + # FIXME, this method's type doesn't say returning None is possible + data = self._raw_read(amt, read1=True) + if not decode_content or data is None: + return data + + self._init_decoder() + while True: + flush_decoder = not data + decoded_data = self._decode(data, decode_content, flush_decoder) + self._decoded_buffer.put(decoded_data) + if decoded_data or flush_decoder: + break + data = self._raw_read(8192, read1=True) + + if amt is None: + return self._decoded_buffer.get_all() + return self._decoded_buffer.get(amt) + + def stream( + self, amt: int | None = 2**16, decode_content: bool | None = None + ) -> typing.Generator[bytes]: + """ + A generator wrapper for the read() method. A call will block until + ``amt`` bytes have been read from the connection or until the + connection is closed. + + :param amt: + How much of the content to read. The generator will return up to + much data per iteration, but may return less. This is particularly + likely when using compressed data. However, the empty string will + never be returned. + + :param decode_content: + If True, will attempt to decode the body based on the + 'content-encoding' header. + """ + if self.chunked and self.supports_chunked_reads(): + yield from self.read_chunked(amt, decode_content=decode_content) + else: + while not is_fp_closed(self._fp) or len(self._decoded_buffer) > 0: + data = self.read(amt=amt, decode_content=decode_content) + + if data: + yield data + + # Overrides from io.IOBase + def readable(self) -> bool: + return True + + def shutdown(self) -> None: + if not self._sock_shutdown: + raise ValueError("Cannot shutdown socket as self._sock_shutdown is not set") + if self._connection is None: + raise RuntimeError( + "Cannot shutdown as connection has already been released to the pool" + ) + self._sock_shutdown(socket.SHUT_RD) + + def close(self) -> None: + self._sock_shutdown = None + + if not self.closed and self._fp: + self._fp.close() + + if self._connection: + self._connection.close() + + if not self.auto_close: + io.IOBase.close(self) + + @property + def closed(self) -> bool: + if not self.auto_close: + return io.IOBase.closed.__get__(self) # type: ignore[no-any-return] + elif self._fp is None: + return True + elif hasattr(self._fp, "isclosed"): + return self._fp.isclosed() + elif hasattr(self._fp, "closed"): + return self._fp.closed + else: + return True + + def fileno(self) -> int: + if self._fp is None: + raise OSError("HTTPResponse has no file to get a fileno from") + elif hasattr(self._fp, "fileno"): + return self._fp.fileno() + else: + raise OSError( + "The file-like object this HTTPResponse is wrapped " + "around has no file descriptor" + ) + + def flush(self) -> None: + if ( + self._fp is not None + and hasattr(self._fp, "flush") + and not getattr(self._fp, "closed", False) + ): + return self._fp.flush() + + def supports_chunked_reads(self) -> bool: + """ + Checks if the underlying file-like object looks like a + :class:`http.client.HTTPResponse` object. We do this by testing for + the fp attribute. If it is present we assume it returns raw chunks as + processed by read_chunked(). + """ + return hasattr(self._fp, "fp") + + def _update_chunk_length(self) -> None: + # First, we'll figure out length of a chunk and then + # we'll try to read it from socket. + if self.chunk_left is not None: + return None + line = self._fp.fp.readline() # type: ignore[union-attr] + line = line.split(b";", 1)[0] + try: + self.chunk_left = int(line, 16) + except ValueError: + self.close() + if line: + # Invalid chunked protocol response, abort. + raise InvalidChunkLength(self, line) from None + else: + # Truncated at start of next chunk + raise ProtocolError("Response ended prematurely") from None + + def _handle_chunk(self, amt: int | None) -> bytes: + returned_chunk = None + if amt is None: + chunk = self._fp._safe_read(self.chunk_left) # type: ignore[union-attr] + returned_chunk = chunk + self._fp._safe_read(2) # type: ignore[union-attr] # Toss the CRLF at the end of the chunk. + self.chunk_left = None + elif self.chunk_left is not None and amt < self.chunk_left: + value = self._fp._safe_read(amt) # type: ignore[union-attr] + self.chunk_left = self.chunk_left - amt + returned_chunk = value + elif amt == self.chunk_left: + value = self._fp._safe_read(amt) # type: ignore[union-attr] + self._fp._safe_read(2) # type: ignore[union-attr] # Toss the CRLF at the end of the chunk. + self.chunk_left = None + returned_chunk = value + else: # amt > self.chunk_left + returned_chunk = self._fp._safe_read(self.chunk_left) # type: ignore[union-attr] + self._fp._safe_read(2) # type: ignore[union-attr] # Toss the CRLF at the end of the chunk. + self.chunk_left = None + return returned_chunk # type: ignore[no-any-return] + + def read_chunked( + self, amt: int | None = None, decode_content: bool | None = None + ) -> typing.Generator[bytes]: + """ + Similar to :meth:`HTTPResponse.read`, but with an additional + parameter: ``decode_content``. + + :param amt: + How much of the content to read. If specified, caching is skipped + because it doesn't make sense to cache partial content as the full + response. + + :param decode_content: + If True, will attempt to decode the body based on the + 'content-encoding' header. + """ + self._init_decoder() + # FIXME: Rewrite this method and make it a class with a better structured logic. + if not self.chunked: + raise ResponseNotChunked( + "Response is not chunked. " + "Header 'transfer-encoding: chunked' is missing." + ) + if not self.supports_chunked_reads(): + raise BodyNotHttplibCompatible( + "Body should be http.client.HTTPResponse like. " + "It should have have an fp attribute which returns raw chunks." + ) + + with self._error_catcher(): + # Don't bother reading the body of a HEAD request. + if self._original_response and is_response_to_head(self._original_response): + self._original_response.close() + return None + + # If a response is already read and closed + # then return immediately. + if self._fp.fp is None: # type: ignore[union-attr] + return None + + if amt and amt < 0: + # Negative numbers and `None` should be treated the same, + # but httplib handles only `None` correctly. + amt = None + + while True: + self._update_chunk_length() + if self.chunk_left == 0: + break + chunk = self._handle_chunk(amt) + decoded = self._decode( + chunk, decode_content=decode_content, flush_decoder=False + ) + if decoded: + yield decoded + + if decode_content: + # On CPython and PyPy, we should never need to flush the + # decoder. However, on Jython we *might* need to, so + # lets defensively do it anyway. + decoded = self._flush_decoder() + if decoded: # Platform-specific: Jython. + yield decoded + + # Chunk content ends with \r\n: discard it. + while self._fp is not None: + line = self._fp.fp.readline() + if not line: + # Some sites may not end with '\r\n'. + break + if line == b"\r\n": + break + + # We read everything; close the "file". + if self._original_response: + self._original_response.close() + + @property + def url(self) -> str | None: + """ + Returns the URL that was the source of this response. + If the request that generated this response redirected, this method + will return the final redirect location. + """ + return self._request_url + + @url.setter + def url(self, url: str) -> None: + self._request_url = url + + def __iter__(self) -> typing.Iterator[bytes]: + buffer: list[bytes] = [] + for chunk in self.stream(decode_content=True): + if b"\n" in chunk: + chunks = chunk.split(b"\n") + yield b"".join(buffer) + chunks[0] + b"\n" + for x in chunks[1:-1]: + yield x + b"\n" + if chunks[-1]: + buffer = [chunks[-1]] + else: + buffer = [] + else: + buffer.append(chunk) + if buffer: + yield b"".join(buffer) diff --git a/venv/Lib/site-packages/urllib3/util/__init__.py b/venv/Lib/site-packages/urllib3/util/__init__.py new file mode 100644 index 00000000..53412603 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/util/__init__.py @@ -0,0 +1,42 @@ +# For backwards compatibility, provide imports that used to be here. +from __future__ import annotations + +from .connection import is_connection_dropped +from .request import SKIP_HEADER, SKIPPABLE_HEADERS, make_headers +from .response import is_fp_closed +from .retry import Retry +from .ssl_ import ( + ALPN_PROTOCOLS, + IS_PYOPENSSL, + SSLContext, + assert_fingerprint, + create_urllib3_context, + resolve_cert_reqs, + resolve_ssl_version, + ssl_wrap_socket, +) +from .timeout import Timeout +from .url import Url, parse_url +from .wait import wait_for_read, wait_for_write + +__all__ = ( + "IS_PYOPENSSL", + "SSLContext", + "ALPN_PROTOCOLS", + "Retry", + "Timeout", + "Url", + "assert_fingerprint", + "create_urllib3_context", + "is_connection_dropped", + "is_fp_closed", + "parse_url", + "make_headers", + "resolve_cert_reqs", + "resolve_ssl_version", + "ssl_wrap_socket", + "wait_for_read", + "wait_for_write", + "SKIP_HEADER", + "SKIPPABLE_HEADERS", +) diff --git a/venv/Lib/site-packages/urllib3/util/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/urllib3/util/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..bbe95760 Binary files /dev/null and b/venv/Lib/site-packages/urllib3/util/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/util/__pycache__/connection.cpython-312.pyc b/venv/Lib/site-packages/urllib3/util/__pycache__/connection.cpython-312.pyc new file mode 100644 index 00000000..06639ea8 Binary files /dev/null and b/venv/Lib/site-packages/urllib3/util/__pycache__/connection.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/util/__pycache__/proxy.cpython-312.pyc b/venv/Lib/site-packages/urllib3/util/__pycache__/proxy.cpython-312.pyc new file mode 100644 index 00000000..3d092e2a Binary files /dev/null and b/venv/Lib/site-packages/urllib3/util/__pycache__/proxy.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/util/__pycache__/request.cpython-312.pyc b/venv/Lib/site-packages/urllib3/util/__pycache__/request.cpython-312.pyc new file mode 100644 index 00000000..30890a11 Binary files /dev/null and b/venv/Lib/site-packages/urllib3/util/__pycache__/request.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/util/__pycache__/response.cpython-312.pyc b/venv/Lib/site-packages/urllib3/util/__pycache__/response.cpython-312.pyc new file mode 100644 index 00000000..d74532db Binary files /dev/null and b/venv/Lib/site-packages/urllib3/util/__pycache__/response.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/util/__pycache__/retry.cpython-312.pyc b/venv/Lib/site-packages/urllib3/util/__pycache__/retry.cpython-312.pyc new file mode 100644 index 00000000..a42d07a0 Binary files /dev/null and b/venv/Lib/site-packages/urllib3/util/__pycache__/retry.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/util/__pycache__/ssl_.cpython-312.pyc b/venv/Lib/site-packages/urllib3/util/__pycache__/ssl_.cpython-312.pyc new file mode 100644 index 00000000..542f6d4f Binary files /dev/null and b/venv/Lib/site-packages/urllib3/util/__pycache__/ssl_.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/util/__pycache__/ssl_match_hostname.cpython-312.pyc b/venv/Lib/site-packages/urllib3/util/__pycache__/ssl_match_hostname.cpython-312.pyc new file mode 100644 index 00000000..3ec7e437 Binary files /dev/null and b/venv/Lib/site-packages/urllib3/util/__pycache__/ssl_match_hostname.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/util/__pycache__/ssltransport.cpython-312.pyc b/venv/Lib/site-packages/urllib3/util/__pycache__/ssltransport.cpython-312.pyc new file mode 100644 index 00000000..32573de5 Binary files /dev/null and b/venv/Lib/site-packages/urllib3/util/__pycache__/ssltransport.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/util/__pycache__/timeout.cpython-312.pyc b/venv/Lib/site-packages/urllib3/util/__pycache__/timeout.cpython-312.pyc new file mode 100644 index 00000000..12cfe263 Binary files /dev/null and b/venv/Lib/site-packages/urllib3/util/__pycache__/timeout.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/util/__pycache__/url.cpython-312.pyc b/venv/Lib/site-packages/urllib3/util/__pycache__/url.cpython-312.pyc new file mode 100644 index 00000000..33f1c603 Binary files /dev/null and b/venv/Lib/site-packages/urllib3/util/__pycache__/url.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/util/__pycache__/util.cpython-312.pyc b/venv/Lib/site-packages/urllib3/util/__pycache__/util.cpython-312.pyc new file mode 100644 index 00000000..9ad03ef1 Binary files /dev/null and b/venv/Lib/site-packages/urllib3/util/__pycache__/util.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/util/__pycache__/wait.cpython-312.pyc b/venv/Lib/site-packages/urllib3/util/__pycache__/wait.cpython-312.pyc new file mode 100644 index 00000000..dbe8c4da Binary files /dev/null and b/venv/Lib/site-packages/urllib3/util/__pycache__/wait.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/urllib3/util/connection.py b/venv/Lib/site-packages/urllib3/util/connection.py new file mode 100644 index 00000000..f92519ee --- /dev/null +++ b/venv/Lib/site-packages/urllib3/util/connection.py @@ -0,0 +1,137 @@ +from __future__ import annotations + +import socket +import typing + +from ..exceptions import LocationParseError +from .timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT + +_TYPE_SOCKET_OPTIONS = list[tuple[int, int, typing.Union[int, bytes]]] + +if typing.TYPE_CHECKING: + from .._base_connection import BaseHTTPConnection + + +def is_connection_dropped(conn: BaseHTTPConnection) -> bool: # Platform-specific + """ + Returns True if the connection is dropped and should be closed. + :param conn: :class:`urllib3.connection.HTTPConnection` object. + """ + return not conn.is_connected + + +# This function is copied from socket.py in the Python 2.7 standard +# library test suite. Added to its signature is only `socket_options`. +# One additional modification is that we avoid binding to IPv6 servers +# discovered in DNS if the system doesn't have IPv6 functionality. +def create_connection( + address: tuple[str, int], + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + socket_options: _TYPE_SOCKET_OPTIONS | None = None, +) -> socket.socket: + """Connect to *address* and return the socket object. + + Convenience function. Connect to *address* (a 2-tuple ``(host, + port)``) and return the socket object. Passing the optional + *timeout* parameter will set the timeout on the socket instance + before attempting to connect. If no *timeout* is supplied, the + global default timeout setting returned by :func:`socket.getdefaulttimeout` + is used. If *source_address* is set it must be a tuple of (host, port) + for the socket to bind as a source address before making the connection. + An host of '' or port 0 tells the OS to use the default. + """ + + host, port = address + if host.startswith("["): + host = host.strip("[]") + err = None + + # Using the value from allowed_gai_family() in the context of getaddrinfo lets + # us select whether to work with IPv4 DNS records, IPv6 records, or both. + # The original create_connection function always returns all records. + family = allowed_gai_family() + + try: + host.encode("idna") + except UnicodeError: + raise LocationParseError(f"'{host}', label empty or too long") from None + + for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): + af, socktype, proto, canonname, sa = res + sock = None + try: + sock = socket.socket(af, socktype, proto) + + # If provided, set socket level options before connecting. + _set_socket_options(sock, socket_options) + + if timeout is not _DEFAULT_TIMEOUT: + sock.settimeout(timeout) + if source_address: + sock.bind(source_address) + sock.connect(sa) + # Break explicitly a reference cycle + err = None + return sock + + except OSError as _: + err = _ + if sock is not None: + sock.close() + + if err is not None: + try: + raise err + finally: + # Break explicitly a reference cycle + err = None + else: + raise OSError("getaddrinfo returns an empty list") + + +def _set_socket_options( + sock: socket.socket, options: _TYPE_SOCKET_OPTIONS | None +) -> None: + if options is None: + return + + for opt in options: + sock.setsockopt(*opt) + + +def allowed_gai_family() -> socket.AddressFamily: + """This function is designed to work in the context of + getaddrinfo, where family=socket.AF_UNSPEC is the default and + will perform a DNS search for both IPv6 and IPv4 records.""" + + family = socket.AF_INET + if HAS_IPV6: + family = socket.AF_UNSPEC + return family + + +def _has_ipv6(host: str) -> bool: + """Returns True if the system can bind an IPv6 address.""" + sock = None + has_ipv6 = False + + if socket.has_ipv6: + # has_ipv6 returns true if cPython was compiled with IPv6 support. + # It does not tell us if the system has IPv6 support enabled. To + # determine that we must bind to an IPv6 address. + # https://github.com/urllib3/urllib3/pull/611 + # https://bugs.python.org/issue658327 + try: + sock = socket.socket(socket.AF_INET6) + sock.bind((host, 0)) + has_ipv6 = True + except Exception: + pass + + if sock: + sock.close() + return has_ipv6 + + +HAS_IPV6 = _has_ipv6("::1") diff --git a/venv/Lib/site-packages/urllib3/util/proxy.py b/venv/Lib/site-packages/urllib3/util/proxy.py new file mode 100644 index 00000000..908fc662 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/util/proxy.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +import typing + +from .url import Url + +if typing.TYPE_CHECKING: + from ..connection import ProxyConfig + + +def connection_requires_http_tunnel( + proxy_url: Url | None = None, + proxy_config: ProxyConfig | None = None, + destination_scheme: str | None = None, +) -> bool: + """ + Returns True if the connection requires an HTTP CONNECT through the proxy. + + :param URL proxy_url: + URL of the proxy. + :param ProxyConfig proxy_config: + Proxy configuration from poolmanager.py + :param str destination_scheme: + The scheme of the destination. (i.e https, http, etc) + """ + # If we're not using a proxy, no way to use a tunnel. + if proxy_url is None: + return False + + # HTTP destinations never require tunneling, we always forward. + if destination_scheme == "http": + return False + + # Support for forwarding with HTTPS proxies and HTTPS destinations. + if ( + proxy_url.scheme == "https" + and proxy_config + and proxy_config.use_forwarding_for_https + ): + return False + + # Otherwise always use a tunnel. + return True diff --git a/venv/Lib/site-packages/urllib3/util/request.py b/venv/Lib/site-packages/urllib3/util/request.py new file mode 100644 index 00000000..23605c52 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/util/request.py @@ -0,0 +1,266 @@ +from __future__ import annotations + +import io +import typing +from base64 import b64encode +from enum import Enum + +from ..exceptions import UnrewindableBodyError +from .util import to_bytes + +if typing.TYPE_CHECKING: + from typing import Final + +# Pass as a value within ``headers`` to skip +# emitting some HTTP headers that are added automatically. +# The only headers that are supported are ``Accept-Encoding``, +# ``Host``, and ``User-Agent``. +SKIP_HEADER = "@@@SKIP_HEADER@@@" +SKIPPABLE_HEADERS = frozenset(["accept-encoding", "host", "user-agent"]) + +ACCEPT_ENCODING = "gzip,deflate" +try: + try: + import brotlicffi as _unused_module_brotli # type: ignore[import-not-found] # noqa: F401 + except ImportError: + import brotli as _unused_module_brotli # type: ignore[import-not-found] # noqa: F401 +except ImportError: + pass +else: + ACCEPT_ENCODING += ",br" + +try: + from compression import ( # type: ignore[import-not-found] # noqa: F401 + zstd as _unused_module_zstd, + ) + + ACCEPT_ENCODING += ",zstd" +except ImportError: + try: + import zstandard as _unused_module_zstd # noqa: F401 + + ACCEPT_ENCODING += ",zstd" + except ImportError: + pass + + +class _TYPE_FAILEDTELL(Enum): + token = 0 + + +_FAILEDTELL: Final[_TYPE_FAILEDTELL] = _TYPE_FAILEDTELL.token + +_TYPE_BODY_POSITION = typing.Union[int, _TYPE_FAILEDTELL] + +# When sending a request with these methods we aren't expecting +# a body so don't need to set an explicit 'Content-Length: 0' +# The reason we do this in the negative instead of tracking methods +# which 'should' have a body is because unknown methods should be +# treated as if they were 'POST' which *does* expect a body. +_METHODS_NOT_EXPECTING_BODY = {"GET", "HEAD", "DELETE", "TRACE", "OPTIONS", "CONNECT"} + + +def make_headers( + keep_alive: bool | None = None, + accept_encoding: bool | list[str] | str | None = None, + user_agent: str | None = None, + basic_auth: str | None = None, + proxy_basic_auth: str | None = None, + disable_cache: bool | None = None, +) -> dict[str, str]: + """ + Shortcuts for generating request headers. + + :param keep_alive: + If ``True``, adds 'connection: keep-alive' header. + + :param accept_encoding: + Can be a boolean, list, or string. + ``True`` translates to 'gzip,deflate'. If the dependencies for + Brotli (either the ``brotli`` or ``brotlicffi`` package) and/or Zstandard + (the ``zstandard`` package) algorithms are installed, then their encodings are + included in the string ('br' and 'zstd', respectively). + List will get joined by comma. + String will be used as provided. + + :param user_agent: + String representing the user-agent you want, such as + "python-urllib3/0.6" + + :param basic_auth: + Colon-separated username:password string for 'authorization: basic ...' + auth header. + + :param proxy_basic_auth: + Colon-separated username:password string for 'proxy-authorization: basic ...' + auth header. + + :param disable_cache: + If ``True``, adds 'cache-control: no-cache' header. + + Example: + + .. code-block:: python + + import urllib3 + + print(urllib3.util.make_headers(keep_alive=True, user_agent="Batman/1.0")) + # {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'} + print(urllib3.util.make_headers(accept_encoding=True)) + # {'accept-encoding': 'gzip,deflate'} + """ + headers: dict[str, str] = {} + if accept_encoding: + if isinstance(accept_encoding, str): + pass + elif isinstance(accept_encoding, list): + accept_encoding = ",".join(accept_encoding) + else: + accept_encoding = ACCEPT_ENCODING + headers["accept-encoding"] = accept_encoding + + if user_agent: + headers["user-agent"] = user_agent + + if keep_alive: + headers["connection"] = "keep-alive" + + if basic_auth: + headers["authorization"] = ( + f"Basic {b64encode(basic_auth.encode('latin-1')).decode()}" + ) + + if proxy_basic_auth: + headers["proxy-authorization"] = ( + f"Basic {b64encode(proxy_basic_auth.encode('latin-1')).decode()}" + ) + + if disable_cache: + headers["cache-control"] = "no-cache" + + return headers + + +def set_file_position( + body: typing.Any, pos: _TYPE_BODY_POSITION | None +) -> _TYPE_BODY_POSITION | None: + """ + If a position is provided, move file to that point. + Otherwise, we'll attempt to record a position for future use. + """ + if pos is not None: + rewind_body(body, pos) + elif getattr(body, "tell", None) is not None: + try: + pos = body.tell() + except OSError: + # This differentiates from None, allowing us to catch + # a failed `tell()` later when trying to rewind the body. + pos = _FAILEDTELL + + return pos + + +def rewind_body(body: typing.IO[typing.AnyStr], body_pos: _TYPE_BODY_POSITION) -> None: + """ + Attempt to rewind body to a certain position. + Primarily used for request redirects and retries. + + :param body: + File-like object that supports seek. + + :param int pos: + Position to seek to in file. + """ + body_seek = getattr(body, "seek", None) + if body_seek is not None and isinstance(body_pos, int): + try: + body_seek(body_pos) + except OSError as e: + raise UnrewindableBodyError( + "An error occurred when rewinding request body for redirect/retry." + ) from e + elif body_pos is _FAILEDTELL: + raise UnrewindableBodyError( + "Unable to record file position for rewinding " + "request body during a redirect/retry." + ) + else: + raise ValueError( + f"body_pos must be of type integer, instead it was {type(body_pos)}." + ) + + +class ChunksAndContentLength(typing.NamedTuple): + chunks: typing.Iterable[bytes] | None + content_length: int | None + + +def body_to_chunks( + body: typing.Any | None, method: str, blocksize: int +) -> ChunksAndContentLength: + """Takes the HTTP request method, body, and blocksize and + transforms them into an iterable of chunks to pass to + socket.sendall() and an optional 'Content-Length' header. + + A 'Content-Length' of 'None' indicates the length of the body + can't be determined so should use 'Transfer-Encoding: chunked' + for framing instead. + """ + + chunks: typing.Iterable[bytes] | None + content_length: int | None + + # No body, we need to make a recommendation on 'Content-Length' + # based on whether that request method is expected to have + # a body or not. + if body is None: + chunks = None + if method.upper() not in _METHODS_NOT_EXPECTING_BODY: + content_length = 0 + else: + content_length = None + + # Bytes or strings become bytes + elif isinstance(body, (str, bytes)): + chunks = (to_bytes(body),) + content_length = len(chunks[0]) + + # File-like object, TODO: use seek() and tell() for length? + elif hasattr(body, "read"): + + def chunk_readable() -> typing.Iterable[bytes]: + nonlocal body, blocksize + encode = isinstance(body, io.TextIOBase) + while True: + datablock = body.read(blocksize) + if not datablock: + break + if encode: + datablock = datablock.encode("utf-8") + yield datablock + + chunks = chunk_readable() + content_length = None + + # Otherwise we need to start checking via duck-typing. + else: + try: + # Check if the body implements the buffer API. + mv = memoryview(body) + except TypeError: + try: + # Check if the body is an iterable + chunks = iter(body) + content_length = None + except TypeError: + raise TypeError( + f"'body' must be a bytes-like object, file-like " + f"object, or iterable. Instead was {body!r}" + ) from None + else: + # Since it implements the buffer API can be passed directly to socket.sendall() + chunks = (body,) + content_length = mv.nbytes + + return ChunksAndContentLength(chunks=chunks, content_length=content_length) diff --git a/venv/Lib/site-packages/urllib3/util/response.py b/venv/Lib/site-packages/urllib3/util/response.py new file mode 100644 index 00000000..0f457869 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/util/response.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +import http.client as httplib +from email.errors import MultipartInvariantViolationDefect, StartBoundaryNotFoundDefect + +from ..exceptions import HeaderParsingError + + +def is_fp_closed(obj: object) -> bool: + """ + Checks whether a given file-like object is closed. + + :param obj: + The file-like object to check. + """ + + try: + # Check `isclosed()` first, in case Python3 doesn't set `closed`. + # GH Issue #928 + return obj.isclosed() # type: ignore[no-any-return, attr-defined] + except AttributeError: + pass + + try: + # Check via the official file-like-object way. + return obj.closed # type: ignore[no-any-return, attr-defined] + except AttributeError: + pass + + try: + # Check if the object is a container for another file-like object that + # gets released on exhaustion (e.g. HTTPResponse). + return obj.fp is None # type: ignore[attr-defined] + except AttributeError: + pass + + raise ValueError("Unable to determine whether fp is closed.") + + +def assert_header_parsing(headers: httplib.HTTPMessage) -> None: + """ + Asserts whether all headers have been successfully parsed. + Extracts encountered errors from the result of parsing headers. + + Only works on Python 3. + + :param http.client.HTTPMessage headers: Headers to verify. + + :raises urllib3.exceptions.HeaderParsingError: + If parsing errors are found. + """ + + # This will fail silently if we pass in the wrong kind of parameter. + # To make debugging easier add an explicit check. + if not isinstance(headers, httplib.HTTPMessage): + raise TypeError(f"expected httplib.Message, got {type(headers)}.") + + unparsed_data = None + + # get_payload is actually email.message.Message.get_payload; + # we're only interested in the result if it's not a multipart message + if not headers.is_multipart(): + payload = headers.get_payload() + + if isinstance(payload, (bytes, str)): + unparsed_data = payload + + # httplib is assuming a response body is available + # when parsing headers even when httplib only sends + # header data to parse_headers() This results in + # defects on multipart responses in particular. + # See: https://github.com/urllib3/urllib3/issues/800 + + # So we ignore the following defects: + # - StartBoundaryNotFoundDefect: + # The claimed start boundary was never found. + # - MultipartInvariantViolationDefect: + # A message claimed to be a multipart but no subparts were found. + defects = [ + defect + for defect in headers.defects + if not isinstance( + defect, (StartBoundaryNotFoundDefect, MultipartInvariantViolationDefect) + ) + ] + + if defects or unparsed_data: + raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data) + + +def is_response_to_head(response: httplib.HTTPResponse) -> bool: + """ + Checks whether the request of a response has been a HEAD-request. + + :param http.client.HTTPResponse response: + Response to check if the originating request + used 'HEAD' as a method. + """ + # FIXME: Can we do this somehow without accessing private httplib _method? + method_str = response._method # type: str # type: ignore[attr-defined] + return method_str.upper() == "HEAD" diff --git a/venv/Lib/site-packages/urllib3/util/retry.py b/venv/Lib/site-packages/urllib3/util/retry.py new file mode 100644 index 00000000..0456cceb --- /dev/null +++ b/venv/Lib/site-packages/urllib3/util/retry.py @@ -0,0 +1,533 @@ +from __future__ import annotations + +import email +import logging +import random +import re +import time +import typing +from itertools import takewhile +from types import TracebackType + +from ..exceptions import ( + ConnectTimeoutError, + InvalidHeader, + MaxRetryError, + ProtocolError, + ProxyError, + ReadTimeoutError, + ResponseError, +) +from .util import reraise + +if typing.TYPE_CHECKING: + from typing_extensions import Self + + from ..connectionpool import ConnectionPool + from ..response import BaseHTTPResponse + +log = logging.getLogger(__name__) + + +# Data structure for representing the metadata of requests that result in a retry. +class RequestHistory(typing.NamedTuple): + method: str | None + url: str | None + error: Exception | None + status: int | None + redirect_location: str | None + + +class Retry: + """Retry configuration. + + Each retry attempt will create a new Retry object with updated values, so + they can be safely reused. + + Retries can be defined as a default for a pool: + + .. code-block:: python + + retries = Retry(connect=5, read=2, redirect=5) + http = PoolManager(retries=retries) + response = http.request("GET", "https://example.com/") + + Or per-request (which overrides the default for the pool): + + .. code-block:: python + + response = http.request("GET", "https://example.com/", retries=Retry(10)) + + Retries can be disabled by passing ``False``: + + .. code-block:: python + + response = http.request("GET", "https://example.com/", retries=False) + + Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless + retries are disabled, in which case the causing exception will be raised. + + :param int total: + Total number of retries to allow. Takes precedence over other counts. + + Set to ``None`` to remove this constraint and fall back on other + counts. + + Set to ``0`` to fail on the first retry. + + Set to ``False`` to disable and imply ``raise_on_redirect=False``. + + :param int connect: + How many connection-related errors to retry on. + + These are errors raised before the request is sent to the remote server, + which we assume has not triggered the server to process the request. + + Set to ``0`` to fail on the first retry of this type. + + :param int read: + How many times to retry on read errors. + + These errors are raised after the request was sent to the server, so the + request may have side-effects. + + Set to ``0`` to fail on the first retry of this type. + + :param int redirect: + How many redirects to perform. Limit this to avoid infinite redirect + loops. + + A redirect is a HTTP response with a status code 301, 302, 303, 307 or + 308. + + Set to ``0`` to fail on the first retry of this type. + + Set to ``False`` to disable and imply ``raise_on_redirect=False``. + + :param int status: + How many times to retry on bad status codes. + + These are retries made on responses, where status code matches + ``status_forcelist``. + + Set to ``0`` to fail on the first retry of this type. + + :param int other: + How many times to retry on other errors. + + Other errors are errors that are not connect, read, redirect or status errors. + These errors might be raised after the request was sent to the server, so the + request might have side-effects. + + Set to ``0`` to fail on the first retry of this type. + + If ``total`` is not set, it's a good idea to set this to 0 to account + for unexpected edge cases and avoid infinite retry loops. + + :param Collection allowed_methods: + Set of uppercased HTTP method verbs that we should retry on. + + By default, we only retry on methods which are considered to be + idempotent (multiple requests with the same parameters end with the + same state). See :attr:`Retry.DEFAULT_ALLOWED_METHODS`. + + Set to a ``None`` value to retry on any verb. + + :param Collection status_forcelist: + A set of integer HTTP status codes that we should force a retry on. + A retry is initiated if the request method is in ``allowed_methods`` + and the response status code is in ``status_forcelist``. + + By default, this is disabled with ``None``. + + :param float backoff_factor: + A backoff factor to apply between attempts after the second try + (most errors are resolved immediately by a second try without a + delay). urllib3 will sleep for:: + + {backoff factor} * (2 ** ({number of previous retries})) + + seconds. If `backoff_jitter` is non-zero, this sleep is extended by:: + + random.uniform(0, {backoff jitter}) + + seconds. For example, if the backoff_factor is 0.1, then :func:`Retry.sleep` will + sleep for [0.0s, 0.2s, 0.4s, 0.8s, ...] between retries. No backoff will ever + be longer than `backoff_max`. + + By default, backoff is disabled (factor set to 0). + + :param bool raise_on_redirect: Whether, if the number of redirects is + exhausted, to raise a MaxRetryError, or to return a response with a + response code in the 3xx range. + + :param bool raise_on_status: Similar meaning to ``raise_on_redirect``: + whether we should raise an exception, or return a response, + if status falls in ``status_forcelist`` range and retries have + been exhausted. + + :param tuple history: The history of the request encountered during + each call to :meth:`~Retry.increment`. The list is in the order + the requests occurred. Each list item is of class :class:`RequestHistory`. + + :param bool respect_retry_after_header: + Whether to respect Retry-After header on status codes defined as + :attr:`Retry.RETRY_AFTER_STATUS_CODES` or not. + + :param Collection remove_headers_on_redirect: + Sequence of headers to remove from the request when a response + indicating a redirect is returned before firing off the redirected + request. + """ + + #: Default methods to be used for ``allowed_methods`` + DEFAULT_ALLOWED_METHODS = frozenset( + ["HEAD", "GET", "PUT", "DELETE", "OPTIONS", "TRACE"] + ) + + #: Default status codes to be used for ``status_forcelist`` + RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503]) + + #: Default headers to be used for ``remove_headers_on_redirect`` + DEFAULT_REMOVE_HEADERS_ON_REDIRECT = frozenset( + ["Cookie", "Authorization", "Proxy-Authorization"] + ) + + #: Default maximum backoff time. + DEFAULT_BACKOFF_MAX = 120 + + # Backward compatibility; assigned outside of the class. + DEFAULT: typing.ClassVar[Retry] + + def __init__( + self, + total: bool | int | None = 10, + connect: int | None = None, + read: int | None = None, + redirect: bool | int | None = None, + status: int | None = None, + other: int | None = None, + allowed_methods: typing.Collection[str] | None = DEFAULT_ALLOWED_METHODS, + status_forcelist: typing.Collection[int] | None = None, + backoff_factor: float = 0, + backoff_max: float = DEFAULT_BACKOFF_MAX, + raise_on_redirect: bool = True, + raise_on_status: bool = True, + history: tuple[RequestHistory, ...] | None = None, + respect_retry_after_header: bool = True, + remove_headers_on_redirect: typing.Collection[ + str + ] = DEFAULT_REMOVE_HEADERS_ON_REDIRECT, + backoff_jitter: float = 0.0, + ) -> None: + self.total = total + self.connect = connect + self.read = read + self.status = status + self.other = other + + if redirect is False or total is False: + redirect = 0 + raise_on_redirect = False + + self.redirect = redirect + self.status_forcelist = status_forcelist or set() + self.allowed_methods = allowed_methods + self.backoff_factor = backoff_factor + self.backoff_max = backoff_max + self.raise_on_redirect = raise_on_redirect + self.raise_on_status = raise_on_status + self.history = history or () + self.respect_retry_after_header = respect_retry_after_header + self.remove_headers_on_redirect = frozenset( + h.lower() for h in remove_headers_on_redirect + ) + self.backoff_jitter = backoff_jitter + + def new(self, **kw: typing.Any) -> Self: + params = dict( + total=self.total, + connect=self.connect, + read=self.read, + redirect=self.redirect, + status=self.status, + other=self.other, + allowed_methods=self.allowed_methods, + status_forcelist=self.status_forcelist, + backoff_factor=self.backoff_factor, + backoff_max=self.backoff_max, + raise_on_redirect=self.raise_on_redirect, + raise_on_status=self.raise_on_status, + history=self.history, + remove_headers_on_redirect=self.remove_headers_on_redirect, + respect_retry_after_header=self.respect_retry_after_header, + backoff_jitter=self.backoff_jitter, + ) + + params.update(kw) + return type(self)(**params) # type: ignore[arg-type] + + @classmethod + def from_int( + cls, + retries: Retry | bool | int | None, + redirect: bool | int | None = True, + default: Retry | bool | int | None = None, + ) -> Retry: + """Backwards-compatibility for the old retries format.""" + if retries is None: + retries = default if default is not None else cls.DEFAULT + + if isinstance(retries, Retry): + return retries + + redirect = bool(redirect) and None + new_retries = cls(retries, redirect=redirect) + log.debug("Converted retries value: %r -> %r", retries, new_retries) + return new_retries + + def get_backoff_time(self) -> float: + """Formula for computing the current backoff + + :rtype: float + """ + # We want to consider only the last consecutive errors sequence (Ignore redirects). + consecutive_errors_len = len( + list( + takewhile(lambda x: x.redirect_location is None, reversed(self.history)) + ) + ) + if consecutive_errors_len <= 1: + return 0 + + backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1)) + if self.backoff_jitter != 0.0: + backoff_value += random.random() * self.backoff_jitter + return float(max(0, min(self.backoff_max, backoff_value))) + + def parse_retry_after(self, retry_after: str) -> float: + seconds: float + # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4 + if re.match(r"^\s*[0-9]+\s*$", retry_after): + seconds = int(retry_after) + else: + retry_date_tuple = email.utils.parsedate_tz(retry_after) + if retry_date_tuple is None: + raise InvalidHeader(f"Invalid Retry-After header: {retry_after}") + + retry_date = email.utils.mktime_tz(retry_date_tuple) + seconds = retry_date - time.time() + + seconds = max(seconds, 0) + + return seconds + + def get_retry_after(self, response: BaseHTTPResponse) -> float | None: + """Get the value of Retry-After in seconds.""" + + retry_after = response.headers.get("Retry-After") + + if retry_after is None: + return None + + return self.parse_retry_after(retry_after) + + def sleep_for_retry(self, response: BaseHTTPResponse) -> bool: + retry_after = self.get_retry_after(response) + if retry_after: + time.sleep(retry_after) + return True + + return False + + def _sleep_backoff(self) -> None: + backoff = self.get_backoff_time() + if backoff <= 0: + return + time.sleep(backoff) + + def sleep(self, response: BaseHTTPResponse | None = None) -> None: + """Sleep between retry attempts. + + This method will respect a server's ``Retry-After`` response header + and sleep the duration of the time requested. If that is not present, it + will use an exponential backoff. By default, the backoff factor is 0 and + this method will return immediately. + """ + + if self.respect_retry_after_header and response: + slept = self.sleep_for_retry(response) + if slept: + return + + self._sleep_backoff() + + def _is_connection_error(self, err: Exception) -> bool: + """Errors when we're fairly sure that the server did not receive the + request, so it should be safe to retry. + """ + if isinstance(err, ProxyError): + err = err.original_error + return isinstance(err, ConnectTimeoutError) + + def _is_read_error(self, err: Exception) -> bool: + """Errors that occur after the request has been started, so we should + assume that the server began processing it. + """ + return isinstance(err, (ReadTimeoutError, ProtocolError)) + + def _is_method_retryable(self, method: str) -> bool: + """Checks if a given HTTP method should be retried upon, depending if + it is included in the allowed_methods + """ + if self.allowed_methods and method.upper() not in self.allowed_methods: + return False + return True + + def is_retry( + self, method: str, status_code: int, has_retry_after: bool = False + ) -> bool: + """Is this method/status code retryable? (Based on allowlists and control + variables such as the number of total retries to allow, whether to + respect the Retry-After header, whether this header is present, and + whether the returned status code is on the list of status codes to + be retried upon on the presence of the aforementioned header) + """ + if not self._is_method_retryable(method): + return False + + if self.status_forcelist and status_code in self.status_forcelist: + return True + + return bool( + self.total + and self.respect_retry_after_header + and has_retry_after + and (status_code in self.RETRY_AFTER_STATUS_CODES) + ) + + def is_exhausted(self) -> bool: + """Are we out of retries?""" + retry_counts = [ + x + for x in ( + self.total, + self.connect, + self.read, + self.redirect, + self.status, + self.other, + ) + if x + ] + if not retry_counts: + return False + + return min(retry_counts) < 0 + + def increment( + self, + method: str | None = None, + url: str | None = None, + response: BaseHTTPResponse | None = None, + error: Exception | None = None, + _pool: ConnectionPool | None = None, + _stacktrace: TracebackType | None = None, + ) -> Self: + """Return a new Retry object with incremented retry counters. + + :param response: A response object, or None, if the server did not + return a response. + :type response: :class:`~urllib3.response.BaseHTTPResponse` + :param Exception error: An error encountered during the request, or + None if the response was received successfully. + + :return: A new ``Retry`` object. + """ + if self.total is False and error: + # Disabled, indicate to re-raise the error. + raise reraise(type(error), error, _stacktrace) + + total = self.total + if total is not None: + total -= 1 + + connect = self.connect + read = self.read + redirect = self.redirect + status_count = self.status + other = self.other + cause = "unknown" + status = None + redirect_location = None + + if error and self._is_connection_error(error): + # Connect retry? + if connect is False: + raise reraise(type(error), error, _stacktrace) + elif connect is not None: + connect -= 1 + + elif error and self._is_read_error(error): + # Read retry? + if read is False or method is None or not self._is_method_retryable(method): + raise reraise(type(error), error, _stacktrace) + elif read is not None: + read -= 1 + + elif error: + # Other retry? + if other is not None: + other -= 1 + + elif response and response.get_redirect_location(): + # Redirect retry? + if redirect is not None: + redirect -= 1 + cause = "too many redirects" + response_redirect_location = response.get_redirect_location() + if response_redirect_location: + redirect_location = response_redirect_location + status = response.status + + else: + # Incrementing because of a server error like a 500 in + # status_forcelist and the given method is in the allowed_methods + cause = ResponseError.GENERIC_ERROR + if response and response.status: + if status_count is not None: + status_count -= 1 + cause = ResponseError.SPECIFIC_ERROR.format(status_code=response.status) + status = response.status + + history = self.history + ( + RequestHistory(method, url, error, status, redirect_location), + ) + + new_retry = self.new( + total=total, + connect=connect, + read=read, + redirect=redirect, + status=status_count, + other=other, + history=history, + ) + + if new_retry.is_exhausted(): + reason = error or ResponseError(cause) + raise MaxRetryError(_pool, url, reason) from reason # type: ignore[arg-type] + + log.debug("Incremented Retry for (url='%s'): %r", url, new_retry) + + return new_retry + + def __repr__(self) -> str: + return ( + f"{type(self).__name__}(total={self.total}, connect={self.connect}, " + f"read={self.read}, redirect={self.redirect}, status={self.status})" + ) + + +# For backwards compatibility (equivalent to pre-v1.9): +Retry.DEFAULT = Retry(3) diff --git a/venv/Lib/site-packages/urllib3/util/ssl_.py b/venv/Lib/site-packages/urllib3/util/ssl_.py new file mode 100644 index 00000000..b2cc1aa7 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/util/ssl_.py @@ -0,0 +1,524 @@ +from __future__ import annotations + +import hashlib +import hmac +import os +import socket +import sys +import typing +import warnings +from binascii import unhexlify + +from ..exceptions import ProxySchemeUnsupported, SSLError +from .url import _BRACELESS_IPV6_ADDRZ_RE, _IPV4_RE + +SSLContext = None +SSLTransport = None +HAS_NEVER_CHECK_COMMON_NAME = False +IS_PYOPENSSL = False +ALPN_PROTOCOLS = ["http/1.1"] + +_TYPE_VERSION_INFO = tuple[int, int, int, str, int] + +# Maps the length of a digest to a possible hash function producing this digest +HASHFUNC_MAP = { + length: getattr(hashlib, algorithm, None) + for length, algorithm in ((32, "md5"), (40, "sha1"), (64, "sha256")) +} + + +def _is_bpo_43522_fixed( + implementation_name: str, + version_info: _TYPE_VERSION_INFO, + pypy_version_info: _TYPE_VERSION_INFO | None, +) -> bool: + """Return True for CPython 3.9.3+ or 3.10+ and PyPy 7.3.8+ where + setting SSLContext.hostname_checks_common_name to False works. + + Outside of CPython and PyPy we don't know which implementations work + or not so we conservatively use our hostname matching as we know that works + on all implementations. + + https://github.com/urllib3/urllib3/issues/2192#issuecomment-821832963 + https://foss.heptapod.net/pypy/pypy/-/issues/3539 + """ + if implementation_name == "pypy": + # https://foss.heptapod.net/pypy/pypy/-/issues/3129 + return pypy_version_info >= (7, 3, 8) # type: ignore[operator] + elif implementation_name == "cpython": + major_minor = version_info[:2] + micro = version_info[2] + return (major_minor == (3, 9) and micro >= 3) or major_minor >= (3, 10) + else: # Defensive: + return False + + +def _is_has_never_check_common_name_reliable( + openssl_version: str, + openssl_version_number: int, + implementation_name: str, + version_info: _TYPE_VERSION_INFO, + pypy_version_info: _TYPE_VERSION_INFO | None, +) -> bool: + # As of May 2023, all released versions of LibreSSL fail to reject certificates with + # only common names, see https://github.com/urllib3/urllib3/pull/3024 + is_openssl = openssl_version.startswith("OpenSSL ") + # Before fixing OpenSSL issue #14579, the SSL_new() API was not copying hostflags + # like X509_CHECK_FLAG_NEVER_CHECK_SUBJECT, which tripped up CPython. + # https://github.com/openssl/openssl/issues/14579 + # This was released in OpenSSL 1.1.1l+ (>=0x101010cf) + is_openssl_issue_14579_fixed = openssl_version_number >= 0x101010CF + + return is_openssl and ( + is_openssl_issue_14579_fixed + or _is_bpo_43522_fixed(implementation_name, version_info, pypy_version_info) + ) + + +if typing.TYPE_CHECKING: + from ssl import VerifyMode + from typing import TypedDict + + from .ssltransport import SSLTransport as SSLTransportType + + class _TYPE_PEER_CERT_RET_DICT(TypedDict, total=False): + subjectAltName: tuple[tuple[str, str], ...] + subject: tuple[tuple[tuple[str, str], ...], ...] + serialNumber: str + + +# Mapping from 'ssl.PROTOCOL_TLSX' to 'TLSVersion.X' +_SSL_VERSION_TO_TLS_VERSION: dict[int, int] = {} + +try: # Do we have ssl at all? + import ssl + from ssl import ( # type: ignore[assignment] + CERT_REQUIRED, + HAS_NEVER_CHECK_COMMON_NAME, + OP_NO_COMPRESSION, + OP_NO_TICKET, + OPENSSL_VERSION, + OPENSSL_VERSION_NUMBER, + PROTOCOL_TLS, + PROTOCOL_TLS_CLIENT, + VERIFY_X509_STRICT, + OP_NO_SSLv2, + OP_NO_SSLv3, + SSLContext, + TLSVersion, + ) + + PROTOCOL_SSLv23 = PROTOCOL_TLS + + # Needed for Python 3.9 which does not define this + VERIFY_X509_PARTIAL_CHAIN = getattr(ssl, "VERIFY_X509_PARTIAL_CHAIN", 0x80000) + + # Setting SSLContext.hostname_checks_common_name = False didn't work before CPython + # 3.9.3, and 3.10 (but OK on PyPy) or OpenSSL 1.1.1l+ + if HAS_NEVER_CHECK_COMMON_NAME and not _is_has_never_check_common_name_reliable( + OPENSSL_VERSION, + OPENSSL_VERSION_NUMBER, + sys.implementation.name, + sys.version_info, + sys.pypy_version_info if sys.implementation.name == "pypy" else None, # type: ignore[attr-defined] + ): # Defensive: for Python < 3.9.3 + HAS_NEVER_CHECK_COMMON_NAME = False + + # Need to be careful here in case old TLS versions get + # removed in future 'ssl' module implementations. + for attr in ("TLSv1", "TLSv1_1", "TLSv1_2"): + try: + _SSL_VERSION_TO_TLS_VERSION[getattr(ssl, f"PROTOCOL_{attr}")] = getattr( + TLSVersion, attr + ) + except AttributeError: # Defensive: + continue + + from .ssltransport import SSLTransport # type: ignore[assignment] +except ImportError: + OP_NO_COMPRESSION = 0x20000 # type: ignore[assignment] + OP_NO_TICKET = 0x4000 # type: ignore[assignment] + OP_NO_SSLv2 = 0x1000000 # type: ignore[assignment] + OP_NO_SSLv3 = 0x2000000 # type: ignore[assignment] + PROTOCOL_SSLv23 = PROTOCOL_TLS = 2 # type: ignore[assignment] + PROTOCOL_TLS_CLIENT = 16 # type: ignore[assignment] + VERIFY_X509_PARTIAL_CHAIN = 0x80000 + VERIFY_X509_STRICT = 0x20 # type: ignore[assignment] + + +_TYPE_PEER_CERT_RET = typing.Union["_TYPE_PEER_CERT_RET_DICT", bytes, None] + + +def assert_fingerprint(cert: bytes | None, fingerprint: str) -> None: + """ + Checks if given fingerprint matches the supplied certificate. + + :param cert: + Certificate as bytes object. + :param fingerprint: + Fingerprint as string of hexdigits, can be interspersed by colons. + """ + + if cert is None: + raise SSLError("No certificate for the peer.") + + fingerprint = fingerprint.replace(":", "").lower() + digest_length = len(fingerprint) + if digest_length not in HASHFUNC_MAP: + raise SSLError(f"Fingerprint of invalid length: {fingerprint}") + hashfunc = HASHFUNC_MAP.get(digest_length) + if hashfunc is None: + raise SSLError( + f"Hash function implementation unavailable for fingerprint length: {digest_length}" + ) + + # We need encode() here for py32; works on py2 and p33. + fingerprint_bytes = unhexlify(fingerprint.encode()) + + cert_digest = hashfunc(cert).digest() + + if not hmac.compare_digest(cert_digest, fingerprint_bytes): + raise SSLError( + f'Fingerprints did not match. Expected "{fingerprint}", got "{cert_digest.hex()}"' + ) + + +def resolve_cert_reqs(candidate: None | int | str) -> VerifyMode: + """ + Resolves the argument to a numeric constant, which can be passed to + the wrap_socket function/method from the ssl module. + Defaults to :data:`ssl.CERT_REQUIRED`. + If given a string it is assumed to be the name of the constant in the + :mod:`ssl` module or its abbreviation. + (So you can specify `REQUIRED` instead of `CERT_REQUIRED`. + If it's neither `None` nor a string we assume it is already the numeric + constant which can directly be passed to wrap_socket. + """ + if candidate is None: + return CERT_REQUIRED + + if isinstance(candidate, str): + res = getattr(ssl, candidate, None) + if res is None: + res = getattr(ssl, "CERT_" + candidate) + return res # type: ignore[no-any-return] + + return candidate # type: ignore[return-value] + + +def resolve_ssl_version(candidate: None | int | str) -> int: + """ + like resolve_cert_reqs + """ + if candidate is None: + return PROTOCOL_TLS + + if isinstance(candidate, str): + res = getattr(ssl, candidate, None) + if res is None: + res = getattr(ssl, "PROTOCOL_" + candidate) + return typing.cast(int, res) + + return candidate + + +def create_urllib3_context( + ssl_version: int | None = None, + cert_reqs: int | None = None, + options: int | None = None, + ciphers: str | None = None, + ssl_minimum_version: int | None = None, + ssl_maximum_version: int | None = None, + verify_flags: int | None = None, +) -> ssl.SSLContext: + """Creates and configures an :class:`ssl.SSLContext` instance for use with urllib3. + + :param ssl_version: + The desired protocol version to use. This will default to + PROTOCOL_SSLv23 which will negotiate the highest protocol that both + the server and your installation of OpenSSL support. + + This parameter is deprecated instead use 'ssl_minimum_version'. + :param ssl_minimum_version: + The minimum version of TLS to be used. Use the 'ssl.TLSVersion' enum for specifying the value. + :param ssl_maximum_version: + The maximum version of TLS to be used. Use the 'ssl.TLSVersion' enum for specifying the value. + Not recommended to set to anything other than 'ssl.TLSVersion.MAXIMUM_SUPPORTED' which is the + default value. + :param cert_reqs: + Whether to require the certificate verification. This defaults to + ``ssl.CERT_REQUIRED``. + :param options: + Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, + ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``, and ``ssl.OP_NO_TICKET``. + :param ciphers: + Which cipher suites to allow the server to select. Defaults to either system configured + ciphers if OpenSSL 1.1.1+, otherwise uses a secure default set of ciphers. + :param verify_flags: + The flags for certificate verification operations. These default to + ``ssl.VERIFY_X509_PARTIAL_CHAIN`` and ``ssl.VERIFY_X509_STRICT`` for Python 3.13+. + :returns: + Constructed SSLContext object with specified options + :rtype: SSLContext + """ + if SSLContext is None: + raise TypeError("Can't create an SSLContext object without an ssl module") + + # This means 'ssl_version' was specified as an exact value. + if ssl_version not in (None, PROTOCOL_TLS, PROTOCOL_TLS_CLIENT): + # Disallow setting 'ssl_version' and 'ssl_minimum|maximum_version' + # to avoid conflicts. + if ssl_minimum_version is not None or ssl_maximum_version is not None: + raise ValueError( + "Can't specify both 'ssl_version' and either " + "'ssl_minimum_version' or 'ssl_maximum_version'" + ) + + # 'ssl_version' is deprecated and will be removed in the future. + else: + # Use 'ssl_minimum_version' and 'ssl_maximum_version' instead. + ssl_minimum_version = _SSL_VERSION_TO_TLS_VERSION.get( + ssl_version, TLSVersion.MINIMUM_SUPPORTED + ) + ssl_maximum_version = _SSL_VERSION_TO_TLS_VERSION.get( + ssl_version, TLSVersion.MAXIMUM_SUPPORTED + ) + + # This warning message is pushing users to use 'ssl_minimum_version' + # instead of both min/max. Best practice is to only set the minimum version and + # keep the maximum version to be it's default value: 'TLSVersion.MAXIMUM_SUPPORTED' + warnings.warn( + "'ssl_version' option is deprecated and will be " + "removed in urllib3 v2.6.0. Instead use 'ssl_minimum_version'", + category=DeprecationWarning, + stacklevel=2, + ) + + # PROTOCOL_TLS is deprecated in Python 3.10 so we always use PROTOCOL_TLS_CLIENT + context = SSLContext(PROTOCOL_TLS_CLIENT) + + if ssl_minimum_version is not None: + context.minimum_version = ssl_minimum_version + else: # Python <3.10 defaults to 'MINIMUM_SUPPORTED' so explicitly set TLSv1.2 here + context.minimum_version = TLSVersion.TLSv1_2 + + if ssl_maximum_version is not None: + context.maximum_version = ssl_maximum_version + + # Unless we're given ciphers defer to either system ciphers in + # the case of OpenSSL 1.1.1+ or use our own secure default ciphers. + if ciphers: + context.set_ciphers(ciphers) + + # Setting the default here, as we may have no ssl module on import + cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs + + if options is None: + options = 0 + # SSLv2 is easily broken and is considered harmful and dangerous + options |= OP_NO_SSLv2 + # SSLv3 has several problems and is now dangerous + options |= OP_NO_SSLv3 + # Disable compression to prevent CRIME attacks for OpenSSL 1.0+ + # (issue #309) + options |= OP_NO_COMPRESSION + # TLSv1.2 only. Unless set explicitly, do not request tickets. + # This may save some bandwidth on wire, and although the ticket is encrypted, + # there is a risk associated with it being on wire, + # if the server is not rotating its ticketing keys properly. + options |= OP_NO_TICKET + + context.options |= options + + if verify_flags is None: + verify_flags = 0 + # In Python 3.13+ ssl.create_default_context() sets VERIFY_X509_PARTIAL_CHAIN + # and VERIFY_X509_STRICT so we do the same + if sys.version_info >= (3, 13): + verify_flags |= VERIFY_X509_PARTIAL_CHAIN + verify_flags |= VERIFY_X509_STRICT + + context.verify_flags |= verify_flags + + # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is + # necessary for conditional client cert authentication with TLS 1.3. + # The attribute is None for OpenSSL <= 1.1.0 or does not exist when using + # an SSLContext created by pyOpenSSL. + if getattr(context, "post_handshake_auth", None) is not None: + context.post_handshake_auth = True + + # The order of the below lines setting verify_mode and check_hostname + # matter due to safe-guards SSLContext has to prevent an SSLContext with + # check_hostname=True, verify_mode=NONE/OPTIONAL. + # We always set 'check_hostname=False' for pyOpenSSL so we rely on our own + # 'ssl.match_hostname()' implementation. + if cert_reqs == ssl.CERT_REQUIRED and not IS_PYOPENSSL: + context.verify_mode = cert_reqs + context.check_hostname = True + else: + context.check_hostname = False + context.verify_mode = cert_reqs + + try: + context.hostname_checks_common_name = False + except AttributeError: # Defensive: for CPython < 3.9.3; for PyPy < 7.3.8 + pass + + sslkeylogfile = os.environ.get("SSLKEYLOGFILE") + if sslkeylogfile: + context.keylog_filename = sslkeylogfile + + return context + + +@typing.overload +def ssl_wrap_socket( + sock: socket.socket, + keyfile: str | None = ..., + certfile: str | None = ..., + cert_reqs: int | None = ..., + ca_certs: str | None = ..., + server_hostname: str | None = ..., + ssl_version: int | None = ..., + ciphers: str | None = ..., + ssl_context: ssl.SSLContext | None = ..., + ca_cert_dir: str | None = ..., + key_password: str | None = ..., + ca_cert_data: None | str | bytes = ..., + tls_in_tls: typing.Literal[False] = ..., +) -> ssl.SSLSocket: ... + + +@typing.overload +def ssl_wrap_socket( + sock: socket.socket, + keyfile: str | None = ..., + certfile: str | None = ..., + cert_reqs: int | None = ..., + ca_certs: str | None = ..., + server_hostname: str | None = ..., + ssl_version: int | None = ..., + ciphers: str | None = ..., + ssl_context: ssl.SSLContext | None = ..., + ca_cert_dir: str | None = ..., + key_password: str | None = ..., + ca_cert_data: None | str | bytes = ..., + tls_in_tls: bool = ..., +) -> ssl.SSLSocket | SSLTransportType: ... + + +def ssl_wrap_socket( + sock: socket.socket, + keyfile: str | None = None, + certfile: str | None = None, + cert_reqs: int | None = None, + ca_certs: str | None = None, + server_hostname: str | None = None, + ssl_version: int | None = None, + ciphers: str | None = None, + ssl_context: ssl.SSLContext | None = None, + ca_cert_dir: str | None = None, + key_password: str | None = None, + ca_cert_data: None | str | bytes = None, + tls_in_tls: bool = False, +) -> ssl.SSLSocket | SSLTransportType: + """ + All arguments except for server_hostname, ssl_context, tls_in_tls, ca_cert_data and + ca_cert_dir have the same meaning as they do when using + :func:`ssl.create_default_context`, :meth:`ssl.SSLContext.load_cert_chain`, + :meth:`ssl.SSLContext.set_ciphers` and :meth:`ssl.SSLContext.wrap_socket`. + + :param server_hostname: + When SNI is supported, the expected hostname of the certificate + :param ssl_context: + A pre-made :class:`SSLContext` object. If none is provided, one will + be created using :func:`create_urllib3_context`. + :param ciphers: + A string of ciphers we wish the client to support. + :param ca_cert_dir: + A directory containing CA certificates in multiple separate files, as + supported by OpenSSL's -CApath flag or the capath argument to + SSLContext.load_verify_locations(). + :param key_password: + Optional password if the keyfile is encrypted. + :param ca_cert_data: + Optional string containing CA certificates in PEM format suitable for + passing as the cadata parameter to SSLContext.load_verify_locations() + :param tls_in_tls: + Use SSLTransport to wrap the existing socket. + """ + context = ssl_context + if context is None: + # Note: This branch of code and all the variables in it are only used in tests. + # We should consider deprecating and removing this code. + context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers) + + if ca_certs or ca_cert_dir or ca_cert_data: + try: + context.load_verify_locations(ca_certs, ca_cert_dir, ca_cert_data) + except OSError as e: + raise SSLError(e) from e + + elif ssl_context is None and hasattr(context, "load_default_certs"): + # try to load OS default certs; works well on Windows. + context.load_default_certs() + + # Attempt to detect if we get the goofy behavior of the + # keyfile being encrypted and OpenSSL asking for the + # passphrase via the terminal and instead error out. + if keyfile and key_password is None and _is_key_file_encrypted(keyfile): + raise SSLError("Client private key is encrypted, password is required") + + if certfile: + if key_password is None: + context.load_cert_chain(certfile, keyfile) + else: + context.load_cert_chain(certfile, keyfile, key_password) + + context.set_alpn_protocols(ALPN_PROTOCOLS) + + ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls, server_hostname) + return ssl_sock + + +def is_ipaddress(hostname: str | bytes) -> bool: + """Detects whether the hostname given is an IPv4 or IPv6 address. + Also detects IPv6 addresses with Zone IDs. + + :param str hostname: Hostname to examine. + :return: True if the hostname is an IP address, False otherwise. + """ + if isinstance(hostname, bytes): + # IDN A-label bytes are ASCII compatible. + hostname = hostname.decode("ascii") + return bool(_IPV4_RE.match(hostname) or _BRACELESS_IPV6_ADDRZ_RE.match(hostname)) + + +def _is_key_file_encrypted(key_file: str) -> bool: + """Detects if a key file is encrypted or not.""" + with open(key_file) as f: + for line in f: + # Look for Proc-Type: 4,ENCRYPTED + if "ENCRYPTED" in line: + return True + + return False + + +def _ssl_wrap_socket_impl( + sock: socket.socket, + ssl_context: ssl.SSLContext, + tls_in_tls: bool, + server_hostname: str | None = None, +) -> ssl.SSLSocket | SSLTransportType: + if tls_in_tls: + if not SSLTransport: + # Import error, ssl is not available. + raise ProxySchemeUnsupported( + "TLS in TLS requires support for the 'ssl' module" + ) + + SSLTransport._validate_ssl_context_for_tls_in_tls(ssl_context) + return SSLTransport(sock, ssl_context, server_hostname) + + return ssl_context.wrap_socket(sock, server_hostname=server_hostname) diff --git a/venv/Lib/site-packages/urllib3/util/ssl_match_hostname.py b/venv/Lib/site-packages/urllib3/util/ssl_match_hostname.py new file mode 100644 index 00000000..25d91000 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/util/ssl_match_hostname.py @@ -0,0 +1,159 @@ +"""The match_hostname() function from Python 3.5, essential when using SSL.""" + +# Note: This file is under the PSF license as the code comes from the python +# stdlib. http://docs.python.org/3/license.html +# It is modified to remove commonName support. + +from __future__ import annotations + +import ipaddress +import re +import typing +from ipaddress import IPv4Address, IPv6Address + +if typing.TYPE_CHECKING: + from .ssl_ import _TYPE_PEER_CERT_RET_DICT + +__version__ = "3.5.0.1" + + +class CertificateError(ValueError): + pass + + +def _dnsname_match( + dn: typing.Any, hostname: str, max_wildcards: int = 1 +) -> typing.Match[str] | None | bool: + """Matching according to RFC 6125, section 6.4.3 + + http://tools.ietf.org/html/rfc6125#section-6.4.3 + """ + pats = [] + if not dn: + return False + + # Ported from python3-syntax: + # leftmost, *remainder = dn.split(r'.') + parts = dn.split(r".") + leftmost = parts[0] + remainder = parts[1:] + + wildcards = leftmost.count("*") + if wildcards > max_wildcards: + # Issue #17980: avoid denials of service by refusing more + # than one wildcard per fragment. A survey of established + # policy among SSL implementations showed it to be a + # reasonable choice. + raise CertificateError( + "too many wildcards in certificate DNS name: " + repr(dn) + ) + + # speed up common case w/o wildcards + if not wildcards: + return bool(dn.lower() == hostname.lower()) + + # RFC 6125, section 6.4.3, subitem 1. + # The client SHOULD NOT attempt to match a presented identifier in which + # the wildcard character comprises a label other than the left-most label. + if leftmost == "*": + # When '*' is a fragment by itself, it matches a non-empty dotless + # fragment. + pats.append("[^.]+") + elif leftmost.startswith("xn--") or hostname.startswith("xn--"): + # RFC 6125, section 6.4.3, subitem 3. + # The client SHOULD NOT attempt to match a presented identifier + # where the wildcard character is embedded within an A-label or + # U-label of an internationalized domain name. + pats.append(re.escape(leftmost)) + else: + # Otherwise, '*' matches any dotless string, e.g. www* + pats.append(re.escape(leftmost).replace(r"\*", "[^.]*")) + + # add the remaining fragments, ignore any wildcards + for frag in remainder: + pats.append(re.escape(frag)) + + pat = re.compile(r"\A" + r"\.".join(pats) + r"\Z", re.IGNORECASE) + return pat.match(hostname) + + +def _ipaddress_match(ipname: str, host_ip: IPv4Address | IPv6Address) -> bool: + """Exact matching of IP addresses. + + RFC 9110 section 4.3.5: "A reference identity of IP-ID contains the decoded + bytes of the IP address. An IP version 4 address is 4 octets, and an IP + version 6 address is 16 octets. [...] A reference identity of type IP-ID + matches if the address is identical to an iPAddress value of the + subjectAltName extension of the certificate." + """ + # OpenSSL may add a trailing newline to a subjectAltName's IP address + # Divergence from upstream: ipaddress can't handle byte str + ip = ipaddress.ip_address(ipname.rstrip()) + return bool(ip.packed == host_ip.packed) + + +def match_hostname( + cert: _TYPE_PEER_CERT_RET_DICT | None, + hostname: str, + hostname_checks_common_name: bool = False, +) -> None: + """Verify that *cert* (in decoded format as returned by + SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 + rules are followed, but IP addresses are not accepted for *hostname*. + + CertificateError is raised on failure. On success, the function + returns nothing. + """ + if not cert: + raise ValueError( + "empty or no certificate, match_hostname needs a " + "SSL socket or SSL context with either " + "CERT_OPTIONAL or CERT_REQUIRED" + ) + try: + # Divergence from upstream: ipaddress can't handle byte str + # + # The ipaddress module shipped with Python < 3.9 does not support + # scoped IPv6 addresses so we unconditionally strip the Zone IDs for + # now. Once we drop support for Python 3.9 we can remove this branch. + if "%" in hostname: + host_ip = ipaddress.ip_address(hostname[: hostname.rfind("%")]) + else: + host_ip = ipaddress.ip_address(hostname) + + except ValueError: + # Not an IP address (common case) + host_ip = None + dnsnames = [] + san: tuple[tuple[str, str], ...] = cert.get("subjectAltName", ()) + key: str + value: str + for key, value in san: + if key == "DNS": + if host_ip is None and _dnsname_match(value, hostname): + return + dnsnames.append(value) + elif key == "IP Address": + if host_ip is not None and _ipaddress_match(value, host_ip): + return + dnsnames.append(value) + + # We only check 'commonName' if it's enabled and we're not verifying + # an IP address. IP addresses aren't valid within 'commonName'. + if hostname_checks_common_name and host_ip is None and not dnsnames: + for sub in cert.get("subject", ()): + for key, value in sub: + if key == "commonName": + if _dnsname_match(value, hostname): + return + dnsnames.append(value) # Defensive: for Python < 3.9.3 + + if len(dnsnames) > 1: + raise CertificateError( + "hostname %r " + "doesn't match either of %s" % (hostname, ", ".join(map(repr, dnsnames))) + ) + elif len(dnsnames) == 1: + raise CertificateError(f"hostname {hostname!r} doesn't match {dnsnames[0]!r}") + else: + raise CertificateError("no appropriate subjectAltName fields were found") diff --git a/venv/Lib/site-packages/urllib3/util/ssltransport.py b/venv/Lib/site-packages/urllib3/util/ssltransport.py new file mode 100644 index 00000000..6d59bc3b --- /dev/null +++ b/venv/Lib/site-packages/urllib3/util/ssltransport.py @@ -0,0 +1,271 @@ +from __future__ import annotations + +import io +import socket +import ssl +import typing + +from ..exceptions import ProxySchemeUnsupported + +if typing.TYPE_CHECKING: + from typing_extensions import Self + + from .ssl_ import _TYPE_PEER_CERT_RET, _TYPE_PEER_CERT_RET_DICT + + +_WriteBuffer = typing.Union[bytearray, memoryview] +_ReturnValue = typing.TypeVar("_ReturnValue") + +SSL_BLOCKSIZE = 16384 + + +class SSLTransport: + """ + The SSLTransport wraps an existing socket and establishes an SSL connection. + + Contrary to Python's implementation of SSLSocket, it allows you to chain + multiple TLS connections together. It's particularly useful if you need to + implement TLS within TLS. + + The class supports most of the socket API operations. + """ + + @staticmethod + def _validate_ssl_context_for_tls_in_tls(ssl_context: ssl.SSLContext) -> None: + """ + Raises a ProxySchemeUnsupported if the provided ssl_context can't be used + for TLS in TLS. + + The only requirement is that the ssl_context provides the 'wrap_bio' + methods. + """ + + if not hasattr(ssl_context, "wrap_bio"): + raise ProxySchemeUnsupported( + "TLS in TLS requires SSLContext.wrap_bio() which isn't " + "available on non-native SSLContext" + ) + + def __init__( + self, + socket: socket.socket, + ssl_context: ssl.SSLContext, + server_hostname: str | None = None, + suppress_ragged_eofs: bool = True, + ) -> None: + """ + Create an SSLTransport around socket using the provided ssl_context. + """ + self.incoming = ssl.MemoryBIO() + self.outgoing = ssl.MemoryBIO() + + self.suppress_ragged_eofs = suppress_ragged_eofs + self.socket = socket + + self.sslobj = ssl_context.wrap_bio( + self.incoming, self.outgoing, server_hostname=server_hostname + ) + + # Perform initial handshake. + self._ssl_io_loop(self.sslobj.do_handshake) + + def __enter__(self) -> Self: + return self + + def __exit__(self, *_: typing.Any) -> None: + self.close() + + def fileno(self) -> int: + return self.socket.fileno() + + def read(self, len: int = 1024, buffer: typing.Any | None = None) -> int | bytes: + return self._wrap_ssl_read(len, buffer) + + def recv(self, buflen: int = 1024, flags: int = 0) -> int | bytes: + if flags != 0: + raise ValueError("non-zero flags not allowed in calls to recv") + return self._wrap_ssl_read(buflen) + + def recv_into( + self, + buffer: _WriteBuffer, + nbytes: int | None = None, + flags: int = 0, + ) -> None | int | bytes: + if flags != 0: + raise ValueError("non-zero flags not allowed in calls to recv_into") + if nbytes is None: + nbytes = len(buffer) + return self.read(nbytes, buffer) + + def sendall(self, data: bytes, flags: int = 0) -> None: + if flags != 0: + raise ValueError("non-zero flags not allowed in calls to sendall") + count = 0 + with memoryview(data) as view, view.cast("B") as byte_view: + amount = len(byte_view) + while count < amount: + v = self.send(byte_view[count:]) + count += v + + def send(self, data: bytes, flags: int = 0) -> int: + if flags != 0: + raise ValueError("non-zero flags not allowed in calls to send") + return self._ssl_io_loop(self.sslobj.write, data) + + def makefile( + self, + mode: str, + buffering: int | None = None, + *, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> typing.BinaryIO | typing.TextIO | socket.SocketIO: + """ + Python's httpclient uses makefile and buffered io when reading HTTP + messages and we need to support it. + + This is unfortunately a copy and paste of socket.py makefile with small + changes to point to the socket directly. + """ + if not set(mode) <= {"r", "w", "b"}: + raise ValueError(f"invalid mode {mode!r} (only r, w, b allowed)") + + writing = "w" in mode + reading = "r" in mode or not writing + assert reading or writing + binary = "b" in mode + rawmode = "" + if reading: + rawmode += "r" + if writing: + rawmode += "w" + raw = socket.SocketIO(self, rawmode) # type: ignore[arg-type] + self.socket._io_refs += 1 # type: ignore[attr-defined] + if buffering is None: + buffering = -1 + if buffering < 0: + buffering = io.DEFAULT_BUFFER_SIZE + if buffering == 0: + if not binary: + raise ValueError("unbuffered streams must be binary") + return raw + buffer: typing.BinaryIO + if reading and writing: + buffer = io.BufferedRWPair(raw, raw, buffering) # type: ignore[assignment] + elif reading: + buffer = io.BufferedReader(raw, buffering) + else: + assert writing + buffer = io.BufferedWriter(raw, buffering) + if binary: + return buffer + text = io.TextIOWrapper(buffer, encoding, errors, newline) + text.mode = mode # type: ignore[misc] + return text + + def unwrap(self) -> None: + self._ssl_io_loop(self.sslobj.unwrap) + + def close(self) -> None: + self.socket.close() + + @typing.overload + def getpeercert( + self, binary_form: typing.Literal[False] = ... + ) -> _TYPE_PEER_CERT_RET_DICT | None: ... + + @typing.overload + def getpeercert(self, binary_form: typing.Literal[True]) -> bytes | None: ... + + def getpeercert(self, binary_form: bool = False) -> _TYPE_PEER_CERT_RET: + return self.sslobj.getpeercert(binary_form) # type: ignore[return-value] + + def version(self) -> str | None: + return self.sslobj.version() + + def cipher(self) -> tuple[str, str, int] | None: + return self.sslobj.cipher() + + def selected_alpn_protocol(self) -> str | None: + return self.sslobj.selected_alpn_protocol() + + def shared_ciphers(self) -> list[tuple[str, str, int]] | None: + return self.sslobj.shared_ciphers() + + def compression(self) -> str | None: + return self.sslobj.compression() + + def settimeout(self, value: float | None) -> None: + self.socket.settimeout(value) + + def gettimeout(self) -> float | None: + return self.socket.gettimeout() + + def _decref_socketios(self) -> None: + self.socket._decref_socketios() # type: ignore[attr-defined] + + def _wrap_ssl_read(self, len: int, buffer: bytearray | None = None) -> int | bytes: + try: + return self._ssl_io_loop(self.sslobj.read, len, buffer) + except ssl.SSLError as e: + if e.errno == ssl.SSL_ERROR_EOF and self.suppress_ragged_eofs: + return 0 # eof, return 0. + else: + raise + + # func is sslobj.do_handshake or sslobj.unwrap + @typing.overload + def _ssl_io_loop(self, func: typing.Callable[[], None]) -> None: ... + + # func is sslobj.write, arg1 is data + @typing.overload + def _ssl_io_loop(self, func: typing.Callable[[bytes], int], arg1: bytes) -> int: ... + + # func is sslobj.read, arg1 is len, arg2 is buffer + @typing.overload + def _ssl_io_loop( + self, + func: typing.Callable[[int, bytearray | None], bytes], + arg1: int, + arg2: bytearray | None, + ) -> bytes: ... + + def _ssl_io_loop( + self, + func: typing.Callable[..., _ReturnValue], + arg1: None | bytes | int = None, + arg2: bytearray | None = None, + ) -> _ReturnValue: + """Performs an I/O loop between incoming/outgoing and the socket.""" + should_loop = True + ret = None + + while should_loop: + errno = None + try: + if arg1 is None and arg2 is None: + ret = func() + elif arg2 is None: + ret = func(arg1) + else: + ret = func(arg1, arg2) + except ssl.SSLError as e: + if e.errno not in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE): + # WANT_READ, and WANT_WRITE are expected, others are not. + raise e + errno = e.errno + + buf = self.outgoing.read() + self.socket.sendall(buf) + + if errno is None: + should_loop = False + elif errno == ssl.SSL_ERROR_WANT_READ: + buf = self.socket.recv(SSL_BLOCKSIZE) + if buf: + self.incoming.write(buf) + else: + self.incoming.write_eof() + return typing.cast(_ReturnValue, ret) diff --git a/venv/Lib/site-packages/urllib3/util/timeout.py b/venv/Lib/site-packages/urllib3/util/timeout.py new file mode 100644 index 00000000..4bb1be11 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/util/timeout.py @@ -0,0 +1,275 @@ +from __future__ import annotations + +import time +import typing +from enum import Enum +from socket import getdefaulttimeout + +from ..exceptions import TimeoutStateError + +if typing.TYPE_CHECKING: + from typing import Final + + +class _TYPE_DEFAULT(Enum): + # This value should never be passed to socket.settimeout() so for safety we use a -1. + # socket.settimout() raises a ValueError for negative values. + token = -1 + + +_DEFAULT_TIMEOUT: Final[_TYPE_DEFAULT] = _TYPE_DEFAULT.token + +_TYPE_TIMEOUT = typing.Optional[typing.Union[float, _TYPE_DEFAULT]] + + +class Timeout: + """Timeout configuration. + + Timeouts can be defined as a default for a pool: + + .. code-block:: python + + import urllib3 + + timeout = urllib3.util.Timeout(connect=2.0, read=7.0) + + http = urllib3.PoolManager(timeout=timeout) + + resp = http.request("GET", "https://example.com/") + + print(resp.status) + + Or per-request (which overrides the default for the pool): + + .. code-block:: python + + response = http.request("GET", "https://example.com/", timeout=Timeout(10)) + + Timeouts can be disabled by setting all the parameters to ``None``: + + .. code-block:: python + + no_timeout = Timeout(connect=None, read=None) + response = http.request("GET", "https://example.com/", timeout=no_timeout) + + + :param total: + This combines the connect and read timeouts into one; the read timeout + will be set to the time leftover from the connect attempt. In the + event that both a connect timeout and a total are specified, or a read + timeout and a total are specified, the shorter timeout will be applied. + + Defaults to None. + + :type total: int, float, or None + + :param connect: + The maximum amount of time (in seconds) to wait for a connection + attempt to a server to succeed. Omitting the parameter will default the + connect timeout to the system default, probably `the global default + timeout in socket.py + `_. + None will set an infinite timeout for connection attempts. + + :type connect: int, float, or None + + :param read: + The maximum amount of time (in seconds) to wait between consecutive + read operations for a response from the server. Omitting the parameter + will default the read timeout to the system default, probably `the + global default timeout in socket.py + `_. + None will set an infinite timeout. + + :type read: int, float, or None + + .. note:: + + Many factors can affect the total amount of time for urllib3 to return + an HTTP response. + + For example, Python's DNS resolver does not obey the timeout specified + on the socket. Other factors that can affect total request time include + high CPU load, high swap, the program running at a low priority level, + or other behaviors. + + In addition, the read and total timeouts only measure the time between + read operations on the socket connecting the client and the server, + not the total amount of time for the request to return a complete + response. For most requests, the timeout is raised because the server + has not sent the first byte in the specified time. This is not always + the case; if a server streams one byte every fifteen seconds, a timeout + of 20 seconds will not trigger, even though the request will take + several minutes to complete. + """ + + #: A sentinel object representing the default timeout value + DEFAULT_TIMEOUT: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT + + def __init__( + self, + total: _TYPE_TIMEOUT = None, + connect: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + read: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + ) -> None: + self._connect = self._validate_timeout(connect, "connect") + self._read = self._validate_timeout(read, "read") + self.total = self._validate_timeout(total, "total") + self._start_connect: float | None = None + + def __repr__(self) -> str: + return f"{type(self).__name__}(connect={self._connect!r}, read={self._read!r}, total={self.total!r})" + + # __str__ provided for backwards compatibility + __str__ = __repr__ + + @staticmethod + def resolve_default_timeout(timeout: _TYPE_TIMEOUT) -> float | None: + return getdefaulttimeout() if timeout is _DEFAULT_TIMEOUT else timeout + + @classmethod + def _validate_timeout(cls, value: _TYPE_TIMEOUT, name: str) -> _TYPE_TIMEOUT: + """Check that a timeout attribute is valid. + + :param value: The timeout value to validate + :param name: The name of the timeout attribute to validate. This is + used to specify in error messages. + :return: The validated and casted version of the given value. + :raises ValueError: If it is a numeric value less than or equal to + zero, or the type is not an integer, float, or None. + """ + if value is None or value is _DEFAULT_TIMEOUT: + return value + + if isinstance(value, bool): + raise ValueError( + "Timeout cannot be a boolean value. It must " + "be an int, float or None." + ) + try: + float(value) + except (TypeError, ValueError): + raise ValueError( + "Timeout value %s was %s, but it must be an " + "int, float or None." % (name, value) + ) from None + + try: + if value <= 0: + raise ValueError( + "Attempted to set %s timeout to %s, but the " + "timeout cannot be set to a value less " + "than or equal to 0." % (name, value) + ) + except TypeError: + raise ValueError( + "Timeout value %s was %s, but it must be an " + "int, float or None." % (name, value) + ) from None + + return value + + @classmethod + def from_float(cls, timeout: _TYPE_TIMEOUT) -> Timeout: + """Create a new Timeout from a legacy timeout value. + + The timeout value used by httplib.py sets the same timeout on the + connect(), and recv() socket requests. This creates a :class:`Timeout` + object that sets the individual timeouts to the ``timeout`` value + passed to this function. + + :param timeout: The legacy timeout value. + :type timeout: integer, float, :attr:`urllib3.util.Timeout.DEFAULT_TIMEOUT`, or None + :return: Timeout object + :rtype: :class:`Timeout` + """ + return Timeout(read=timeout, connect=timeout) + + def clone(self) -> Timeout: + """Create a copy of the timeout object + + Timeout properties are stored per-pool but each request needs a fresh + Timeout object to ensure each one has its own start/stop configured. + + :return: a copy of the timeout object + :rtype: :class:`Timeout` + """ + # We can't use copy.deepcopy because that will also create a new object + # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to + # detect the user default. + return Timeout(connect=self._connect, read=self._read, total=self.total) + + def start_connect(self) -> float: + """Start the timeout clock, used during a connect() attempt + + :raises urllib3.exceptions.TimeoutStateError: if you attempt + to start a timer that has been started already. + """ + if self._start_connect is not None: + raise TimeoutStateError("Timeout timer has already been started.") + self._start_connect = time.monotonic() + return self._start_connect + + def get_connect_duration(self) -> float: + """Gets the time elapsed since the call to :meth:`start_connect`. + + :return: Elapsed time in seconds. + :rtype: float + :raises urllib3.exceptions.TimeoutStateError: if you attempt + to get duration for a timer that hasn't been started. + """ + if self._start_connect is None: + raise TimeoutStateError( + "Can't get connect duration for timer that has not started." + ) + return time.monotonic() - self._start_connect + + @property + def connect_timeout(self) -> _TYPE_TIMEOUT: + """Get the value to use when setting a connection timeout. + + This will be a positive float or integer, the value None + (never timeout), or the default system timeout. + + :return: Connect timeout. + :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None + """ + if self.total is None: + return self._connect + + if self._connect is None or self._connect is _DEFAULT_TIMEOUT: + return self.total + + return min(self._connect, self.total) # type: ignore[type-var] + + @property + def read_timeout(self) -> float | None: + """Get the value for the read timeout. + + This assumes some time has elapsed in the connection timeout and + computes the read timeout appropriately. + + If self.total is set, the read timeout is dependent on the amount of + time taken by the connect timeout. If the connection time has not been + established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be + raised. + + :return: Value to use for the read timeout. + :rtype: int, float or None + :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect` + has not yet been called on this object. + """ + if ( + self.total is not None + and self.total is not _DEFAULT_TIMEOUT + and self._read is not None + and self._read is not _DEFAULT_TIMEOUT + ): + # In case the connect timeout has not yet been established. + if self._start_connect is None: + return self._read + return max(0, min(self.total - self.get_connect_duration(), self._read)) + elif self.total is not None and self.total is not _DEFAULT_TIMEOUT: + return max(0, self.total - self.get_connect_duration()) + else: + return self.resolve_default_timeout(self._read) diff --git a/venv/Lib/site-packages/urllib3/util/url.py b/venv/Lib/site-packages/urllib3/util/url.py new file mode 100644 index 00000000..db057f17 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/util/url.py @@ -0,0 +1,469 @@ +from __future__ import annotations + +import re +import typing + +from ..exceptions import LocationParseError +from .util import to_str + +# We only want to normalize urls with an HTTP(S) scheme. +# urllib3 infers URLs without a scheme (None) to be http. +_NORMALIZABLE_SCHEMES = ("http", "https", None) + +# Almost all of these patterns were derived from the +# 'rfc3986' module: https://github.com/python-hyper/rfc3986 +_PERCENT_RE = re.compile(r"%[a-fA-F0-9]{2}") +_SCHEME_RE = re.compile(r"^(?:[a-zA-Z][a-zA-Z0-9+-]*:|/)") +_URI_RE = re.compile( + r"^(?:([a-zA-Z][a-zA-Z0-9+.-]*):)?" + r"(?://([^\\/?#]*))?" + r"([^?#]*)" + r"(?:\?([^#]*))?" + r"(?:#(.*))?$", + re.UNICODE | re.DOTALL, +) + +_IPV4_PAT = r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}" +_HEX_PAT = "[0-9A-Fa-f]{1,4}" +_LS32_PAT = "(?:{hex}:{hex}|{ipv4})".format(hex=_HEX_PAT, ipv4=_IPV4_PAT) +_subs = {"hex": _HEX_PAT, "ls32": _LS32_PAT} +_variations = [ + # 6( h16 ":" ) ls32 + "(?:%(hex)s:){6}%(ls32)s", + # "::" 5( h16 ":" ) ls32 + "::(?:%(hex)s:){5}%(ls32)s", + # [ h16 ] "::" 4( h16 ":" ) ls32 + "(?:%(hex)s)?::(?:%(hex)s:){4}%(ls32)s", + # [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + "(?:(?:%(hex)s:)?%(hex)s)?::(?:%(hex)s:){3}%(ls32)s", + # [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + "(?:(?:%(hex)s:){0,2}%(hex)s)?::(?:%(hex)s:){2}%(ls32)s", + # [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + "(?:(?:%(hex)s:){0,3}%(hex)s)?::%(hex)s:%(ls32)s", + # [ *4( h16 ":" ) h16 ] "::" ls32 + "(?:(?:%(hex)s:){0,4}%(hex)s)?::%(ls32)s", + # [ *5( h16 ":" ) h16 ] "::" h16 + "(?:(?:%(hex)s:){0,5}%(hex)s)?::%(hex)s", + # [ *6( h16 ":" ) h16 ] "::" + "(?:(?:%(hex)s:){0,6}%(hex)s)?::", +] + +_UNRESERVED_PAT = r"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._\-~" +_IPV6_PAT = "(?:" + "|".join([x % _subs for x in _variations]) + ")" +_ZONE_ID_PAT = "(?:%25|%)(?:[" + _UNRESERVED_PAT + "]|%[a-fA-F0-9]{2})+" +_IPV6_ADDRZ_PAT = r"\[" + _IPV6_PAT + r"(?:" + _ZONE_ID_PAT + r")?\]" +_REG_NAME_PAT = r"(?:[^\[\]%:/?#]|%[a-fA-F0-9]{2})*" +_TARGET_RE = re.compile(r"^(/[^?#]*)(?:\?([^#]*))?(?:#.*)?$") + +_IPV4_RE = re.compile("^" + _IPV4_PAT + "$") +_IPV6_RE = re.compile("^" + _IPV6_PAT + "$") +_IPV6_ADDRZ_RE = re.compile("^" + _IPV6_ADDRZ_PAT + "$") +_BRACELESS_IPV6_ADDRZ_RE = re.compile("^" + _IPV6_ADDRZ_PAT[2:-2] + "$") +_ZONE_ID_RE = re.compile("(" + _ZONE_ID_PAT + r")\]$") + +_HOST_PORT_PAT = ("^(%s|%s|%s)(?::0*?(|0|[1-9][0-9]{0,4}))?$") % ( + _REG_NAME_PAT, + _IPV4_PAT, + _IPV6_ADDRZ_PAT, +) +_HOST_PORT_RE = re.compile(_HOST_PORT_PAT, re.UNICODE | re.DOTALL) + +_UNRESERVED_CHARS = set( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-~" +) +_SUB_DELIM_CHARS = set("!$&'()*+,;=") +_USERINFO_CHARS = _UNRESERVED_CHARS | _SUB_DELIM_CHARS | {":"} +_PATH_CHARS = _USERINFO_CHARS | {"@", "/"} +_QUERY_CHARS = _FRAGMENT_CHARS = _PATH_CHARS | {"?"} + + +class Url( + typing.NamedTuple( + "Url", + [ + ("scheme", typing.Optional[str]), + ("auth", typing.Optional[str]), + ("host", typing.Optional[str]), + ("port", typing.Optional[int]), + ("path", typing.Optional[str]), + ("query", typing.Optional[str]), + ("fragment", typing.Optional[str]), + ], + ) +): + """ + Data structure for representing an HTTP URL. Used as a return value for + :func:`parse_url`. Both the scheme and host are normalized as they are + both case-insensitive according to RFC 3986. + """ + + def __new__( # type: ignore[no-untyped-def] + cls, + scheme: str | None = None, + auth: str | None = None, + host: str | None = None, + port: int | None = None, + path: str | None = None, + query: str | None = None, + fragment: str | None = None, + ): + if path and not path.startswith("/"): + path = "/" + path + if scheme is not None: + scheme = scheme.lower() + return super().__new__(cls, scheme, auth, host, port, path, query, fragment) + + @property + def hostname(self) -> str | None: + """For backwards-compatibility with urlparse. We're nice like that.""" + return self.host + + @property + def request_uri(self) -> str: + """Absolute path including the query string.""" + uri = self.path or "/" + + if self.query is not None: + uri += "?" + self.query + + return uri + + @property + def authority(self) -> str | None: + """ + Authority component as defined in RFC 3986 3.2. + This includes userinfo (auth), host and port. + + i.e. + userinfo@host:port + """ + userinfo = self.auth + netloc = self.netloc + if netloc is None or userinfo is None: + return netloc + else: + return f"{userinfo}@{netloc}" + + @property + def netloc(self) -> str | None: + """ + Network location including host and port. + + If you need the equivalent of urllib.parse's ``netloc``, + use the ``authority`` property instead. + """ + if self.host is None: + return None + if self.port: + return f"{self.host}:{self.port}" + return self.host + + @property + def url(self) -> str: + """ + Convert self into a url + + This function should more or less round-trip with :func:`.parse_url`. The + returned url may not be exactly the same as the url inputted to + :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls + with a blank port will have : removed). + + Example: + + .. code-block:: python + + import urllib3 + + U = urllib3.util.parse_url("https://google.com/mail/") + + print(U.url) + # "https://google.com/mail/" + + print( urllib3.util.Url("https", "username:password", + "host.com", 80, "/path", "query", "fragment" + ).url + ) + # "https://username:password@host.com:80/path?query#fragment" + """ + scheme, auth, host, port, path, query, fragment = self + url = "" + + # We use "is not None" we want things to happen with empty strings (or 0 port) + if scheme is not None: + url += scheme + "://" + if auth is not None: + url += auth + "@" + if host is not None: + url += host + if port is not None: + url += ":" + str(port) + if path is not None: + url += path + if query is not None: + url += "?" + query + if fragment is not None: + url += "#" + fragment + + return url + + def __str__(self) -> str: + return self.url + + +@typing.overload +def _encode_invalid_chars( + component: str, allowed_chars: typing.Container[str] +) -> str: # Abstract + ... + + +@typing.overload +def _encode_invalid_chars( + component: None, allowed_chars: typing.Container[str] +) -> None: # Abstract + ... + + +def _encode_invalid_chars( + component: str | None, allowed_chars: typing.Container[str] +) -> str | None: + """Percent-encodes a URI component without reapplying + onto an already percent-encoded component. + """ + if component is None: + return component + + component = to_str(component) + + # Normalize existing percent-encoded bytes. + # Try to see if the component we're encoding is already percent-encoded + # so we can skip all '%' characters but still encode all others. + component, percent_encodings = _PERCENT_RE.subn( + lambda match: match.group(0).upper(), component + ) + + uri_bytes = component.encode("utf-8", "surrogatepass") + is_percent_encoded = percent_encodings == uri_bytes.count(b"%") + encoded_component = bytearray() + + for i in range(0, len(uri_bytes)): + # Will return a single character bytestring + byte = uri_bytes[i : i + 1] + byte_ord = ord(byte) + if (is_percent_encoded and byte == b"%") or ( + byte_ord < 128 and byte.decode() in allowed_chars + ): + encoded_component += byte + continue + encoded_component.extend(b"%" + (hex(byte_ord)[2:].encode().zfill(2).upper())) + + return encoded_component.decode() + + +def _remove_path_dot_segments(path: str) -> str: + # See http://tools.ietf.org/html/rfc3986#section-5.2.4 for pseudo-code + segments = path.split("/") # Turn the path into a list of segments + output = [] # Initialize the variable to use to store output + + for segment in segments: + # '.' is the current directory, so ignore it, it is superfluous + if segment == ".": + continue + # Anything other than '..', should be appended to the output + if segment != "..": + output.append(segment) + # In this case segment == '..', if we can, we should pop the last + # element + elif output: + output.pop() + + # If the path starts with '/' and the output is empty or the first string + # is non-empty + if path.startswith("/") and (not output or output[0]): + output.insert(0, "") + + # If the path starts with '/.' or '/..' ensure we add one more empty + # string to add a trailing '/' + if path.endswith(("/.", "/..")): + output.append("") + + return "/".join(output) + + +@typing.overload +def _normalize_host(host: None, scheme: str | None) -> None: ... + + +@typing.overload +def _normalize_host(host: str, scheme: str | None) -> str: ... + + +def _normalize_host(host: str | None, scheme: str | None) -> str | None: + if host: + if scheme in _NORMALIZABLE_SCHEMES: + is_ipv6 = _IPV6_ADDRZ_RE.match(host) + if is_ipv6: + # IPv6 hosts of the form 'a::b%zone' are encoded in a URL as + # such per RFC 6874: 'a::b%25zone'. Unquote the ZoneID + # separator as necessary to return a valid RFC 4007 scoped IP. + match = _ZONE_ID_RE.search(host) + if match: + start, end = match.span(1) + zone_id = host[start:end] + + if zone_id.startswith("%25") and zone_id != "%25": + zone_id = zone_id[3:] + else: + zone_id = zone_id[1:] + zone_id = _encode_invalid_chars(zone_id, _UNRESERVED_CHARS) + return f"{host[:start].lower()}%{zone_id}{host[end:]}" + else: + return host.lower() + elif not _IPV4_RE.match(host): + return to_str( + b".".join([_idna_encode(label) for label in host.split(".")]), + "ascii", + ) + return host + + +def _idna_encode(name: str) -> bytes: + if not name.isascii(): + try: + import idna + except ImportError: + raise LocationParseError( + "Unable to parse URL without the 'idna' module" + ) from None + + try: + return idna.encode(name.lower(), strict=True, std3_rules=True) + except idna.IDNAError: + raise LocationParseError( + f"Name '{name}' is not a valid IDNA label" + ) from None + + return name.lower().encode("ascii") + + +def _encode_target(target: str) -> str: + """Percent-encodes a request target so that there are no invalid characters + + Pre-condition for this function is that 'target' must start with '/'. + If that is the case then _TARGET_RE will always produce a match. + """ + match = _TARGET_RE.match(target) + if not match: # Defensive: + raise LocationParseError(f"{target!r} is not a valid request URI") + + path, query = match.groups() + encoded_target = _encode_invalid_chars(path, _PATH_CHARS) + if query is not None: + query = _encode_invalid_chars(query, _QUERY_CHARS) + encoded_target += "?" + query + return encoded_target + + +def parse_url(url: str) -> Url: + """ + Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is + performed to parse incomplete urls. Fields not provided will be None. + This parser is RFC 3986 and RFC 6874 compliant. + + The parser logic and helper functions are based heavily on + work done in the ``rfc3986`` module. + + :param str url: URL to parse into a :class:`.Url` namedtuple. + + Partly backwards-compatible with :mod:`urllib.parse`. + + Example: + + .. code-block:: python + + import urllib3 + + print( urllib3.util.parse_url('http://google.com/mail/')) + # Url(scheme='http', host='google.com', port=None, path='/mail/', ...) + + print( urllib3.util.parse_url('google.com:80')) + # Url(scheme=None, host='google.com', port=80, path=None, ...) + + print( urllib3.util.parse_url('/foo?bar')) + # Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...) + """ + if not url: + # Empty + return Url() + + source_url = url + if not _SCHEME_RE.search(url): + url = "//" + url + + scheme: str | None + authority: str | None + auth: str | None + host: str | None + port: str | None + port_int: int | None + path: str | None + query: str | None + fragment: str | None + + try: + scheme, authority, path, query, fragment = _URI_RE.match(url).groups() # type: ignore[union-attr] + normalize_uri = scheme is None or scheme.lower() in _NORMALIZABLE_SCHEMES + + if scheme: + scheme = scheme.lower() + + if authority: + auth, _, host_port = authority.rpartition("@") + auth = auth or None + host, port = _HOST_PORT_RE.match(host_port).groups() # type: ignore[union-attr] + if auth and normalize_uri: + auth = _encode_invalid_chars(auth, _USERINFO_CHARS) + if port == "": + port = None + else: + auth, host, port = None, None, None + + if port is not None: + port_int = int(port) + if not (0 <= port_int <= 65535): + raise LocationParseError(url) + else: + port_int = None + + host = _normalize_host(host, scheme) + + if normalize_uri and path: + path = _remove_path_dot_segments(path) + path = _encode_invalid_chars(path, _PATH_CHARS) + if normalize_uri and query: + query = _encode_invalid_chars(query, _QUERY_CHARS) + if normalize_uri and fragment: + fragment = _encode_invalid_chars(fragment, _FRAGMENT_CHARS) + + except (ValueError, AttributeError) as e: + raise LocationParseError(source_url) from e + + # For the sake of backwards compatibility we put empty + # string values for path if there are any defined values + # beyond the path in the URL. + # TODO: Remove this when we break backwards compatibility. + if not path: + if query is not None or fragment is not None: + path = "" + else: + path = None + + return Url( + scheme=scheme, + auth=auth, + host=host, + port=port_int, + path=path, + query=query, + fragment=fragment, + ) diff --git a/venv/Lib/site-packages/urllib3/util/util.py b/venv/Lib/site-packages/urllib3/util/util.py new file mode 100644 index 00000000..35c77e40 --- /dev/null +++ b/venv/Lib/site-packages/urllib3/util/util.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +import typing +from types import TracebackType + + +def to_bytes( + x: str | bytes, encoding: str | None = None, errors: str | None = None +) -> bytes: + if isinstance(x, bytes): + return x + elif not isinstance(x, str): + raise TypeError(f"not expecting type {type(x).__name__}") + if encoding or errors: + return x.encode(encoding or "utf-8", errors=errors or "strict") + return x.encode() + + +def to_str( + x: str | bytes, encoding: str | None = None, errors: str | None = None +) -> str: + if isinstance(x, str): + return x + elif not isinstance(x, bytes): + raise TypeError(f"not expecting type {type(x).__name__}") + if encoding or errors: + return x.decode(encoding or "utf-8", errors=errors or "strict") + return x.decode() + + +def reraise( + tp: type[BaseException] | None, + value: BaseException, + tb: TracebackType | None = None, +) -> typing.NoReturn: + try: + if value.__traceback__ is not tb: + raise value.with_traceback(tb) + raise value + finally: + value = None # type: ignore[assignment] + tb = None diff --git a/venv/Lib/site-packages/urllib3/util/wait.py b/venv/Lib/site-packages/urllib3/util/wait.py new file mode 100644 index 00000000..aeca0c7a --- /dev/null +++ b/venv/Lib/site-packages/urllib3/util/wait.py @@ -0,0 +1,124 @@ +from __future__ import annotations + +import select +import socket +from functools import partial + +__all__ = ["wait_for_read", "wait_for_write"] + + +# How should we wait on sockets? +# +# There are two types of APIs you can use for waiting on sockets: the fancy +# modern stateful APIs like epoll/kqueue, and the older stateless APIs like +# select/poll. The stateful APIs are more efficient when you have a lots of +# sockets to keep track of, because you can set them up once and then use them +# lots of times. But we only ever want to wait on a single socket at a time +# and don't want to keep track of state, so the stateless APIs are actually +# more efficient. So we want to use select() or poll(). +# +# Now, how do we choose between select() and poll()? On traditional Unixes, +# select() has a strange calling convention that makes it slow, or fail +# altogether, for high-numbered file descriptors. The point of poll() is to fix +# that, so on Unixes, we prefer poll(). +# +# On Windows, there is no poll() (or at least Python doesn't provide a wrapper +# for it), but that's OK, because on Windows, select() doesn't have this +# strange calling convention; plain select() works fine. +# +# So: on Windows we use select(), and everywhere else we use poll(). We also +# fall back to select() in case poll() is somehow broken or missing. + + +def select_wait_for_socket( + sock: socket.socket, + read: bool = False, + write: bool = False, + timeout: float | None = None, +) -> bool: + if not read and not write: + raise RuntimeError("must specify at least one of read=True, write=True") + rcheck = [] + wcheck = [] + if read: + rcheck.append(sock) + if write: + wcheck.append(sock) + # When doing a non-blocking connect, most systems signal success by + # marking the socket writable. Windows, though, signals success by marked + # it as "exceptional". We paper over the difference by checking the write + # sockets for both conditions. (The stdlib selectors module does the same + # thing.) + fn = partial(select.select, rcheck, wcheck, wcheck) + rready, wready, xready = fn(timeout) + return bool(rready or wready or xready) + + +def poll_wait_for_socket( + sock: socket.socket, + read: bool = False, + write: bool = False, + timeout: float | None = None, +) -> bool: + if not read and not write: + raise RuntimeError("must specify at least one of read=True, write=True") + mask = 0 + if read: + mask |= select.POLLIN + if write: + mask |= select.POLLOUT + poll_obj = select.poll() + poll_obj.register(sock, mask) + + # For some reason, poll() takes timeout in milliseconds + def do_poll(t: float | None) -> list[tuple[int, int]]: + if t is not None: + t *= 1000 + return poll_obj.poll(t) + + return bool(do_poll(timeout)) + + +def _have_working_poll() -> bool: + # Apparently some systems have a select.poll that fails as soon as you try + # to use it, either due to strange configuration or broken monkeypatching + # from libraries like eventlet/greenlet. + try: + poll_obj = select.poll() + poll_obj.poll(0) + except (AttributeError, OSError): + return False + else: + return True + + +def wait_for_socket( + sock: socket.socket, + read: bool = False, + write: bool = False, + timeout: float | None = None, +) -> bool: + # We delay choosing which implementation to use until the first time we're + # called. We could do it at import time, but then we might make the wrong + # decision if someone goes wild with monkeypatching select.poll after + # we're imported. + global wait_for_socket + if _have_working_poll(): + wait_for_socket = poll_wait_for_socket + elif hasattr(select, "select"): + wait_for_socket = select_wait_for_socket + return wait_for_socket(sock, read, write, timeout) + + +def wait_for_read(sock: socket.socket, timeout: float | None = None) -> bool: + """Waits for reading to be available on a given socket. + Returns True if the socket is readable, or False if the timeout expired. + """ + return wait_for_socket(sock, read=True, timeout=timeout) + + +def wait_for_write(sock: socket.socket, timeout: float | None = None) -> bool: + """Waits for writing to be available on a given socket. + Returns True if the socket is readable, or False if the timeout expired. + """ + return wait_for_socket(sock, write=True, timeout=timeout) diff --git a/venv/Lib/site-packages/uvicorn-0.35.0.dist-info/INSTALLER b/venv/Lib/site-packages/uvicorn-0.35.0.dist-info/INSTALLER new file mode 100644 index 00000000..a1b589e3 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn-0.35.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/Lib/site-packages/uvicorn-0.35.0.dist-info/METADATA b/venv/Lib/site-packages/uvicorn-0.35.0.dist-info/METADATA new file mode 100644 index 00000000..e392d27f --- /dev/null +++ b/venv/Lib/site-packages/uvicorn-0.35.0.dist-info/METADATA @@ -0,0 +1,186 @@ +Metadata-Version: 2.4 +Name: uvicorn +Version: 0.35.0 +Summary: The lightning-fast ASGI server. +Project-URL: Changelog, https://www.uvicorn.org/release-notes +Project-URL: Funding, https://github.com/sponsors/encode +Project-URL: Homepage, https://www.uvicorn.org/ +Project-URL: Source, https://github.com/encode/uvicorn +Author-email: Tom Christie , Marcelo Trylesinski +License-Expression: BSD-3-Clause +License-File: LICENSE.md +Classifier: Development Status :: 4 - Beta +Classifier: Environment :: Web Environment +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Internet :: WWW/HTTP +Requires-Python: >=3.9 +Requires-Dist: click>=7.0 +Requires-Dist: h11>=0.8 +Requires-Dist: typing-extensions>=4.0; python_version < '3.11' +Provides-Extra: standard +Requires-Dist: colorama>=0.4; (sys_platform == 'win32') and extra == 'standard' +Requires-Dist: httptools>=0.6.3; extra == 'standard' +Requires-Dist: python-dotenv>=0.13; extra == 'standard' +Requires-Dist: pyyaml>=5.1; extra == 'standard' +Requires-Dist: uvloop>=0.15.1; (sys_platform != 'win32' and (sys_platform != 'cygwin' and platform_python_implementation != 'PyPy')) and extra == 'standard' +Requires-Dist: watchfiles>=0.13; extra == 'standard' +Requires-Dist: websockets>=10.4; extra == 'standard' +Description-Content-Type: text/markdown + +

+ uvicorn +

+ +

+An ASGI web server, for Python. +

+ +--- + +[![Build Status](https://github.com/encode/uvicorn/workflows/Test%20Suite/badge.svg)](https://github.com/encode/uvicorn/actions) +[![Package version](https://badge.fury.io/py/uvicorn.svg)](https://pypi.python.org/pypi/uvicorn) +[![Supported Python Version](https://img.shields.io/pypi/pyversions/uvicorn.svg?color=%2334D058)](https://pypi.org/project/uvicorn) + +**Documentation**: [https://www.uvicorn.org](https://www.uvicorn.org) + +--- + +Uvicorn is an ASGI web server implementation for Python. + +Until recently Python has lacked a minimal low-level server/application interface for +async frameworks. The [ASGI specification][asgi] fills this gap, and means we're now able to +start building a common set of tooling usable across all async frameworks. + +Uvicorn supports HTTP/1.1 and WebSockets. + +## Quickstart + +Install using `pip`: + +```shell +$ pip install uvicorn +``` + +This will install uvicorn with minimal (pure Python) dependencies. + +```shell +$ pip install 'uvicorn[standard]' +``` + +This will install uvicorn with "Cython-based" dependencies (where possible) and other "optional extras". + +In this context, "Cython-based" means the following: + +- the event loop `uvloop` will be installed and used if possible. +- the http protocol will be handled by `httptools` if possible. + +Moreover, "optional extras" means that: + +- the websocket protocol will be handled by `websockets` (should you want to use `wsproto` you'd need to install it manually) if possible. +- the `--reload` flag in development mode will use `watchfiles`. +- windows users will have `colorama` installed for the colored logs. +- `python-dotenv` will be installed should you want to use the `--env-file` option. +- `PyYAML` will be installed to allow you to provide a `.yaml` file to `--log-config`, if desired. + +Create an application, in `example.py`: + +```python +async def app(scope, receive, send): + assert scope['type'] == 'http' + + await send({ + 'type': 'http.response.start', + 'status': 200, + 'headers': [ + (b'content-type', b'text/plain'), + ], + }) + await send({ + 'type': 'http.response.body', + 'body': b'Hello, world!', + }) +``` + +Run the server: + +```shell +$ uvicorn example:app +``` + +--- + +## Why ASGI? + +Most well established Python Web frameworks started out as WSGI-based frameworks. + +WSGI applications are a single, synchronous callable that takes a request and returns a response. +This doesn’t allow for long-lived connections, like you get with long-poll HTTP or WebSocket connections, +which WSGI doesn't support well. + +Having an async concurrency model also allows for options such as lightweight background tasks, +and can be less of a limiting factor for endpoints that have long periods being blocked on network +I/O such as dealing with slow HTTP requests. + +--- + +## Alternative ASGI servers + +A strength of the ASGI protocol is that it decouples the server implementation +from the application framework. This allows for an ecosystem of interoperating +webservers and application frameworks. + +### Daphne + +The first ASGI server implementation, originally developed to power Django Channels, is [the Daphne webserver][daphne]. + +It is run widely in production, and supports HTTP/1.1, HTTP/2, and WebSockets. + +Any of the example applications given here can equally well be run using `daphne` instead. + +``` +$ pip install daphne +$ daphne app:App +``` + +### Hypercorn + +[Hypercorn][hypercorn] was initially part of the Quart web framework, before +being separated out into a standalone ASGI server. + +Hypercorn supports HTTP/1.1, HTTP/2, and WebSockets. + +It also supports [the excellent `trio` async framework][trio], as an alternative to `asyncio`. + +``` +$ pip install hypercorn +$ hypercorn app:App +``` + +### Mangum + +[Mangum][mangum] is an adapter for using ASGI applications with AWS Lambda & API Gateway. + +### Granian + +[Granian][granian] is an ASGI compatible Rust HTTP server which supports HTTP/2, TLS and WebSockets. + +--- + +

Uvicorn is BSD licensed code.
Designed & crafted with care.

— 🦄 —

+ +[asgi]: https://asgi.readthedocs.io/en/latest/ +[daphne]: https://github.com/django/daphne +[hypercorn]: https://github.com/pgjones/hypercorn +[trio]: https://trio.readthedocs.io +[mangum]: https://github.com/jordaneremieff/mangum +[granian]: https://github.com/emmett-framework/granian diff --git a/venv/Lib/site-packages/uvicorn-0.35.0.dist-info/RECORD b/venv/Lib/site-packages/uvicorn-0.35.0.dist-info/RECORD new file mode 100644 index 00000000..cba214f6 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn-0.35.0.dist-info/RECORD @@ -0,0 +1,87 @@ +../../Scripts/uvicorn.exe,sha256=Tsk4Zl9fZRRXxM1YJ4lBu-83LpXT_MTaO4QsCM5VBbo,108405 +uvicorn-0.35.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +uvicorn-0.35.0.dist-info/METADATA,sha256=a1sVo25u3fbfeGXSMmFdYOuPPnBXF8WjHlYq1oc2qTo,6531 +uvicorn-0.35.0.dist-info/RECORD,, +uvicorn-0.35.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +uvicorn-0.35.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +uvicorn-0.35.0.dist-info/entry_points.txt,sha256=FW1w-hkc9QgwaGoovMvm0ZY73w_NcycWdGAUfDsNGxw,46 +uvicorn-0.35.0.dist-info/licenses/LICENSE.md,sha256=7-Gs8-YvuZwoiw7HPlp3O3Jo70Mg_nV-qZQhTktjw3E,1526 +uvicorn/__init__.py,sha256=pMIkABPLJ9eS0OuDO-bP506aVdLfWlHDtk9uzSTgE5E,147 +uvicorn/__main__.py,sha256=DQizy6nKP0ywhPpnCHgmRDYIMfcqZKVEzNIWQZjqtVQ,62 +uvicorn/__pycache__/__init__.cpython-312.pyc,, +uvicorn/__pycache__/__main__.cpython-312.pyc,, +uvicorn/__pycache__/_subprocess.cpython-312.pyc,, +uvicorn/__pycache__/_types.cpython-312.pyc,, +uvicorn/__pycache__/config.cpython-312.pyc,, +uvicorn/__pycache__/importer.cpython-312.pyc,, +uvicorn/__pycache__/logging.cpython-312.pyc,, +uvicorn/__pycache__/main.cpython-312.pyc,, +uvicorn/__pycache__/server.cpython-312.pyc,, +uvicorn/__pycache__/workers.cpython-312.pyc,, +uvicorn/_subprocess.py,sha256=HbfRnsCkXyg7xCWVAWWzXQTeWlvLKfTlIF5wevFBkR4,2766 +uvicorn/_types.py,sha256=5FcPvvIfeKsJDjGhTrceDv8TmwzYI8yPF7mXsXTWOUM,7775 +uvicorn/config.py,sha256=OHgnEBBuk7XMhwKByt1hlBJsXk8EGWRYGpCQ_G1deaA,21013 +uvicorn/importer.py,sha256=nRt0QQ3qpi264-n_mR0l55C2ddM8nowTNzT1jsWaam8,1128 +uvicorn/lifespan/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +uvicorn/lifespan/__pycache__/__init__.cpython-312.pyc,, +uvicorn/lifespan/__pycache__/off.cpython-312.pyc,, +uvicorn/lifespan/__pycache__/on.cpython-312.pyc,, +uvicorn/lifespan/off.py,sha256=nfI6qHAUo_8-BEXMBKoHQ9wUbsXrPaXLCbDSS0vKSr8,332 +uvicorn/lifespan/on.py,sha256=1KYuFNNyQONIjtEHhKZAJp-OOokIyjj74wpGCGBv4lk,5184 +uvicorn/logging.py,sha256=-eCE4nOJmFbtB9qfNJuEVNF0Y13LGUHqvFzemYT0PaQ,4235 +uvicorn/loops/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +uvicorn/loops/__pycache__/__init__.cpython-312.pyc,, +uvicorn/loops/__pycache__/asyncio.cpython-312.pyc,, +uvicorn/loops/__pycache__/auto.cpython-312.pyc,, +uvicorn/loops/__pycache__/uvloop.cpython-312.pyc,, +uvicorn/loops/asyncio.py,sha256=qPnQLT2htZkcGG_ncnTyrSH38jEkqjg8guwP0lA146A,301 +uvicorn/loops/auto.py,sha256=BWVq18ce9SoFTo3z5zNW2IU2850u2tRrc6WyK7idsdI,400 +uvicorn/loops/uvloop.py,sha256=K4QybYVxtK9C2emDhDPUCkBXR4XMT5Ofv9BPFPoX0ok,148 +uvicorn/main.py,sha256=83-MEMVc6ErEdvUfW6x-gELYJ78GiWRNMsmuing9DUI,17231 +uvicorn/middleware/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +uvicorn/middleware/__pycache__/__init__.cpython-312.pyc,, +uvicorn/middleware/__pycache__/asgi2.cpython-312.pyc,, +uvicorn/middleware/__pycache__/message_logger.cpython-312.pyc,, +uvicorn/middleware/__pycache__/proxy_headers.cpython-312.pyc,, +uvicorn/middleware/__pycache__/wsgi.cpython-312.pyc,, +uvicorn/middleware/asgi2.py,sha256=YQrQNm3RehFts3mzk3k4yw8aD8Egtj0tRS3N45YkQa0,394 +uvicorn/middleware/message_logger.py,sha256=IHEZUSnFNaMFUFdwtZO3AuFATnYcSor-gVtOjbCzt8M,2859 +uvicorn/middleware/proxy_headers.py,sha256=f1VDAc-ipPHdNTuLNHwYCeDgYXoCL_VjD6hDTUXZT_U,5790 +uvicorn/middleware/wsgi.py,sha256=N6fWyOnHoeHbUevX0mDYFNmI4lsMv7Y0qnd7Y3fJVL4,7105 +uvicorn/protocols/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +uvicorn/protocols/__pycache__/__init__.cpython-312.pyc,, +uvicorn/protocols/__pycache__/utils.cpython-312.pyc,, +uvicorn/protocols/http/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +uvicorn/protocols/http/__pycache__/__init__.cpython-312.pyc,, +uvicorn/protocols/http/__pycache__/auto.cpython-312.pyc,, +uvicorn/protocols/http/__pycache__/flow_control.cpython-312.pyc,, +uvicorn/protocols/http/__pycache__/h11_impl.cpython-312.pyc,, +uvicorn/protocols/http/__pycache__/httptools_impl.cpython-312.pyc,, +uvicorn/protocols/http/auto.py,sha256=YfXGyzWTaaE2p_jkTPWrJCXsxEaQnC3NK0-G7Wgmnls,403 +uvicorn/protocols/http/flow_control.py,sha256=050WVg31EvPOkHwynCoMP1zXFl_vO3U4durlc5vyp4U,1701 +uvicorn/protocols/http/h11_impl.py,sha256=4b-KswK57FBaRPeHXlK_oy8pKM6vG1haALCIeRH-1bA,20694 +uvicorn/protocols/http/httptools_impl.py,sha256=tuQBCiD6rf5DQeyQwHVc45rxH9ouojMpkXi9KG6NRBk,21805 +uvicorn/protocols/utils.py,sha256=rCjYLd4_uwPeZkbRXQ6beCfxyI_oYpvJCwz3jEGNOiE,1849 +uvicorn/protocols/websockets/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +uvicorn/protocols/websockets/__pycache__/__init__.cpython-312.pyc,, +uvicorn/protocols/websockets/__pycache__/auto.cpython-312.pyc,, +uvicorn/protocols/websockets/__pycache__/websockets_impl.cpython-312.pyc,, +uvicorn/protocols/websockets/__pycache__/websockets_sansio_impl.cpython-312.pyc,, +uvicorn/protocols/websockets/__pycache__/wsproto_impl.cpython-312.pyc,, +uvicorn/protocols/websockets/auto.py,sha256=SH_KV_3vwR8_oGda2GrHFt38VG-IwY0ufjvHOu4VA0o,581 +uvicorn/protocols/websockets/websockets_impl.py,sha256=qonQJxz9wMKMwB2RnYZezeP-XfmAsxCvNeGgu4sC3Lc,15546 +uvicorn/protocols/websockets/websockets_sansio_impl.py,sha256=TxpjkbuhaTd0UXYc1VMe4UgBr6kn_JwJV-hqegHHmxs,17145 +uvicorn/protocols/websockets/wsproto_impl.py,sha256=u2TKyzRUCmQpS1e4E_X6Uou9QIuoKZNNNmHU1IzkWPU,15366 +uvicorn/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 +uvicorn/server.py,sha256=3AKFM50WbZkwnqjZFxSd8wLBVIkcxZjmvP8gPZf95_s,12998 +uvicorn/supervisors/__init__.py,sha256=wT8eOEIqT1yWQgytZtv5taWMul7xoTIY0xm1m4oyPTw,507 +uvicorn/supervisors/__pycache__/__init__.cpython-312.pyc,, +uvicorn/supervisors/__pycache__/basereload.cpython-312.pyc,, +uvicorn/supervisors/__pycache__/multiprocess.cpython-312.pyc,, +uvicorn/supervisors/__pycache__/statreload.cpython-312.pyc,, +uvicorn/supervisors/__pycache__/watchfilesreload.cpython-312.pyc,, +uvicorn/supervisors/basereload.py,sha256=MAXSQ3ckZPwqzJ8Un9yDhk3W0yyAArQtZLuOE0OInSc,4036 +uvicorn/supervisors/multiprocess.py,sha256=Opt0XvOUj1DIMXYwb4OlkJZxeh_RjweFnTmDPYItONw,7507 +uvicorn/supervisors/statreload.py,sha256=uYblmoxM3IbPbvMDzr5Abw2-WykQl8NxTTzeLfVyvnU,1566 +uvicorn/supervisors/watchfilesreload.py,sha256=W86Ybb0E5SdMYYuWHJ3bpAFXdw5ZurvLRdFcvLnYEIA,2859 +uvicorn/workers.py,sha256=7KGgGAapxGkGeXUcBGunOjSNdI9R44KCoWTGEAqAdfs,3895 diff --git a/venv/Lib/site-packages/uvicorn-0.35.0.dist-info/REQUESTED b/venv/Lib/site-packages/uvicorn-0.35.0.dist-info/REQUESTED new file mode 100644 index 00000000..e69de29b diff --git a/venv/Lib/site-packages/uvicorn-0.35.0.dist-info/WHEEL b/venv/Lib/site-packages/uvicorn-0.35.0.dist-info/WHEEL new file mode 100644 index 00000000..12228d41 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn-0.35.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/venv/Lib/site-packages/uvicorn-0.35.0.dist-info/entry_points.txt b/venv/Lib/site-packages/uvicorn-0.35.0.dist-info/entry_points.txt new file mode 100644 index 00000000..4b00fcb6 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn-0.35.0.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +uvicorn = uvicorn.main:main diff --git a/venv/Lib/site-packages/uvicorn-0.35.0.dist-info/licenses/LICENSE.md b/venv/Lib/site-packages/uvicorn-0.35.0.dist-info/licenses/LICENSE.md new file mode 100644 index 00000000..a6bba145 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn-0.35.0.dist-info/licenses/LICENSE.md @@ -0,0 +1,27 @@ +Copyright © 2017-present, [Encode OSS Ltd](https://www.encode.io/). +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/venv/Lib/site-packages/uvicorn/__init__.py b/venv/Lib/site-packages/uvicorn/__init__.py new file mode 100644 index 00000000..3424aadb --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/__init__.py @@ -0,0 +1,5 @@ +from uvicorn.config import Config +from uvicorn.main import Server, main, run + +__version__ = "0.35.0" +__all__ = ["main", "run", "Config", "Server"] diff --git a/venv/Lib/site-packages/uvicorn/__main__.py b/venv/Lib/site-packages/uvicorn/__main__.py new file mode 100644 index 00000000..8a1dc979 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/__main__.py @@ -0,0 +1,4 @@ +import uvicorn + +if __name__ == "__main__": + uvicorn.main() diff --git a/venv/Lib/site-packages/uvicorn/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..8acaffa7 Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/__pycache__/__main__.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/__pycache__/__main__.cpython-312.pyc new file mode 100644 index 00000000..02d751a7 Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/__pycache__/__main__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/__pycache__/_subprocess.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/__pycache__/_subprocess.cpython-312.pyc new file mode 100644 index 00000000..82a8a1e1 Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/__pycache__/_subprocess.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/__pycache__/_types.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/__pycache__/_types.cpython-312.pyc new file mode 100644 index 00000000..1cc5bdbf Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/__pycache__/_types.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/__pycache__/config.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/__pycache__/config.cpython-312.pyc new file mode 100644 index 00000000..66670b9b Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/__pycache__/config.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/__pycache__/importer.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/__pycache__/importer.cpython-312.pyc new file mode 100644 index 00000000..633e3b71 Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/__pycache__/importer.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/__pycache__/logging.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/__pycache__/logging.cpython-312.pyc new file mode 100644 index 00000000..0f7d9f14 Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/__pycache__/logging.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/__pycache__/main.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/__pycache__/main.cpython-312.pyc new file mode 100644 index 00000000..c2381b13 Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/__pycache__/main.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/__pycache__/server.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/__pycache__/server.cpython-312.pyc new file mode 100644 index 00000000..d4913485 Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/__pycache__/server.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/__pycache__/workers.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/__pycache__/workers.cpython-312.pyc new file mode 100644 index 00000000..9909655f Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/__pycache__/workers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/_subprocess.py b/venv/Lib/site-packages/uvicorn/_subprocess.py new file mode 100644 index 00000000..1c06844d --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/_subprocess.py @@ -0,0 +1,84 @@ +""" +Some light wrappers around Python's multiprocessing, to deal with cleanly +starting child processes. +""" + +from __future__ import annotations + +import multiprocessing +import os +import sys +from multiprocessing.context import SpawnProcess +from socket import socket +from typing import Callable + +from uvicorn.config import Config + +multiprocessing.allow_connection_pickling() +spawn = multiprocessing.get_context("spawn") + + +def get_subprocess( + config: Config, + target: Callable[..., None], + sockets: list[socket], +) -> SpawnProcess: + """ + Called in the parent process, to instantiate a new child process instance. + The child is not yet started at this point. + + * config - The Uvicorn configuration instance. + * target - A callable that accepts a list of sockets. In practice this will + be the `Server.run()` method. + * sockets - A list of sockets to pass to the server. Sockets are bound once + by the parent process, and then passed to the child processes. + """ + # We pass across the stdin fileno, and reopen it in the child process. + # This is required for some debugging environments. + try: + stdin_fileno = sys.stdin.fileno() + # The `sys.stdin` can be `None`, see https://docs.python.org/3/library/sys.html#sys.__stdin__. + except (AttributeError, OSError): + stdin_fileno = None + + kwargs = { + "config": config, + "target": target, + "sockets": sockets, + "stdin_fileno": stdin_fileno, + } + + return spawn.Process(target=subprocess_started, kwargs=kwargs) + + +def subprocess_started( + config: Config, + target: Callable[..., None], + sockets: list[socket], + stdin_fileno: int | None, +) -> None: + """ + Called when the child process starts. + + * config - The Uvicorn configuration instance. + * target - A callable that accepts a list of sockets. In practice this will + be the `Server.run()` method. + * sockets - A list of sockets to pass to the server. Sockets are bound once + by the parent process, and then passed to the child processes. + * stdin_fileno - The file number of sys.stdin, so that it can be reattached + to the child process. + """ + # Re-open stdin. + if stdin_fileno is not None: + sys.stdin = os.fdopen(stdin_fileno) # pragma: full coverage + + # Logging needs to be setup again for each child. + config.configure_logging() + + try: + # Now we can call into `Server.run(sockets=sockets)` + target(sockets=sockets) + except KeyboardInterrupt: # pragma: no cover + # supress the exception to avoid a traceback from subprocess.Popen + # the parent already expects us to end, so no vital information is lost + pass diff --git a/venv/Lib/site-packages/uvicorn/_types.py b/venv/Lib/site-packages/uvicorn/_types.py new file mode 100644 index 00000000..c927cc11 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/_types.py @@ -0,0 +1,281 @@ +""" +Copyright (c) Django Software Foundation and individual contributors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of Django nor the names of its contributors may be used + to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" + +from __future__ import annotations + +import sys +import types +from collections.abc import Awaitable, Iterable, MutableMapping +from typing import Any, Callable, Literal, Optional, Protocol, TypedDict, Union + +if sys.version_info >= (3, 11): # pragma: py-lt-311 + from typing import NotRequired +else: # pragma: py-gte-311 + from typing_extensions import NotRequired + +# WSGI +Environ = MutableMapping[str, Any] +ExcInfo = tuple[type[BaseException], BaseException, Optional[types.TracebackType]] +StartResponse = Callable[[str, Iterable[tuple[str, str]], Optional[ExcInfo]], None] +WSGIApp = Callable[[Environ, StartResponse], Union[Iterable[bytes], BaseException]] + + +# ASGI +class ASGIVersions(TypedDict): + spec_version: str + version: Literal["2.0"] | Literal["3.0"] + + +class HTTPScope(TypedDict): + type: Literal["http"] + asgi: ASGIVersions + http_version: str + method: str + scheme: str + path: str + raw_path: bytes + query_string: bytes + root_path: str + headers: Iterable[tuple[bytes, bytes]] + client: tuple[str, int] | None + server: tuple[str, int | None] | None + state: NotRequired[dict[str, Any]] + extensions: NotRequired[dict[str, dict[object, object]]] + + +class WebSocketScope(TypedDict): + type: Literal["websocket"] + asgi: ASGIVersions + http_version: str + scheme: str + path: str + raw_path: bytes + query_string: bytes + root_path: str + headers: Iterable[tuple[bytes, bytes]] + client: tuple[str, int] | None + server: tuple[str, int | None] | None + subprotocols: Iterable[str] + state: NotRequired[dict[str, Any]] + extensions: NotRequired[dict[str, dict[object, object]]] + + +class LifespanScope(TypedDict): + type: Literal["lifespan"] + asgi: ASGIVersions + state: NotRequired[dict[str, Any]] + + +WWWScope = Union[HTTPScope, WebSocketScope] +Scope = Union[HTTPScope, WebSocketScope, LifespanScope] + + +class HTTPRequestEvent(TypedDict): + type: Literal["http.request"] + body: bytes + more_body: bool + + +class HTTPResponseDebugEvent(TypedDict): + type: Literal["http.response.debug"] + info: dict[str, object] + + +class HTTPResponseStartEvent(TypedDict): + type: Literal["http.response.start"] + status: int + headers: NotRequired[Iterable[tuple[bytes, bytes]]] + trailers: NotRequired[bool] + + +class HTTPResponseBodyEvent(TypedDict): + type: Literal["http.response.body"] + body: bytes + more_body: NotRequired[bool] + + +class HTTPResponseTrailersEvent(TypedDict): + type: Literal["http.response.trailers"] + headers: Iterable[tuple[bytes, bytes]] + more_trailers: bool + + +class HTTPServerPushEvent(TypedDict): + type: Literal["http.response.push"] + path: str + headers: Iterable[tuple[bytes, bytes]] + + +class HTTPDisconnectEvent(TypedDict): + type: Literal["http.disconnect"] + + +class WebSocketConnectEvent(TypedDict): + type: Literal["websocket.connect"] + + +class WebSocketAcceptEvent(TypedDict): + type: Literal["websocket.accept"] + subprotocol: NotRequired[str | None] + headers: NotRequired[Iterable[tuple[bytes, bytes]]] + + +class _WebSocketReceiveEventBytes(TypedDict): + type: Literal["websocket.receive"] + bytes: bytes + text: NotRequired[None] + + +class _WebSocketReceiveEventText(TypedDict): + type: Literal["websocket.receive"] + bytes: NotRequired[None] + text: str + + +WebSocketReceiveEvent = Union[_WebSocketReceiveEventBytes, _WebSocketReceiveEventText] + + +class _WebSocketSendEventBytes(TypedDict): + type: Literal["websocket.send"] + bytes: bytes + text: NotRequired[None] + + +class _WebSocketSendEventText(TypedDict): + type: Literal["websocket.send"] + bytes: NotRequired[None] + text: str + + +WebSocketSendEvent = Union[_WebSocketSendEventBytes, _WebSocketSendEventText] + + +class WebSocketResponseStartEvent(TypedDict): + type: Literal["websocket.http.response.start"] + status: int + headers: Iterable[tuple[bytes, bytes]] + + +class WebSocketResponseBodyEvent(TypedDict): + type: Literal["websocket.http.response.body"] + body: bytes + more_body: NotRequired[bool] + + +class WebSocketDisconnectEvent(TypedDict): + type: Literal["websocket.disconnect"] + code: int + reason: NotRequired[str | None] + + +class WebSocketCloseEvent(TypedDict): + type: Literal["websocket.close"] + code: NotRequired[int] + reason: NotRequired[str | None] + + +class LifespanStartupEvent(TypedDict): + type: Literal["lifespan.startup"] + + +class LifespanShutdownEvent(TypedDict): + type: Literal["lifespan.shutdown"] + + +class LifespanStartupCompleteEvent(TypedDict): + type: Literal["lifespan.startup.complete"] + + +class LifespanStartupFailedEvent(TypedDict): + type: Literal["lifespan.startup.failed"] + message: str + + +class LifespanShutdownCompleteEvent(TypedDict): + type: Literal["lifespan.shutdown.complete"] + + +class LifespanShutdownFailedEvent(TypedDict): + type: Literal["lifespan.shutdown.failed"] + message: str + + +WebSocketEvent = Union[WebSocketReceiveEvent, WebSocketDisconnectEvent, WebSocketConnectEvent] + + +ASGIReceiveEvent = Union[ + HTTPRequestEvent, + HTTPDisconnectEvent, + WebSocketConnectEvent, + WebSocketReceiveEvent, + WebSocketDisconnectEvent, + LifespanStartupEvent, + LifespanShutdownEvent, +] + + +ASGISendEvent = Union[ + HTTPResponseStartEvent, + HTTPResponseBodyEvent, + HTTPResponseTrailersEvent, + HTTPServerPushEvent, + HTTPDisconnectEvent, + WebSocketAcceptEvent, + WebSocketSendEvent, + WebSocketResponseStartEvent, + WebSocketResponseBodyEvent, + WebSocketCloseEvent, + LifespanStartupCompleteEvent, + LifespanStartupFailedEvent, + LifespanShutdownCompleteEvent, + LifespanShutdownFailedEvent, +] + + +ASGIReceiveCallable = Callable[[], Awaitable[ASGIReceiveEvent]] +ASGISendCallable = Callable[[ASGISendEvent], Awaitable[None]] + + +class ASGI2Protocol(Protocol): + def __init__(self, scope: Scope) -> None: ... # pragma: no cover + + async def __call__(self, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None: ... # pragma: no cover + + +ASGI2Application = type[ASGI2Protocol] +ASGI3Application = Callable[ + [ + Scope, + ASGIReceiveCallable, + ASGISendCallable, + ], + Awaitable[None], +] +ASGIApplication = Union[ASGI2Application, ASGI3Application] diff --git a/venv/Lib/site-packages/uvicorn/config.py b/venv/Lib/site-packages/uvicorn/config.py new file mode 100644 index 00000000..7f6aaea7 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/config.py @@ -0,0 +1,531 @@ +from __future__ import annotations + +import asyncio +import inspect +import json +import logging +import logging.config +import os +import socket +import ssl +import sys +from collections.abc import Awaitable +from configparser import RawConfigParser +from pathlib import Path +from typing import IO, Any, Callable, Literal + +import click + +from uvicorn._types import ASGIApplication +from uvicorn.importer import ImportFromStringError, import_from_string +from uvicorn.logging import TRACE_LOG_LEVEL +from uvicorn.middleware.asgi2 import ASGI2Middleware +from uvicorn.middleware.message_logger import MessageLoggerMiddleware +from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware +from uvicorn.middleware.wsgi import WSGIMiddleware + +HTTPProtocolType = Literal["auto", "h11", "httptools"] +WSProtocolType = Literal["auto", "none", "websockets", "websockets-sansio", "wsproto"] +LifespanType = Literal["auto", "on", "off"] +LoopSetupType = Literal["none", "auto", "asyncio", "uvloop"] +InterfaceType = Literal["auto", "asgi3", "asgi2", "wsgi"] + +LOG_LEVELS: dict[str, int] = { + "critical": logging.CRITICAL, + "error": logging.ERROR, + "warning": logging.WARNING, + "info": logging.INFO, + "debug": logging.DEBUG, + "trace": TRACE_LOG_LEVEL, +} +HTTP_PROTOCOLS: dict[HTTPProtocolType, str] = { + "auto": "uvicorn.protocols.http.auto:AutoHTTPProtocol", + "h11": "uvicorn.protocols.http.h11_impl:H11Protocol", + "httptools": "uvicorn.protocols.http.httptools_impl:HttpToolsProtocol", +} +WS_PROTOCOLS: dict[WSProtocolType, str | None] = { + "auto": "uvicorn.protocols.websockets.auto:AutoWebSocketsProtocol", + "none": None, + "websockets": "uvicorn.protocols.websockets.websockets_impl:WebSocketProtocol", + "websockets-sansio": "uvicorn.protocols.websockets.websockets_sansio_impl:WebSocketsSansIOProtocol", + "wsproto": "uvicorn.protocols.websockets.wsproto_impl:WSProtocol", +} +LIFESPAN: dict[LifespanType, str] = { + "auto": "uvicorn.lifespan.on:LifespanOn", + "on": "uvicorn.lifespan.on:LifespanOn", + "off": "uvicorn.lifespan.off:LifespanOff", +} +LOOP_SETUPS: dict[LoopSetupType, str | None] = { + "none": None, + "auto": "uvicorn.loops.auto:auto_loop_setup", + "asyncio": "uvicorn.loops.asyncio:asyncio_setup", + "uvloop": "uvicorn.loops.uvloop:uvloop_setup", +} +INTERFACES: list[InterfaceType] = ["auto", "asgi3", "asgi2", "wsgi"] + +SSL_PROTOCOL_VERSION: int = ssl.PROTOCOL_TLS_SERVER + +LOGGING_CONFIG: dict[str, Any] = { + "version": 1, + "disable_existing_loggers": False, + "formatters": { + "default": { + "()": "uvicorn.logging.DefaultFormatter", + "fmt": "%(levelprefix)s %(message)s", + "use_colors": None, + }, + "access": { + "()": "uvicorn.logging.AccessFormatter", + "fmt": '%(levelprefix)s %(client_addr)s - "%(request_line)s" %(status_code)s', # noqa: E501 + }, + }, + "handlers": { + "default": { + "formatter": "default", + "class": "logging.StreamHandler", + "stream": "ext://sys.stderr", + }, + "access": { + "formatter": "access", + "class": "logging.StreamHandler", + "stream": "ext://sys.stdout", + }, + }, + "loggers": { + "uvicorn": {"handlers": ["default"], "level": "INFO", "propagate": False}, + "uvicorn.error": {"level": "INFO"}, + "uvicorn.access": {"handlers": ["access"], "level": "INFO", "propagate": False}, + }, +} + +logger = logging.getLogger("uvicorn.error") + + +def create_ssl_context( + certfile: str | os.PathLike[str], + keyfile: str | os.PathLike[str] | None, + password: str | None, + ssl_version: int, + cert_reqs: int, + ca_certs: str | os.PathLike[str] | None, + ciphers: str | None, +) -> ssl.SSLContext: + ctx = ssl.SSLContext(ssl_version) + get_password = (lambda: password) if password else None + ctx.load_cert_chain(certfile, keyfile, get_password) + ctx.verify_mode = ssl.VerifyMode(cert_reqs) + if ca_certs: + ctx.load_verify_locations(ca_certs) + if ciphers: + ctx.set_ciphers(ciphers) + return ctx + + +def is_dir(path: Path) -> bool: + try: + if not path.is_absolute(): + path = path.resolve() + return path.is_dir() + except OSError: # pragma: full coverage + return False + + +def resolve_reload_patterns(patterns_list: list[str], directories_list: list[str]) -> tuple[list[str], list[Path]]: + directories: list[Path] = list(set(map(Path, directories_list.copy()))) + patterns: list[str] = patterns_list.copy() + + current_working_directory = Path.cwd() + for pattern in patterns_list: + # Special case for the .* pattern, otherwise this would only match + # hidden directories which is probably undesired + if pattern == ".*": + continue # pragma: py-not-linux + patterns.append(pattern) + if is_dir(Path(pattern)): + directories.append(Path(pattern)) + else: + for match in current_working_directory.glob(pattern): + if is_dir(match): + directories.append(match) + + directories = list(set(directories)) + directories = list(map(Path, directories)) + directories = list(map(lambda x: x.resolve(), directories)) + directories = list({reload_path for reload_path in directories if is_dir(reload_path)}) + + children = [] + for j in range(len(directories)): + for k in range(j + 1, len(directories)): # pragma: full coverage + if directories[j] in directories[k].parents: + children.append(directories[k]) + elif directories[k] in directories[j].parents: + children.append(directories[j]) + + directories = list(set(directories).difference(set(children))) + + return list(set(patterns)), directories + + +def _normalize_dirs(dirs: list[str] | str | None) -> list[str]: + if dirs is None: + return [] + if isinstance(dirs, str): + return [dirs] + return list(set(dirs)) + + +class Config: + def __init__( + self, + app: ASGIApplication | Callable[..., Any] | str, + host: str = "127.0.0.1", + port: int = 8000, + uds: str | None = None, + fd: int | None = None, + loop: LoopSetupType = "auto", + http: type[asyncio.Protocol] | HTTPProtocolType = "auto", + ws: type[asyncio.Protocol] | WSProtocolType = "auto", + ws_max_size: int = 16 * 1024 * 1024, + ws_max_queue: int = 32, + ws_ping_interval: float | None = 20.0, + ws_ping_timeout: float | None = 20.0, + ws_per_message_deflate: bool = True, + lifespan: LifespanType = "auto", + env_file: str | os.PathLike[str] | None = None, + log_config: dict[str, Any] | str | RawConfigParser | IO[Any] | None = LOGGING_CONFIG, + log_level: str | int | None = None, + access_log: bool = True, + use_colors: bool | None = None, + interface: InterfaceType = "auto", + reload: bool = False, + reload_dirs: list[str] | str | None = None, + reload_delay: float = 0.25, + reload_includes: list[str] | str | None = None, + reload_excludes: list[str] | str | None = None, + workers: int | None = None, + proxy_headers: bool = True, + server_header: bool = True, + date_header: bool = True, + forwarded_allow_ips: list[str] | str | None = None, + root_path: str = "", + limit_concurrency: int | None = None, + limit_max_requests: int | None = None, + backlog: int = 2048, + timeout_keep_alive: int = 5, + timeout_notify: int = 30, + timeout_graceful_shutdown: int | None = None, + callback_notify: Callable[..., Awaitable[None]] | None = None, + ssl_keyfile: str | os.PathLike[str] | None = None, + ssl_certfile: str | os.PathLike[str] | None = None, + ssl_keyfile_password: str | None = None, + ssl_version: int = SSL_PROTOCOL_VERSION, + ssl_cert_reqs: int = ssl.CERT_NONE, + ssl_ca_certs: str | None = None, + ssl_ciphers: str = "TLSv1", + headers: list[tuple[str, str]] | None = None, + factory: bool = False, + h11_max_incomplete_event_size: int | None = None, + ): + self.app = app + self.host = host + self.port = port + self.uds = uds + self.fd = fd + self.loop = loop + self.http = http + self.ws = ws + self.ws_max_size = ws_max_size + self.ws_max_queue = ws_max_queue + self.ws_ping_interval = ws_ping_interval + self.ws_ping_timeout = ws_ping_timeout + self.ws_per_message_deflate = ws_per_message_deflate + self.lifespan = lifespan + self.log_config = log_config + self.log_level = log_level + self.access_log = access_log + self.use_colors = use_colors + self.interface = interface + self.reload = reload + self.reload_delay = reload_delay + self.workers = workers or 1 + self.proxy_headers = proxy_headers + self.server_header = server_header + self.date_header = date_header + self.root_path = root_path + self.limit_concurrency = limit_concurrency + self.limit_max_requests = limit_max_requests + self.backlog = backlog + self.timeout_keep_alive = timeout_keep_alive + self.timeout_notify = timeout_notify + self.timeout_graceful_shutdown = timeout_graceful_shutdown + self.callback_notify = callback_notify + self.ssl_keyfile = ssl_keyfile + self.ssl_certfile = ssl_certfile + self.ssl_keyfile_password = ssl_keyfile_password + self.ssl_version = ssl_version + self.ssl_cert_reqs = ssl_cert_reqs + self.ssl_ca_certs = ssl_ca_certs + self.ssl_ciphers = ssl_ciphers + self.headers: list[tuple[str, str]] = headers or [] + self.encoded_headers: list[tuple[bytes, bytes]] = [] + self.factory = factory + self.h11_max_incomplete_event_size = h11_max_incomplete_event_size + + self.loaded = False + self.configure_logging() + + self.reload_dirs: list[Path] = [] + self.reload_dirs_excludes: list[Path] = [] + self.reload_includes: list[str] = [] + self.reload_excludes: list[str] = [] + + if (reload_dirs or reload_includes or reload_excludes) and not self.should_reload: + logger.warning( + "Current configuration will not reload as not all conditions are met, please refer to documentation." + ) + + if self.should_reload: + reload_dirs = _normalize_dirs(reload_dirs) + reload_includes = _normalize_dirs(reload_includes) + reload_excludes = _normalize_dirs(reload_excludes) + + self.reload_includes, self.reload_dirs = resolve_reload_patterns(reload_includes, reload_dirs) + + self.reload_excludes, self.reload_dirs_excludes = resolve_reload_patterns(reload_excludes, []) + + reload_dirs_tmp = self.reload_dirs.copy() + + for directory in self.reload_dirs_excludes: + for reload_directory in reload_dirs_tmp: + if directory == reload_directory or directory in reload_directory.parents: + try: + self.reload_dirs.remove(reload_directory) + except ValueError: # pragma: full coverage + pass + + for pattern in self.reload_excludes: + if pattern in self.reload_includes: + self.reload_includes.remove(pattern) # pragma: full coverage + + if not self.reload_dirs: + if reload_dirs: + logger.warning( + "Provided reload directories %s did not contain valid " + + "directories, watching current working directory.", + reload_dirs, + ) + self.reload_dirs = [Path.cwd()] + + logger.info( + "Will watch for changes in these directories: %s", + sorted(list(map(str, self.reload_dirs))), + ) + + if env_file is not None: + from dotenv import load_dotenv + + logger.info("Loading environment from '%s'", env_file) + load_dotenv(dotenv_path=env_file) + + if workers is None and "WEB_CONCURRENCY" in os.environ: + self.workers = int(os.environ["WEB_CONCURRENCY"]) + + self.forwarded_allow_ips: list[str] | str + if forwarded_allow_ips is None: + self.forwarded_allow_ips = os.environ.get("FORWARDED_ALLOW_IPS", "127.0.0.1") + else: + self.forwarded_allow_ips = forwarded_allow_ips # pragma: full coverage + + if self.reload and self.workers > 1: + logger.warning('"workers" flag is ignored when reloading is enabled.') + + @property + def asgi_version(self) -> Literal["2.0", "3.0"]: + mapping: dict[str, Literal["2.0", "3.0"]] = { + "asgi2": "2.0", + "asgi3": "3.0", + "wsgi": "3.0", + } + return mapping[self.interface] + + @property + def is_ssl(self) -> bool: + return bool(self.ssl_keyfile or self.ssl_certfile) + + @property + def use_subprocess(self) -> bool: + return bool(self.reload or self.workers > 1) + + def configure_logging(self) -> None: + logging.addLevelName(TRACE_LOG_LEVEL, "TRACE") + + if self.log_config is not None: + if isinstance(self.log_config, dict): + if self.use_colors in (True, False): + self.log_config["formatters"]["default"]["use_colors"] = self.use_colors + self.log_config["formatters"]["access"]["use_colors"] = self.use_colors + logging.config.dictConfig(self.log_config) + elif isinstance(self.log_config, str) and self.log_config.endswith(".json"): + with open(self.log_config) as file: + loaded_config = json.load(file) + logging.config.dictConfig(loaded_config) + elif isinstance(self.log_config, str) and self.log_config.endswith((".yaml", ".yml")): + # Install the PyYAML package or the uvicorn[standard] optional + # dependencies to enable this functionality. + import yaml + + with open(self.log_config) as file: + loaded_config = yaml.safe_load(file) + logging.config.dictConfig(loaded_config) + else: + # See the note about fileConfig() here: + # https://docs.python.org/3/library/logging.config.html#configuration-file-format + logging.config.fileConfig(self.log_config, disable_existing_loggers=False) + + if self.log_level is not None: + if isinstance(self.log_level, str): + log_level = LOG_LEVELS[self.log_level] + else: + log_level = self.log_level + logging.getLogger("uvicorn.error").setLevel(log_level) + logging.getLogger("uvicorn.access").setLevel(log_level) + logging.getLogger("uvicorn.asgi").setLevel(log_level) + if self.access_log is False: + logging.getLogger("uvicorn.access").handlers = [] + logging.getLogger("uvicorn.access").propagate = False + + def load(self) -> None: + assert not self.loaded + + if self.is_ssl: + assert self.ssl_certfile + self.ssl: ssl.SSLContext | None = create_ssl_context( + keyfile=self.ssl_keyfile, + certfile=self.ssl_certfile, + password=self.ssl_keyfile_password, + ssl_version=self.ssl_version, + cert_reqs=self.ssl_cert_reqs, + ca_certs=self.ssl_ca_certs, + ciphers=self.ssl_ciphers, + ) + else: + self.ssl = None + + encoded_headers = [(key.lower().encode("latin1"), value.encode("latin1")) for key, value in self.headers] + self.encoded_headers = ( + [(b"server", b"uvicorn")] + encoded_headers + if b"server" not in dict(encoded_headers) and self.server_header + else encoded_headers + ) + + if isinstance(self.http, str): + http_protocol_class = import_from_string(HTTP_PROTOCOLS[self.http]) + self.http_protocol_class: type[asyncio.Protocol] = http_protocol_class + else: + self.http_protocol_class = self.http + + if isinstance(self.ws, str): + ws_protocol_class = import_from_string(WS_PROTOCOLS[self.ws]) + self.ws_protocol_class: type[asyncio.Protocol] | None = ws_protocol_class + else: + self.ws_protocol_class = self.ws + + self.lifespan_class = import_from_string(LIFESPAN[self.lifespan]) + + try: + self.loaded_app = import_from_string(self.app) + except ImportFromStringError as exc: + logger.error("Error loading ASGI app. %s" % exc) + sys.exit(1) + + try: + self.loaded_app = self.loaded_app() + except TypeError as exc: + if self.factory: + logger.error("Error loading ASGI app factory: %s", exc) + sys.exit(1) + else: + if not self.factory: + logger.warning( + "ASGI app factory detected. Using it, but please consider setting the --factory flag explicitly." + ) + + if self.interface == "auto": + if inspect.isclass(self.loaded_app): + use_asgi_3 = hasattr(self.loaded_app, "__await__") + elif inspect.isfunction(self.loaded_app): + use_asgi_3 = asyncio.iscoroutinefunction(self.loaded_app) + else: + call = getattr(self.loaded_app, "__call__", None) + use_asgi_3 = asyncio.iscoroutinefunction(call) + self.interface = "asgi3" if use_asgi_3 else "asgi2" + + if self.interface == "wsgi": + self.loaded_app = WSGIMiddleware(self.loaded_app) + self.ws_protocol_class = None + elif self.interface == "asgi2": + self.loaded_app = ASGI2Middleware(self.loaded_app) + + if logger.getEffectiveLevel() <= TRACE_LOG_LEVEL: + self.loaded_app = MessageLoggerMiddleware(self.loaded_app) + if self.proxy_headers: + self.loaded_app = ProxyHeadersMiddleware(self.loaded_app, trusted_hosts=self.forwarded_allow_ips) + + self.loaded = True + + def setup_event_loop(self) -> None: + loop_setup: Callable | None = import_from_string(LOOP_SETUPS[self.loop]) + if loop_setup is not None: + loop_setup(use_subprocess=self.use_subprocess) + + def bind_socket(self) -> socket.socket: + logger_args: list[str | int] + if self.uds: # pragma: py-win32 + path = self.uds + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + sock.bind(path) + uds_perms = 0o666 + os.chmod(self.uds, uds_perms) + except OSError as exc: # pragma: full coverage + logger.error(exc) + sys.exit(1) + + message = "Uvicorn running on unix socket %s (Press CTRL+C to quit)" + sock_name_format = "%s" + color_message = "Uvicorn running on " + click.style(sock_name_format, bold=True) + " (Press CTRL+C to quit)" + logger_args = [self.uds] + elif self.fd: # pragma: py-win32 + sock = socket.fromfd(self.fd, socket.AF_UNIX, socket.SOCK_STREAM) + message = "Uvicorn running on socket %s (Press CTRL+C to quit)" + fd_name_format = "%s" + color_message = "Uvicorn running on " + click.style(fd_name_format, bold=True) + " (Press CTRL+C to quit)" + logger_args = [sock.getsockname()] + else: + family = socket.AF_INET + addr_format = "%s://%s:%d" + + if self.host and ":" in self.host: # pragma: full coverage + # It's an IPv6 address. + family = socket.AF_INET6 + addr_format = "%s://[%s]:%d" + + sock = socket.socket(family=family) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + try: + sock.bind((self.host, self.port)) + except OSError as exc: # pragma: full coverage + logger.error(exc) + sys.exit(1) + + message = f"Uvicorn running on {addr_format} (Press CTRL+C to quit)" + color_message = "Uvicorn running on " + click.style(addr_format, bold=True) + " (Press CTRL+C to quit)" + protocol_name = "https" if self.is_ssl else "http" + logger_args = [protocol_name, self.host, sock.getsockname()[1]] + logger.info(message, *logger_args, extra={"color_message": color_message}) + sock.set_inheritable(True) + return sock + + @property + def should_reload(self) -> bool: + return isinstance(self.app, str) and self.reload diff --git a/venv/Lib/site-packages/uvicorn/importer.py b/venv/Lib/site-packages/uvicorn/importer.py new file mode 100644 index 00000000..f77520ee --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/importer.py @@ -0,0 +1,34 @@ +import importlib +from typing import Any + + +class ImportFromStringError(Exception): + pass + + +def import_from_string(import_str: Any) -> Any: + if not isinstance(import_str, str): + return import_str + + module_str, _, attrs_str = import_str.partition(":") + if not module_str or not attrs_str: + message = 'Import string "{import_str}" must be in format ":".' + raise ImportFromStringError(message.format(import_str=import_str)) + + try: + module = importlib.import_module(module_str) + except ModuleNotFoundError as exc: + if exc.name != module_str: + raise exc from None + message = 'Could not import module "{module_str}".' + raise ImportFromStringError(message.format(module_str=module_str)) + + instance = module + try: + for attr_str in attrs_str.split("."): + instance = getattr(instance, attr_str) + except AttributeError: + message = 'Attribute "{attrs_str}" not found in module "{module_str}".' + raise ImportFromStringError(message.format(attrs_str=attrs_str, module_str=module_str)) + + return instance diff --git a/venv/Lib/site-packages/uvicorn/lifespan/__init__.py b/venv/Lib/site-packages/uvicorn/lifespan/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/venv/Lib/site-packages/uvicorn/lifespan/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/lifespan/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..28c2a495 Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/lifespan/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/lifespan/__pycache__/off.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/lifespan/__pycache__/off.cpython-312.pyc new file mode 100644 index 00000000..605680a6 Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/lifespan/__pycache__/off.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/lifespan/__pycache__/on.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/lifespan/__pycache__/on.cpython-312.pyc new file mode 100644 index 00000000..2c99e576 Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/lifespan/__pycache__/on.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/lifespan/off.py b/venv/Lib/site-packages/uvicorn/lifespan/off.py new file mode 100644 index 00000000..74554b1e --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/lifespan/off.py @@ -0,0 +1,17 @@ +from __future__ import annotations + +from typing import Any + +from uvicorn import Config + + +class LifespanOff: + def __init__(self, config: Config) -> None: + self.should_exit = False + self.state: dict[str, Any] = {} + + async def startup(self) -> None: + pass + + async def shutdown(self) -> None: + pass diff --git a/venv/Lib/site-packages/uvicorn/lifespan/on.py b/venv/Lib/site-packages/uvicorn/lifespan/on.py new file mode 100644 index 00000000..09df984e --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/lifespan/on.py @@ -0,0 +1,137 @@ +from __future__ import annotations + +import asyncio +import logging +from asyncio import Queue +from typing import Any, Union + +from uvicorn import Config +from uvicorn._types import ( + LifespanScope, + LifespanShutdownCompleteEvent, + LifespanShutdownEvent, + LifespanShutdownFailedEvent, + LifespanStartupCompleteEvent, + LifespanStartupEvent, + LifespanStartupFailedEvent, +) + +LifespanReceiveMessage = Union[LifespanStartupEvent, LifespanShutdownEvent] +LifespanSendMessage = Union[ + LifespanStartupFailedEvent, + LifespanShutdownFailedEvent, + LifespanStartupCompleteEvent, + LifespanShutdownCompleteEvent, +] + + +STATE_TRANSITION_ERROR = "Got invalid state transition on lifespan protocol." + + +class LifespanOn: + def __init__(self, config: Config) -> None: + if not config.loaded: + config.load() + + self.config = config + self.logger = logging.getLogger("uvicorn.error") + self.startup_event = asyncio.Event() + self.shutdown_event = asyncio.Event() + self.receive_queue: Queue[LifespanReceiveMessage] = asyncio.Queue() + self.error_occured = False + self.startup_failed = False + self.shutdown_failed = False + self.should_exit = False + self.state: dict[str, Any] = {} + + async def startup(self) -> None: + self.logger.info("Waiting for application startup.") + + loop = asyncio.get_event_loop() + main_lifespan_task = loop.create_task(self.main()) # noqa: F841 + # Keep a hard reference to prevent garbage collection + # See https://github.com/encode/uvicorn/pull/972 + startup_event: LifespanStartupEvent = {"type": "lifespan.startup"} + await self.receive_queue.put(startup_event) + await self.startup_event.wait() + + if self.startup_failed or (self.error_occured and self.config.lifespan == "on"): + self.logger.error("Application startup failed. Exiting.") + self.should_exit = True + else: + self.logger.info("Application startup complete.") + + async def shutdown(self) -> None: + if self.error_occured: + return + self.logger.info("Waiting for application shutdown.") + shutdown_event: LifespanShutdownEvent = {"type": "lifespan.shutdown"} + await self.receive_queue.put(shutdown_event) + await self.shutdown_event.wait() + + if self.shutdown_failed or (self.error_occured and self.config.lifespan == "on"): + self.logger.error("Application shutdown failed. Exiting.") + self.should_exit = True + else: + self.logger.info("Application shutdown complete.") + + async def main(self) -> None: + try: + app = self.config.loaded_app + scope: LifespanScope = { + "type": "lifespan", + "asgi": {"version": self.config.asgi_version, "spec_version": "2.0"}, + "state": self.state, + } + await app(scope, self.receive, self.send) + except BaseException as exc: + self.asgi = None + self.error_occured = True + if self.startup_failed or self.shutdown_failed: + return + if self.config.lifespan == "auto": + msg = "ASGI 'lifespan' protocol appears unsupported." + self.logger.info(msg) + else: + msg = "Exception in 'lifespan' protocol\n" + self.logger.error(msg, exc_info=exc) + finally: + self.startup_event.set() + self.shutdown_event.set() + + async def send(self, message: LifespanSendMessage) -> None: + assert message["type"] in ( + "lifespan.startup.complete", + "lifespan.startup.failed", + "lifespan.shutdown.complete", + "lifespan.shutdown.failed", + ) + + if message["type"] == "lifespan.startup.complete": + assert not self.startup_event.is_set(), STATE_TRANSITION_ERROR + assert not self.shutdown_event.is_set(), STATE_TRANSITION_ERROR + self.startup_event.set() + + elif message["type"] == "lifespan.startup.failed": + assert not self.startup_event.is_set(), STATE_TRANSITION_ERROR + assert not self.shutdown_event.is_set(), STATE_TRANSITION_ERROR + self.startup_event.set() + self.startup_failed = True + if message.get("message"): + self.logger.error(message["message"]) + + elif message["type"] == "lifespan.shutdown.complete": + assert self.startup_event.is_set(), STATE_TRANSITION_ERROR + assert not self.shutdown_event.is_set(), STATE_TRANSITION_ERROR + self.shutdown_event.set() + + elif message["type"] == "lifespan.shutdown.failed": + assert self.startup_event.is_set(), STATE_TRANSITION_ERROR + assert not self.shutdown_event.is_set(), STATE_TRANSITION_ERROR + self.shutdown_event.set() + self.shutdown_failed = True + if message.get("message"): + self.logger.error(message["message"]) + + async def receive(self) -> LifespanReceiveMessage: + return await self.receive_queue.get() diff --git a/venv/Lib/site-packages/uvicorn/logging.py b/venv/Lib/site-packages/uvicorn/logging.py new file mode 100644 index 00000000..02f455d8 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/logging.py @@ -0,0 +1,117 @@ +from __future__ import annotations + +import http +import logging +import sys +from copy import copy +from typing import Literal + +import click + +TRACE_LOG_LEVEL = 5 + + +class ColourizedFormatter(logging.Formatter): + """ + A custom log formatter class that: + + * Outputs the LOG_LEVEL with an appropriate color. + * If a log call includes an `extra={"color_message": ...}` it will be used + for formatting the output, instead of the plain text message. + """ + + level_name_colors = { + TRACE_LOG_LEVEL: lambda level_name: click.style(str(level_name), fg="blue"), + logging.DEBUG: lambda level_name: click.style(str(level_name), fg="cyan"), + logging.INFO: lambda level_name: click.style(str(level_name), fg="green"), + logging.WARNING: lambda level_name: click.style(str(level_name), fg="yellow"), + logging.ERROR: lambda level_name: click.style(str(level_name), fg="red"), + logging.CRITICAL: lambda level_name: click.style(str(level_name), fg="bright_red"), + } + + def __init__( + self, + fmt: str | None = None, + datefmt: str | None = None, + style: Literal["%", "{", "$"] = "%", + use_colors: bool | None = None, + ): + if use_colors in (True, False): + self.use_colors = use_colors + else: + self.use_colors = sys.stdout.isatty() + super().__init__(fmt=fmt, datefmt=datefmt, style=style) + + def color_level_name(self, level_name: str, level_no: int) -> str: + def default(level_name: str) -> str: + return str(level_name) # pragma: no cover + + func = self.level_name_colors.get(level_no, default) + return func(level_name) + + def should_use_colors(self) -> bool: + return True # pragma: no cover + + def formatMessage(self, record: logging.LogRecord) -> str: + recordcopy = copy(record) + levelname = recordcopy.levelname + seperator = " " * (8 - len(recordcopy.levelname)) + if self.use_colors: + levelname = self.color_level_name(levelname, recordcopy.levelno) + if "color_message" in recordcopy.__dict__: + recordcopy.msg = recordcopy.__dict__["color_message"] + recordcopy.__dict__["message"] = recordcopy.getMessage() + recordcopy.__dict__["levelprefix"] = levelname + ":" + seperator + return super().formatMessage(recordcopy) + + +class DefaultFormatter(ColourizedFormatter): + def should_use_colors(self) -> bool: + return sys.stderr.isatty() # pragma: no cover + + +class AccessFormatter(ColourizedFormatter): + status_code_colours = { + 1: lambda code: click.style(str(code), fg="bright_white"), + 2: lambda code: click.style(str(code), fg="green"), + 3: lambda code: click.style(str(code), fg="yellow"), + 4: lambda code: click.style(str(code), fg="red"), + 5: lambda code: click.style(str(code), fg="bright_red"), + } + + def get_status_code(self, status_code: int) -> str: + try: + status_phrase = http.HTTPStatus(status_code).phrase + except ValueError: + status_phrase = "" + status_and_phrase = f"{status_code} {status_phrase}" + if self.use_colors: + + def default(code: int) -> str: + return status_and_phrase # pragma: no cover + + func = self.status_code_colours.get(status_code // 100, default) + return func(status_and_phrase) + return status_and_phrase + + def formatMessage(self, record: logging.LogRecord) -> str: + recordcopy = copy(record) + ( + client_addr, + method, + full_path, + http_version, + status_code, + ) = recordcopy.args # type: ignore[misc] + status_code = self.get_status_code(int(status_code)) # type: ignore[arg-type] + request_line = f"{method} {full_path} HTTP/{http_version}" + if self.use_colors: + request_line = click.style(request_line, bold=True) + recordcopy.__dict__.update( + { + "client_addr": client_addr, + "request_line": request_line, + "status_code": status_code, + } + ) + return super().formatMessage(recordcopy) diff --git a/venv/Lib/site-packages/uvicorn/loops/__init__.py b/venv/Lib/site-packages/uvicorn/loops/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/venv/Lib/site-packages/uvicorn/loops/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/loops/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..f7b680c6 Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/loops/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/loops/__pycache__/asyncio.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/loops/__pycache__/asyncio.cpython-312.pyc new file mode 100644 index 00000000..d0bd2bf1 Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/loops/__pycache__/asyncio.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/loops/__pycache__/auto.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/loops/__pycache__/auto.cpython-312.pyc new file mode 100644 index 00000000..1d7d0211 Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/loops/__pycache__/auto.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/loops/__pycache__/uvloop.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/loops/__pycache__/uvloop.cpython-312.pyc new file mode 100644 index 00000000..1139161f Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/loops/__pycache__/uvloop.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/loops/asyncio.py b/venv/Lib/site-packages/uvicorn/loops/asyncio.py new file mode 100644 index 00000000..1bead4a0 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/loops/asyncio.py @@ -0,0 +1,10 @@ +import asyncio +import logging +import sys + +logger = logging.getLogger("uvicorn.error") + + +def asyncio_setup(use_subprocess: bool = False) -> None: + if sys.platform == "win32" and use_subprocess: + asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) # pragma: full coverage diff --git a/venv/Lib/site-packages/uvicorn/loops/auto.py b/venv/Lib/site-packages/uvicorn/loops/auto.py new file mode 100644 index 00000000..2285457b --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/loops/auto.py @@ -0,0 +1,11 @@ +def auto_loop_setup(use_subprocess: bool = False) -> None: + try: + import uvloop # noqa + except ImportError: # pragma: no cover + from uvicorn.loops.asyncio import asyncio_setup as loop_setup + + loop_setup(use_subprocess=use_subprocess) + else: # pragma: no cover + from uvicorn.loops.uvloop import uvloop_setup + + uvloop_setup(use_subprocess=use_subprocess) diff --git a/venv/Lib/site-packages/uvicorn/loops/uvloop.py b/venv/Lib/site-packages/uvicorn/loops/uvloop.py new file mode 100644 index 00000000..0e2fd1eb --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/loops/uvloop.py @@ -0,0 +1,7 @@ +import asyncio + +import uvloop + + +def uvloop_setup(use_subprocess: bool = False) -> None: + asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) diff --git a/venv/Lib/site-packages/uvicorn/main.py b/venv/Lib/site-packages/uvicorn/main.py new file mode 100644 index 00000000..e3d297ee --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/main.py @@ -0,0 +1,604 @@ +from __future__ import annotations + +import asyncio +import logging +import os +import platform +import ssl +import sys +import warnings +from configparser import RawConfigParser +from typing import IO, Any, Callable + +import click + +import uvicorn +from uvicorn._types import ASGIApplication +from uvicorn.config import ( + HTTP_PROTOCOLS, + INTERFACES, + LIFESPAN, + LOG_LEVELS, + LOGGING_CONFIG, + LOOP_SETUPS, + SSL_PROTOCOL_VERSION, + WS_PROTOCOLS, + Config, + HTTPProtocolType, + InterfaceType, + LifespanType, + LoopSetupType, + WSProtocolType, +) +from uvicorn.server import Server +from uvicorn.supervisors import ChangeReload, Multiprocess + +LEVEL_CHOICES = click.Choice(list(LOG_LEVELS.keys())) +HTTP_CHOICES = click.Choice(list(HTTP_PROTOCOLS.keys())) +WS_CHOICES = click.Choice(list(WS_PROTOCOLS.keys())) +LIFESPAN_CHOICES = click.Choice(list(LIFESPAN.keys())) +LOOP_CHOICES = click.Choice([key for key in LOOP_SETUPS.keys() if key != "none"]) +INTERFACE_CHOICES = click.Choice(INTERFACES) + +STARTUP_FAILURE = 3 + +logger = logging.getLogger("uvicorn.error") + + +def print_version(ctx: click.Context, param: click.Parameter, value: bool) -> None: + if not value or ctx.resilient_parsing: + return + click.echo( + "Running uvicorn {version} with {py_implementation} {py_version} on {system}".format( # noqa: UP032 + version=uvicorn.__version__, + py_implementation=platform.python_implementation(), + py_version=platform.python_version(), + system=platform.system(), + ) + ) + ctx.exit() + + +@click.command(context_settings={"auto_envvar_prefix": "UVICORN"}) +@click.argument("app", envvar="UVICORN_APP") +@click.option( + "--host", + type=str, + default="127.0.0.1", + help="Bind socket to this host.", + show_default=True, +) +@click.option( + "--port", + type=int, + default=8000, + help="Bind socket to this port. If 0, an available port will be picked.", + show_default=True, +) +@click.option("--uds", type=str, default=None, help="Bind to a UNIX domain socket.") +@click.option("--fd", type=int, default=None, help="Bind to socket from this file descriptor.") +@click.option("--reload", is_flag=True, default=False, help="Enable auto-reload.") +@click.option( + "--reload-dir", + "reload_dirs", + multiple=True, + help="Set reload directories explicitly, instead of using the current working directory.", + type=click.Path(exists=True), +) +@click.option( + "--reload-include", + "reload_includes", + multiple=True, + help="Set glob patterns to include while watching for files. Includes '*.py' " + "by default; these defaults can be overridden with `--reload-exclude`. " + "This option has no effect unless watchfiles is installed.", +) +@click.option( + "--reload-exclude", + "reload_excludes", + multiple=True, + help="Set glob patterns to exclude while watching for files. Includes " + "'.*, .py[cod], .sw.*, ~*' by default; these defaults can be overridden " + "with `--reload-include`. This option has no effect unless watchfiles is " + "installed.", +) +@click.option( + "--reload-delay", + type=float, + default=0.25, + show_default=True, + help="Delay between previous and next check if application needs to be. Defaults to 0.25s.", +) +@click.option( + "--workers", + default=None, + type=int, + help="Number of worker processes. Defaults to the $WEB_CONCURRENCY environment" + " variable if available, or 1. Not valid with --reload.", +) +@click.option( + "--loop", + type=LOOP_CHOICES, + default="auto", + help="Event loop implementation.", + show_default=True, +) +@click.option( + "--http", + type=HTTP_CHOICES, + default="auto", + help="HTTP protocol implementation.", + show_default=True, +) +@click.option( + "--ws", + type=WS_CHOICES, + default="auto", + help="WebSocket protocol implementation.", + show_default=True, +) +@click.option( + "--ws-max-size", + type=int, + default=16777216, + help="WebSocket max size message in bytes", + show_default=True, +) +@click.option( + "--ws-max-queue", + type=int, + default=32, + help="The maximum length of the WebSocket message queue.", + show_default=True, +) +@click.option( + "--ws-ping-interval", + type=float, + default=20.0, + help="WebSocket ping interval in seconds.", + show_default=True, +) +@click.option( + "--ws-ping-timeout", + type=float, + default=20.0, + help="WebSocket ping timeout in seconds.", + show_default=True, +) +@click.option( + "--ws-per-message-deflate", + type=bool, + default=True, + help="WebSocket per-message-deflate compression", + show_default=True, +) +@click.option( + "--lifespan", + type=LIFESPAN_CHOICES, + default="auto", + help="Lifespan implementation.", + show_default=True, +) +@click.option( + "--interface", + type=INTERFACE_CHOICES, + default="auto", + help="Select ASGI3, ASGI2, or WSGI as the application interface.", + show_default=True, +) +@click.option( + "--env-file", + type=click.Path(exists=True), + default=None, + help="Environment configuration file.", + show_default=True, +) +@click.option( + "--log-config", + type=click.Path(exists=True), + default=None, + help="Logging configuration file. Supported formats: .ini, .json, .yaml.", + show_default=True, +) +@click.option( + "--log-level", + type=LEVEL_CHOICES, + default=None, + help="Log level. [default: info]", + show_default=True, +) +@click.option( + "--access-log/--no-access-log", + is_flag=True, + default=True, + help="Enable/Disable access log.", +) +@click.option( + "--use-colors/--no-use-colors", + is_flag=True, + default=None, + help="Enable/Disable colorized logging.", +) +@click.option( + "--proxy-headers/--no-proxy-headers", + is_flag=True, + default=True, + help="Enable/Disable X-Forwarded-Proto, X-Forwarded-For to populate url scheme and remote address info.", +) +@click.option( + "--server-header/--no-server-header", + is_flag=True, + default=True, + help="Enable/Disable default Server header.", +) +@click.option( + "--date-header/--no-date-header", + is_flag=True, + default=True, + help="Enable/Disable default Date header.", +) +@click.option( + "--forwarded-allow-ips", + type=str, + default=None, + help="Comma separated list of IP Addresses, IP Networks, or literals " + "(e.g. UNIX Socket path) to trust with proxy headers. Defaults to the " + "$FORWARDED_ALLOW_IPS environment variable if available, or '127.0.0.1'. " + "The literal '*' means trust everything.", +) +@click.option( + "--root-path", + type=str, + default="", + help="Set the ASGI 'root_path' for applications submounted below a given URL path.", +) +@click.option( + "--limit-concurrency", + type=int, + default=None, + help="Maximum number of concurrent connections or tasks to allow, before issuing HTTP 503 responses.", +) +@click.option( + "--backlog", + type=int, + default=2048, + help="Maximum number of connections to hold in backlog", +) +@click.option( + "--limit-max-requests", + type=int, + default=None, + help="Maximum number of requests to service before terminating the process.", +) +@click.option( + "--timeout-keep-alive", + type=int, + default=5, + help="Close Keep-Alive connections if no new data is received within this timeout.", + show_default=True, +) +@click.option( + "--timeout-graceful-shutdown", + type=int, + default=None, + help="Maximum number of seconds to wait for graceful shutdown.", +) +@click.option("--ssl-keyfile", type=str, default=None, help="SSL key file", show_default=True) +@click.option( + "--ssl-certfile", + type=str, + default=None, + help="SSL certificate file", + show_default=True, +) +@click.option( + "--ssl-keyfile-password", + type=str, + default=None, + help="SSL keyfile password", + show_default=True, +) +@click.option( + "--ssl-version", + type=int, + default=int(SSL_PROTOCOL_VERSION), + help="SSL version to use (see stdlib ssl module's)", + show_default=True, +) +@click.option( + "--ssl-cert-reqs", + type=int, + default=int(ssl.CERT_NONE), + help="Whether client certificate is required (see stdlib ssl module's)", + show_default=True, +) +@click.option( + "--ssl-ca-certs", + type=str, + default=None, + help="CA certificates file", + show_default=True, +) +@click.option( + "--ssl-ciphers", + type=str, + default="TLSv1", + help="Ciphers to use (see stdlib ssl module's)", + show_default=True, +) +@click.option( + "--header", + "headers", + multiple=True, + help="Specify custom default HTTP response headers as a Name:Value pair", +) +@click.option( + "--version", + is_flag=True, + callback=print_version, + expose_value=False, + is_eager=True, + help="Display the uvicorn version and exit.", +) +@click.option( + "--app-dir", + default="", + show_default=True, + help="Look for APP in the specified directory, by adding this to the PYTHONPATH." + " Defaults to the current working directory.", +) +@click.option( + "--h11-max-incomplete-event-size", + "h11_max_incomplete_event_size", + type=int, + default=None, + help="For h11, the maximum number of bytes to buffer of an incomplete event.", +) +@click.option( + "--factory", + is_flag=True, + default=False, + help="Treat APP as an application factory, i.e. a () -> callable.", + show_default=True, +) +def main( + app: str, + host: str, + port: int, + uds: str, + fd: int, + loop: LoopSetupType, + http: HTTPProtocolType, + ws: WSProtocolType, + ws_max_size: int, + ws_max_queue: int, + ws_ping_interval: float, + ws_ping_timeout: float, + ws_per_message_deflate: bool, + lifespan: LifespanType, + interface: InterfaceType, + reload: bool, + reload_dirs: list[str], + reload_includes: list[str], + reload_excludes: list[str], + reload_delay: float, + workers: int, + env_file: str, + log_config: str, + log_level: str, + access_log: bool, + proxy_headers: bool, + server_header: bool, + date_header: bool, + forwarded_allow_ips: str, + root_path: str, + limit_concurrency: int, + backlog: int, + limit_max_requests: int, + timeout_keep_alive: int, + timeout_graceful_shutdown: int | None, + ssl_keyfile: str, + ssl_certfile: str, + ssl_keyfile_password: str, + ssl_version: int, + ssl_cert_reqs: int, + ssl_ca_certs: str, + ssl_ciphers: str, + headers: list[str], + use_colors: bool, + app_dir: str, + h11_max_incomplete_event_size: int | None, + factory: bool, +) -> None: + run( + app, + host=host, + port=port, + uds=uds, + fd=fd, + loop=loop, + http=http, + ws=ws, + ws_max_size=ws_max_size, + ws_max_queue=ws_max_queue, + ws_ping_interval=ws_ping_interval, + ws_ping_timeout=ws_ping_timeout, + ws_per_message_deflate=ws_per_message_deflate, + lifespan=lifespan, + env_file=env_file, + log_config=LOGGING_CONFIG if log_config is None else log_config, + log_level=log_level, + access_log=access_log, + interface=interface, + reload=reload, + reload_dirs=reload_dirs or None, + reload_includes=reload_includes or None, + reload_excludes=reload_excludes or None, + reload_delay=reload_delay, + workers=workers, + proxy_headers=proxy_headers, + server_header=server_header, + date_header=date_header, + forwarded_allow_ips=forwarded_allow_ips, + root_path=root_path, + limit_concurrency=limit_concurrency, + backlog=backlog, + limit_max_requests=limit_max_requests, + timeout_keep_alive=timeout_keep_alive, + timeout_graceful_shutdown=timeout_graceful_shutdown, + ssl_keyfile=ssl_keyfile, + ssl_certfile=ssl_certfile, + ssl_keyfile_password=ssl_keyfile_password, + ssl_version=ssl_version, + ssl_cert_reqs=ssl_cert_reqs, + ssl_ca_certs=ssl_ca_certs, + ssl_ciphers=ssl_ciphers, + headers=[header.split(":", 1) for header in headers], # type: ignore[misc] + use_colors=use_colors, + factory=factory, + app_dir=app_dir, + h11_max_incomplete_event_size=h11_max_incomplete_event_size, + ) + + +def run( + app: ASGIApplication | Callable[..., Any] | str, + *, + host: str = "127.0.0.1", + port: int = 8000, + uds: str | None = None, + fd: int | None = None, + loop: LoopSetupType = "auto", + http: type[asyncio.Protocol] | HTTPProtocolType = "auto", + ws: type[asyncio.Protocol] | WSProtocolType = "auto", + ws_max_size: int = 16777216, + ws_max_queue: int = 32, + ws_ping_interval: float | None = 20.0, + ws_ping_timeout: float | None = 20.0, + ws_per_message_deflate: bool = True, + lifespan: LifespanType = "auto", + interface: InterfaceType = "auto", + reload: bool = False, + reload_dirs: list[str] | str | None = None, + reload_includes: list[str] | str | None = None, + reload_excludes: list[str] | str | None = None, + reload_delay: float = 0.25, + workers: int | None = None, + env_file: str | os.PathLike[str] | None = None, + log_config: dict[str, Any] | str | RawConfigParser | IO[Any] | None = LOGGING_CONFIG, + log_level: str | int | None = None, + access_log: bool = True, + proxy_headers: bool = True, + server_header: bool = True, + date_header: bool = True, + forwarded_allow_ips: list[str] | str | None = None, + root_path: str = "", + limit_concurrency: int | None = None, + backlog: int = 2048, + limit_max_requests: int | None = None, + timeout_keep_alive: int = 5, + timeout_graceful_shutdown: int | None = None, + ssl_keyfile: str | os.PathLike[str] | None = None, + ssl_certfile: str | os.PathLike[str] | None = None, + ssl_keyfile_password: str | None = None, + ssl_version: int = SSL_PROTOCOL_VERSION, + ssl_cert_reqs: int = ssl.CERT_NONE, + ssl_ca_certs: str | None = None, + ssl_ciphers: str = "TLSv1", + headers: list[tuple[str, str]] | None = None, + use_colors: bool | None = None, + app_dir: str | None = None, + factory: bool = False, + h11_max_incomplete_event_size: int | None = None, +) -> None: + if app_dir is not None: + sys.path.insert(0, app_dir) + + config = Config( + app, + host=host, + port=port, + uds=uds, + fd=fd, + loop=loop, + http=http, + ws=ws, + ws_max_size=ws_max_size, + ws_max_queue=ws_max_queue, + ws_ping_interval=ws_ping_interval, + ws_ping_timeout=ws_ping_timeout, + ws_per_message_deflate=ws_per_message_deflate, + lifespan=lifespan, + interface=interface, + reload=reload, + reload_dirs=reload_dirs, + reload_includes=reload_includes, + reload_excludes=reload_excludes, + reload_delay=reload_delay, + workers=workers, + env_file=env_file, + log_config=log_config, + log_level=log_level, + access_log=access_log, + proxy_headers=proxy_headers, + server_header=server_header, + date_header=date_header, + forwarded_allow_ips=forwarded_allow_ips, + root_path=root_path, + limit_concurrency=limit_concurrency, + backlog=backlog, + limit_max_requests=limit_max_requests, + timeout_keep_alive=timeout_keep_alive, + timeout_graceful_shutdown=timeout_graceful_shutdown, + ssl_keyfile=ssl_keyfile, + ssl_certfile=ssl_certfile, + ssl_keyfile_password=ssl_keyfile_password, + ssl_version=ssl_version, + ssl_cert_reqs=ssl_cert_reqs, + ssl_ca_certs=ssl_ca_certs, + ssl_ciphers=ssl_ciphers, + headers=headers, + use_colors=use_colors, + factory=factory, + h11_max_incomplete_event_size=h11_max_incomplete_event_size, + ) + server = Server(config=config) + + if (config.reload or config.workers > 1) and not isinstance(app, str): + logger = logging.getLogger("uvicorn.error") + logger.warning("You must pass the application as an import string to enable 'reload' or 'workers'.") + sys.exit(1) + + try: + if config.should_reload: + sock = config.bind_socket() + ChangeReload(config, target=server.run, sockets=[sock]).run() + elif config.workers > 1: + sock = config.bind_socket() + Multiprocess(config, target=server.run, sockets=[sock]).run() + else: + server.run() + except KeyboardInterrupt: + pass # pragma: full coverage + finally: + if config.uds and os.path.exists(config.uds): + os.remove(config.uds) # pragma: py-win32 + + if not server.started and not config.should_reload and config.workers == 1: + sys.exit(STARTUP_FAILURE) + + +def __getattr__(name: str) -> Any: + if name == "ServerState": + warnings.warn( + "uvicorn.main.ServerState is deprecated, use uvicorn.server.ServerState instead.", + DeprecationWarning, + ) + from uvicorn.server import ServerState + + return ServerState + raise AttributeError(f"module {__name__} has no attribute {name}") + + +if __name__ == "__main__": + main() # pragma: no cover diff --git a/venv/Lib/site-packages/uvicorn/middleware/__init__.py b/venv/Lib/site-packages/uvicorn/middleware/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/venv/Lib/site-packages/uvicorn/middleware/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/middleware/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..a24ac94b Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/middleware/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/middleware/__pycache__/asgi2.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/middleware/__pycache__/asgi2.cpython-312.pyc new file mode 100644 index 00000000..0855824e Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/middleware/__pycache__/asgi2.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/middleware/__pycache__/message_logger.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/middleware/__pycache__/message_logger.cpython-312.pyc new file mode 100644 index 00000000..02b507c0 Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/middleware/__pycache__/message_logger.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/middleware/__pycache__/proxy_headers.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/middleware/__pycache__/proxy_headers.cpython-312.pyc new file mode 100644 index 00000000..562343be Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/middleware/__pycache__/proxy_headers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/middleware/__pycache__/wsgi.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/middleware/__pycache__/wsgi.cpython-312.pyc new file mode 100644 index 00000000..e60fa129 Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/middleware/__pycache__/wsgi.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/middleware/asgi2.py b/venv/Lib/site-packages/uvicorn/middleware/asgi2.py new file mode 100644 index 00000000..4e15d159 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/middleware/asgi2.py @@ -0,0 +1,15 @@ +from uvicorn._types import ( + ASGI2Application, + ASGIReceiveCallable, + ASGISendCallable, + Scope, +) + + +class ASGI2Middleware: + def __init__(self, app: "ASGI2Application"): + self.app = app + + async def __call__(self, scope: "Scope", receive: "ASGIReceiveCallable", send: "ASGISendCallable") -> None: + instance = self.app(scope) + await instance(receive, send) diff --git a/venv/Lib/site-packages/uvicorn/middleware/message_logger.py b/venv/Lib/site-packages/uvicorn/middleware/message_logger.py new file mode 100644 index 00000000..0174bcce --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/middleware/message_logger.py @@ -0,0 +1,87 @@ +import logging +from typing import Any + +from uvicorn._types import ( + ASGI3Application, + ASGIReceiveCallable, + ASGIReceiveEvent, + ASGISendCallable, + ASGISendEvent, + WWWScope, +) +from uvicorn.logging import TRACE_LOG_LEVEL + +PLACEHOLDER_FORMAT = { + "body": "<{length} bytes>", + "bytes": "<{length} bytes>", + "text": "<{length} chars>", + "headers": "<...>", +} + + +def message_with_placeholders(message: Any) -> Any: + """ + Return an ASGI message, with any body-type content omitted and replaced + with a placeholder. + """ + new_message = message.copy() + for attr in PLACEHOLDER_FORMAT.keys(): + if message.get(attr) is not None: + content = message[attr] + placeholder = PLACEHOLDER_FORMAT[attr].format(length=len(content)) + new_message[attr] = placeholder + return new_message + + +class MessageLoggerMiddleware: + def __init__(self, app: "ASGI3Application"): + self.task_counter = 0 + self.app = app + self.logger = logging.getLogger("uvicorn.asgi") + + def trace(message: Any, *args: Any, **kwargs: Any) -> None: + self.logger.log(TRACE_LOG_LEVEL, message, *args, **kwargs) + + self.logger.trace = trace # type: ignore + + async def __call__( + self, + scope: "WWWScope", + receive: "ASGIReceiveCallable", + send: "ASGISendCallable", + ) -> None: + self.task_counter += 1 + + task_counter = self.task_counter + client = scope.get("client") + prefix = "%s:%d - ASGI" % (client[0], client[1]) if client else "ASGI" + + async def inner_receive() -> "ASGIReceiveEvent": + message = await receive() + logged_message = message_with_placeholders(message) + log_text = "%s [%d] Receive %s" + self.logger.trace( # type: ignore + log_text, prefix, task_counter, logged_message + ) + return message + + async def inner_send(message: "ASGISendEvent") -> None: + logged_message = message_with_placeholders(message) + log_text = "%s [%d] Send %s" + self.logger.trace( # type: ignore + log_text, prefix, task_counter, logged_message + ) + await send(message) + + logged_scope = message_with_placeholders(scope) + log_text = "%s [%d] Started scope=%s" + self.logger.trace(log_text, prefix, task_counter, logged_scope) # type: ignore + try: + await self.app(scope, inner_receive, inner_send) + except BaseException as exc: + log_text = "%s [%d] Raised exception" + self.logger.trace(log_text, prefix, task_counter) # type: ignore + raise exc from None + else: + log_text = "%s [%d] Completed" + self.logger.trace(log_text, prefix, task_counter) # type: ignore diff --git a/venv/Lib/site-packages/uvicorn/middleware/proxy_headers.py b/venv/Lib/site-packages/uvicorn/middleware/proxy_headers.py new file mode 100644 index 00000000..7c3609de --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/middleware/proxy_headers.py @@ -0,0 +1,142 @@ +from __future__ import annotations + +import ipaddress + +from uvicorn._types import ASGI3Application, ASGIReceiveCallable, ASGISendCallable, Scope + + +class ProxyHeadersMiddleware: + """Middleware for handling known proxy headers + + This middleware can be used when a known proxy is fronting the application, + and is trusted to be properly setting the `X-Forwarded-Proto` and + `X-Forwarded-For` headers with the connecting client information. + + Modifies the `client` and `scheme` information so that they reference + the connecting client, rather that the connecting proxy. + + References: + - + - + """ + + def __init__(self, app: ASGI3Application, trusted_hosts: list[str] | str = "127.0.0.1") -> None: + self.app = app + self.trusted_hosts = _TrustedHosts(trusted_hosts) + + async def __call__(self, scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None: + if scope["type"] == "lifespan": + return await self.app(scope, receive, send) + + client_addr = scope.get("client") + client_host = client_addr[0] if client_addr else None + + if client_host in self.trusted_hosts: + headers = dict(scope["headers"]) + + if b"x-forwarded-proto" in headers: + x_forwarded_proto = headers[b"x-forwarded-proto"].decode("latin1").strip() + + if x_forwarded_proto in {"http", "https", "ws", "wss"}: + if scope["type"] == "websocket": + scope["scheme"] = x_forwarded_proto.replace("http", "ws") + else: + scope["scheme"] = x_forwarded_proto + + if b"x-forwarded-for" in headers: + x_forwarded_for = headers[b"x-forwarded-for"].decode("latin1") + host = self.trusted_hosts.get_trusted_client_host(x_forwarded_for) + + if host: + # If the x-forwarded-for header is empty then host is an empty string. + # Only set the client if we actually got something usable. + # See: https://github.com/encode/uvicorn/issues/1068 + + # We've lost the connecting client's port information by now, + # so only include the host. + port = 0 + scope["client"] = (host, port) + + return await self.app(scope, receive, send) + + +def _parse_raw_hosts(value: str) -> list[str]: + return [item.strip() for item in value.split(",")] + + +class _TrustedHosts: + """Container for trusted hosts and networks""" + + def __init__(self, trusted_hosts: list[str] | str) -> None: + self.always_trust: bool = trusted_hosts in ("*", ["*"]) + + self.trusted_literals: set[str] = set() + self.trusted_hosts: set[ipaddress.IPv4Address | ipaddress.IPv6Address] = set() + self.trusted_networks: set[ipaddress.IPv4Network | ipaddress.IPv6Network] = set() + + # Notes: + # - We separate hosts from literals as there are many ways to write + # an IPv6 Address so we need to compare by object. + # - We don't convert IP Address to single host networks (e.g. /32 / 128) as + # it more efficient to do an address lookup in a set than check for + # membership in each network. + # - We still allow literals as it might be possible that we receive a + # something that isn't an IP Address e.g. a unix socket. + + if not self.always_trust: + if isinstance(trusted_hosts, str): + trusted_hosts = _parse_raw_hosts(trusted_hosts) + + for host in trusted_hosts: + # Note: because we always convert invalid IP types to literals it + # is not possible for the user to know they provided a malformed IP + # type - this may lead to unexpected / difficult to debug behaviour. + + if "/" in host: + # Looks like a network + try: + self.trusted_networks.add(ipaddress.ip_network(host)) + except ValueError: + # Was not a valid IP Network + self.trusted_literals.add(host) + else: + try: + self.trusted_hosts.add(ipaddress.ip_address(host)) + except ValueError: + # Was not a valid IP Address + self.trusted_literals.add(host) + + def __contains__(self, host: str | None) -> bool: + if self.always_trust: + return True + + if not host: + return False + + try: + ip = ipaddress.ip_address(host) + if ip in self.trusted_hosts: + return True + return any(ip in net for net in self.trusted_networks) + + except ValueError: + return host in self.trusted_literals + + def get_trusted_client_host(self, x_forwarded_for: str) -> str: + """Extract the client host from x_forwarded_for header + + In general this is the first "untrusted" host in the forwarded for list. + """ + x_forwarded_for_hosts = _parse_raw_hosts(x_forwarded_for) + + if self.always_trust: + return x_forwarded_for_hosts[0] + + # Note: each proxy appends to the header list so check it in reverse order + for host in reversed(x_forwarded_for_hosts): + if host not in self: + return host + + # All hosts are trusted meaning that the client was also a trusted proxy + # See https://github.com/encode/uvicorn/issues/1068#issuecomment-855371576 + return x_forwarded_for_hosts[0] diff --git a/venv/Lib/site-packages/uvicorn/middleware/wsgi.py b/venv/Lib/site-packages/uvicorn/middleware/wsgi.py new file mode 100644 index 00000000..d53a8b06 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/middleware/wsgi.py @@ -0,0 +1,199 @@ +from __future__ import annotations + +import asyncio +import concurrent.futures +import io +import sys +import warnings +from collections import deque +from collections.abc import Iterable + +from uvicorn._types import ( + ASGIReceiveCallable, + ASGIReceiveEvent, + ASGISendCallable, + ASGISendEvent, + Environ, + ExcInfo, + HTTPRequestEvent, + HTTPResponseBodyEvent, + HTTPResponseStartEvent, + HTTPScope, + StartResponse, + WSGIApp, +) + + +def build_environ(scope: HTTPScope, message: ASGIReceiveEvent, body: io.BytesIO) -> Environ: + """ + Builds a scope and request message into a WSGI environ object. + """ + script_name = scope.get("root_path", "").encode("utf8").decode("latin1") + path_info = scope["path"].encode("utf8").decode("latin1") + if path_info.startswith(script_name): + path_info = path_info[len(script_name) :] + environ = { + "REQUEST_METHOD": scope["method"], + "SCRIPT_NAME": script_name, + "PATH_INFO": path_info, + "QUERY_STRING": scope["query_string"].decode("ascii"), + "SERVER_PROTOCOL": "HTTP/%s" % scope["http_version"], + "wsgi.version": (1, 0), + "wsgi.url_scheme": scope.get("scheme", "http"), + "wsgi.input": body, + "wsgi.errors": sys.stdout, + "wsgi.multithread": True, + "wsgi.multiprocess": True, + "wsgi.run_once": False, + } + + # Get server name and port - required in WSGI, not in ASGI + server = scope.get("server") + if server is None: + server = ("localhost", 80) + environ["SERVER_NAME"] = server[0] + environ["SERVER_PORT"] = server[1] + + # Get client IP address + client = scope.get("client") + if client is not None: + environ["REMOTE_ADDR"] = client[0] + + # Go through headers and make them into environ entries + for name, value in scope.get("headers", []): + name_str: str = name.decode("latin1") + if name_str == "content-length": + corrected_name = "CONTENT_LENGTH" + elif name_str == "content-type": + corrected_name = "CONTENT_TYPE" + else: + corrected_name = "HTTP_%s" % name_str.upper().replace("-", "_") + # HTTPbis say only ASCII chars are allowed in headers, but we latin1 + # just in case + value_str: str = value.decode("latin1") + if corrected_name in environ: + corrected_name_environ = environ[corrected_name] + assert isinstance(corrected_name_environ, str) + value_str = corrected_name_environ + "," + value_str + environ[corrected_name] = value_str + return environ + + +class _WSGIMiddleware: + def __init__(self, app: WSGIApp, workers: int = 10): + warnings.warn( + "Uvicorn's native WSGI implementation is deprecated, you should switch to a2wsgi (`pip install a2wsgi`).", + DeprecationWarning, + ) + self.app = app + self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=workers) + + async def __call__( + self, + scope: HTTPScope, + receive: ASGIReceiveCallable, + send: ASGISendCallable, + ) -> None: + assert scope["type"] == "http" + instance = WSGIResponder(self.app, self.executor, scope) + await instance(receive, send) + + +class WSGIResponder: + def __init__( + self, + app: WSGIApp, + executor: concurrent.futures.ThreadPoolExecutor, + scope: HTTPScope, + ): + self.app = app + self.executor = executor + self.scope = scope + self.status = None + self.response_headers = None + self.send_event = asyncio.Event() + self.send_queue: deque[ASGISendEvent | None] = deque() + self.loop: asyncio.AbstractEventLoop = asyncio.get_event_loop() + self.response_started = False + self.exc_info: ExcInfo | None = None + + async def __call__(self, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None: + message: HTTPRequestEvent = await receive() # type: ignore[assignment] + body = io.BytesIO(message.get("body", b"")) + more_body = message.get("more_body", False) + if more_body: + body.seek(0, io.SEEK_END) + while more_body: + body_message: HTTPRequestEvent = ( + await receive() # type: ignore[assignment] + ) + body.write(body_message.get("body", b"")) + more_body = body_message.get("more_body", False) + body.seek(0) + environ = build_environ(self.scope, message, body) + self.loop = asyncio.get_event_loop() + wsgi = self.loop.run_in_executor(self.executor, self.wsgi, environ, self.start_response) + sender = self.loop.create_task(self.sender(send)) + try: + await asyncio.wait_for(wsgi, None) + finally: + self.send_queue.append(None) + self.send_event.set() + await asyncio.wait_for(sender, None) + if self.exc_info is not None: + raise self.exc_info[0].with_traceback(self.exc_info[1], self.exc_info[2]) + + async def sender(self, send: ASGISendCallable) -> None: + while True: + if self.send_queue: + message = self.send_queue.popleft() + if message is None: + return + await send(message) + else: + await self.send_event.wait() + self.send_event.clear() + + def start_response( + self, + status: str, + response_headers: Iterable[tuple[str, str]], + exc_info: ExcInfo | None = None, + ) -> None: + self.exc_info = exc_info + if not self.response_started: + self.response_started = True + status_code_str, _ = status.split(" ", 1) + status_code = int(status_code_str) + headers = [(name.encode("ascii"), value.encode("ascii")) for name, value in response_headers] + http_response_start_event: HTTPResponseStartEvent = { + "type": "http.response.start", + "status": status_code, + "headers": headers, + } + self.send_queue.append(http_response_start_event) + self.loop.call_soon_threadsafe(self.send_event.set) + + def wsgi(self, environ: Environ, start_response: StartResponse) -> None: + for chunk in self.app(environ, start_response): # type: ignore + response_body: HTTPResponseBodyEvent = { + "type": "http.response.body", + "body": chunk, + "more_body": True, + } + self.send_queue.append(response_body) + self.loop.call_soon_threadsafe(self.send_event.set) + + empty_body: HTTPResponseBodyEvent = { + "type": "http.response.body", + "body": b"", + "more_body": False, + } + self.send_queue.append(empty_body) + self.loop.call_soon_threadsafe(self.send_event.set) + + +try: + from a2wsgi import WSGIMiddleware +except ModuleNotFoundError: # pragma: no cover + WSGIMiddleware = _WSGIMiddleware # type: ignore[misc, assignment] diff --git a/venv/Lib/site-packages/uvicorn/protocols/__init__.py b/venv/Lib/site-packages/uvicorn/protocols/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/venv/Lib/site-packages/uvicorn/protocols/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/protocols/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..c53c0297 Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/protocols/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/protocols/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/protocols/__pycache__/utils.cpython-312.pyc new file mode 100644 index 00000000..8c3f1939 Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/protocols/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/protocols/http/__init__.py b/venv/Lib/site-packages/uvicorn/protocols/http/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/venv/Lib/site-packages/uvicorn/protocols/http/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/protocols/http/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..6dfcf1f5 Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/protocols/http/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/protocols/http/__pycache__/auto.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/protocols/http/__pycache__/auto.cpython-312.pyc new file mode 100644 index 00000000..3c67d742 Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/protocols/http/__pycache__/auto.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/protocols/http/__pycache__/flow_control.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/protocols/http/__pycache__/flow_control.cpython-312.pyc new file mode 100644 index 00000000..369be53a Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/protocols/http/__pycache__/flow_control.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/protocols/http/__pycache__/h11_impl.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/protocols/http/__pycache__/h11_impl.cpython-312.pyc new file mode 100644 index 00000000..cd3b419d Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/protocols/http/__pycache__/h11_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/protocols/http/__pycache__/httptools_impl.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/protocols/http/__pycache__/httptools_impl.cpython-312.pyc new file mode 100644 index 00000000..d2e94b2e Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/protocols/http/__pycache__/httptools_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/protocols/http/auto.py b/venv/Lib/site-packages/uvicorn/protocols/http/auto.py new file mode 100644 index 00000000..a14bec14 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/protocols/http/auto.py @@ -0,0 +1,15 @@ +from __future__ import annotations + +import asyncio + +AutoHTTPProtocol: type[asyncio.Protocol] +try: + import httptools # noqa +except ImportError: # pragma: no cover + from uvicorn.protocols.http.h11_impl import H11Protocol + + AutoHTTPProtocol = H11Protocol +else: # pragma: no cover + from uvicorn.protocols.http.httptools_impl import HttpToolsProtocol + + AutoHTTPProtocol = HttpToolsProtocol diff --git a/venv/Lib/site-packages/uvicorn/protocols/http/flow_control.py b/venv/Lib/site-packages/uvicorn/protocols/http/flow_control.py new file mode 100644 index 00000000..2d1b5fa2 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/protocols/http/flow_control.py @@ -0,0 +1,54 @@ +import asyncio + +from uvicorn._types import ASGIReceiveCallable, ASGISendCallable, Scope + +CLOSE_HEADER = (b"connection", b"close") + +HIGH_WATER_LIMIT = 65536 + + +class FlowControl: + def __init__(self, transport: asyncio.Transport) -> None: + self._transport = transport + self.read_paused = False + self.write_paused = False + self._is_writable_event = asyncio.Event() + self._is_writable_event.set() + + async def drain(self) -> None: + await self._is_writable_event.wait() # pragma: full coverage + + def pause_reading(self) -> None: + if not self.read_paused: + self.read_paused = True + self._transport.pause_reading() + + def resume_reading(self) -> None: + if self.read_paused: + self.read_paused = False + self._transport.resume_reading() + + def pause_writing(self) -> None: + if not self.write_paused: # pragma: full coverage + self.write_paused = True + self._is_writable_event.clear() + + def resume_writing(self) -> None: + if self.write_paused: # pragma: full coverage + self.write_paused = False + self._is_writable_event.set() + + +async def service_unavailable(scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None: + await send( + { + "type": "http.response.start", + "status": 503, + "headers": [ + (b"content-type", b"text/plain; charset=utf-8"), + (b"content-length", b"19"), + (b"connection", b"close"), + ], + } + ) + await send({"type": "http.response.body", "body": b"Service Unavailable", "more_body": False}) diff --git a/venv/Lib/site-packages/uvicorn/protocols/http/h11_impl.py b/venv/Lib/site-packages/uvicorn/protocols/http/h11_impl.py new file mode 100644 index 00000000..b8cdde3a --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/protocols/http/h11_impl.py @@ -0,0 +1,543 @@ +from __future__ import annotations + +import asyncio +import http +import logging +from typing import Any, Callable, Literal, cast +from urllib.parse import unquote + +import h11 +from h11._connection import DEFAULT_MAX_INCOMPLETE_EVENT_SIZE + +from uvicorn._types import ( + ASGI3Application, + ASGIReceiveEvent, + ASGISendEvent, + HTTPRequestEvent, + HTTPResponseBodyEvent, + HTTPResponseStartEvent, + HTTPScope, +) +from uvicorn.config import Config +from uvicorn.logging import TRACE_LOG_LEVEL +from uvicorn.protocols.http.flow_control import CLOSE_HEADER, HIGH_WATER_LIMIT, FlowControl, service_unavailable +from uvicorn.protocols.utils import get_client_addr, get_local_addr, get_path_with_query_string, get_remote_addr, is_ssl +from uvicorn.server import ServerState + + +def _get_status_phrase(status_code: int) -> bytes: + try: + return http.HTTPStatus(status_code).phrase.encode() + except ValueError: + return b"" + + +STATUS_PHRASES = {status_code: _get_status_phrase(status_code) for status_code in range(100, 600)} + + +class H11Protocol(asyncio.Protocol): + def __init__( + self, + config: Config, + server_state: ServerState, + app_state: dict[str, Any], + _loop: asyncio.AbstractEventLoop | None = None, + ) -> None: + if not config.loaded: + config.load() + + self.config = config + self.app = config.loaded_app + self.loop = _loop or asyncio.get_event_loop() + self.logger = logging.getLogger("uvicorn.error") + self.access_logger = logging.getLogger("uvicorn.access") + self.access_log = self.access_logger.hasHandlers() + self.conn = h11.Connection( + h11.SERVER, + config.h11_max_incomplete_event_size + if config.h11_max_incomplete_event_size is not None + else DEFAULT_MAX_INCOMPLETE_EVENT_SIZE, + ) + self.ws_protocol_class = config.ws_protocol_class + self.root_path = config.root_path + self.limit_concurrency = config.limit_concurrency + self.app_state = app_state + + # Timeouts + self.timeout_keep_alive_task: asyncio.TimerHandle | None = None + self.timeout_keep_alive = config.timeout_keep_alive + + # Shared server state + self.server_state = server_state + self.connections = server_state.connections + self.tasks = server_state.tasks + + # Per-connection state + self.transport: asyncio.Transport = None # type: ignore[assignment] + self.flow: FlowControl = None # type: ignore[assignment] + self.server: tuple[str, int] | None = None + self.client: tuple[str, int] | None = None + self.scheme: Literal["http", "https"] | None = None + + # Per-request state + self.scope: HTTPScope = None # type: ignore[assignment] + self.headers: list[tuple[bytes, bytes]] = None # type: ignore[assignment] + self.cycle: RequestResponseCycle = None # type: ignore[assignment] + + # Protocol interface + def connection_made( # type: ignore[override] + self, transport: asyncio.Transport + ) -> None: + self.connections.add(self) + + self.transport = transport + self.flow = FlowControl(transport) + self.server = get_local_addr(transport) + self.client = get_remote_addr(transport) + self.scheme = "https" if is_ssl(transport) else "http" + + if self.logger.level <= TRACE_LOG_LEVEL: + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sHTTP connection made", prefix) + + def connection_lost(self, exc: Exception | None) -> None: + self.connections.discard(self) + + if self.logger.level <= TRACE_LOG_LEVEL: + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sHTTP connection lost", prefix) + + if self.cycle and not self.cycle.response_complete: + self.cycle.disconnected = True + if self.conn.our_state != h11.ERROR: + event = h11.ConnectionClosed() + try: + self.conn.send(event) + except h11.LocalProtocolError: + # Premature client disconnect + pass + + if self.cycle is not None: + self.cycle.message_event.set() + if self.flow is not None: + self.flow.resume_writing() + if exc is None: + self.transport.close() + self._unset_keepalive_if_required() + + def eof_received(self) -> None: + pass + + def _unset_keepalive_if_required(self) -> None: + if self.timeout_keep_alive_task is not None: + self.timeout_keep_alive_task.cancel() + self.timeout_keep_alive_task = None + + def _get_upgrade(self) -> bytes | None: + connection = [] + upgrade = None + for name, value in self.headers: + if name == b"connection": + connection = [token.lower().strip() for token in value.split(b",")] + if name == b"upgrade": + upgrade = value.lower() + if b"upgrade" in connection: + return upgrade + return None + + def _should_upgrade_to_ws(self) -> bool: + if self.ws_protocol_class is None: + return False + return True + + def _unsupported_upgrade_warning(self) -> None: + msg = "Unsupported upgrade request." + self.logger.warning(msg) + if not self._should_upgrade_to_ws(): + msg = "No supported WebSocket library detected. Please use \"pip install 'uvicorn[standard]'\", or install 'websockets' or 'wsproto' manually." # noqa: E501 + self.logger.warning(msg) + + def _should_upgrade(self) -> bool: + upgrade = self._get_upgrade() + if upgrade == b"websocket" and self._should_upgrade_to_ws(): + return True + if upgrade is not None: + self._unsupported_upgrade_warning() + return False + + def data_received(self, data: bytes) -> None: + self._unset_keepalive_if_required() + + self.conn.receive_data(data) + self.handle_events() + + def handle_events(self) -> None: + while True: + try: + event = self.conn.next_event() + except h11.RemoteProtocolError: + msg = "Invalid HTTP request received." + self.logger.warning(msg) + self.send_400_response(msg) + return + + if event is h11.NEED_DATA: + break + + elif event is h11.PAUSED: + # This case can occur in HTTP pipelining, so we need to + # stop reading any more data, and ensure that at the end + # of the active request/response cycle we handle any + # events that have been buffered up. + self.flow.pause_reading() + break + + elif isinstance(event, h11.Request): + self.headers = [(key.lower(), value) for key, value in event.headers] + raw_path, _, query_string = event.target.partition(b"?") + path = unquote(raw_path.decode("ascii")) + full_path = self.root_path + path + full_raw_path = self.root_path.encode("ascii") + raw_path + self.scope = { + "type": "http", + "asgi": {"version": self.config.asgi_version, "spec_version": "2.3"}, + "http_version": event.http_version.decode("ascii"), + "server": self.server, + "client": self.client, + "scheme": self.scheme, # type: ignore[typeddict-item] + "method": event.method.decode("ascii"), + "root_path": self.root_path, + "path": full_path, + "raw_path": full_raw_path, + "query_string": query_string, + "headers": self.headers, + "state": self.app_state.copy(), + } + if self._should_upgrade(): + self.handle_websocket_upgrade(event) + return + + # Handle 503 responses when 'limit_concurrency' is exceeded. + if self.limit_concurrency is not None and ( + len(self.connections) >= self.limit_concurrency or len(self.tasks) >= self.limit_concurrency + ): + app = service_unavailable + message = "Exceeded concurrency limit." + self.logger.warning(message) + else: + app = self.app + + # When starting to process a request, disable the keep-alive + # timeout. Normally we disable this when receiving data from + # client and set back when finishing processing its request. + # However, for pipelined requests processing finishes after + # already receiving the next request and thus the timer may + # be set here, which we don't want. + self._unset_keepalive_if_required() + + self.cycle = RequestResponseCycle( + scope=self.scope, + conn=self.conn, + transport=self.transport, + flow=self.flow, + logger=self.logger, + access_logger=self.access_logger, + access_log=self.access_log, + default_headers=self.server_state.default_headers, + message_event=asyncio.Event(), + on_response=self.on_response_complete, + ) + task = self.loop.create_task(self.cycle.run_asgi(app)) + task.add_done_callback(self.tasks.discard) + self.tasks.add(task) + + elif isinstance(event, h11.Data): + if self.conn.our_state is h11.DONE: + continue + self.cycle.body += event.data + if len(self.cycle.body) > HIGH_WATER_LIMIT: + self.flow.pause_reading() + self.cycle.message_event.set() + + elif isinstance(event, h11.EndOfMessage): + if self.conn.our_state is h11.DONE: + self.transport.resume_reading() + self.conn.start_next_cycle() + continue + self.cycle.more_body = False + self.cycle.message_event.set() + if self.conn.their_state == h11.MUST_CLOSE: + break + + def handle_websocket_upgrade(self, event: h11.Request) -> None: + if self.logger.level <= TRACE_LOG_LEVEL: # pragma: full coverage + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sUpgrading to WebSocket", prefix) + + self.connections.discard(self) + output = [event.method, b" ", event.target, b" HTTP/1.1\r\n"] + for name, value in self.headers: + output += [name, b": ", value, b"\r\n"] + output.append(b"\r\n") + protocol = self.ws_protocol_class( # type: ignore[call-arg, misc] + config=self.config, + server_state=self.server_state, + app_state=self.app_state, + ) + protocol.connection_made(self.transport) + protocol.data_received(b"".join(output)) + self.transport.set_protocol(protocol) + + def send_400_response(self, msg: str) -> None: + reason = STATUS_PHRASES[400] + headers: list[tuple[bytes, bytes]] = [ + (b"content-type", b"text/plain; charset=utf-8"), + (b"connection", b"close"), + ] + event = h11.Response(status_code=400, headers=headers, reason=reason) + output = self.conn.send(event) + self.transport.write(output) + + output = self.conn.send(event=h11.Data(data=msg.encode("ascii"))) + self.transport.write(output) + + output = self.conn.send(event=h11.EndOfMessage()) + self.transport.write(output) + + self.transport.close() + + def on_response_complete(self) -> None: + self.server_state.total_requests += 1 + + if self.transport.is_closing(): + return + + # Set a short Keep-Alive timeout. + self._unset_keepalive_if_required() + + self.timeout_keep_alive_task = self.loop.call_later(self.timeout_keep_alive, self.timeout_keep_alive_handler) + + # Unpause data reads if needed. + self.flow.resume_reading() + + # Unblock any pipelined events. + if self.conn.our_state is h11.DONE and self.conn.their_state is h11.DONE: + self.conn.start_next_cycle() + self.handle_events() + + def shutdown(self) -> None: + """ + Called by the server to commence a graceful shutdown. + """ + if self.cycle is None or self.cycle.response_complete: + event = h11.ConnectionClosed() + self.conn.send(event) + self.transport.close() + else: + self.cycle.keep_alive = False + + def pause_writing(self) -> None: + """ + Called by the transport when the write buffer exceeds the high water mark. + """ + self.flow.pause_writing() # pragma: full coverage + + def resume_writing(self) -> None: + """ + Called by the transport when the write buffer drops below the low water mark. + """ + self.flow.resume_writing() # pragma: full coverage + + def timeout_keep_alive_handler(self) -> None: + """ + Called on a keep-alive connection if no new data is received after a short + delay. + """ + if not self.transport.is_closing(): + event = h11.ConnectionClosed() + self.conn.send(event) + self.transport.close() + + +class RequestResponseCycle: + def __init__( + self, + scope: HTTPScope, + conn: h11.Connection, + transport: asyncio.Transport, + flow: FlowControl, + logger: logging.Logger, + access_logger: logging.Logger, + access_log: bool, + default_headers: list[tuple[bytes, bytes]], + message_event: asyncio.Event, + on_response: Callable[..., None], + ) -> None: + self.scope = scope + self.conn = conn + self.transport = transport + self.flow = flow + self.logger = logger + self.access_logger = access_logger + self.access_log = access_log + self.default_headers = default_headers + self.message_event = message_event + self.on_response = on_response + + # Connection state + self.disconnected = False + self.keep_alive = True + self.waiting_for_100_continue = conn.they_are_waiting_for_100_continue + + # Request state + self.body = b"" + self.more_body = True + + # Response state + self.response_started = False + self.response_complete = False + + # ASGI exception wrapper + async def run_asgi(self, app: ASGI3Application) -> None: + try: + result = await app( # type: ignore[func-returns-value] + self.scope, self.receive, self.send + ) + except BaseException as exc: + msg = "Exception in ASGI application\n" + self.logger.error(msg, exc_info=exc) + if not self.response_started: + await self.send_500_response() + else: + self.transport.close() + else: + if result is not None: + msg = "ASGI callable should return None, but returned '%s'." + self.logger.error(msg, result) + self.transport.close() + elif not self.response_started and not self.disconnected: + msg = "ASGI callable returned without starting response." + self.logger.error(msg) + await self.send_500_response() + elif not self.response_complete and not self.disconnected: + msg = "ASGI callable returned without completing response." + self.logger.error(msg) + self.transport.close() + finally: + self.on_response = lambda: None + + async def send_500_response(self) -> None: + response_start_event: HTTPResponseStartEvent = { + "type": "http.response.start", + "status": 500, + "headers": [ + (b"content-type", b"text/plain; charset=utf-8"), + (b"connection", b"close"), + ], + } + await self.send(response_start_event) + response_body_event: HTTPResponseBodyEvent = { + "type": "http.response.body", + "body": b"Internal Server Error", + "more_body": False, + } + await self.send(response_body_event) + + # ASGI interface + async def send(self, message: ASGISendEvent) -> None: + message_type = message["type"] + + if self.flow.write_paused and not self.disconnected: + await self.flow.drain() # pragma: full coverage + + if self.disconnected: + return # pragma: full coverage + + if not self.response_started: + # Sending response status line and headers + if message_type != "http.response.start": + msg = "Expected ASGI message 'http.response.start', but got '%s'." + raise RuntimeError(msg % message_type) + message = cast("HTTPResponseStartEvent", message) + + self.response_started = True + self.waiting_for_100_continue = False + + status = message["status"] + headers = self.default_headers + list(message.get("headers", [])) + + if CLOSE_HEADER in self.scope["headers"] and CLOSE_HEADER not in headers: + headers = headers + [CLOSE_HEADER] + + if self.access_log: + self.access_logger.info( + '%s - "%s %s HTTP/%s" %d', + get_client_addr(self.scope), + self.scope["method"], + get_path_with_query_string(self.scope), + self.scope["http_version"], + status, + ) + + # Write response status line and headers + reason = STATUS_PHRASES[status] + response = h11.Response(status_code=status, headers=headers, reason=reason) + output = self.conn.send(event=response) + self.transport.write(output) + + elif not self.response_complete: + # Sending response body + if message_type != "http.response.body": + msg = "Expected ASGI message 'http.response.body', but got '%s'." + raise RuntimeError(msg % message_type) + message = cast("HTTPResponseBodyEvent", message) + + body = message.get("body", b"") + more_body = message.get("more_body", False) + + # Write response body + data = b"" if self.scope["method"] == "HEAD" else body + output = self.conn.send(event=h11.Data(data=data)) + self.transport.write(output) + + # Handle response completion + if not more_body: + self.response_complete = True + self.message_event.set() + output = self.conn.send(event=h11.EndOfMessage()) + self.transport.write(output) + + else: + # Response already sent + msg = "Unexpected ASGI message '%s' sent, after response already completed." + raise RuntimeError(msg % message_type) + + if self.response_complete: + if self.conn.our_state is h11.MUST_CLOSE or not self.keep_alive: + self.conn.send(event=h11.ConnectionClosed()) + self.transport.close() + self.on_response() + + async def receive(self) -> ASGIReceiveEvent: + if self.waiting_for_100_continue and not self.transport.is_closing(): + headers: list[tuple[str, str]] = [] + event = h11.InformationalResponse(status_code=100, headers=headers, reason="Continue") + output = self.conn.send(event=event) + self.transport.write(output) + self.waiting_for_100_continue = False + + if not self.disconnected and not self.response_complete: + self.flow.resume_reading() + await self.message_event.wait() + self.message_event.clear() + + if self.disconnected or self.response_complete: + return {"type": "http.disconnect"} + + message: HTTPRequestEvent = { + "type": "http.request", + "body": self.body, + "more_body": self.more_body, + } + self.body = b"" + return message diff --git a/venv/Lib/site-packages/uvicorn/protocols/http/httptools_impl.py b/venv/Lib/site-packages/uvicorn/protocols/http/httptools_impl.py new file mode 100644 index 00000000..e8795ed3 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/protocols/http/httptools_impl.py @@ -0,0 +1,570 @@ +from __future__ import annotations + +import asyncio +import http +import logging +import re +import urllib +from asyncio.events import TimerHandle +from collections import deque +from typing import Any, Callable, Literal, cast + +import httptools + +from uvicorn._types import ( + ASGI3Application, + ASGIReceiveEvent, + ASGISendEvent, + HTTPRequestEvent, + HTTPResponseStartEvent, + HTTPScope, +) +from uvicorn.config import Config +from uvicorn.logging import TRACE_LOG_LEVEL +from uvicorn.protocols.http.flow_control import CLOSE_HEADER, HIGH_WATER_LIMIT, FlowControl, service_unavailable +from uvicorn.protocols.utils import get_client_addr, get_local_addr, get_path_with_query_string, get_remote_addr, is_ssl +from uvicorn.server import ServerState + +HEADER_RE = re.compile(b'[\x00-\x1f\x7f()<>@,;:[]={} \t\\"]') +HEADER_VALUE_RE = re.compile(b"[\x00-\x08\x0a-\x1f\x7f]") + + +def _get_status_line(status_code: int) -> bytes: + try: + phrase = http.HTTPStatus(status_code).phrase.encode() + except ValueError: + phrase = b"" + return b"".join([b"HTTP/1.1 ", str(status_code).encode(), b" ", phrase, b"\r\n"]) + + +STATUS_LINE = {status_code: _get_status_line(status_code) for status_code in range(100, 600)} + + +class HttpToolsProtocol(asyncio.Protocol): + def __init__( + self, + config: Config, + server_state: ServerState, + app_state: dict[str, Any], + _loop: asyncio.AbstractEventLoop | None = None, + ) -> None: + if not config.loaded: + config.load() + + self.config = config + self.app = config.loaded_app + self.loop = _loop or asyncio.get_event_loop() + self.logger = logging.getLogger("uvicorn.error") + self.access_logger = logging.getLogger("uvicorn.access") + self.access_log = self.access_logger.hasHandlers() + self.parser = httptools.HttpRequestParser(self) + + try: + # Enable dangerous leniencies to allow server to a response on the first request from a pipelined request. + self.parser.set_dangerous_leniencies(lenient_data_after_close=True) + except AttributeError: # pragma: no cover + # httptools < 0.6.3 + pass + + self.ws_protocol_class = config.ws_protocol_class + self.root_path = config.root_path + self.limit_concurrency = config.limit_concurrency + self.app_state = app_state + + # Timeouts + self.timeout_keep_alive_task: TimerHandle | None = None + self.timeout_keep_alive = config.timeout_keep_alive + + # Global state + self.server_state = server_state + self.connections = server_state.connections + self.tasks = server_state.tasks + + # Per-connection state + self.transport: asyncio.Transport = None # type: ignore[assignment] + self.flow: FlowControl = None # type: ignore[assignment] + self.server: tuple[str, int] | None = None + self.client: tuple[str, int] | None = None + self.scheme: Literal["http", "https"] | None = None + self.pipeline: deque[tuple[RequestResponseCycle, ASGI3Application]] = deque() + + # Per-request state + self.scope: HTTPScope = None # type: ignore[assignment] + self.headers: list[tuple[bytes, bytes]] = None # type: ignore[assignment] + self.expect_100_continue = False + self.cycle: RequestResponseCycle = None # type: ignore[assignment] + + # Protocol interface + def connection_made( # type: ignore[override] + self, transport: asyncio.Transport + ) -> None: + self.connections.add(self) + + self.transport = transport + self.flow = FlowControl(transport) + self.server = get_local_addr(transport) + self.client = get_remote_addr(transport) + self.scheme = "https" if is_ssl(transport) else "http" + + if self.logger.level <= TRACE_LOG_LEVEL: + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sHTTP connection made", prefix) + + def connection_lost(self, exc: Exception | None) -> None: + self.connections.discard(self) + + if self.logger.level <= TRACE_LOG_LEVEL: + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sHTTP connection lost", prefix) + + if self.cycle and not self.cycle.response_complete: + self.cycle.disconnected = True + if self.cycle is not None: + self.cycle.message_event.set() + if self.flow is not None: + self.flow.resume_writing() + if exc is None: + self.transport.close() + self._unset_keepalive_if_required() + + self.parser = None + + def eof_received(self) -> None: + pass + + def _unset_keepalive_if_required(self) -> None: + if self.timeout_keep_alive_task is not None: + self.timeout_keep_alive_task.cancel() + self.timeout_keep_alive_task = None + + def _get_upgrade(self) -> bytes | None: + connection = [] + upgrade = None + for name, value in self.headers: + if name == b"connection": + connection = [token.lower().strip() for token in value.split(b",")] + if name == b"upgrade": + upgrade = value.lower() + if b"upgrade" in connection: + return upgrade + return None # pragma: full coverage + + def _should_upgrade_to_ws(self) -> bool: + if self.ws_protocol_class is None: + return False + return True + + def _unsupported_upgrade_warning(self) -> None: + self.logger.warning("Unsupported upgrade request.") + if not self._should_upgrade_to_ws(): + msg = "No supported WebSocket library detected. Please use \"pip install 'uvicorn[standard]'\", or install 'websockets' or 'wsproto' manually." # noqa: E501 + self.logger.warning(msg) + + def _should_upgrade(self) -> bool: + upgrade = self._get_upgrade() + return upgrade == b"websocket" and self._should_upgrade_to_ws() + + def data_received(self, data: bytes) -> None: + self._unset_keepalive_if_required() + + try: + self.parser.feed_data(data) + except httptools.HttpParserError: + msg = "Invalid HTTP request received." + self.logger.warning(msg) + self.send_400_response(msg) + return + except httptools.HttpParserUpgrade: + if self._should_upgrade(): + self.handle_websocket_upgrade() + else: + self._unsupported_upgrade_warning() + + def handle_websocket_upgrade(self) -> None: + if self.logger.level <= TRACE_LOG_LEVEL: + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sUpgrading to WebSocket", prefix) + + self.connections.discard(self) + method = self.scope["method"].encode() + output = [method, b" ", self.url, b" HTTP/1.1\r\n"] + for name, value in self.scope["headers"]: + output += [name, b": ", value, b"\r\n"] + output.append(b"\r\n") + protocol = self.ws_protocol_class( # type: ignore[call-arg, misc] + config=self.config, + server_state=self.server_state, + app_state=self.app_state, + ) + protocol.connection_made(self.transport) + protocol.data_received(b"".join(output)) + self.transport.set_protocol(protocol) + + def send_400_response(self, msg: str) -> None: + content = [STATUS_LINE[400]] + for name, value in self.server_state.default_headers: + content.extend([name, b": ", value, b"\r\n"]) # pragma: full coverage + content.extend( + [ + b"content-type: text/plain; charset=utf-8\r\n", + b"content-length: " + str(len(msg)).encode("ascii") + b"\r\n", + b"connection: close\r\n", + b"\r\n", + msg.encode("ascii"), + ] + ) + self.transport.write(b"".join(content)) + self.transport.close() + + def on_message_begin(self) -> None: + self.url = b"" + self.expect_100_continue = False + self.headers = [] + self.scope = { # type: ignore[typeddict-item] + "type": "http", + "asgi": {"version": self.config.asgi_version, "spec_version": "2.3"}, + "http_version": "1.1", + "server": self.server, + "client": self.client, + "scheme": self.scheme, # type: ignore[typeddict-item] + "root_path": self.root_path, + "headers": self.headers, + "state": self.app_state.copy(), + } + + # Parser callbacks + def on_url(self, url: bytes) -> None: + self.url += url + + def on_header(self, name: bytes, value: bytes) -> None: + name = name.lower() + if name == b"expect" and value.lower() == b"100-continue": + self.expect_100_continue = True + self.headers.append((name, value)) + + def on_headers_complete(self) -> None: + http_version = self.parser.get_http_version() + method = self.parser.get_method() + self.scope["method"] = method.decode("ascii") + if http_version != "1.1": + self.scope["http_version"] = http_version + if self.parser.should_upgrade() and self._should_upgrade(): + return + parsed_url = httptools.parse_url(self.url) + raw_path = parsed_url.path + path = raw_path.decode("ascii") + if "%" in path: + path = urllib.parse.unquote(path) + full_path = self.root_path + path + full_raw_path = self.root_path.encode("ascii") + raw_path + self.scope["path"] = full_path + self.scope["raw_path"] = full_raw_path + self.scope["query_string"] = parsed_url.query or b"" + + # Handle 503 responses when 'limit_concurrency' is exceeded. + if self.limit_concurrency is not None and ( + len(self.connections) >= self.limit_concurrency or len(self.tasks) >= self.limit_concurrency + ): + app = service_unavailable + message = "Exceeded concurrency limit." + self.logger.warning(message) + else: + app = self.app + + existing_cycle = self.cycle + self.cycle = RequestResponseCycle( + scope=self.scope, + transport=self.transport, + flow=self.flow, + logger=self.logger, + access_logger=self.access_logger, + access_log=self.access_log, + default_headers=self.server_state.default_headers, + message_event=asyncio.Event(), + expect_100_continue=self.expect_100_continue, + keep_alive=http_version != "1.0", + on_response=self.on_response_complete, + ) + if existing_cycle is None or existing_cycle.response_complete: + # Standard case - start processing the request. + task = self.loop.create_task(self.cycle.run_asgi(app)) + task.add_done_callback(self.tasks.discard) + self.tasks.add(task) + else: + # Pipelined HTTP requests need to be queued up. + self.flow.pause_reading() + self.pipeline.appendleft((self.cycle, app)) + + def on_body(self, body: bytes) -> None: + if (self.parser.should_upgrade() and self._should_upgrade()) or self.cycle.response_complete: + return + self.cycle.body += body + if len(self.cycle.body) > HIGH_WATER_LIMIT: + self.flow.pause_reading() + self.cycle.message_event.set() + + def on_message_complete(self) -> None: + if (self.parser.should_upgrade() and self._should_upgrade()) or self.cycle.response_complete: + return + self.cycle.more_body = False + self.cycle.message_event.set() + + def on_response_complete(self) -> None: + # Callback for pipelined HTTP requests to be started. + self.server_state.total_requests += 1 + + if self.transport.is_closing(): + return + + self._unset_keepalive_if_required() + + # Unpause data reads if needed. + self.flow.resume_reading() + + # Unblock any pipelined events. If there are none, arm the + # Keep-Alive timeout instead. + if self.pipeline: + cycle, app = self.pipeline.pop() + task = self.loop.create_task(cycle.run_asgi(app)) + task.add_done_callback(self.tasks.discard) + self.tasks.add(task) + else: + self.timeout_keep_alive_task = self.loop.call_later( + self.timeout_keep_alive, self.timeout_keep_alive_handler + ) + + def shutdown(self) -> None: + """ + Called by the server to commence a graceful shutdown. + """ + if self.cycle is None or self.cycle.response_complete: + self.transport.close() + else: + self.cycle.keep_alive = False + + def pause_writing(self) -> None: + """ + Called by the transport when the write buffer exceeds the high water mark. + """ + self.flow.pause_writing() # pragma: full coverage + + def resume_writing(self) -> None: + """ + Called by the transport when the write buffer drops below the low water mark. + """ + self.flow.resume_writing() # pragma: full coverage + + def timeout_keep_alive_handler(self) -> None: + """ + Called on a keep-alive connection if no new data is received after a short + delay. + """ + if not self.transport.is_closing(): + self.transport.close() + + +class RequestResponseCycle: + def __init__( + self, + scope: HTTPScope, + transport: asyncio.Transport, + flow: FlowControl, + logger: logging.Logger, + access_logger: logging.Logger, + access_log: bool, + default_headers: list[tuple[bytes, bytes]], + message_event: asyncio.Event, + expect_100_continue: bool, + keep_alive: bool, + on_response: Callable[..., None], + ): + self.scope = scope + self.transport = transport + self.flow = flow + self.logger = logger + self.access_logger = access_logger + self.access_log = access_log + self.default_headers = default_headers + self.message_event = message_event + self.on_response = on_response + + # Connection state + self.disconnected = False + self.keep_alive = keep_alive + self.waiting_for_100_continue = expect_100_continue + + # Request state + self.body = b"" + self.more_body = True + + # Response state + self.response_started = False + self.response_complete = False + self.chunked_encoding: bool | None = None + self.expected_content_length = 0 + + # ASGI exception wrapper + async def run_asgi(self, app: ASGI3Application) -> None: + try: + result = await app( # type: ignore[func-returns-value] + self.scope, self.receive, self.send + ) + except BaseException as exc: + msg = "Exception in ASGI application\n" + self.logger.error(msg, exc_info=exc) + if not self.response_started: + await self.send_500_response() + else: + self.transport.close() + else: + if result is not None: + msg = "ASGI callable should return None, but returned '%s'." + self.logger.error(msg, result) + self.transport.close() + elif not self.response_started and not self.disconnected: + msg = "ASGI callable returned without starting response." + self.logger.error(msg) + await self.send_500_response() + elif not self.response_complete and not self.disconnected: + msg = "ASGI callable returned without completing response." + self.logger.error(msg) + self.transport.close() + finally: + self.on_response = lambda: None + + async def send_500_response(self) -> None: + await self.send( + { + "type": "http.response.start", + "status": 500, + "headers": [ + (b"content-type", b"text/plain; charset=utf-8"), + (b"content-length", b"21"), + (b"connection", b"close"), + ], + } + ) + await self.send({"type": "http.response.body", "body": b"Internal Server Error", "more_body": False}) + + # ASGI interface + async def send(self, message: ASGISendEvent) -> None: + message_type = message["type"] + + if self.flow.write_paused and not self.disconnected: + await self.flow.drain() # pragma: full coverage + + if self.disconnected: + return # pragma: full coverage + + if not self.response_started: + # Sending response status line and headers + if message_type != "http.response.start": + msg = "Expected ASGI message 'http.response.start', but got '%s'." + raise RuntimeError(msg % message_type) + message = cast("HTTPResponseStartEvent", message) + + self.response_started = True + self.waiting_for_100_continue = False + + status_code = message["status"] + headers = self.default_headers + list(message.get("headers", [])) + + if CLOSE_HEADER in self.scope["headers"] and CLOSE_HEADER not in headers: + headers = headers + [CLOSE_HEADER] + + if self.access_log: + self.access_logger.info( + '%s - "%s %s HTTP/%s" %d', + get_client_addr(self.scope), + self.scope["method"], + get_path_with_query_string(self.scope), + self.scope["http_version"], + status_code, + ) + + # Write response status line and headers + content = [STATUS_LINE[status_code]] + + for name, value in headers: + if HEADER_RE.search(name): + raise RuntimeError("Invalid HTTP header name.") # pragma: full coverage + if HEADER_VALUE_RE.search(value): + raise RuntimeError("Invalid HTTP header value.") + + name = name.lower() + if name == b"content-length" and self.chunked_encoding is None: + self.expected_content_length = int(value.decode()) + self.chunked_encoding = False + elif name == b"transfer-encoding" and value.lower() == b"chunked": + self.expected_content_length = 0 + self.chunked_encoding = True + elif name == b"connection" and value.lower() == b"close": + self.keep_alive = False + content.extend([name, b": ", value, b"\r\n"]) + + if self.chunked_encoding is None and self.scope["method"] != "HEAD" and status_code not in (204, 304): + # Neither content-length nor transfer-encoding specified + self.chunked_encoding = True + content.append(b"transfer-encoding: chunked\r\n") + + content.append(b"\r\n") + self.transport.write(b"".join(content)) + + elif not self.response_complete: + # Sending response body + if message_type != "http.response.body": + msg = "Expected ASGI message 'http.response.body', but got '%s'." + raise RuntimeError(msg % message_type) + + body = cast(bytes, message.get("body", b"")) + more_body = message.get("more_body", False) + + # Write response body + if self.scope["method"] == "HEAD": + self.expected_content_length = 0 + elif self.chunked_encoding: + if body: + content = [b"%x\r\n" % len(body), body, b"\r\n"] + else: + content = [] + if not more_body: + content.append(b"0\r\n\r\n") + self.transport.write(b"".join(content)) + else: + num_bytes = len(body) + if num_bytes > self.expected_content_length: + raise RuntimeError("Response content longer than Content-Length") + else: + self.expected_content_length -= num_bytes + self.transport.write(body) + + # Handle response completion + if not more_body: + if self.expected_content_length != 0: + raise RuntimeError("Response content shorter than Content-Length") + self.response_complete = True + self.message_event.set() + if not self.keep_alive: + self.transport.close() + self.on_response() + + else: + # Response already sent + msg = "Unexpected ASGI message '%s' sent, after response already completed." + raise RuntimeError(msg % message_type) + + async def receive(self) -> ASGIReceiveEvent: + if self.waiting_for_100_continue and not self.transport.is_closing(): + self.transport.write(b"HTTP/1.1 100 Continue\r\n\r\n") + self.waiting_for_100_continue = False + + if not self.disconnected and not self.response_complete: + self.flow.resume_reading() + await self.message_event.wait() + self.message_event.clear() + + if self.disconnected or self.response_complete: + return {"type": "http.disconnect"} + message: HTTPRequestEvent = {"type": "http.request", "body": self.body, "more_body": self.more_body} + self.body = b"" + return message diff --git a/venv/Lib/site-packages/uvicorn/protocols/utils.py b/venv/Lib/site-packages/uvicorn/protocols/utils.py new file mode 100644 index 00000000..e1d6f01d --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/protocols/utils.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +import asyncio +import urllib.parse + +from uvicorn._types import WWWScope + + +class ClientDisconnected(OSError): ... + + +def get_remote_addr(transport: asyncio.Transport) -> tuple[str, int] | None: + socket_info = transport.get_extra_info("socket") + if socket_info is not None: + try: + info = socket_info.getpeername() + return (str(info[0]), int(info[1])) if isinstance(info, tuple) else None + except OSError: # pragma: no cover + # This case appears to inconsistently occur with uvloop + # bound to a unix domain socket. + return None + + info = transport.get_extra_info("peername") + if info is not None and isinstance(info, (list, tuple)) and len(info) == 2: + return (str(info[0]), int(info[1])) + return None + + +def get_local_addr(transport: asyncio.Transport) -> tuple[str, int] | None: + socket_info = transport.get_extra_info("socket") + if socket_info is not None: + info = socket_info.getsockname() + + return (str(info[0]), int(info[1])) if isinstance(info, tuple) else None + info = transport.get_extra_info("sockname") + if info is not None and isinstance(info, (list, tuple)) and len(info) == 2: + return (str(info[0]), int(info[1])) + return None + + +def is_ssl(transport: asyncio.Transport) -> bool: + return bool(transport.get_extra_info("sslcontext")) + + +def get_client_addr(scope: WWWScope) -> str: + client = scope.get("client") + if not client: + return "" + return "%s:%d" % client + + +def get_path_with_query_string(scope: WWWScope) -> str: + path_with_query_string = urllib.parse.quote(scope["path"]) + if scope["query_string"]: + path_with_query_string = "{}?{}".format(path_with_query_string, scope["query_string"].decode("ascii")) + return path_with_query_string diff --git a/venv/Lib/site-packages/uvicorn/protocols/websockets/__init__.py b/venv/Lib/site-packages/uvicorn/protocols/websockets/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/venv/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..f2fedb3a Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/auto.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/auto.cpython-312.pyc new file mode 100644 index 00000000..981388ed Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/auto.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/websockets_impl.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/websockets_impl.cpython-312.pyc new file mode 100644 index 00000000..506c61a2 Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/websockets_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/websockets_sansio_impl.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/websockets_sansio_impl.cpython-312.pyc new file mode 100644 index 00000000..c30531be Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/websockets_sansio_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/wsproto_impl.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/wsproto_impl.cpython-312.pyc new file mode 100644 index 00000000..be119a06 Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/wsproto_impl.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/protocols/websockets/auto.py b/venv/Lib/site-packages/uvicorn/protocols/websockets/auto.py new file mode 100644 index 00000000..b74ac30e --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/protocols/websockets/auto.py @@ -0,0 +1,21 @@ +from __future__ import annotations + +import asyncio +from typing import Callable + +AutoWebSocketsProtocol: Callable[..., asyncio.Protocol] | None +try: + import websockets # noqa +except ImportError: # pragma: no cover + try: + import wsproto # noqa + except ImportError: + AutoWebSocketsProtocol = None + else: + from uvicorn.protocols.websockets.wsproto_impl import WSProtocol + + AutoWebSocketsProtocol = WSProtocol +else: + from uvicorn.protocols.websockets.websockets_impl import WebSocketProtocol + + AutoWebSocketsProtocol = WebSocketProtocol diff --git a/venv/Lib/site-packages/uvicorn/protocols/websockets/websockets_impl.py b/venv/Lib/site-packages/uvicorn/protocols/websockets/websockets_impl.py new file mode 100644 index 00000000..09e24071 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/protocols/websockets/websockets_impl.py @@ -0,0 +1,387 @@ +from __future__ import annotations + +import asyncio +import http +import logging +from collections.abc import Sequence +from typing import Any, Literal, Optional, cast +from urllib.parse import unquote + +import websockets +import websockets.legacy.handshake +from websockets.datastructures import Headers +from websockets.exceptions import ConnectionClosed +from websockets.extensions.base import ServerExtensionFactory +from websockets.extensions.permessage_deflate import ServerPerMessageDeflateFactory +from websockets.legacy.server import HTTPResponse +from websockets.server import WebSocketServerProtocol +from websockets.typing import Subprotocol + +from uvicorn._types import ( + ASGI3Application, + ASGISendEvent, + WebSocketAcceptEvent, + WebSocketCloseEvent, + WebSocketConnectEvent, + WebSocketDisconnectEvent, + WebSocketReceiveEvent, + WebSocketResponseBodyEvent, + WebSocketResponseStartEvent, + WebSocketScope, + WebSocketSendEvent, +) +from uvicorn.config import Config +from uvicorn.logging import TRACE_LOG_LEVEL +from uvicorn.protocols.utils import ( + ClientDisconnected, + get_client_addr, + get_local_addr, + get_path_with_query_string, + get_remote_addr, + is_ssl, +) +from uvicorn.server import ServerState + + +class Server: + closing = False + + def register(self, ws: WebSocketServerProtocol) -> None: + pass + + def unregister(self, ws: WebSocketServerProtocol) -> None: + pass + + def is_serving(self) -> bool: + return not self.closing + + +class WebSocketProtocol(WebSocketServerProtocol): + extra_headers: list[tuple[str, str]] + logger: logging.Logger | logging.LoggerAdapter[Any] + + def __init__( + self, + config: Config, + server_state: ServerState, + app_state: dict[str, Any], + _loop: asyncio.AbstractEventLoop | None = None, + ): + if not config.loaded: + config.load() + + self.config = config + self.app = cast(ASGI3Application, config.loaded_app) + self.loop = _loop or asyncio.get_event_loop() + self.root_path = config.root_path + self.app_state = app_state + + # Shared server state + self.connections = server_state.connections + self.tasks = server_state.tasks + + # Connection state + self.transport: asyncio.Transport = None # type: ignore[assignment] + self.server: tuple[str, int] | None = None + self.client: tuple[str, int] | None = None + self.scheme: Literal["wss", "ws"] = None # type: ignore[assignment] + + # Connection events + self.scope: WebSocketScope + self.handshake_started_event = asyncio.Event() + self.handshake_completed_event = asyncio.Event() + self.closed_event = asyncio.Event() + self.initial_response: HTTPResponse | None = None + self.connect_sent = False + self.lost_connection_before_handshake = False + self.accepted_subprotocol: Subprotocol | None = None + + self.ws_server: Server = Server() # type: ignore[assignment] + + extensions: list[ServerExtensionFactory] = [] + if self.config.ws_per_message_deflate: + extensions.append(ServerPerMessageDeflateFactory()) + + super().__init__( + ws_handler=self.ws_handler, + ws_server=self.ws_server, # type: ignore[arg-type] + max_size=self.config.ws_max_size, + max_queue=self.config.ws_max_queue, + ping_interval=self.config.ws_ping_interval, + ping_timeout=self.config.ws_ping_timeout, + extensions=extensions, + logger=logging.getLogger("uvicorn.error"), + ) + self.server_header = None + self.extra_headers = [ + (name.decode("latin-1"), value.decode("latin-1")) for name, value in server_state.default_headers + ] + + def connection_made( # type: ignore[override] + self, transport: asyncio.Transport + ) -> None: + self.connections.add(self) + self.transport = transport + self.server = get_local_addr(transport) + self.client = get_remote_addr(transport) + self.scheme = "wss" if is_ssl(transport) else "ws" + + if self.logger.isEnabledFor(TRACE_LOG_LEVEL): + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sWebSocket connection made", prefix) + + super().connection_made(transport) + + def connection_lost(self, exc: Exception | None) -> None: + self.connections.remove(self) + + if self.logger.isEnabledFor(TRACE_LOG_LEVEL): + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sWebSocket connection lost", prefix) + + self.lost_connection_before_handshake = not self.handshake_completed_event.is_set() + self.handshake_completed_event.set() + super().connection_lost(exc) + if exc is None: + self.transport.close() + + def shutdown(self) -> None: + self.ws_server.closing = True + if self.handshake_completed_event.is_set(): + self.fail_connection(1012) + else: + self.send_500_response() + self.transport.close() + + def on_task_complete(self, task: asyncio.Task[None]) -> None: + self.tasks.discard(task) + + async def process_request(self, path: str, request_headers: Headers) -> HTTPResponse | None: + """ + This hook is called to determine if the websocket should return + an HTTP response and close. + + Our behavior here is to start the ASGI application, and then wait + for either `accept` or `close` in order to determine if we should + close the connection. + """ + path_portion, _, query_string = path.partition("?") + + websockets.legacy.handshake.check_request(request_headers) + + subprotocols: list[str] = [] + for header in request_headers.get_all("Sec-WebSocket-Protocol"): + subprotocols.extend([token.strip() for token in header.split(",")]) + + asgi_headers = [ + (name.encode("ascii"), value.encode("ascii", errors="surrogateescape")) + for name, value in request_headers.raw_items() + ] + path = unquote(path_portion) + full_path = self.root_path + path + full_raw_path = self.root_path.encode("ascii") + path_portion.encode("ascii") + + self.scope = { + "type": "websocket", + "asgi": {"version": self.config.asgi_version, "spec_version": "2.4"}, + "http_version": "1.1", + "scheme": self.scheme, + "server": self.server, + "client": self.client, + "root_path": self.root_path, + "path": full_path, + "raw_path": full_raw_path, + "query_string": query_string.encode("ascii"), + "headers": asgi_headers, + "subprotocols": subprotocols, + "state": self.app_state.copy(), + "extensions": {"websocket.http.response": {}}, + } + task = self.loop.create_task(self.run_asgi()) + task.add_done_callback(self.on_task_complete) + self.tasks.add(task) + await self.handshake_started_event.wait() + return self.initial_response + + def process_subprotocol( + self, headers: Headers, available_subprotocols: Sequence[Subprotocol] | None + ) -> Subprotocol | None: + """ + We override the standard 'process_subprotocol' behavior here so that + we return whatever subprotocol is sent in the 'accept' message. + """ + return self.accepted_subprotocol + + def send_500_response(self) -> None: + msg = b"Internal Server Error" + content = [ + b"HTTP/1.1 500 Internal Server Error\r\ncontent-type: text/plain; charset=utf-8\r\n", + b"content-length: " + str(len(msg)).encode("ascii") + b"\r\n", + b"connection: close\r\n", + b"\r\n", + msg, + ] + self.transport.write(b"".join(content)) + # Allow handler task to terminate cleanly, as websockets doesn't cancel it by + # itself (see https://github.com/encode/uvicorn/issues/920) + self.handshake_started_event.set() + + async def ws_handler(self, protocol: WebSocketServerProtocol, path: str) -> Any: # type: ignore[override] + """ + This is the main handler function for the 'websockets' implementation + to call into. We just wait for close then return, and instead allow + 'send' and 'receive' events to drive the flow. + """ + self.handshake_completed_event.set() + await self.wait_closed() + + async def run_asgi(self) -> None: + """ + Wrapper around the ASGI callable, handling exceptions and unexpected + termination states. + """ + try: + result = await self.app(self.scope, self.asgi_receive, self.asgi_send) # type: ignore[func-returns-value] + except ClientDisconnected: # pragma: full coverage + self.closed_event.set() + self.transport.close() + except BaseException: + self.closed_event.set() + self.logger.exception("Exception in ASGI application\n") + if not self.handshake_started_event.is_set(): + self.send_500_response() + else: + await self.handshake_completed_event.wait() + self.transport.close() + else: + self.closed_event.set() + if not self.handshake_started_event.is_set(): + self.logger.error("ASGI callable returned without sending handshake.") + self.send_500_response() + self.transport.close() + elif result is not None: + self.logger.error("ASGI callable should return None, but returned '%s'.", result) + await self.handshake_completed_event.wait() + self.transport.close() + + async def asgi_send(self, message: ASGISendEvent) -> None: + message_type = message["type"] + + if not self.handshake_started_event.is_set(): + if message_type == "websocket.accept": + message = cast("WebSocketAcceptEvent", message) + self.logger.info( + '%s - "WebSocket %s" [accepted]', + get_client_addr(self.scope), + get_path_with_query_string(self.scope), + ) + self.initial_response = None + self.accepted_subprotocol = cast(Optional[Subprotocol], message.get("subprotocol")) + if "headers" in message: + self.extra_headers.extend( + # ASGI spec requires bytes + # But for compatibility we need to convert it to strings + (name.decode("latin-1"), value.decode("latin-1")) + for name, value in message["headers"] + ) + self.handshake_started_event.set() + + elif message_type == "websocket.close": + message = cast("WebSocketCloseEvent", message) + self.logger.info( + '%s - "WebSocket %s" 403', + get_client_addr(self.scope), + get_path_with_query_string(self.scope), + ) + self.initial_response = (http.HTTPStatus.FORBIDDEN, [], b"") + self.handshake_started_event.set() + self.closed_event.set() + + elif message_type == "websocket.http.response.start": + message = cast("WebSocketResponseStartEvent", message) + self.logger.info( + '%s - "WebSocket %s" %d', + get_client_addr(self.scope), + get_path_with_query_string(self.scope), + message["status"], + ) + # websockets requires the status to be an enum. look it up. + status = http.HTTPStatus(message["status"]) + headers = [ + (name.decode("latin-1"), value.decode("latin-1")) for name, value in message.get("headers", []) + ] + self.initial_response = (status, headers, b"") + self.handshake_started_event.set() + + else: + msg = ( + "Expected ASGI message 'websocket.accept', 'websocket.close', " + "or 'websocket.http.response.start' but got '%s'." + ) + raise RuntimeError(msg % message_type) + + elif not self.closed_event.is_set() and self.initial_response is None: + await self.handshake_completed_event.wait() + + try: + if message_type == "websocket.send": + message = cast("WebSocketSendEvent", message) + bytes_data = message.get("bytes") + text_data = message.get("text") + data = text_data if bytes_data is None else bytes_data + await self.send(data) # type: ignore[arg-type] + + elif message_type == "websocket.close": + message = cast("WebSocketCloseEvent", message) + code = message.get("code", 1000) + reason = message.get("reason", "") or "" + await self.close(code, reason) + self.closed_event.set() + + else: + msg = "Expected ASGI message 'websocket.send' or 'websocket.close', but got '%s'." + raise RuntimeError(msg % message_type) + except ConnectionClosed as exc: + raise ClientDisconnected from exc + + elif self.initial_response is not None: + if message_type == "websocket.http.response.body": + message = cast("WebSocketResponseBodyEvent", message) + body = self.initial_response[2] + message["body"] + self.initial_response = self.initial_response[:2] + (body,) + if not message.get("more_body", False): + self.closed_event.set() + else: + msg = "Expected ASGI message 'websocket.http.response.body' but got '%s'." + raise RuntimeError(msg % message_type) + + else: + msg = "Unexpected ASGI message '%s', after sending 'websocket.close' or response already completed." + raise RuntimeError(msg % message_type) + + async def asgi_receive(self) -> WebSocketDisconnectEvent | WebSocketConnectEvent | WebSocketReceiveEvent: + if not self.connect_sent: + self.connect_sent = True + return {"type": "websocket.connect"} + + await self.handshake_completed_event.wait() + + if self.lost_connection_before_handshake: + # If the handshake failed or the app closed before handshake completion, + # use 1006 Abnormal Closure. + return {"type": "websocket.disconnect", "code": 1006} + + if self.closed_event.is_set(): + return {"type": "websocket.disconnect", "code": 1005} + + try: + data = await self.recv() + except ConnectionClosed: + self.closed_event.set() + if self.ws_server.closing: + return {"type": "websocket.disconnect", "code": 1012} + return {"type": "websocket.disconnect", "code": self.close_code or 1005, "reason": self.close_reason} + + if isinstance(data, str): + return {"type": "websocket.receive", "text": data} + return {"type": "websocket.receive", "bytes": data} diff --git a/venv/Lib/site-packages/uvicorn/protocols/websockets/websockets_sansio_impl.py b/venv/Lib/site-packages/uvicorn/protocols/websockets/websockets_sansio_impl.py new file mode 100644 index 00000000..abd4c2b3 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/protocols/websockets/websockets_sansio_impl.py @@ -0,0 +1,417 @@ +from __future__ import annotations + +import asyncio +import logging +import sys +from asyncio.transports import BaseTransport, Transport +from http import HTTPStatus +from typing import Any, Literal, cast +from urllib.parse import unquote + +from websockets.exceptions import InvalidState +from websockets.extensions.permessage_deflate import ServerPerMessageDeflateFactory +from websockets.frames import Frame, Opcode +from websockets.http11 import Request +from websockets.server import ServerProtocol + +from uvicorn._types import ( + ASGIReceiveEvent, + ASGISendEvent, + WebSocketAcceptEvent, + WebSocketCloseEvent, + WebSocketResponseBodyEvent, + WebSocketResponseStartEvent, + WebSocketScope, + WebSocketSendEvent, +) +from uvicorn.config import Config +from uvicorn.logging import TRACE_LOG_LEVEL +from uvicorn.protocols.utils import ( + ClientDisconnected, + get_local_addr, + get_path_with_query_string, + get_remote_addr, + is_ssl, +) +from uvicorn.server import ServerState + +if sys.version_info >= (3, 11): # pragma: no cover + from typing import assert_never +else: # pragma: no cover + from typing_extensions import assert_never + + +class WebSocketsSansIOProtocol(asyncio.Protocol): + def __init__( + self, + config: Config, + server_state: ServerState, + app_state: dict[str, Any], + _loop: asyncio.AbstractEventLoop | None = None, + ) -> None: + if not config.loaded: + config.load() # pragma: no cover + + self.config = config + self.app = config.loaded_app + self.loop = _loop or asyncio.get_event_loop() + self.logger = logging.getLogger("uvicorn.error") + self.root_path = config.root_path + self.app_state = app_state + + # Shared server state + self.connections = server_state.connections + self.tasks = server_state.tasks + self.default_headers = server_state.default_headers + + # Connection state + self.transport: asyncio.Transport = None # type: ignore[assignment] + self.server: tuple[str, int] | None = None + self.client: tuple[str, int] | None = None + self.scheme: Literal["wss", "ws"] = None # type: ignore[assignment] + + # WebSocket state + self.queue: asyncio.Queue[ASGIReceiveEvent] = asyncio.Queue() + self.handshake_initiated = False + self.handshake_complete = False + self.close_sent = False + self.initial_response: tuple[int, list[tuple[str, str]], bytes] | None = None + + extensions = [] + if self.config.ws_per_message_deflate: + extensions = [ + ServerPerMessageDeflateFactory( + server_max_window_bits=12, + client_max_window_bits=12, + compress_settings={"memLevel": 5}, + ) + ] + self.conn = ServerProtocol( + extensions=extensions, + max_size=self.config.ws_max_size, + logger=logging.getLogger("uvicorn.error"), + ) + + self.read_paused = False + self.writable = asyncio.Event() + self.writable.set() + + # Buffers + self.bytes = b"" + + def connection_made(self, transport: BaseTransport) -> None: + """Called when a connection is made.""" + transport = cast(Transport, transport) + self.connections.add(self) + self.transport = transport + self.server = get_local_addr(transport) + self.client = get_remote_addr(transport) + self.scheme = "wss" if is_ssl(transport) else "ws" + + if self.logger.level <= TRACE_LOG_LEVEL: + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sWebSocket connection made", prefix) + + def connection_lost(self, exc: Exception | None) -> None: + code = 1005 if self.handshake_complete else 1006 + self.queue.put_nowait({"type": "websocket.disconnect", "code": code}) + self.connections.remove(self) + + if self.logger.level <= TRACE_LOG_LEVEL: + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sWebSocket connection lost", prefix) + + self.handshake_complete = True + if exc is None: + self.transport.close() + + def eof_received(self) -> None: + pass + + def shutdown(self) -> None: + if self.handshake_complete: + self.queue.put_nowait({"type": "websocket.disconnect", "code": 1012}) + self.conn.send_close(1012) + output = self.conn.data_to_send() + self.transport.write(b"".join(output)) + else: + self.send_500_response() + self.transport.close() + + def data_received(self, data: bytes) -> None: + self.conn.receive_data(data) + if self.conn.parser_exc is not None: # pragma: no cover + self.handle_parser_exception() + return + self.handle_events() + + def handle_events(self) -> None: + for event in self.conn.events_received(): + if isinstance(event, Request): + self.handle_connect(event) + if isinstance(event, Frame): + if event.opcode == Opcode.CONT: + self.handle_cont(event) # pragma: no cover + elif event.opcode == Opcode.TEXT: + self.handle_text(event) + elif event.opcode == Opcode.BINARY: + self.handle_bytes(event) + elif event.opcode == Opcode.PING: + self.handle_ping() + elif event.opcode == Opcode.PONG: + pass # pragma: no cover + elif event.opcode == Opcode.CLOSE: + self.handle_close(event) + else: + assert_never(event.opcode) # pragma: no cover + + # Event handlers + + def handle_connect(self, event: Request) -> None: + self.request = event + self.response = self.conn.accept(event) + self.handshake_initiated = True + if self.response.status_code != 101: + self.handshake_complete = True + self.close_sent = True + self.conn.send_response(self.response) + output = self.conn.data_to_send() + self.transport.write(b"".join(output)) + self.transport.close() + return + + headers = [ + (key.encode("ascii"), value.encode("ascii", errors="surrogateescape")) + for key, value in event.headers.raw_items() + ] + raw_path, _, query_string = event.path.partition("?") + self.scope: WebSocketScope = { + "type": "websocket", + "asgi": {"version": self.config.asgi_version, "spec_version": "2.3"}, + "http_version": "1.1", + "scheme": self.scheme, + "server": self.server, + "client": self.client, + "root_path": self.root_path, + "path": unquote(raw_path), + "raw_path": raw_path.encode("ascii"), + "query_string": query_string.encode("ascii"), + "headers": headers, + "subprotocols": event.headers.get_all("Sec-WebSocket-Protocol"), + "state": self.app_state.copy(), + "extensions": {"websocket.http.response": {}}, + } + self.queue.put_nowait({"type": "websocket.connect"}) + task = self.loop.create_task(self.run_asgi()) + task.add_done_callback(self.on_task_complete) + self.tasks.add(task) + + def handle_cont(self, event: Frame) -> None: # pragma: no cover + self.bytes += event.data + if event.fin: + self.send_receive_event_to_app() + + def handle_text(self, event: Frame) -> None: + self.bytes = event.data + self.curr_msg_data_type: Literal["text", "bytes"] = "text" + if event.fin: + self.send_receive_event_to_app() + + def handle_bytes(self, event: Frame) -> None: + self.bytes = event.data + self.curr_msg_data_type = "bytes" + if event.fin: + self.send_receive_event_to_app() + + def send_receive_event_to_app(self) -> None: + if self.curr_msg_data_type == "text": + try: + self.queue.put_nowait({"type": "websocket.receive", "text": self.bytes.decode()}) + except UnicodeDecodeError: # pragma: no cover + self.logger.exception("Invalid UTF-8 sequence received from client.") + self.conn.send_close(1007) + self.handle_parser_exception() + return + else: + self.queue.put_nowait({"type": "websocket.receive", "bytes": self.bytes}) + if not self.read_paused: + self.read_paused = True + self.transport.pause_reading() + + def handle_ping(self) -> None: + output = self.conn.data_to_send() + self.transport.write(b"".join(output)) + + def handle_close(self, event: Frame) -> None: + if not self.close_sent and not self.transport.is_closing(): + assert self.conn.close_rcvd is not None + code = self.conn.close_rcvd.code + reason = self.conn.close_rcvd.reason + self.queue.put_nowait({"type": "websocket.disconnect", "code": code, "reason": reason}) + + output = self.conn.data_to_send() + self.transport.write(b"".join(output)) + self.transport.close() + + def handle_parser_exception(self) -> None: # pragma: no cover + assert self.conn.close_sent is not None + code = self.conn.close_sent.code + reason = self.conn.close_sent.reason + self.queue.put_nowait({"type": "websocket.disconnect", "code": code, "reason": reason}) + + output = self.conn.data_to_send() + self.transport.write(b"".join(output)) + self.close_sent = True + self.transport.close() + + def on_task_complete(self, task: asyncio.Task[None]) -> None: + self.tasks.discard(task) + + async def run_asgi(self) -> None: + try: + result = await self.app(self.scope, self.receive, self.send) + except ClientDisconnected: + self.transport.close() # pragma: no cover + except BaseException: + self.logger.exception("Exception in ASGI application\n") + self.send_500_response() + self.transport.close() + else: + if not self.handshake_complete: + self.logger.error("ASGI callable returned without completing handshake.") + self.send_500_response() + self.transport.close() + elif result is not None: + self.logger.error("ASGI callable should return None, but returned '%s'.", result) + self.transport.close() + + def send_500_response(self) -> None: + if self.initial_response or self.handshake_complete: + return + response = self.conn.reject(500, "Internal Server Error") + self.conn.send_response(response) + output = self.conn.data_to_send() + self.transport.write(b"".join(output)) + + async def send(self, message: ASGISendEvent) -> None: + await self.writable.wait() + + message_type = message["type"] + + if not self.handshake_complete and self.initial_response is None: + if message_type == "websocket.accept": + message = cast(WebSocketAcceptEvent, message) + self.logger.info( + '%s - "WebSocket %s" [accepted]', + self.scope["client"], + get_path_with_query_string(self.scope), + ) + headers = [ + (name.decode("latin-1").lower(), value.decode("latin-1").lower()) + for name, value in (self.default_headers + list(message.get("headers", []))) + ] + accepted_subprotocol = message.get("subprotocol") + if accepted_subprotocol: + headers.append(("Sec-WebSocket-Protocol", accepted_subprotocol)) + self.response.headers.update(headers) + + if not self.transport.is_closing(): + self.handshake_complete = True + self.conn.send_response(self.response) + output = self.conn.data_to_send() + self.transport.write(b"".join(output)) + + elif message_type == "websocket.close": + message = cast(WebSocketCloseEvent, message) + self.queue.put_nowait({"type": "websocket.disconnect", "code": 1006}) + self.logger.info( + '%s - "WebSocket %s" 403', + self.scope["client"], + get_path_with_query_string(self.scope), + ) + response = self.conn.reject(HTTPStatus.FORBIDDEN, "") + self.conn.send_response(response) + output = self.conn.data_to_send() + self.close_sent = True + self.handshake_complete = True + self.transport.write(b"".join(output)) + self.transport.close() + elif message_type == "websocket.http.response.start" and self.initial_response is None: + message = cast(WebSocketResponseStartEvent, message) + if not (100 <= message["status"] < 600): + raise RuntimeError("Invalid HTTP status code '%d' in response." % message["status"]) + self.logger.info( + '%s - "WebSocket %s" %d', + self.scope["client"], + get_path_with_query_string(self.scope), + message["status"], + ) + headers = [ + (name.decode("latin-1"), value.decode("latin-1")) + for name, value in list(message.get("headers", [])) + ] + self.initial_response = (message["status"], headers, b"") + else: + msg = ( + "Expected ASGI message 'websocket.accept', 'websocket.close' " + "or 'websocket.http.response.start' " + "but got '%s'." + ) + raise RuntimeError(msg % message_type) + + elif not self.close_sent and self.initial_response is None: + try: + if message_type == "websocket.send": + message = cast(WebSocketSendEvent, message) + bytes_data = message.get("bytes") + text_data = message.get("text") + if text_data: + self.conn.send_text(text_data.encode()) + elif bytes_data: + self.conn.send_binary(bytes_data) + output = self.conn.data_to_send() + self.transport.write(b"".join(output)) + + elif message_type == "websocket.close" and not self.transport.is_closing(): + message = cast(WebSocketCloseEvent, message) + code = message.get("code", 1000) + reason = message.get("reason", "") or "" + self.queue.put_nowait({"type": "websocket.disconnect", "code": code, "reason": reason}) + self.conn.send_close(code, reason) + output = self.conn.data_to_send() + self.transport.write(b"".join(output)) + self.close_sent = True + self.transport.close() + else: + msg = "Expected ASGI message 'websocket.send' or 'websocket.close', but got '%s'." + raise RuntimeError(msg % message_type) + except InvalidState: + raise ClientDisconnected() + elif self.initial_response is not None: + if message_type == "websocket.http.response.body": + message = cast(WebSocketResponseBodyEvent, message) + body = self.initial_response[2] + message["body"] + self.initial_response = self.initial_response[:2] + (body,) + if not message.get("more_body", False): + response = self.conn.reject(self.initial_response[0], body.decode()) + response.headers.update(self.initial_response[1]) + self.queue.put_nowait({"type": "websocket.disconnect", "code": 1006}) + self.conn.send_response(response) + output = self.conn.data_to_send() + self.close_sent = True + self.transport.write(b"".join(output)) + self.transport.close() + else: # pragma: no cover + msg = "Expected ASGI message 'websocket.http.response.body' but got '%s'." + raise RuntimeError(msg % message_type) + + else: + msg = "Unexpected ASGI message '%s', after sending 'websocket.close'." + raise RuntimeError(msg % message_type) + + async def receive(self) -> ASGIReceiveEvent: + message = await self.queue.get() + if self.read_paused and self.queue.empty(): + self.read_paused = False + self.transport.resume_reading() + return message diff --git a/venv/Lib/site-packages/uvicorn/protocols/websockets/wsproto_impl.py b/venv/Lib/site-packages/uvicorn/protocols/websockets/wsproto_impl.py new file mode 100644 index 00000000..14f50110 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/protocols/websockets/wsproto_impl.py @@ -0,0 +1,377 @@ +from __future__ import annotations + +import asyncio +import logging +from typing import Any, Literal, cast +from urllib.parse import unquote + +import wsproto +from wsproto import ConnectionType, events +from wsproto.connection import ConnectionState +from wsproto.extensions import Extension, PerMessageDeflate +from wsproto.utilities import LocalProtocolError, RemoteProtocolError + +from uvicorn._types import ( + ASGI3Application, + ASGISendEvent, + WebSocketAcceptEvent, + WebSocketCloseEvent, + WebSocketEvent, + WebSocketResponseBodyEvent, + WebSocketResponseStartEvent, + WebSocketScope, + WebSocketSendEvent, +) +from uvicorn.config import Config +from uvicorn.logging import TRACE_LOG_LEVEL +from uvicorn.protocols.utils import ( + ClientDisconnected, + get_client_addr, + get_local_addr, + get_path_with_query_string, + get_remote_addr, + is_ssl, +) +from uvicorn.server import ServerState + + +class WSProtocol(asyncio.Protocol): + def __init__( + self, + config: Config, + server_state: ServerState, + app_state: dict[str, Any], + _loop: asyncio.AbstractEventLoop | None = None, + ) -> None: + if not config.loaded: + config.load() # pragma: full coverage + + self.config = config + self.app = cast(ASGI3Application, config.loaded_app) + self.loop = _loop or asyncio.get_event_loop() + self.logger = logging.getLogger("uvicorn.error") + self.root_path = config.root_path + self.app_state = app_state + + # Shared server state + self.connections = server_state.connections + self.tasks = server_state.tasks + self.default_headers = server_state.default_headers + + # Connection state + self.transport: asyncio.Transport = None # type: ignore[assignment] + self.server: tuple[str, int] | None = None + self.client: tuple[str, int] | None = None + self.scheme: Literal["wss", "ws"] = None # type: ignore[assignment] + + # WebSocket state + self.queue: asyncio.Queue[WebSocketEvent] = asyncio.Queue() + self.handshake_complete = False + self.close_sent = False + + # Rejection state + self.response_started = False + + self.conn = wsproto.WSConnection(connection_type=ConnectionType.SERVER) + + self.read_paused = False + self.writable = asyncio.Event() + self.writable.set() + + # Buffers + self.bytes = b"" + self.text = "" + + # Protocol interface + + def connection_made( # type: ignore[override] + self, transport: asyncio.Transport + ) -> None: + self.connections.add(self) + self.transport = transport + self.server = get_local_addr(transport) + self.client = get_remote_addr(transport) + self.scheme = "wss" if is_ssl(transport) else "ws" + + if self.logger.level <= TRACE_LOG_LEVEL: + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sWebSocket connection made", prefix) + + def connection_lost(self, exc: Exception | None) -> None: + code = 1005 if self.handshake_complete else 1006 + self.queue.put_nowait({"type": "websocket.disconnect", "code": code}) + self.connections.remove(self) + + if self.logger.level <= TRACE_LOG_LEVEL: + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sWebSocket connection lost", prefix) + + self.handshake_complete = True + if exc is None: + self.transport.close() + + def eof_received(self) -> None: + pass + + def data_received(self, data: bytes) -> None: + try: + self.conn.receive_data(data) + except RemoteProtocolError as err: + # TODO: Remove `type: ignore` when wsproto fixes the type annotation. + self.transport.write(self.conn.send(err.event_hint)) # type: ignore[arg-type] # noqa: E501 + self.transport.close() + else: + self.handle_events() + + def handle_events(self) -> None: + for event in self.conn.events(): + if isinstance(event, events.Request): + self.handle_connect(event) + elif isinstance(event, events.TextMessage): + self.handle_text(event) + elif isinstance(event, events.BytesMessage): + self.handle_bytes(event) + elif isinstance(event, events.CloseConnection): + self.handle_close(event) + elif isinstance(event, events.Ping): + self.handle_ping(event) + + def pause_writing(self) -> None: + """ + Called by the transport when the write buffer exceeds the high water mark. + """ + self.writable.clear() # pragma: full coverage + + def resume_writing(self) -> None: + """ + Called by the transport when the write buffer drops below the low water mark. + """ + self.writable.set() # pragma: full coverage + + def shutdown(self) -> None: + if self.handshake_complete: + self.queue.put_nowait({"type": "websocket.disconnect", "code": 1012}) + output = self.conn.send(wsproto.events.CloseConnection(code=1012)) + self.transport.write(output) + else: + self.send_500_response() + self.transport.close() + + def on_task_complete(self, task: asyncio.Task[None]) -> None: + self.tasks.discard(task) + + # Event handlers + + def handle_connect(self, event: events.Request) -> None: + headers = [(b"host", event.host.encode())] + headers += [(key.lower(), value) for key, value in event.extra_headers] + raw_path, _, query_string = event.target.partition("?") + path = unquote(raw_path) + full_path = self.root_path + path + full_raw_path = self.root_path.encode("ascii") + raw_path.encode("ascii") + self.scope: WebSocketScope = { + "type": "websocket", + "asgi": {"version": self.config.asgi_version, "spec_version": "2.4"}, + "http_version": "1.1", + "scheme": self.scheme, + "server": self.server, + "client": self.client, + "root_path": self.root_path, + "path": full_path, + "raw_path": full_raw_path, + "query_string": query_string.encode("ascii"), + "headers": headers, + "subprotocols": event.subprotocols, + "state": self.app_state.copy(), + "extensions": {"websocket.http.response": {}}, + } + self.queue.put_nowait({"type": "websocket.connect"}) + task = self.loop.create_task(self.run_asgi()) + task.add_done_callback(self.on_task_complete) + self.tasks.add(task) + + def handle_text(self, event: events.TextMessage) -> None: + self.text += event.data + if event.message_finished: + self.queue.put_nowait({"type": "websocket.receive", "text": self.text}) + self.text = "" + if not self.read_paused: + self.read_paused = True + self.transport.pause_reading() + + def handle_bytes(self, event: events.BytesMessage) -> None: + self.bytes += event.data + # todo: we may want to guard the size of self.bytes and self.text + if event.message_finished: + self.queue.put_nowait({"type": "websocket.receive", "bytes": self.bytes}) + self.bytes = b"" + if not self.read_paused: + self.read_paused = True + self.transport.pause_reading() + + def handle_close(self, event: events.CloseConnection) -> None: + if self.conn.state == ConnectionState.REMOTE_CLOSING: + self.transport.write(self.conn.send(event.response())) + self.queue.put_nowait({"type": "websocket.disconnect", "code": event.code, "reason": event.reason}) + self.transport.close() + + def handle_ping(self, event: events.Ping) -> None: + self.transport.write(self.conn.send(event.response())) + + def send_500_response(self) -> None: + if self.response_started or self.handshake_complete: + return # we cannot send responses anymore + headers: list[tuple[bytes, bytes]] = [ + (b"content-type", b"text/plain; charset=utf-8"), + (b"connection", b"close"), + (b"content-length", b"21"), + ] + output = self.conn.send(wsproto.events.RejectConnection(status_code=500, headers=headers, has_body=True)) + output += self.conn.send(wsproto.events.RejectData(data=b"Internal Server Error")) + self.transport.write(output) + + async def run_asgi(self) -> None: + try: + result = await self.app(self.scope, self.receive, self.send) # type: ignore[func-returns-value] + except ClientDisconnected: + self.transport.close() # pragma: full coverage + except BaseException: + self.logger.exception("Exception in ASGI application\n") + self.send_500_response() + self.transport.close() + else: + if not self.handshake_complete: + self.logger.error("ASGI callable returned without completing handshake.") + self.send_500_response() + self.transport.close() + elif result is not None: + self.logger.error("ASGI callable should return None, but returned '%s'.", result) + self.transport.close() + + async def send(self, message: ASGISendEvent) -> None: + await self.writable.wait() + + message_type = message["type"] + + if not self.handshake_complete: + if message_type == "websocket.accept": + message = cast(WebSocketAcceptEvent, message) + self.logger.info( + '%s - "WebSocket %s" [accepted]', + get_client_addr(self.scope), + get_path_with_query_string(self.scope), + ) + subprotocol = message.get("subprotocol") + extra_headers = self.default_headers + list(message.get("headers", [])) + extensions: list[Extension] = [] + if self.config.ws_per_message_deflate: + extensions.append(PerMessageDeflate()) + if not self.transport.is_closing(): + self.handshake_complete = True + output = self.conn.send( + wsproto.events.AcceptConnection( + subprotocol=subprotocol, + extensions=extensions, + extra_headers=extra_headers, + ) + ) + self.transport.write(output) + + elif message_type == "websocket.close": + self.queue.put_nowait({"type": "websocket.disconnect", "code": 1006}) + self.logger.info( + '%s - "WebSocket %s" 403', + get_client_addr(self.scope), + get_path_with_query_string(self.scope), + ) + self.handshake_complete = True + self.close_sent = True + event = events.RejectConnection(status_code=403, headers=[]) + output = self.conn.send(event) + self.transport.write(output) + self.transport.close() + + elif message_type == "websocket.http.response.start": + message = cast(WebSocketResponseStartEvent, message) + # ensure status code is in the valid range + if not (100 <= message["status"] < 600): + msg = "Invalid HTTP status code '%d' in response." + raise RuntimeError(msg % message["status"]) + self.logger.info( + '%s - "WebSocket %s" %d', + get_client_addr(self.scope), + get_path_with_query_string(self.scope), + message["status"], + ) + self.handshake_complete = True + event = events.RejectConnection( + status_code=message["status"], + headers=list(message["headers"]), + has_body=True, + ) + output = self.conn.send(event) + self.transport.write(output) + self.response_started = True + + else: + msg = ( + "Expected ASGI message 'websocket.accept', 'websocket.close' " + "or 'websocket.http.response.start' " + "but got '%s'." + ) + raise RuntimeError(msg % message_type) + + elif not self.close_sent and not self.response_started: + try: + if message_type == "websocket.send": + message = cast(WebSocketSendEvent, message) + bytes_data = message.get("bytes") + text_data = message.get("text") + data = text_data if bytes_data is None else bytes_data + output = self.conn.send(wsproto.events.Message(data=data)) # type: ignore + if not self.transport.is_closing(): + self.transport.write(output) + + elif message_type == "websocket.close": + message = cast(WebSocketCloseEvent, message) + self.close_sent = True + code = message.get("code", 1000) + reason = message.get("reason", "") or "" + self.queue.put_nowait({"type": "websocket.disconnect", "code": code, "reason": reason}) + output = self.conn.send(wsproto.events.CloseConnection(code=code, reason=reason)) + if not self.transport.is_closing(): + self.transport.write(output) + self.transport.close() + + else: + msg = "Expected ASGI message 'websocket.send' or 'websocket.close', but got '%s'." + raise RuntimeError(msg % message_type) + except LocalProtocolError as exc: + raise ClientDisconnected from exc + elif self.response_started: + if message_type == "websocket.http.response.body": + message = cast("WebSocketResponseBodyEvent", message) + body_finished = not message.get("more_body", False) + reject_data = events.RejectData(data=message["body"], body_finished=body_finished) + output = self.conn.send(reject_data) + self.transport.write(output) + + if body_finished: + self.queue.put_nowait({"type": "websocket.disconnect", "code": 1006}) + self.close_sent = True + self.transport.close() + + else: + msg = "Expected ASGI message 'websocket.http.response.body' but got '%s'." + raise RuntimeError(msg % message_type) + + else: + msg = "Unexpected ASGI message '%s', after sending 'websocket.close'." + raise RuntimeError(msg % message_type) + + async def receive(self) -> WebSocketEvent: + message = await self.queue.get() + if self.read_paused and self.queue.empty(): + self.read_paused = False + self.transport.resume_reading() + return message diff --git a/venv/Lib/site-packages/uvicorn/py.typed b/venv/Lib/site-packages/uvicorn/py.typed new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/py.typed @@ -0,0 +1 @@ + diff --git a/venv/Lib/site-packages/uvicorn/server.py b/venv/Lib/site-packages/uvicorn/server.py new file mode 100644 index 00000000..c00a23eb --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/server.py @@ -0,0 +1,338 @@ +from __future__ import annotations + +import asyncio +import contextlib +import logging +import os +import platform +import signal +import socket +import sys +import threading +import time +from collections.abc import Generator, Sequence +from email.utils import formatdate +from types import FrameType +from typing import TYPE_CHECKING, Union + +import click + +from uvicorn.config import Config + +if TYPE_CHECKING: + from uvicorn.protocols.http.h11_impl import H11Protocol + from uvicorn.protocols.http.httptools_impl import HttpToolsProtocol + from uvicorn.protocols.websockets.websockets_impl import WebSocketProtocol + from uvicorn.protocols.websockets.websockets_sansio_impl import WebSocketsSansIOProtocol + from uvicorn.protocols.websockets.wsproto_impl import WSProtocol + + Protocols = Union[H11Protocol, HttpToolsProtocol, WSProtocol, WebSocketProtocol, WebSocketsSansIOProtocol] + +HANDLED_SIGNALS = ( + signal.SIGINT, # Unix signal 2. Sent by Ctrl+C. + signal.SIGTERM, # Unix signal 15. Sent by `kill `. +) +if sys.platform == "win32": # pragma: py-not-win32 + HANDLED_SIGNALS += (signal.SIGBREAK,) # Windows signal 21. Sent by Ctrl+Break. + +logger = logging.getLogger("uvicorn.error") + + +class ServerState: + """ + Shared servers state that is available between all protocol instances. + """ + + def __init__(self) -> None: + self.total_requests = 0 + self.connections: set[Protocols] = set() + self.tasks: set[asyncio.Task[None]] = set() + self.default_headers: list[tuple[bytes, bytes]] = [] + + +class Server: + def __init__(self, config: Config) -> None: + self.config = config + self.server_state = ServerState() + + self.started = False + self.should_exit = False + self.force_exit = False + self.last_notified = 0.0 + + self._captured_signals: list[int] = [] + + def run(self, sockets: list[socket.socket] | None = None) -> None: + self.config.setup_event_loop() + return asyncio.run(self.serve(sockets=sockets)) + + async def serve(self, sockets: list[socket.socket] | None = None) -> None: + with self.capture_signals(): + await self._serve(sockets) + + async def _serve(self, sockets: list[socket.socket] | None = None) -> None: + process_id = os.getpid() + + config = self.config + if not config.loaded: + config.load() + + self.lifespan = config.lifespan_class(config) + + message = "Started server process [%d]" + color_message = "Started server process [" + click.style("%d", fg="cyan") + "]" + logger.info(message, process_id, extra={"color_message": color_message}) + + await self.startup(sockets=sockets) + if self.should_exit: + return + await self.main_loop() + await self.shutdown(sockets=sockets) + + message = "Finished server process [%d]" + color_message = "Finished server process [" + click.style("%d", fg="cyan") + "]" + logger.info(message, process_id, extra={"color_message": color_message}) + + async def startup(self, sockets: list[socket.socket] | None = None) -> None: + await self.lifespan.startup() + if self.lifespan.should_exit: + self.should_exit = True + return + + config = self.config + + def create_protocol( + _loop: asyncio.AbstractEventLoop | None = None, + ) -> asyncio.Protocol: + return config.http_protocol_class( # type: ignore[call-arg] + config=config, + server_state=self.server_state, + app_state=self.lifespan.state, + _loop=_loop, + ) + + loop = asyncio.get_running_loop() + + listeners: Sequence[socket.SocketType] + if sockets is not None: # pragma: full coverage + # Explicitly passed a list of open sockets. + # We use this when the server is run from a Gunicorn worker. + + def _share_socket( + sock: socket.SocketType, + ) -> socket.SocketType: # pragma py-not-win32 + # Windows requires the socket be explicitly shared across + # multiple workers (processes). + from socket import fromshare # type: ignore[attr-defined] + + sock_data = sock.share(os.getpid()) # type: ignore[attr-defined] + return fromshare(sock_data) + + self.servers: list[asyncio.base_events.Server] = [] + for sock in sockets: + is_windows = platform.system() == "Windows" + if config.workers > 1 and is_windows: # pragma: py-not-win32 + sock = _share_socket(sock) # type: ignore[assignment] + server = await loop.create_server(create_protocol, sock=sock, ssl=config.ssl, backlog=config.backlog) + self.servers.append(server) + listeners = sockets + + elif config.fd is not None: # pragma: py-win32 + # Use an existing socket, from a file descriptor. + sock = socket.fromfd(config.fd, socket.AF_UNIX, socket.SOCK_STREAM) + server = await loop.create_server(create_protocol, sock=sock, ssl=config.ssl, backlog=config.backlog) + assert server.sockets is not None # mypy + listeners = server.sockets + self.servers = [server] + + elif config.uds is not None: # pragma: py-win32 + # Create a socket using UNIX domain socket. + uds_perms = 0o666 + if os.path.exists(config.uds): + uds_perms = os.stat(config.uds).st_mode # pragma: full coverage + server = await loop.create_unix_server( + create_protocol, path=config.uds, ssl=config.ssl, backlog=config.backlog + ) + os.chmod(config.uds, uds_perms) + assert server.sockets is not None # mypy + listeners = server.sockets + self.servers = [server] + + else: + # Standard case. Create a socket from a host/port pair. + try: + server = await loop.create_server( + create_protocol, + host=config.host, + port=config.port, + ssl=config.ssl, + backlog=config.backlog, + ) + except OSError as exc: + logger.error(exc) + await self.lifespan.shutdown() + sys.exit(1) + + assert server.sockets is not None + listeners = server.sockets + self.servers = [server] + + if sockets is None: + self._log_started_message(listeners) + else: + # We're most likely running multiple workers, so a message has already been + # logged by `config.bind_socket()`. + pass # pragma: full coverage + + self.started = True + + def _log_started_message(self, listeners: Sequence[socket.SocketType]) -> None: + config = self.config + + if config.fd is not None: # pragma: py-win32 + sock = listeners[0] + logger.info( + "Uvicorn running on socket %s (Press CTRL+C to quit)", + sock.getsockname(), + ) + + elif config.uds is not None: # pragma: py-win32 + logger.info("Uvicorn running on unix socket %s (Press CTRL+C to quit)", config.uds) + + else: + addr_format = "%s://%s:%d" + host = "0.0.0.0" if config.host is None else config.host + if ":" in host: + # It's an IPv6 address. + addr_format = "%s://[%s]:%d" + + port = config.port + if port == 0: + port = listeners[0].getsockname()[1] + + protocol_name = "https" if config.ssl else "http" + message = f"Uvicorn running on {addr_format} (Press CTRL+C to quit)" + color_message = "Uvicorn running on " + click.style(addr_format, bold=True) + " (Press CTRL+C to quit)" + logger.info( + message, + protocol_name, + host, + port, + extra={"color_message": color_message}, + ) + + async def main_loop(self) -> None: + counter = 0 + should_exit = await self.on_tick(counter) + while not should_exit: + counter += 1 + counter = counter % 864000 + await asyncio.sleep(0.1) + should_exit = await self.on_tick(counter) + + async def on_tick(self, counter: int) -> bool: + # Update the default headers, once per second. + if counter % 10 == 0: + current_time = time.time() + current_date = formatdate(current_time, usegmt=True).encode() + + if self.config.date_header: + date_header = [(b"date", current_date)] + else: + date_header = [] + + self.server_state.default_headers = date_header + self.config.encoded_headers + + # Callback to `callback_notify` once every `timeout_notify` seconds. + if self.config.callback_notify is not None: + if current_time - self.last_notified > self.config.timeout_notify: # pragma: full coverage + self.last_notified = current_time + await self.config.callback_notify() + + # Determine if we should exit. + if self.should_exit: + return True + + max_requests = self.config.limit_max_requests + if max_requests is not None and self.server_state.total_requests >= max_requests: + logger.warning(f"Maximum request limit of {max_requests} exceeded. Terminating process.") + return True + + return False + + async def shutdown(self, sockets: list[socket.socket] | None = None) -> None: + logger.info("Shutting down") + + # Stop accepting new connections. + for server in self.servers: + server.close() + for sock in sockets or []: + sock.close() # pragma: full coverage + + # Request shutdown on all existing connections. + for connection in list(self.server_state.connections): + connection.shutdown() + await asyncio.sleep(0.1) + + # When 3.10 is not supported anymore, use `async with asyncio.timeout(...):`. + try: + await asyncio.wait_for( + self._wait_tasks_to_complete(), + timeout=self.config.timeout_graceful_shutdown, + ) + except asyncio.TimeoutError: + logger.error( + "Cancel %s running task(s), timeout graceful shutdown exceeded", + len(self.server_state.tasks), + ) + for t in self.server_state.tasks: + t.cancel(msg="Task cancelled, timeout graceful shutdown exceeded") + + # Send the lifespan shutdown event, and wait for application shutdown. + if not self.force_exit: + await self.lifespan.shutdown() + + async def _wait_tasks_to_complete(self) -> None: + # Wait for existing connections to finish sending responses. + if self.server_state.connections and not self.force_exit: + msg = "Waiting for connections to close. (CTRL+C to force quit)" + logger.info(msg) + while self.server_state.connections and not self.force_exit: + await asyncio.sleep(0.1) + + # Wait for existing tasks to complete. + if self.server_state.tasks and not self.force_exit: + msg = "Waiting for background tasks to complete. (CTRL+C to force quit)" + logger.info(msg) + while self.server_state.tasks and not self.force_exit: + await asyncio.sleep(0.1) + + for server in self.servers: + await server.wait_closed() + + @contextlib.contextmanager + def capture_signals(self) -> Generator[None, None, None]: + # Signals can only be listened to from the main thread. + if threading.current_thread() is not threading.main_thread(): + yield + return + # always use signal.signal, even if loop.add_signal_handler is available + # this allows to restore previous signal handlers later on + original_handlers = {sig: signal.signal(sig, self.handle_exit) for sig in HANDLED_SIGNALS} + try: + yield + finally: + for sig, handler in original_handlers.items(): + signal.signal(sig, handler) + # If we did gracefully shut down due to a signal, try to + # trigger the expected behaviour now; multiple signals would be + # done LIFO, see https://stackoverflow.com/questions/48434964 + for captured_signal in reversed(self._captured_signals): + signal.raise_signal(captured_signal) + + def handle_exit(self, sig: int, frame: FrameType | None) -> None: + self._captured_signals.append(sig) + if self.should_exit and sig == signal.SIGINT: + self.force_exit = True # pragma: full coverage + else: + self.should_exit = True diff --git a/venv/Lib/site-packages/uvicorn/supervisors/__init__.py b/venv/Lib/site-packages/uvicorn/supervisors/__init__.py new file mode 100644 index 00000000..cfceb6b9 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/supervisors/__init__.py @@ -0,0 +1,16 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from uvicorn.supervisors.basereload import BaseReload +from uvicorn.supervisors.multiprocess import Multiprocess + +if TYPE_CHECKING: + ChangeReload: type[BaseReload] +else: + try: + from uvicorn.supervisors.watchfilesreload import WatchFilesReload as ChangeReload + except ImportError: # pragma: no cover + from uvicorn.supervisors.statreload import StatReload as ChangeReload + +__all__ = ["Multiprocess", "ChangeReload"] diff --git a/venv/Lib/site-packages/uvicorn/supervisors/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/supervisors/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 00000000..9f390f6b Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/supervisors/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/supervisors/__pycache__/basereload.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/supervisors/__pycache__/basereload.cpython-312.pyc new file mode 100644 index 00000000..fad5841a Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/supervisors/__pycache__/basereload.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/supervisors/__pycache__/multiprocess.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/supervisors/__pycache__/multiprocess.cpython-312.pyc new file mode 100644 index 00000000..75190a29 Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/supervisors/__pycache__/multiprocess.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/supervisors/__pycache__/statreload.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/supervisors/__pycache__/statreload.cpython-312.pyc new file mode 100644 index 00000000..12e06f89 Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/supervisors/__pycache__/statreload.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/supervisors/__pycache__/watchfilesreload.cpython-312.pyc b/venv/Lib/site-packages/uvicorn/supervisors/__pycache__/watchfilesreload.cpython-312.pyc new file mode 100644 index 00000000..1605fb16 Binary files /dev/null and b/venv/Lib/site-packages/uvicorn/supervisors/__pycache__/watchfilesreload.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/uvicorn/supervisors/basereload.py b/venv/Lib/site-packages/uvicorn/supervisors/basereload.py new file mode 100644 index 00000000..eed99923 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/supervisors/basereload.py @@ -0,0 +1,126 @@ +from __future__ import annotations + +import logging +import os +import signal +import sys +import threading +from collections.abc import Iterator +from pathlib import Path +from socket import socket +from types import FrameType +from typing import Callable + +import click + +from uvicorn._subprocess import get_subprocess +from uvicorn.config import Config + +HANDLED_SIGNALS = ( + signal.SIGINT, # Unix signal 2. Sent by Ctrl+C. + signal.SIGTERM, # Unix signal 15. Sent by `kill `. +) + +logger = logging.getLogger("uvicorn.error") + + +class BaseReload: + def __init__( + self, + config: Config, + target: Callable[[list[socket] | None], None], + sockets: list[socket], + ) -> None: + self.config = config + self.target = target + self.sockets = sockets + self.should_exit = threading.Event() + self.pid = os.getpid() + self.is_restarting = False + self.reloader_name: str | None = None + + def signal_handler(self, sig: int, frame: FrameType | None) -> None: # pragma: full coverage + """ + A signal handler that is registered with the parent process. + """ + if sys.platform == "win32" and self.is_restarting: + self.is_restarting = False + else: + self.should_exit.set() + + def run(self) -> None: + self.startup() + for changes in self: + if changes: + logger.warning( + "%s detected changes in %s. Reloading...", + self.reloader_name, + ", ".join(map(_display_path, changes)), + ) + self.restart() + + self.shutdown() + + def pause(self) -> None: + if self.should_exit.wait(self.config.reload_delay): + raise StopIteration() + + def __iter__(self) -> Iterator[list[Path] | None]: + return self + + def __next__(self) -> list[Path] | None: + return self.should_restart() + + def startup(self) -> None: + message = f"Started reloader process [{self.pid}] using {self.reloader_name}" + color_message = "Started reloader process [{}] using {}".format( + click.style(str(self.pid), fg="cyan", bold=True), + click.style(str(self.reloader_name), fg="cyan", bold=True), + ) + logger.info(message, extra={"color_message": color_message}) + + for sig in HANDLED_SIGNALS: + signal.signal(sig, self.signal_handler) + + self.process = get_subprocess(config=self.config, target=self.target, sockets=self.sockets) + self.process.start() + + def restart(self) -> None: + if sys.platform == "win32": # pragma: py-not-win32 + self.is_restarting = True + assert self.process.pid is not None + os.kill(self.process.pid, signal.CTRL_C_EVENT) + + # This is a workaround to ensure the Ctrl+C event is processed + sys.stdout.write(" ") # This has to be a non-empty string + sys.stdout.flush() + else: # pragma: py-win32 + self.process.terminate() + self.process.join() + + self.process = get_subprocess(config=self.config, target=self.target, sockets=self.sockets) + self.process.start() + + def shutdown(self) -> None: + if sys.platform == "win32": + self.should_exit.set() # pragma: py-not-win32 + else: + self.process.terminate() # pragma: py-win32 + self.process.join() + + for sock in self.sockets: + sock.close() + + message = f"Stopping reloader process [{str(self.pid)}]" + color_message = "Stopping reloader process [{}]".format(click.style(str(self.pid), fg="cyan", bold=True)) + logger.info(message, extra={"color_message": color_message}) + + def should_restart(self) -> list[Path] | None: + raise NotImplementedError("Reload strategies should override should_restart()") + + +def _display_path(path: Path) -> str: + try: + return f"'{path.relative_to(Path.cwd())}'" + except ValueError: + return f"'{path}'" diff --git a/venv/Lib/site-packages/uvicorn/supervisors/multiprocess.py b/venv/Lib/site-packages/uvicorn/supervisors/multiprocess.py new file mode 100644 index 00000000..e198fe78 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/supervisors/multiprocess.py @@ -0,0 +1,222 @@ +from __future__ import annotations + +import logging +import os +import signal +import threading +from multiprocessing import Pipe +from socket import socket +from typing import Any, Callable + +import click + +from uvicorn._subprocess import get_subprocess +from uvicorn.config import Config + +SIGNALS = { + getattr(signal, f"SIG{x}"): x + for x in "INT TERM BREAK HUP QUIT TTIN TTOU USR1 USR2 WINCH".split() + if hasattr(signal, f"SIG{x}") +} + +logger = logging.getLogger("uvicorn.error") + + +class Process: + def __init__( + self, + config: Config, + target: Callable[[list[socket] | None], None], + sockets: list[socket], + ) -> None: + self.real_target = target + + self.parent_conn, self.child_conn = Pipe() + self.process = get_subprocess(config, self.target, sockets) + + def ping(self, timeout: float = 5) -> bool: + self.parent_conn.send(b"ping") + if self.parent_conn.poll(timeout): + self.parent_conn.recv() + return True + return False + + def pong(self) -> None: + self.child_conn.recv() + self.child_conn.send(b"pong") + + def always_pong(self) -> None: + while True: + self.pong() + + def target(self, sockets: list[socket] | None = None) -> Any: # pragma: no cover + if os.name == "nt": # pragma: py-not-win32 + # Windows doesn't support SIGTERM, so we use SIGBREAK instead. + # And then we raise SIGTERM when SIGBREAK is received. + # https://learn.microsoft.com/zh-cn/cpp/c-runtime-library/reference/signal?view=msvc-170 + signal.signal( + signal.SIGBREAK, # type: ignore[attr-defined] + lambda sig, frame: signal.raise_signal(signal.SIGTERM), + ) + + threading.Thread(target=self.always_pong, daemon=True).start() + return self.real_target(sockets) + + def is_alive(self, timeout: float = 5) -> bool: + if not self.process.is_alive(): + return False # pragma: full coverage + + return self.ping(timeout) + + def start(self) -> None: + self.process.start() + + def terminate(self) -> None: + if self.process.exitcode is None: # Process is still running + assert self.process.pid is not None + if os.name == "nt": # pragma: py-not-win32 + # Windows doesn't support SIGTERM. + # So send SIGBREAK, and then in process raise SIGTERM. + os.kill(self.process.pid, signal.CTRL_BREAK_EVENT) # type: ignore[attr-defined] + else: + os.kill(self.process.pid, signal.SIGTERM) + logger.info(f"Terminated child process [{self.process.pid}]") + + self.parent_conn.close() + self.child_conn.close() + + def kill(self) -> None: + # In Windows, the method will call `TerminateProcess` to kill the process. + # In Unix, the method will send SIGKILL to the process. + self.process.kill() + + def join(self) -> None: + logger.info(f"Waiting for child process [{self.process.pid}]") + self.process.join() + + @property + def pid(self) -> int | None: + return self.process.pid + + +class Multiprocess: + def __init__( + self, + config: Config, + target: Callable[[list[socket] | None], None], + sockets: list[socket], + ) -> None: + self.config = config + self.target = target + self.sockets = sockets + + self.processes_num = config.workers + self.processes: list[Process] = [] + + self.should_exit = threading.Event() + + self.signal_queue: list[int] = [] + for sig in SIGNALS: + signal.signal(sig, lambda sig, frame: self.signal_queue.append(sig)) + + def init_processes(self) -> None: + for _ in range(self.processes_num): + process = Process(self.config, self.target, self.sockets) + process.start() + self.processes.append(process) + + def terminate_all(self) -> None: + for process in self.processes: + process.terminate() + + def join_all(self) -> None: + for process in self.processes: + process.join() + + def restart_all(self) -> None: + for idx, process in enumerate(self.processes): + process.terminate() + process.join() + new_process = Process(self.config, self.target, self.sockets) + new_process.start() + self.processes[idx] = new_process + + def run(self) -> None: + message = f"Started parent process [{os.getpid()}]" + color_message = "Started parent process [{}]".format(click.style(str(os.getpid()), fg="cyan", bold=True)) + logger.info(message, extra={"color_message": color_message}) + + self.init_processes() + + while not self.should_exit.wait(0.5): + self.handle_signals() + self.keep_subprocess_alive() + + self.terminate_all() + self.join_all() + + message = f"Stopping parent process [{os.getpid()}]" + color_message = "Stopping parent process [{}]".format(click.style(str(os.getpid()), fg="cyan", bold=True)) + logger.info(message, extra={"color_message": color_message}) + + def keep_subprocess_alive(self) -> None: + if self.should_exit.is_set(): + return # parent process is exiting, no need to keep subprocess alive + + for idx, process in enumerate(self.processes): + if process.is_alive(): + continue + + process.kill() # process is hung, kill it + process.join() + + if self.should_exit.is_set(): + return # pragma: full coverage + + logger.info(f"Child process [{process.pid}] died") + process = Process(self.config, self.target, self.sockets) + process.start() + self.processes[idx] = process + + def handle_signals(self) -> None: + for sig in tuple(self.signal_queue): + self.signal_queue.remove(sig) + sig_name = SIGNALS[sig] + sig_handler = getattr(self, f"handle_{sig_name.lower()}", None) + if sig_handler is not None: + sig_handler() + else: # pragma: no cover + logger.debug(f"Received signal {sig_name}, but no handler is defined for it.") + + def handle_int(self) -> None: + logger.info("Received SIGINT, exiting.") + self.should_exit.set() + + def handle_term(self) -> None: + logger.info("Received SIGTERM, exiting.") + self.should_exit.set() + + def handle_break(self) -> None: # pragma: py-not-win32 + logger.info("Received SIGBREAK, exiting.") + self.should_exit.set() + + def handle_hup(self) -> None: # pragma: py-win32 + logger.info("Received SIGHUP, restarting processes.") + self.restart_all() + + def handle_ttin(self) -> None: # pragma: py-win32 + logger.info("Received SIGTTIN, increasing the number of processes.") + self.processes_num += 1 + process = Process(self.config, self.target, self.sockets) + process.start() + self.processes.append(process) + + def handle_ttou(self) -> None: # pragma: py-win32 + logger.info("Received SIGTTOU, decreasing number of processes.") + if self.processes_num <= 1: + logger.info("Already reached one process, cannot decrease the number of processes anymore.") + return + self.processes_num -= 1 + process = self.processes.pop() + process.terminate() + process.join() diff --git a/venv/Lib/site-packages/uvicorn/supervisors/statreload.py b/venv/Lib/site-packages/uvicorn/supervisors/statreload.py new file mode 100644 index 00000000..d9cbd525 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/supervisors/statreload.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +import logging +from collections.abc import Iterator +from pathlib import Path +from socket import socket +from typing import Callable + +from uvicorn.config import Config +from uvicorn.supervisors.basereload import BaseReload + +logger = logging.getLogger("uvicorn.error") + + +class StatReload(BaseReload): + def __init__( + self, + config: Config, + target: Callable[[list[socket] | None], None], + sockets: list[socket], + ) -> None: + super().__init__(config, target, sockets) + self.reloader_name = "StatReload" + self.mtimes: dict[Path, float] = {} + + if config.reload_excludes or config.reload_includes: + logger.warning("--reload-include and --reload-exclude have no effect unless watchfiles is installed.") + + def should_restart(self) -> list[Path] | None: + self.pause() + + for file in self.iter_py_files(): + try: + mtime = file.stat().st_mtime + except OSError: # pragma: nocover + continue + + old_time = self.mtimes.get(file) + if old_time is None: + self.mtimes[file] = mtime + continue + elif mtime > old_time: + return [file] + return None + + def restart(self) -> None: + self.mtimes = {} + return super().restart() + + def iter_py_files(self) -> Iterator[Path]: + for reload_dir in self.config.reload_dirs: + for path in list(reload_dir.rglob("*.py")): + yield path.resolve() diff --git a/venv/Lib/site-packages/uvicorn/supervisors/watchfilesreload.py b/venv/Lib/site-packages/uvicorn/supervisors/watchfilesreload.py new file mode 100644 index 00000000..c13dc745 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/supervisors/watchfilesreload.py @@ -0,0 +1,85 @@ +from __future__ import annotations + +from pathlib import Path +from socket import socket +from typing import Callable + +from watchfiles import watch + +from uvicorn.config import Config +from uvicorn.supervisors.basereload import BaseReload + + +class FileFilter: + def __init__(self, config: Config): + default_includes = ["*.py"] + self.includes = [default for default in default_includes if default not in config.reload_excludes] + self.includes.extend(config.reload_includes) + self.includes = list(set(self.includes)) + + default_excludes = [".*", ".py[cod]", ".sw.*", "~*"] + self.excludes = [default for default in default_excludes if default not in config.reload_includes] + self.exclude_dirs = [] + for e in config.reload_excludes: + p = Path(e) + try: + is_dir = p.is_dir() + except OSError: # pragma: no cover + # gets raised on Windows for values like "*.py" + is_dir = False + + if is_dir: + self.exclude_dirs.append(p) + else: + self.excludes.append(e) # pragma: full coverage + self.excludes = list(set(self.excludes)) + + def __call__(self, path: Path) -> bool: + for include_pattern in self.includes: + if path.match(include_pattern): + if str(path).endswith(include_pattern): + return True # pragma: full coverage + + for exclude_dir in self.exclude_dirs: + if exclude_dir in path.parents: + return False + + for exclude_pattern in self.excludes: + if path.match(exclude_pattern): + return False # pragma: full coverage + + return True + return False + + +class WatchFilesReload(BaseReload): + def __init__( + self, + config: Config, + target: Callable[[list[socket] | None], None], + sockets: list[socket], + ) -> None: + super().__init__(config, target, sockets) + self.reloader_name = "WatchFiles" + self.reload_dirs = [] + for directory in config.reload_dirs: + self.reload_dirs.append(directory) + + self.watch_filter = FileFilter(config) + self.watcher = watch( + *self.reload_dirs, + watch_filter=None, + stop_event=self.should_exit, + # using yield_on_timeout here mostly to make sure tests don't + # hang forever, won't affect the class's behavior + yield_on_timeout=True, + ) + + def should_restart(self) -> list[Path] | None: + self.pause() + + changes = next(self.watcher) + if changes: + unique_paths = {Path(c[1]) for c in changes} + return [p for p in unique_paths if self.watch_filter(p)] + return None diff --git a/venv/Lib/site-packages/uvicorn/workers.py b/venv/Lib/site-packages/uvicorn/workers.py new file mode 100644 index 00000000..06fdf295 --- /dev/null +++ b/venv/Lib/site-packages/uvicorn/workers.py @@ -0,0 +1,114 @@ +from __future__ import annotations + +import asyncio +import logging +import signal +import sys +import warnings +from typing import Any + +from gunicorn.arbiter import Arbiter +from gunicorn.workers.base import Worker + +from uvicorn.config import Config +from uvicorn.server import Server + +warnings.warn( + "The `uvicorn.workers` module is deprecated. Please use `uvicorn-worker` package instead.\n" + "For more details, see https://github.com/Kludex/uvicorn-worker.", + DeprecationWarning, +) + + +class UvicornWorker(Worker): + """ + A worker class for Gunicorn that interfaces with an ASGI consumer callable, + rather than a WSGI callable. + """ + + CONFIG_KWARGS: dict[str, Any] = {"loop": "auto", "http": "auto"} + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + logger = logging.getLogger("uvicorn.error") + logger.handlers = self.log.error_log.handlers + logger.setLevel(self.log.error_log.level) + logger.propagate = False + + logger = logging.getLogger("uvicorn.access") + logger.handlers = self.log.access_log.handlers + logger.setLevel(self.log.access_log.level) + logger.propagate = False + + config_kwargs: dict = { + "app": None, + "log_config": None, + "timeout_keep_alive": self.cfg.keepalive, + "timeout_notify": self.timeout, + "callback_notify": self.callback_notify, + "limit_max_requests": self.max_requests, + "forwarded_allow_ips": self.cfg.forwarded_allow_ips, + } + + if self.cfg.is_ssl: + ssl_kwargs = { + "ssl_keyfile": self.cfg.ssl_options.get("keyfile"), + "ssl_certfile": self.cfg.ssl_options.get("certfile"), + "ssl_keyfile_password": self.cfg.ssl_options.get("password"), + "ssl_version": self.cfg.ssl_options.get("ssl_version"), + "ssl_cert_reqs": self.cfg.ssl_options.get("cert_reqs"), + "ssl_ca_certs": self.cfg.ssl_options.get("ca_certs"), + "ssl_ciphers": self.cfg.ssl_options.get("ciphers"), + } + config_kwargs.update(ssl_kwargs) + + if self.cfg.settings["backlog"].value: + config_kwargs["backlog"] = self.cfg.settings["backlog"].value + + config_kwargs.update(self.CONFIG_KWARGS) + + self.config = Config(**config_kwargs) + + def init_process(self) -> None: + self.config.setup_event_loop() + super().init_process() + + def init_signals(self) -> None: + # Reset signals so Gunicorn doesn't swallow subprocess return codes + # other signals are set up by Server.install_signal_handlers() + # See: https://github.com/encode/uvicorn/issues/894 + for s in self.SIGNALS: + signal.signal(s, signal.SIG_DFL) + + signal.signal(signal.SIGUSR1, self.handle_usr1) + # Don't let SIGUSR1 disturb active requests by interrupting system calls + signal.siginterrupt(signal.SIGUSR1, False) + + def _install_sigquit_handler(self) -> None: + """Install a SIGQUIT handler on workers. + + - https://github.com/encode/uvicorn/issues/1116 + - https://github.com/benoitc/gunicorn/issues/2604 + """ + + loop = asyncio.get_running_loop() + loop.add_signal_handler(signal.SIGQUIT, self.handle_exit, signal.SIGQUIT, None) + + async def _serve(self) -> None: + self.config.app = self.wsgi + server = Server(config=self.config) + self._install_sigquit_handler() + await server.serve(sockets=self.sockets) + if not server.started: + sys.exit(Arbiter.WORKER_BOOT_ERROR) + + def run(self) -> None: + return asyncio.run(self._serve()) + + async def callback_notify(self) -> None: + self.notify() + + +class UvicornH11Worker(UvicornWorker): + CONFIG_KWARGS = {"loop": "asyncio", "http": "h11"} diff --git a/venv/Lib/site-packages/watchfiles/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/watchfiles/__pycache__/__init__.cpython-312.pyc index 756eabd6..606b2aee 100644 Binary files a/venv/Lib/site-packages/watchfiles/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/watchfiles/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/watchfiles/__pycache__/filters.cpython-312.pyc b/venv/Lib/site-packages/watchfiles/__pycache__/filters.cpython-312.pyc index 7d53de59..ea7ad08c 100644 Binary files a/venv/Lib/site-packages/watchfiles/__pycache__/filters.cpython-312.pyc and b/venv/Lib/site-packages/watchfiles/__pycache__/filters.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/watchfiles/__pycache__/main.cpython-312.pyc b/venv/Lib/site-packages/watchfiles/__pycache__/main.cpython-312.pyc index da0d2105..e5a11f68 100644 Binary files a/venv/Lib/site-packages/watchfiles/__pycache__/main.cpython-312.pyc and b/venv/Lib/site-packages/watchfiles/__pycache__/main.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/watchfiles/__pycache__/run.cpython-312.pyc b/venv/Lib/site-packages/watchfiles/__pycache__/run.cpython-312.pyc index 12cc4c49..21022de5 100644 Binary files a/venv/Lib/site-packages/watchfiles/__pycache__/run.cpython-312.pyc and b/venv/Lib/site-packages/watchfiles/__pycache__/run.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/watchfiles/__pycache__/version.cpython-312.pyc b/venv/Lib/site-packages/watchfiles/__pycache__/version.cpython-312.pyc index 38c12a51..df67c14a 100644 Binary files a/venv/Lib/site-packages/watchfiles/__pycache__/version.cpython-312.pyc and b/venv/Lib/site-packages/watchfiles/__pycache__/version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/websockets/__pycache__/__init__.cpython-312.pyc index cde6c8e6..e8a091dd 100644 Binary files a/venv/Lib/site-packages/websockets/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/websockets/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/websockets/__pycache__/client.cpython-312.pyc index b559a4ba..42fb29da 100644 Binary files a/venv/Lib/site-packages/websockets/__pycache__/client.cpython-312.pyc and b/venv/Lib/site-packages/websockets/__pycache__/client.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/__pycache__/datastructures.cpython-312.pyc b/venv/Lib/site-packages/websockets/__pycache__/datastructures.cpython-312.pyc index 19781a4d..30d3109d 100644 Binary files a/venv/Lib/site-packages/websockets/__pycache__/datastructures.cpython-312.pyc and b/venv/Lib/site-packages/websockets/__pycache__/datastructures.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/__pycache__/exceptions.cpython-312.pyc b/venv/Lib/site-packages/websockets/__pycache__/exceptions.cpython-312.pyc index 92702b48..caa6e07c 100644 Binary files a/venv/Lib/site-packages/websockets/__pycache__/exceptions.cpython-312.pyc and b/venv/Lib/site-packages/websockets/__pycache__/exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/__pycache__/frames.cpython-312.pyc b/venv/Lib/site-packages/websockets/__pycache__/frames.cpython-312.pyc index 0e2c9fb5..e50d7ba9 100644 Binary files a/venv/Lib/site-packages/websockets/__pycache__/frames.cpython-312.pyc and b/venv/Lib/site-packages/websockets/__pycache__/frames.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/__pycache__/headers.cpython-312.pyc b/venv/Lib/site-packages/websockets/__pycache__/headers.cpython-312.pyc index bbd70c8b..dbcf222e 100644 Binary files a/venv/Lib/site-packages/websockets/__pycache__/headers.cpython-312.pyc and b/venv/Lib/site-packages/websockets/__pycache__/headers.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/__pycache__/http11.cpython-312.pyc b/venv/Lib/site-packages/websockets/__pycache__/http11.cpython-312.pyc index cf6a1238..1d2e1d6f 100644 Binary files a/venv/Lib/site-packages/websockets/__pycache__/http11.cpython-312.pyc and b/venv/Lib/site-packages/websockets/__pycache__/http11.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/__pycache__/imports.cpython-312.pyc b/venv/Lib/site-packages/websockets/__pycache__/imports.cpython-312.pyc index c26bd3ba..c12866a6 100644 Binary files a/venv/Lib/site-packages/websockets/__pycache__/imports.cpython-312.pyc and b/venv/Lib/site-packages/websockets/__pycache__/imports.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/__pycache__/protocol.cpython-312.pyc b/venv/Lib/site-packages/websockets/__pycache__/protocol.cpython-312.pyc index 69d43970..f6104e03 100644 Binary files a/venv/Lib/site-packages/websockets/__pycache__/protocol.cpython-312.pyc and b/venv/Lib/site-packages/websockets/__pycache__/protocol.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/__pycache__/server.cpython-312.pyc b/venv/Lib/site-packages/websockets/__pycache__/server.cpython-312.pyc index 0e03f91b..c20e9c8c 100644 Binary files a/venv/Lib/site-packages/websockets/__pycache__/server.cpython-312.pyc and b/venv/Lib/site-packages/websockets/__pycache__/server.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/__pycache__/streams.cpython-312.pyc b/venv/Lib/site-packages/websockets/__pycache__/streams.cpython-312.pyc index 37fa25d5..42e59c6f 100644 Binary files a/venv/Lib/site-packages/websockets/__pycache__/streams.cpython-312.pyc and b/venv/Lib/site-packages/websockets/__pycache__/streams.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/__pycache__/typing.cpython-312.pyc b/venv/Lib/site-packages/websockets/__pycache__/typing.cpython-312.pyc index f894eaf8..b35ab28b 100644 Binary files a/venv/Lib/site-packages/websockets/__pycache__/typing.cpython-312.pyc and b/venv/Lib/site-packages/websockets/__pycache__/typing.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/__pycache__/uri.cpython-312.pyc b/venv/Lib/site-packages/websockets/__pycache__/uri.cpython-312.pyc index d416f339..394665f9 100644 Binary files a/venv/Lib/site-packages/websockets/__pycache__/uri.cpython-312.pyc and b/venv/Lib/site-packages/websockets/__pycache__/uri.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/websockets/__pycache__/utils.cpython-312.pyc index 95cb168d..08dda361 100644 Binary files a/venv/Lib/site-packages/websockets/__pycache__/utils.cpython-312.pyc and b/venv/Lib/site-packages/websockets/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/__pycache__/version.cpython-312.pyc b/venv/Lib/site-packages/websockets/__pycache__/version.cpython-312.pyc index f8cb236d..666b3b3b 100644 Binary files a/venv/Lib/site-packages/websockets/__pycache__/version.cpython-312.pyc and b/venv/Lib/site-packages/websockets/__pycache__/version.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/asyncio/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/websockets/asyncio/__pycache__/__init__.cpython-312.pyc index e3e98076..ec05bee0 100644 Binary files a/venv/Lib/site-packages/websockets/asyncio/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/websockets/asyncio/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/asyncio/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/websockets/asyncio/__pycache__/client.cpython-312.pyc index f9db8e68..8cc035fb 100644 Binary files a/venv/Lib/site-packages/websockets/asyncio/__pycache__/client.cpython-312.pyc and b/venv/Lib/site-packages/websockets/asyncio/__pycache__/client.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/asyncio/__pycache__/compatibility.cpython-312.pyc b/venv/Lib/site-packages/websockets/asyncio/__pycache__/compatibility.cpython-312.pyc index 6432efc3..bcbe2de8 100644 Binary files a/venv/Lib/site-packages/websockets/asyncio/__pycache__/compatibility.cpython-312.pyc and b/venv/Lib/site-packages/websockets/asyncio/__pycache__/compatibility.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/asyncio/__pycache__/connection.cpython-312.pyc b/venv/Lib/site-packages/websockets/asyncio/__pycache__/connection.cpython-312.pyc index 2a5bcd98..a24af165 100644 Binary files a/venv/Lib/site-packages/websockets/asyncio/__pycache__/connection.cpython-312.pyc and b/venv/Lib/site-packages/websockets/asyncio/__pycache__/connection.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/asyncio/__pycache__/messages.cpython-312.pyc b/venv/Lib/site-packages/websockets/asyncio/__pycache__/messages.cpython-312.pyc index 15114afb..d7a0f81b 100644 Binary files a/venv/Lib/site-packages/websockets/asyncio/__pycache__/messages.cpython-312.pyc and b/venv/Lib/site-packages/websockets/asyncio/__pycache__/messages.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/extensions/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/websockets/extensions/__pycache__/__init__.cpython-312.pyc index 13318b7c..6a26c63d 100644 Binary files a/venv/Lib/site-packages/websockets/extensions/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/websockets/extensions/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/extensions/__pycache__/base.cpython-312.pyc b/venv/Lib/site-packages/websockets/extensions/__pycache__/base.cpython-312.pyc index c6042c64..71ac469c 100644 Binary files a/venv/Lib/site-packages/websockets/extensions/__pycache__/base.cpython-312.pyc and b/venv/Lib/site-packages/websockets/extensions/__pycache__/base.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/extensions/__pycache__/permessage_deflate.cpython-312.pyc b/venv/Lib/site-packages/websockets/extensions/__pycache__/permessage_deflate.cpython-312.pyc index ed7e4d98..b31df968 100644 Binary files a/venv/Lib/site-packages/websockets/extensions/__pycache__/permessage_deflate.cpython-312.pyc and b/venv/Lib/site-packages/websockets/extensions/__pycache__/permessage_deflate.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/legacy/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/websockets/legacy/__pycache__/__init__.cpython-312.pyc index 51768d3b..c1b06513 100644 Binary files a/venv/Lib/site-packages/websockets/legacy/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/websockets/legacy/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/legacy/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/websockets/legacy/__pycache__/client.cpython-312.pyc index 0b79a4a9..7ca7facf 100644 Binary files a/venv/Lib/site-packages/websockets/legacy/__pycache__/client.cpython-312.pyc and b/venv/Lib/site-packages/websockets/legacy/__pycache__/client.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/legacy/__pycache__/exceptions.cpython-312.pyc b/venv/Lib/site-packages/websockets/legacy/__pycache__/exceptions.cpython-312.pyc index 942be013..7bbd03d2 100644 Binary files a/venv/Lib/site-packages/websockets/legacy/__pycache__/exceptions.cpython-312.pyc and b/venv/Lib/site-packages/websockets/legacy/__pycache__/exceptions.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/legacy/__pycache__/framing.cpython-312.pyc b/venv/Lib/site-packages/websockets/legacy/__pycache__/framing.cpython-312.pyc index 4932897f..3ce2815d 100644 Binary files a/venv/Lib/site-packages/websockets/legacy/__pycache__/framing.cpython-312.pyc and b/venv/Lib/site-packages/websockets/legacy/__pycache__/framing.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/legacy/__pycache__/handshake.cpython-312.pyc b/venv/Lib/site-packages/websockets/legacy/__pycache__/handshake.cpython-312.pyc index 135d82d2..45866e39 100644 Binary files a/venv/Lib/site-packages/websockets/legacy/__pycache__/handshake.cpython-312.pyc and b/venv/Lib/site-packages/websockets/legacy/__pycache__/handshake.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/legacy/__pycache__/http.cpython-312.pyc b/venv/Lib/site-packages/websockets/legacy/__pycache__/http.cpython-312.pyc index 0ec29c5b..75f50738 100644 Binary files a/venv/Lib/site-packages/websockets/legacy/__pycache__/http.cpython-312.pyc and b/venv/Lib/site-packages/websockets/legacy/__pycache__/http.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/legacy/__pycache__/protocol.cpython-312.pyc b/venv/Lib/site-packages/websockets/legacy/__pycache__/protocol.cpython-312.pyc index 05e5f60f..0ead67c3 100644 Binary files a/venv/Lib/site-packages/websockets/legacy/__pycache__/protocol.cpython-312.pyc and b/venv/Lib/site-packages/websockets/legacy/__pycache__/protocol.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/legacy/__pycache__/server.cpython-312.pyc b/venv/Lib/site-packages/websockets/legacy/__pycache__/server.cpython-312.pyc index 6a56fc51..58aeb0c8 100644 Binary files a/venv/Lib/site-packages/websockets/legacy/__pycache__/server.cpython-312.pyc and b/venv/Lib/site-packages/websockets/legacy/__pycache__/server.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/sync/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/websockets/sync/__pycache__/__init__.cpython-312.pyc index a9a411bb..bc08aafc 100644 Binary files a/venv/Lib/site-packages/websockets/sync/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/websockets/sync/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/sync/__pycache__/client.cpython-312.pyc b/venv/Lib/site-packages/websockets/sync/__pycache__/client.cpython-312.pyc index da35261c..0641e4fe 100644 Binary files a/venv/Lib/site-packages/websockets/sync/__pycache__/client.cpython-312.pyc and b/venv/Lib/site-packages/websockets/sync/__pycache__/client.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/sync/__pycache__/connection.cpython-312.pyc b/venv/Lib/site-packages/websockets/sync/__pycache__/connection.cpython-312.pyc index f3782ac9..273825d7 100644 Binary files a/venv/Lib/site-packages/websockets/sync/__pycache__/connection.cpython-312.pyc and b/venv/Lib/site-packages/websockets/sync/__pycache__/connection.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/sync/__pycache__/messages.cpython-312.pyc b/venv/Lib/site-packages/websockets/sync/__pycache__/messages.cpython-312.pyc index 39390de4..ec5a9712 100644 Binary files a/venv/Lib/site-packages/websockets/sync/__pycache__/messages.cpython-312.pyc and b/venv/Lib/site-packages/websockets/sync/__pycache__/messages.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/websockets/sync/__pycache__/utils.cpython-312.pyc b/venv/Lib/site-packages/websockets/sync/__pycache__/utils.cpython-312.pyc index 6c5b33cd..73ae766d 100644 Binary files a/venv/Lib/site-packages/websockets/sync/__pycache__/utils.cpython-312.pyc and b/venv/Lib/site-packages/websockets/sync/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/yarl/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/yarl/__pycache__/__init__.cpython-312.pyc index 07353b8a..c724a6fe 100644 Binary files a/venv/Lib/site-packages/yarl/__pycache__/__init__.cpython-312.pyc and b/venv/Lib/site-packages/yarl/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/yarl/__pycache__/_parse.cpython-312.pyc b/venv/Lib/site-packages/yarl/__pycache__/_parse.cpython-312.pyc index 5999da08..5fb39c1e 100644 Binary files a/venv/Lib/site-packages/yarl/__pycache__/_parse.cpython-312.pyc and b/venv/Lib/site-packages/yarl/__pycache__/_parse.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/yarl/__pycache__/_path.cpython-312.pyc b/venv/Lib/site-packages/yarl/__pycache__/_path.cpython-312.pyc index 5c03588b..6929383d 100644 Binary files a/venv/Lib/site-packages/yarl/__pycache__/_path.cpython-312.pyc and b/venv/Lib/site-packages/yarl/__pycache__/_path.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/yarl/__pycache__/_query.cpython-312.pyc b/venv/Lib/site-packages/yarl/__pycache__/_query.cpython-312.pyc index 98f10058..e28b2f5b 100644 Binary files a/venv/Lib/site-packages/yarl/__pycache__/_query.cpython-312.pyc and b/venv/Lib/site-packages/yarl/__pycache__/_query.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/yarl/__pycache__/_quoters.cpython-312.pyc b/venv/Lib/site-packages/yarl/__pycache__/_quoters.cpython-312.pyc index 9330f831..13b09e25 100644 Binary files a/venv/Lib/site-packages/yarl/__pycache__/_quoters.cpython-312.pyc and b/venv/Lib/site-packages/yarl/__pycache__/_quoters.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/yarl/__pycache__/_quoting.cpython-312.pyc b/venv/Lib/site-packages/yarl/__pycache__/_quoting.cpython-312.pyc index 8a21c2eb..f54d3c07 100644 Binary files a/venv/Lib/site-packages/yarl/__pycache__/_quoting.cpython-312.pyc and b/venv/Lib/site-packages/yarl/__pycache__/_quoting.cpython-312.pyc differ diff --git a/venv/Lib/site-packages/yarl/__pycache__/_url.cpython-312.pyc b/venv/Lib/site-packages/yarl/__pycache__/_url.cpython-312.pyc index 9bcaffe3..c86e1fe4 100644 Binary files a/venv/Lib/site-packages/yarl/__pycache__/_url.cpython-312.pyc and b/venv/Lib/site-packages/yarl/__pycache__/_url.cpython-312.pyc differ diff --git a/venv/Scripts/fastapi.exe b/venv/Scripts/fastapi.exe new file mode 100644 index 00000000..a1a132aa Binary files /dev/null and b/venv/Scripts/fastapi.exe differ diff --git a/venv/Scripts/normalizer.exe b/venv/Scripts/normalizer.exe new file mode 100644 index 00000000..604b6cd6 Binary files /dev/null and b/venv/Scripts/normalizer.exe differ diff --git a/venv/Scripts/uvicorn.exe b/venv/Scripts/uvicorn.exe new file mode 100644 index 00000000..3272efac Binary files /dev/null and b/venv/Scripts/uvicorn.exe differ